Skip to Content
Docs

Raw Platform Calls

How the typed methods, helpers, and capability contract fit together, and when to use the platform.call escape hatch.

Every capability on Platform Capabilities is one or more calls defined by the capability contract. The contract is a catalog of every operation the managed host offers, with its parameters, result, and failure shape. The host checks every call against the contract before it acts. The adapters' typed methods are generated from the contract.

You can call any contract operation directly with platform.call. This page explains when that is the right choice and how to do it safely.

Three Layers

Layer What It Is Use It For
Typed methods records, attachments, actions, messaging, aiSearch, services, ai, cloud, and connections Almost everything. Each returns the value itself and fails with a PlatformError.
Helpers listAll and queryAll, bulkImport, attachment upload, download, list, and open, ai.upload, ai.generateWithTools, and the cloud readers and writers Operations that take several calls. The helper orders the calls, chunks and hashes data, renews transfers, limits paging, and cleans up after a failure.
platform.call The raw channel. It takes any contract operation by name and returns the reply envelope. The escape hatch, described below.

Start with the typed methods. platform.call gives you nothing the host would not also enforce, and it removes the checks the adapter performs for you.

The typed layer does these things for you:

  • It takes required parameters by position and optional ones as options.
  • It returns the reply's value, after checking that it has the contract's shape.
  • It raises a failure as a PlatformError. records.patch is the exception: it returns null on a conflict.
  • The helpers clean up. bulkImport doesn't leave a failed import open. See the bulk import note in Records. upload sends each chunk with its SHA-256 hash, and download checks each range's Content-Range, length, and ETag. Both renew transfers, retry brief Files API failures, never follow redirects, and refuse oversized ranges. Paging stops if the host repeats a page token. Transfers stop when the invocation is cancelled.

When to Use the Escape Hatch

Use platform.call when:

  • The host offers an operation your adapter version doesn't name yet. A new operation reaches the host before the next adapter release. Call it by name until you upgrade.
  • You need to drive a multi-step operation differently than the helper does. Examples: logging import progress after each chunk, choosing your own chunk boundaries, stepping a tool session yourself, or uploading from a source the helper cannot read.
  • You want the raw failure envelope, for example for diagnostics.

Do not use it:

  • To get around a check. The host validates a raw call exactly like a typed one, with the same type allowlist and limits.
  • To get credentials. No operation returns a tenant credential. An attachment transfer intent carries a short-lived token scoped to one file. services.resolve returns a service's location, not access to it, and services.request sends a request with the host's credentials without ever returning them.
  • For the host's own bridge operations: attachments.list and attachments.open, the stream.* operations, http.body, the http.response.* operations, log, and console. The typed methods cover those, and the host refuses them through platform.call. records.get and records.patch work both ways.

An operation the host does not offer fails with code contract and reason unsupported-method.

The Envelope

A raw call returns an envelope. On success it is { "ok": true, "value": … }. On failure:

JSON
{ "ok": false, "code": "platform", "reason": "rate-limited", "retryable": true, "effectMayHaveOccurred": false, "responseStatus": 429 }

The languages differ in what a raw call does with it:

Language Raw Call On Success On Failure (ok: false)
TypeScript context.platform!.call(method, params) Returns the whole envelope Returns the envelope. It does not throw, so check ok.
Rust ctx.platform_call(method, params).await? Returns the whole envelope. Read ["value"]. Err holding a PlatformError
Go c.PlatformCall(method, params, &envelope) Decodes the whole envelope into your struct Returns *worker.PlatformError
Python await ctx.platform_call(method, params) Returns the whole envelope. Read ["value"]. Raises PlatformError
const reply: unknown = await context.platform!.call("aiSearch.query", { profileId, query, topK: 5 })
if (typeof reply !== "object" || reply === null || !("ok" in reply)) throw new Error("aiSearch.query: invalid reply")
// Throw an error whose cause is the envelope itself, not a copy: the host can then tell which call failed.
if (reply.ok !== true) throw new Error("aiSearch.query failed", { cause: reply })
// The value is unchecked data: validate it before you use it.
const value = "value" in reply ? reply.value : undefined

Operation Reference

