Skip to content

An open-source, faster Devin alternative

TypeScript

SDK: the backend exists, so the types stop saying it is in flight; session_publication_unconfirmed reaches the caller with its session id

Igor Zalutski5903ee753cb8
diff --git a/docs/reference/typescript-sdk/agents.mdx b/docs/reference/typescript-sdk/agents.mdx
index 602f697a..1b0a2a82 100644
--- a/docs/reference/typescript-sdk/agents.mdx
+++ b/docs/reference/typescript-sdk/agents.mdx
@@ -47,10 +47,12 @@ field names are the API's own.
Every failed call throws `OpenComputerError` with `code`, `status` and
`message`. `code` is the API's stable code when the body carried one
-(`idempotency_conflict`, `session_ended`, `insufficient_credits`); when the
-body had only text, it is derived from the status: `unauthorized`,
-`forbidden`, `not_found`, `conflict`, `rate_limited`, `unavailable` for `5xx`,
-`request_failed` otherwise. A `429` also carries `retryAfter` in seconds.
+(`idempotency_conflict`, `session_ended`, `insufficient_credits`,
+`session_publication_unconfirmed`); when the body had only text, it is
+derived from the status: `unauthorized`, `forbidden`, `not_found`,
+`conflict`, `rate_limited`, `unavailable` for `5xx`, `request_failed`
+otherwise. A `429` also carries `retryAfter` in seconds, and an error the
+API tied to a session carries `sessionId`.
```typescript
try {
@@ -63,7 +65,25 @@ try {
```
The client does not retry. The API's idempotency keys make a retry safe, and
-the caller decides which calls to repeat and with which key.
+the caller decides which calls to repeat and with which key. The one error
+that asks for a retry, `503 session_publication_unconfirmed` from
+`sessions.create` or `sessions.setLabels`, is thrown like any other: the
+session exists, or its labels are recorded, but its row in the list was not
+confirmed in time, and `error.sessionId` names it. Repeat the same call, with
+the same `idempotencyKey` and params on `create` or the same patch on
+`setLabels`, until it returns; a return means the list reflects the change
+([Management API](/agents/api#create)).
+
+```typescript
+for (;;) {
+ try {
+ return await oc.sessions.create(params, { idempotencyKey: taskId });
+ } catch (error) {
+ if (!(error instanceof OpenComputerError) || error.code !== "session_publication_unconfirmed") throw error;
+ await new Promise((resolve) => setTimeout(resolve, 500));
+ }
+}
+```
The client does not follow redirects. The API key is sent to `baseUrl` and
to no other origin: a redirect answer fails the call with code `redirected`
diff --git a/sdks/typescript/CHANGELOG.md b/sdks/typescript/CHANGELOG.md
index 5391d0ca..6b6cb9e3 100644
--- a/sdks/typescript/CHANGELOG.md
+++ b/sdks/typescript/CHANGELOG.md
@@ -14,9 +14,11 @@ published version that has it, `1.1.1`.
(`sessions`, `sessions.turns`, `sessions.events`, `projects`,
`projects.memory`, `projects.webhooks`, `projects.eventSubscriptions`,
`projects.github`, `agents`, `deployments`), with one `OpenComputerError`
- of `{ code, status, message }`. Its module graph has no Node dependency and
- runs nothing at import, so it loads in Cloudflare Workers without Node
- compatibility.
+ of `{ code, status, message }`, plus `retryAfter` from a `429` and
+ `sessionId` when the API tied the failure to a session
+ (`session_publication_unconfirmed`). The client retries nothing and follows
+ no redirect. Its module graph has no Node dependency and runs nothing at
+ import, so it loads in Cloudflare Workers without Node compatibility.
- `startSessionOnDocument`, the memory types and the event subscription types
move to that subpath; `oc.sessions.startOnDocument` is the same call on the
client. Its `NotFoundError` and `ConflictError` become `OpenComputerError`
diff --git a/sdks/typescript/src/agents/client.test.ts b/sdks/typescript/src/agents/client.test.ts
index c6fbd24f..7b048ad4 100644
--- a/sdks/typescript/src/agents/client.test.ts
+++ b/sdks/typescript/src/agents/client.test.ts
@@ -290,6 +290,44 @@ describe("OpenComputer client", () => {
expect((await client.sessions.turns.send("ses_1", { input: "again" })).status).toBe("stopping");
});
+ // Create and setLabels answer 503 session_publication_unconfirmed when the
+ // session, or its label change, is recorded but its list row is not yet
+ // confirmed. The client throws it with the session id and does not retry:
+ // the caller repeats the same call under the same key, and the replay is
+ // what publishes again.
+ it("surfaces session_publication_unconfirmed with the session id and leaves the retry to the caller", async () => {
+ let creates = 0;
+ const unconfirmed = () =>
+ Response.json(
+ { error: { code: "session_publication_unconfirmed", message: "not listed yet; retry", sessionId: "ses_1" } },
+ { status: 503 },
+ );
+ const api = fakeApi({
+ "POST /api/managed-agents/sessions": () =>
+ ++creates === 1 ? unconfirmed() : Response.json({ session: { id: "ses_1", status: "new", createdAt: "t" } }, { status: 200 }),
+ "PATCH /api/managed-agents/sessions/ses_1/labels": unconfirmed,
+ });
+ const client = oc(api);
+ const first = await client.sessions.create({ agentId: "worker@development" }, { idempotencyKey: "task_1" }).catch((cause: unknown) => cause);
+ expect(first).toBeInstanceOf(OpenComputerError);
+ expect(first).toMatchObject({ code: "session_publication_unconfirmed", status: 503, sessionId: "ses_1", message: "not listed yet; retry" });
+ expect(api.calls).toHaveLength(1);
+ // The caller's retry, same key and body: the replay answers 200, not created.
+ const retry = await client.sessions.create({ agentId: "worker@development" }, { idempotencyKey: "task_1" });
+ expect(retry).toMatchObject({ session: { id: "ses_1" }, created: false });
+ expect(api.calls).toHaveLength(2);
+ expect(api.calls[1].headers["idempotency-key"]).toBe("task_1");
+ expect(api.calls[1].body).toEqual(api.calls[0].body);
+ const patch = await client.sessions.setLabels("ses_1", { set: { outcome: "merged" } }).catch((cause: unknown) => cause);
+ expect(patch).toBeInstanceOf(OpenComputerError);
+ expect(patch).toMatchObject({ code: "session_publication_unconfirmed", status: 503, sessionId: "ses_1" });
+ expect(api.calls).toHaveLength(3);
+ // Errors the API does not tie to a session carry no sessionId.
+ const untied = (await client.sessions.get("missing").catch((cause: unknown) => cause)) as OpenComputerError;
+ expect(untied.code).toBe("not_found");
+ expect(untied.sessionId).toBeUndefined();
+ });
+
it("honours a custom base URL and requires a key", () => {
const api = fakeApi();
const client = new OpenComputer({ apiKey: "k", baseUrl: "https://edge.example.test/mgmt/", fetch: api.fetch });
diff --git a/sdks/typescript/src/agents/client.ts b/sdks/typescript/src/agents/client.ts
index f1f47cc6..8b0e365d 100644
--- a/sdks/typescript/src/agents/client.ts
+++ b/sdks/typescript/src/agents/client.ts
@@ -176,7 +176,7 @@ export class Sessions {
});
}
- /** `PATCH /sessions/<id>/labels`: per-key last-write-wins (per design 1c07584, backend in flight). */
+ /** `PATCH /sessions/<id>/labels`: per-key last-write-wins. */
setLabels(sessionId: string, params: SetLabelsParams, options: CallOptions = {}): Promise<Session> {
return this.http.request("PATCH", `/sessions/${segment(sessionId)}/labels`, shapes.session, {
body: params,
diff --git a/sdks/typescript/src/agents/errors.ts b/sdks/typescript/src/agents/errors.ts
index 3e899308..6d58118c 100644
--- a/sdks/typescript/src/agents/errors.ts
+++ b/sdks/typescript/src/agents/errors.ts
@@ -5,9 +5,21 @@
// the status when the body carried none, so a caller always has one string to
// branch on.
-/** The wire envelope: `{ error: { code, message } }` or `{ error: "<text>" }`. */
+/**
+ * The wire envelope: `{ error: { code, message } }` or `{ error: "<text>" }`.
+ * An error the API ties to a session names it beside the code
+ * (`session_publication_unconfirmed` carries `sessionId`).
+ */
export interface ApiErrorEnvelope {
- error?: { code?: string; message?: string } | string;
+ error?: { code?: string; message?: string; sessionId?: string } | string;
+}
+
+/** What an error carries beside its status, code and message. */
+export interface OpenComputerErrorDetails {
+ /** Seconds to wait before retrying, from `Retry-After`, when the API sent one. */
+ retryAfter?: number;
+ /** The session the failure concerns, when the API named one. */
+ sessionId?: string;
}
const CODE_BY_STATUS: Record<number, string> = {
@@ -27,13 +39,26 @@ export class OpenComputerError extends Error {
readonly status: number;
/** Seconds to wait before retrying, from `Retry-After`, when the API sent one. */
readonly retryAfter?: number;
+ /**
+ * The session the failure concerns, when the API named one:
+ * `session_publication_unconfirmed` carries the id of the session that
+ * exists, or whose labels are recorded, but is not confirmed in the list
+ * yet. The client does not retry; the caller repeats the same call.
+ */
+ readonly sessionId?: string;
- constructor(status: number, code: string | undefined, message: string | undefined, retryAfter?: number) {
+ constructor(
+ status: number,
+ code: string | undefined,
+ message: string | undefined,
+ details: OpenComputerErrorDetails = {},
+ ) {
super(message || `OpenComputer request failed (${status})`);
this.name = "OpenComputerError";
this.status = status;
this.code = code || CODE_BY_STATUS[status] || (status >= 500 ? "unavailable" : "request_failed");
- if (retryAfter !== undefined) this.retryAfter = retryAfter;
+ if (details.retryAfter !== undefined) this.retryAfter = details.retryAfter;
+ if (details.sessionId !== undefined) this.sessionId = details.sessionId;
}
}
@@ -41,14 +66,12 @@ export class OpenComputerError extends Error {
export function errorFromResponse(status: number, body: unknown, headers?: Headers): OpenComputerError {
const envelope = body && typeof body === "object" ? (body as ApiErrorEnvelope) : undefined;
const error = envelope?.error;
- const code = typeof error === "object" && error ? error.code : undefined;
- const message = typeof error === "string" ? error : typeof error === "object" && error ? error.message : undefined;
+ const fields = typeof error === "object" && error ? error : undefined;
+ const message = typeof error === "string" ? error : fields?.message;
const retryAfterHeader = headers?.get("retry-after");
const retryAfter = retryAfterHeader ? Number(retryAfterHeader) : Number.NaN;
- return new OpenComputerError(
- status,
- code,
- message,
- Number.isFinite(retryAfter) && retryAfter > 0 ? retryAfter : undefined,
- );
+ const details: OpenComputerErrorDetails = {};
+ if (Number.isFinite(retryAfter) && retryAfter > 0) details.retryAfter = retryAfter;
+ if (typeof fields?.sessionId === "string" && fields.sessionId) details.sessionId = fields.sessionId;
+ return new OpenComputerError(status, fields?.code, message, details);
}
diff --git a/sdks/typescript/src/agents/index.ts b/sdks/typescript/src/agents/index.ts
index 329b51ec..4de8a5c3 100644
--- a/sdks/typescript/src/agents/index.ts
+++ b/sdks/typescript/src/agents/index.ts
@@ -29,7 +29,7 @@ export {
type StartSessionOnDocumentResult,
} from "./client.js";
export { sessionIdempotencyKey, type StartOnDocumentParams, type StartOnDocumentResult } from "./start-on-document.js";
-export { OpenComputerError, type ApiErrorEnvelope } from "./errors.js";
+export { OpenComputerError, type ApiErrorEnvelope, type OpenComputerErrorDetails } from "./errors.js";
export { DEFAULT_BASE_URL, type HttpOptions } from "./http.js";
export type * from "./types.js";
export type {
diff --git a/sdks/typescript/src/agents/types.ts b/sdks/typescript/src/agents/types.ts
index 89e00ca6..b76743ef 100644
--- a/sdks/typescript/src/agents/types.ts
+++ b/sdks/typescript/src/agents/types.ts
@@ -1,12 +1,9 @@
// The shapes of the management API (docs/agents/api.mdx) and of the session
// event log (docs/agents/events.mdx), as the client sends and returns them.
-// Field names are the API's own; nothing is renamed at the boundary.
-//
-// Fields marked "per design 1c07584, backend in flight" belong to routes and
-// objects the API is gaining (session labels, filtered listing, the typed
-// result, turn payloads, repository listing). They are typed here so an
-// application compiles against the final shape; until the backend lands, the
-// API leaves them absent and the routes answer 404 or 400.
+// Field names are the API's own; nothing is renamed at the boundary. Fields
+// the docs list as present on every response are typed optional where an
+// older session or row may still lack them; the transport (shapes.ts) passes
+// what the API sends and never fills a field in.
import type { MemoryBindings, SessionMemoryBinding } from "./memory.js";
import type { TurnOutcomeDelivery } from "./event-subscriptions.js";
@@ -24,8 +21,7 @@ export type DataValue = string | number | boolean | null | DataValue[] | { [key:
/**
* Where a session is in its life. `stopping` is the state between an
- * interrupt and the settlement of the stopped turn's work (per design
- * 1c07584, backend in flight).
+ * interrupt and the settlement of the stopped turn's work.
*/
export type SessionStatus =
| "new"
@@ -54,7 +50,7 @@ export interface Turn {
input: string;
mode: TurnMode;
status: TurnStatus;
- /** The structured input sent with the turn (per design 1c07584, backend in flight). */
+ /** The structured input sent with the turn. */
payload?: DataValue;
/** Present when an event subscription selected the turn's outcome. */
deliveries?: TurnOutcomeDelivery[];
@@ -64,7 +60,7 @@ export interface Turn {
/**
* The latest committed output of the agent's result tool, with its
- * provenance (per design 1c07584, backend in flight).
+ * provenance.
*/
export interface SessionResult {
/** The turn whose tool call reported it. */
@@ -94,13 +90,13 @@ export interface Session {
memory?: SessionMemoryBinding[];
/** Every turn, oldest first. */
turns: Turn[];
- /** Per design 1c07584, backend in flight. */
+ /** Your metadata on the session; equality filters on the list. */
labels?: SessionLabels;
- /** Per design 1c07584, backend in flight. */
+ /** When the labels last changed. */
labelsUpdatedAt?: string;
- /** Monotonic; every listed mutation increments it (per design 1c07584, backend in flight). */
+ /** Monotonic; every listed mutation increments it. */
revision?: number;
- /** Per design 1c07584, backend in flight. */
+ /** The latest committed output of the result tool, or `null` when none was committed. */
result?: SessionResult | null;
createdAt: string;
updatedAt: string;
@@ -127,7 +123,7 @@ export interface CreateSessionParams {
/** Bindings keyed by resource id, at most eight. */
memory?: MemoryBindings;
source?: SessionSource;
- /** Applied at creation and ignored on an idempotent replay (per design 1c07584, backend in flight). */
+ /** Applied at creation and ignored on an idempotent replay. */
labels?: SessionLabels;
}
@@ -155,11 +151,11 @@ export interface SendTurnParams {
idempotencyKey?: string;
/** `queue` (default), `steer` or `interrupt`. */
mode?: TurnMode;
- /** Structured input the agent reads as `useInput().payload`; at most 32 KB of JSON (per design 1c07584, backend in flight). */
+ /** Structured input the agent reads as `useInput().payload`; at most 32 KB of JSON. */
payload?: DataValue;
}
-/** What a session's activity looks like from a list row (per design 1c07584, backend in flight). */
+/** What a session's activity looks like from a list row. */
export interface SessionActivity {
activeTurnId: string | null;
/** Turns admitted and not yet started. */
@@ -169,8 +165,7 @@ export interface SessionActivity {
/**
* A row of `GET /sessions`. Rows carry no `turns` and no `memory`;
- * `GET /sessions/<id>` has those. `activity`, `revision`, `result` and
- * `labels` are per design 1c07584, backend in flight.
+ * `GET /sessions/<id>` has those.
*/
export interface SessionSummary {
id: string;
@@ -189,11 +184,7 @@ export interface SessionSummary {
result?: SessionResult | null;
}
-/**
- * Filters and paging for `GET /sessions` (per design 1c07584, backend in
- * flight; the API without them returns the fifty most recently updated
- * sessions and ignores nothing, so pass none until they land).
- */
+/** Filters and paging for `GET /sessions`; any other parameter is `400 invalid_query`. */
export interface ListSessionsQuery {
project?: string;
environment?: Environment;
@@ -212,7 +203,7 @@ export interface SessionPage {
nextCursor: string | null;
}
-/** Body of `PATCH /sessions/<id>/labels` (per design 1c07584, backend in flight). */
+/** Body of `PATCH /sessions/<id>/labels`. */
export interface SetLabelsParams {
set?: SessionLabels;
unset?: string[];
@@ -274,7 +265,7 @@ export type SessionEvent =
data: {
reason: "interrupted" | (string & {});
replacementTurnId?: string;
- /** How long after the interrupt the turn settled, once the commands it had started were stopped (per design 1c07584, backend in flight). */
+ /** How long after the interrupt the turn settled, once the commands it had started were stopped. */
settledAfterMs?: number;
/** How many commands were stopped for the turn to settle. */
operationsSettled?: number;
@@ -295,11 +286,21 @@ export type SessionEvent =
callId?: string;
title?: string;
output?: DataValue;
- /** `true` on the call that committed the session's result (per design 1c07584, backend in flight). */
+ /** `true` on the call that committed the session's result. */
result?: boolean;
};
})
- | (EventBase & { type: "tool.failed"; data: { tool: string; callId?: string; title?: string; message?: string } })
+ | (EventBase & {
+ type: "tool.failed";
+ data: {
+ tool: string;
+ callId?: string;
+ title?: string;
+ message?: string;
+ /** Present when the turn's end settled a call that never completed: the terminal event that did it. */
+ settledBy?: "turn.completed" | "turn.failed" | "turn.cancelled";
+ };
+ })
| (EventBase & { type: "memory.saved"; data: { resource: string; documentId: string; revision: string; bytes: number } })
| (EventBase & {
type: "model.route_resolved";