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.patchis the exception: it returns null on a conflict. - The helpers clean up.
bulkImportdoesn't leave a failed import open. See the bulk import note in Records.uploadsends each chunk with its SHA-256 hash, anddownloadchecks each range'sContent-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.resolvereturns a service's location, not access to it, andservices.requestsends a request with the host's credentials without ever returning them. - For the host's own bridge operations:
attachments.listandattachments.open, thestream.*operations,http.body, thehttp.response.*operations,log, andconsole. The typed methods cover those, and the host refuses them throughplatform.call.records.getandrecords.patchwork 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:
{ "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
let reply = ctx.platform_call("aiSearch.query", json!({"profileId": profile_id, "query": query, "topK": 5})).await?;
let items = reply["value"]["items"].clone();
var reply struct {
Value struct {
Items []map[string]any `json:"items"`
} `json:"value"`
}
if err := c.PlatformCall("aiSearch.query", map[string]any{"profileId": profileID, "query": query, "topK": 5}, &reply); err != nil {
return nil, err // a *worker.PlatformError when the host answers ok: false
}
return reply.Value.Items, nil
reply = await ctx.platform_call("aiSearch.query", {"profileId": profile_id, "query": query, "topK": 5})
items = reply["value"]["items"]
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:
records.import.beginreturns animportIdand thechunkBytesto write in. An invocation can run one import at a time.records.import.writesends base64 chunks in order, starting at offset 0. Each reply'sbytesSentmust equal the new offset.records.import.finishcompletes the import and returns the outcome. It fails if nothing was written, so don't begin an import with nothing to send.records.import.abortabandons 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.
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 })
}
}
use base64::{Engine, engine::general_purpose::STANDARD};
use contextual_worker::{Context, PlatformError, Value, anyhow::{Error, Result, bail, ensure}, json};
pub async fn import_with_progress(ctx: &Context, type_id: &str, lines: &[String]) -> Result<Value> {
let data: Vec<u8> = lines.iter().flat_map(|line| format!("{line}\n").into_bytes()).collect();
if data.is_empty() {
bail!("Nothing to import");
}
let begun = ctx.platform_call("records.import.begin", json!({"typeId": type_id})).await?;
let import_id = begun["value"]["importId"].as_str().unwrap_or_default().to_owned();
let chunk_bytes = begun["value"]["chunkBytes"].as_u64().unwrap_or(0) as usize;
ensure!(!import_id.is_empty() && chunk_bytes > 0, "records.import.begin: unexpected reply");
// A write or finish the host fails has already closed the import there, unless it was refused as invalid.
let mut host_failed = false;
let closes = |error: &Error| {
error.downcast_ref::<PlatformError>().is_some_and(|e| e.code() != Some("validation"))
};
let result: Result<Value> = async {
let mut offset = 0usize;
for chunk in data.chunks(chunk_bytes) {
let ack = ctx
.platform_call("records.import.write", json!({"importId": import_id, "offset": offset, "data": STANDARD.encode(chunk)}))
.await
.inspect_err(|e| host_failed = closes(e))?;
offset += chunk.len();
ensure!(ack["value"]["bytesSent"].as_u64() == Some(offset as u64), "records.import.write: unexpected acknowledgement");
ctx.log().info("Import progress", json!({"importId": import_id, "bytesSent": offset})).await?;
}
let finished = ctx
.platform_call("records.import.finish", json!({"importId": import_id}))
.await
.inspect_err(|e| host_failed = closes(e))?;
Ok(finished["value"].clone())
}
.await;
let Err(error) = result else { return result };
if host_failed {
return Err(error);
}
if let Err(abort_error) = ctx.platform_call("records.import.abort", json!({"importId": import_id})).await {
return Err(error.context(format!("aborting the import also failed ({abort_error}); reconcile before retrying")));
}
Err(error.context("Import failed after records may have been sent; reconcile before retrying"))
}
Add base64 = "0.22" to Cargo.toml.
import (
"encoding/base64"
"errors"
"fmt"
"strings"
"contextual.io/worker"
)
type envelope[T any] struct {
Value T `json:"value"`
}
func importWithProgress(c *worker.Context, typeID string, lines []string) (map[string]any, error) {
if len(lines) == 0 {
return nil, errors.New("nothing to import")
}
var begun envelope[struct {
ImportID string `json:"importId"`
ChunkBytes int `json:"chunkBytes"`
}]
if err := c.PlatformCall("records.import.begin", map[string]any{"typeId": typeID}, &begun); err != nil {
return nil, err
}
importID, chunkBytes := begun.Value.ImportID, begun.Value.ChunkBytes
if importID == "" || chunkBytes < 1 {
return nil, errors.New("records.import.begin: unexpected reply")
}
// A write or finish the host fails has already closed the import there, unless it was refused as invalid.
hostFailed := false
closes := func(err error) bool {
var failure *worker.PlatformError
return errors.As(err, &failure) && failure.Code() != "validation"
}
outcome, err := func() (map[string]any, error) {
data := []byte(strings.Join(lines, "\n") + "\n")
for offset := 0; offset < len(data); offset += chunkBytes {
chunk := data[offset:min(offset+chunkBytes, len(data))]
var ack envelope[struct {
BytesSent int `json:"bytesSent"`
}]
params := map[string]any{"importId": importID, "offset": offset, "data": base64.StdEncoding.EncodeToString(chunk)}
if err := c.PlatformCall("records.import.write", params, &ack); err != nil {
hostFailed = closes(err)
return nil, err
}
if ack.Value.BytesSent != offset+len(chunk) {
return nil, errors.New("records.import.write: unexpected acknowledgement")
}
if err := c.Log().Info("Import progress", map[string]any{"importId": importID, "bytesSent": ack.Value.BytesSent}); err != nil {
return nil, err
}
}
var finished envelope[map[string]any]
if err := c.PlatformCall("records.import.finish", map[string]any{"importId": importID}, &finished); err != nil {
hostFailed = closes(err)
return nil, err
}
return finished.Value, nil
}()
if err == nil || hostFailed {
return outcome, err
}
if abortErr := c.PlatformCall("records.import.abort", map[string]any{"importId": importID}, nil); abortErr != nil {
return nil, errors.Join(err, fmt.Errorf("aborting the import also failed; reconcile before retrying: %w", abortErr))
}
return nil, fmt.Errorf("import failed after records may have been sent; reconcile before retrying: %w", err)
}
import base64
from contextual_worker import PlatformError
async def import_with_progress(ctx, type_id: str, lines: list[str]):
data = "".join(f"{line}\n" for line in lines).encode()
if not data:
raise ValueError("Nothing to import")
begun = (await ctx.platform_call("records.import.begin", {"typeId": type_id}))["value"]
import_id, chunk_bytes = begun["importId"], begun["chunkBytes"]
# A write or finish the host fails has already closed the import there, unless it was refused as invalid.
host_failed = False
async def step(method, params):
nonlocal host_failed
try:
return (await ctx.platform_call(method, params))["value"]
except PlatformError as error:
host_failed = error.code != "validation"
raise
try:
for offset in range(0, len(data), chunk_bytes):
chunk = data[offset:offset + chunk_bytes]
ack = await step("records.import.write", {
"importId": import_id, "offset": offset, "data": base64.b64encode(chunk).decode("ascii"),
})
if ack["bytesSent"] != offset + len(chunk):
raise RuntimeError("records.import.write: unexpected acknowledgement")
await ctx.log.info("Import progress", {"importId": import_id, "bytesSent": ack["bytesSent"]})
return await step("records.import.finish", {"importId": import_id})
except Exception as error:
if host_failed:
raise
try:
await ctx.platform_call("records.import.abort", {"importId": import_id})
except Exception as abort_error:
error.add_note(f"Aborting the import also failed ({abort_error}); reconcile before retrying")
raise error
raise RuntimeError("Import failed after records may have been sent; reconcile before retrying") from 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.