Parameter names follow @contextual-io/sdk: a write takes ifHashMatch (the hash you read), forceVersion sets a version deliberately, and records.get takes doNotDecrypt. The catalog is the same for every language. The adapter images in this release don't include the catalog file itself. In the Rust, Go, and Python libraries, the typed methods show the parameters of single-call operations, and the helpers' source shows those of multi-step operations such as imports, transfers, AI, and cloud storage.

Operation Part Of Purpose
records.get, records.list, records.query, records.create, records.replace, records.patch, records.delete Read and write records
records.import.begin, .write, .finish, .abort Bulk import Insert JSON Lines in chunks
actions.execute Run a server-defined action
attachments.get, attachments.search, attachments.delete Attachment metadata and deletion
attachments.begin, .renew, .finish Upload Reserve an upload, renew its transfer, and complete it. The bytes go to the Files API.
attachments.downloadIntent Download A transfer for reading ranges from the Files API
messaging.sendToAgent Send an event to another Agent
ai.generate One generation through an AI Route
ai.generateCall Run a saved AI Call for one result on the Rust host
ai.upload.begin, .write, .finish, .release AI upload Stage media for a generation
ai.session.start, .next, .toolResult, .cancel Tool session A generation that calls your tools
ai.session.streamCall, .next, .cancel Saved Call stream Stream a saved AI Call on the Rust host
aiSearch.query Search an AI Search profile
cloud.read.open, .read.next, .list.open, .list.next, .write.open, .write.chunk, .write.finish, .write.abort, .close, cloud.delete Cloud storage Read, list, write, and delete files
connections.request An HTTP request through a declared connection
services.request A JSON or text HTTP request to a granted platform service. See Call Platform Services.
services.resolve A platform service's location

Saved AI Call Operations

Run these operations from a Worker that uses Rust host 0.18.0 or later. The Worker code can be TypeScript, Rust, Go, or Python. Use the Call reference and variables for your saved Call. Add timeoutMs to the same request object if you need a generation deadline.

Method Parameters Success value
ai.generateCall The Call request The completed result. Read text or object, and call for the version and Route.
ai.session.streamCall The Call request { "started": true }. Call ai.session.next to read output.
ai.session.next Empty object The next event. heartbeat keeps an idle connection active. generate.delta carries incremental output. generate.response carries the completed result in data and closes the session.
ai.session.cancel Empty object null. The call succeeds even if the session is already closed.

Each invocation can have one active AI session at a time. Close an open stream or tool session before starting another.

The typed methods below return the result itself. A raw call returns the reply envelope. Read the result or event from value, and check ok explicitly in TypeScript. For the remaining streaming steps, use the same raw call syntax with ai.session.next or ai.session.cancel and an empty object.

Language Adapter for the typed method Wait for the result Start a stream
TypeScript Node 0.12.0 or later context.ai.generateCall Call ai.session.streamCall through context.platform.call.
Rust Rust 0.9.0 or later ctx.ai().generate_call(request).await? ctx.platform_call("ai.session.streamCall", request).await?
Go Go 0.6.0 or later result, err := c.AI().GenerateCall(request) err := c.PlatformCall("ai.session.streamCall", request, &reply)
Python Python 0.6.0 or later await ctx.ai().generate_call(request) await ctx.platform_call("ai.session.streamCall", request)

For Go raw calls, pass a pointer to a reply struct with a Value field as shown in The Envelope. To wait for one result through the raw interface, use ai.generateCall with the same request.

While waiting for the next event, a Gateway error, disconnect, or deadline closes the session. If your handler stops reading while the session is open, cancel it before returning. An invocation that returns with an open session fails.

Avoid automatic retries when you don’t know whether generation started. If a request times out or the connection drops, the model may already have started generating. A retry can run the Call a second time and use more tokens.

An unhandled error in an Event Worker can cause the same event to be delivered again. This can rerun the Call even if the handler has no retry loop. Before sending the Call, use an atomic write to record the event’s stable id in a durable store shared by all replicas. On redelivery, check that record before sending another Call. If the previous outcome is unknown, record it for follow-up and return successfully to acknowledge the event.

Send another generation request only when the failure confirms that generation did not start. For a failure from ai.generateCall or ai.session.streamCall, check for effectMayHaveOccurred: false. In TypeScript, read the raw failure envelope or, for the typed method, the envelope in PlatformError.cause.

If the host rejects the parameters to ai.session.next, effectMayHaveOccurred: false applies to that poll. The generation may still be running. Correct the poll or cancel the open session. Cancellation asks the Gateway to stop generation, which may already have used tokens.

Drive a Multi-Step Operation Yourself

A multi-step operation is a sequence of calls in a fixed order. For a bulk import:

  1. records.import.begin returns an importId and the chunkBytes to write in. An invocation can run one import at a time.
  2. records.import.write sends base64 chunks in order, starting at offset 0. Each reply's bytesSent must equal the new offset.
  3. records.import.finish completes the import and returns the outcome. It fails if nothing was written, so don't begin an import with nothing to send. records.import.abort abandons it.

When a write or finish fails at the host, the host has already closed the import. Do not abort it then: the host refuses the abort as an unknown import, which is a host fault and fails the invocation even if you catch it. Rethrow the PlatformError instead. The exception is a validation failure, which the host returns before it touches the import, so the import is still open. Abort after a validation failure, and after a failure of your own, such as your data source failing or a reply you reject. An invocation that ends with an import still open fails. Either way, records already sent may be inserted: check what is in the tenant before you retry.

These functions import records and log progress after each chunk. They handle every failure path.

TypeScript
import type { Context } from "./worker-types"

export async function importWithProgress(context: Context<unknown>, typeId: string, lines: string[]) {
  const data = Buffer.from(lines.map(line => `${line}\n`).join(""))
  if (!data.length) throw new Error("Nothing to import")
  // A host failure is an error whose cause is the reply itself, so the host can tell which call failed. Every failure
  // but validation closes the import at the host; validation is refused before the import is touched.
  let hostFailed = false
  const call = async (method: string, params: Record<string, unknown>) => {
    const reply = await context.platform!.call(method, params)
    if (reply?.ok === false) {
      hostFailed = reply.code !== "validation"
      throw new Error(`${method} failed: ${reply.code ?? "platform"}`, { cause: reply })
    }
    if (reply?.ok !== true) throw new Error(`${method}: invalid reply`)
    return reply.value
  }
  const { importId, chunkBytes } = await call("records.import.begin", { typeId })
  try {
    for (let offset = 0; offset < data.length; offset += chunkBytes) {
      const chunk = data.subarray(offset, offset + chunkBytes)
      const { bytesSent } = await call("records.import.write", { importId, offset, data: chunk.toString("base64") })
      if (bytesSent !== offset + chunk.length) throw new Error("records.import.write: the host acknowledged a different offset")
      await context.logger.info("Import progress", { importId, bytesSent })
    }
    return await call("records.import.finish", { importId })
  } catch (error) {
    // The host closed the import when its own step failed: rethrow without aborting.
    if (hostFailed) throw error
    // Otherwise the import is still open: a validation failure, your own failure, or a reply you rejected.
    try { await call("records.import.abort", { importId }) } catch (abortError) {
      throw new AggregateError([error, abortError], "Import failed, and so did aborting it; reconcile before retrying", { cause: error })
    }
    throw new Error("Import failed after records may have been sent; reconcile before retrying", { cause: error })
  }
}

The other multi-step operations follow the same pattern: an attachment upload, an AI upload, a tool session, and cloud reads, listings, and writes. Prefer their helpers. An invocation that ends with an AI upload unreleased, a tool session open, an import open, or a cloud write unfinished fails.

Failures

A PlatformError is the platform's answer, not a crash. Return or raise it, or an error caused by it, and the host records which call failed. On an HTTP Worker, an unhandled failure fails that request with a 500, and the host keeps serving. On an event Worker, it stops the host on the first failure. Only a failed send to another Agent on an event Worker is retried instead, because the broker was at fault. On a scheduled Worker, the run fails. If you catch a PlatformError and handle it, the invocation can still succeed.

A host fault is different: the host failed the call itself, or the bridge to it was lost. It is a CapabilityError in Rust, Go, and Python, or a plain Error in TypeScript, and it fails the invocation even if you catch it. A reply the adapter finds malformed raises an error too, but that alone doesn't fail the invocation: if you catch it, the invocation can still succeed.