An open-source, faster Devin alternative
TypeScript
Receipts keep the persisted turn status; nothing maps to queued
Igor Zalutski9d85f66a7147
diff --git a/docs/agents/api.mdx b/docs/agents/api.mdxindex 6f3b2079..e7ad9b92 100644--- a/docs/agents/api.mdx+++ b/docs/agents/api.mdx@@ -221,8 +221,10 @@ curl -X POST 'https://app.opencomputer.dev/api/managed-agents/sessions/<session-The response is `202 { turnId, status, duplicate }` for a new turn and`200` with `duplicate: true` when the key had already created one. `status`-is `queued` or `running`. Follow the turn in the event log; the response-does not wait for it.+is the turn's status: `queued` or `running` for a new turn, and for a+repeated key whatever the existing turn has reached, `completed`, `failed`+or `cancelled` once it has settled. Follow the turn in the event log; the+response does not wait for it.The key identifies the request, not only the call. A repeat with the same`input`, `payload` and `mode` is the existing turn: key order inside thediff --git a/docs/agents/react.mdx b/docs/agents/react.mdxindex a08924ad..a64cbf5e 100644--- a/docs/agents/react.mdx+++ b/docs/agents/react.mdx@@ -165,10 +165,14 @@ interrupts the running turn without spending a model turn.Two composers that each generate their own keys produce two turns; onecomposer retrying with the key it kept produces one.-`send` resolves once the platform has admitted the input as a turn,-with a receipt `{ sessionId, turnId, status }` where `status` is `queued`-or `running`. The input appears in `messages` at that point; the log's own-record of it confirms that message rather than adding a second one.+`send` resolves once the platform has admitted the input as a turn, with a+receipt `{ sessionId, turnId, status, duplicate }`. `status` is the turn's+persisted status: `queued` or `running` for a new turn, and for a retried+key the existing turn's status, `completed`, `failed` or `cancelled` once it+has settled, with `duplicate` true. Nothing is mapped, so a retry after a+lost reply learns what became of the turn, and a settled duplicate never+sets `isRunning`. The input appears in `messages` at that point; the log's+own record of it confirms that message rather than adding a second one.`isRunning` is true from admission until the log settles the turn, and areply that arrives after the log has already shown the turn completedchanges nothing.@@ -182,6 +186,7 @@ can keep the draft:| `network_error` | The request was not answered | none || `empty_input` | The text was blank; nothing was sent | none || `busy` | Create mode only: a turn is already running | none |+| `invalid_response` | The admission reply was not a turn receipt | none |The hook's `error` is set to the same message either way. A turn that failsafter admission is not a rejection: the receipt was returned, the failure@@ -292,7 +297,7 @@ the web application. Credentials are not bundled into browser code.| --- | --- || `messages` | User and assistant messages, in log order || `turns` | The session's turns with status, input, messages, tool calls, result and failure, in log order |-| `send(text, options?)` | Starts a turn; resolves with `{ sessionId, turnId, status }` or rejects with a `SendError`. `options` carries `idempotencyKey` and `payload`. In create mode the first call creates the session |+| `send(text, options?)` | Starts a turn; resolves with `{ sessionId, turnId, status, duplicate }` or rejects with a `SendError`. `options` carries `idempotencyKey` and `payload`. In create mode the first call creates the session || `stop()` | Interrupts the running turn || `sessionId` | The attached session, or the created one after the first send || `isRunning` | A turn is admitted and not yet settled by the log |diff --git a/docs/reference/typescript-sdk/managed-agents.mdx b/docs/reference/typescript-sdk/managed-agents.mdxindex 7ccf5bba..96603c53 100644--- a/docs/reference/typescript-sdk/managed-agents.mdx+++ b/docs/reference/typescript-sdk/managed-agents.mdx@@ -103,7 +103,11 @@ validate.`create` takes `agentId`, `deploymentId`, `environment`, `memory`, `source`and `labels` as [documented](/agents/api#create). `turns.send` takes `input`,-`idempotencyKey`, `mode` and `payload`. `list` takes `project`,+`idempotencyKey`, `mode` and `payload`. Its receipt carries the turn's+persisted `status`: `queued` or `running` for a new turn, and for a repeated+key the existing turn's status, `completed`, `failed` or `cancelled` once it+has settled, with `duplicate: true`. The client maps nothing, so a retry+after a lost reply learns what became of the turn. `list` takes `project`,`environment`, `agent`, `status`, `labels` (up to three, sent as`label.<key>=<value>`), `cursor` and `limit`.diff --git a/react/src/events.ts b/react/src/events.tsindex fbe138f3..07ec6c91 100644--- a/react/src/events.ts+++ b/react/src/events.ts@@ -129,13 +129,17 @@ export function emptyTimeline(): SessionTimeline {};}+/** Whether a turn status is terminal: completed, failed or cancelled. */+export function isSettledStatus(status: string | undefined): boolean {+ return status === "completed" || status === "failed" || status === "cancelled";+}+/** Whether the log has settled the turn: completed, failed or cancelled. */export function isSettledTurn(timeline: SessionTimeline,turnId: string,): boolean {- const status = timeline.turns[turnId]?.status;- return status === "completed" || status === "failed" || status === "cancelled";+ return isSettledStatus(timeline.turns[turnId]?.status);}/** The turns of a timeline in log order, each with its messages. */diff --git a/react/src/index.ts b/react/src/index.tsindex de9bdcac..d516db67 100644--- a/react/src/index.ts+++ b/react/src/index.ts@@ -5,6 +5,7 @@ import {emptyTimeline,failureMessage,inputMessageId,+ isSettledStatus,isSettledTurn,memorySaveFromEvent,turnsOf,@@ -14,6 +15,7 @@ import {type MemorySave,type SessionTimeline,type Turn,+ type TurnStatus,} from "./events.js";export {@@ -21,6 +23,7 @@ export {applyEvents,applyTurnEvent,emptyTimeline,+ isSettledStatus,isSettledTurn,turnsOf,type AgentEvent,@@ -78,8 +81,15 @@ export type UseAgentOptions = CreateAgentOptions | AttachAgentOptions;export interface SendReceipt {sessionId: string;turnId: string;- /** `queued` behind earlier turns, or `running` at once. */- status: "queued" | "running";+ /**+ * The turn's persisted status: `queued` behind earlier turns or `running`+ * at once for a new turn; for a retried key, whatever the existing turn+ * has reached, `completed`, `failed` or `cancelled` included. Nothing is+ * mapped.+ */+ status: TurnStatus;+ /** `true` when the key had already admitted the turn. */+ duplicate: boolean;}/** The options of one `send`. */@@ -99,8 +109,9 @@ export interface SendOptions {* What `send` rejects with. `code` is the platform's error code when the* request was answered (`session_ended`, `memory_admission_unconfirmed`,* `insufficient_credits`), `network_error` when it was not, `empty_input`- * and `busy` when nothing was sent. `status` is the HTTP status when there- * was one. The hook's `error` is set to the same message.+ * and `busy` when nothing was sent, `invalid_response` when the admission+ * reply was not the documented receipt. `status` is the HTTP status when+ * there was one. The hook's `error` is set to the same message.*/export class SendError extends Error {readonly code: string;@@ -179,9 +190,19 @@ function asSendError(cause: unknown): SendError {);}-interface TurnAdmission {- turnId: string;- status: "queued" | "running";+/** The documented admission reply, checked before it becomes a receipt. */+function turnAdmission(body: unknown): { turnId: string; status: TurnStatus; duplicate: boolean } {+ const reply = body as { turnId?: unknown; status?: unknown; duplicate?: unknown } | null;+ if (+ !reply ||+ typeof reply.turnId !== "string" ||+ !reply.turnId ||+ typeof reply.status !== "string" ||+ !reply.status+ ) {+ throw new SendError("The admission reply was not a turn receipt.", "invalid_response");+ }+ return { turnId: reply.turnId, status: reply.status as TurnStatus, duplicate: reply.duplicate === true };}export function useAgent(@@ -337,24 +358,24 @@ export function useAgent(prompt: string,sendOptions: SendOptions,): Promise<SendReceipt> => {- const admission = await request<TurnAdmission>(- `/sessions/${encodeURIComponent(activeSession)}/turns`,- {- method: "POST",- body: JSON.stringify({- input: prompt,- idempotencyKey: sendOptions.idempotencyKey ?? crypto.randomUUID(),- ...(sendOptions.payload !== undefined- ? { payload: sendOptions.payload }- : {}),- }),- },+ const admission = turnAdmission(+ await request<unknown>(+ `/sessions/${encodeURIComponent(activeSession)}/turns`,+ {+ method: "POST",+ body: JSON.stringify({+ input: prompt,+ idempotencyKey: sendOptions.idempotencyKey ?? crypto.randomUUID(),+ ...(sendOptions.payload !== undefined+ ? { payload: sendOptions.payload }+ : {}),+ }),+ },+ ),);- return {- sessionId: activeSession,- turnId: admission.turnId,- status: admission.status === "running" ? "running" : "queued",- };+ // The receipt is what the platform persisted: a retried key answers+ // with the existing turn, which may have settled since.+ return { sessionId: activeSession, ...admission };},[request],);@@ -390,7 +411,12 @@ export function useAgent(turnId: receipt.turnId,}),});- if (!isSettledTurn(timelineRef.current, receipt.turnId)) {+ // A receipt that already reports a settled turn is not a pending+ // admission, whether or not the log has caught up with it.+ if (+ !isSettledStatus(receipt.status) &&+ !isSettledTurn(timelineRef.current, receipt.turnId)+ ) {setAdmitted((pending) =>pending.includes(receipt.turnId)? pendingdiff --git a/react/src/use-agent.test.ts b/react/src/use-agent.test.tsindex b532f528..3e208b93 100644--- a/react/src/use-agent.test.ts+++ b/react/src/use-agent.test.ts@@ -33,6 +33,7 @@ interface Call {function fakeSession(sessionId: string) {const log: AgentEvent[] = [];const calls: Call[] = [];+ const admitted = new Map<string, string>();let failNext = 0;let turns = 0;// While set, turn admissions are recorded in the log at once but their@@ -65,8 +66,20 @@ function fakeSession(sessionId: string) {});}if (call.method === "POST" && url.pathname === `${prefix}/turns`) {+ // A repeated key returns the existing turn with its persisted status,+ // as the API does: the log's last word on the turn, `duplicate: true`.+ const key = typeof call.body?.idempotencyKey === "string" ? call.body.idempotencyKey : undefined;+ const known = key === undefined ? undefined : admitted.get(key);+ if (known) {+ const last = [...log].reverse().find(+ (event) => event.turnId === known && event.type.startsWith("turn."),+ );+ const status = last ? last.type.slice("turn.".length) : "queued";+ return Response.json({ turnId: known, status, duplicate: true }, { status: 200 });+ }turns += 1;const turnId = `turn-${String(turns)}`;+ if (key !== undefined) admitted.set(key, turnId);append({turnId,type: "message.received",@@ -272,7 +285,7 @@ test("attach sends turns and interrupts through the app's routes without duplicaawait act(async () => {receipt = await view.result().send(" Book the venue ");});- assert.deepEqual(receipt, { sessionId: "ses-3", turnId: "turn-1", status: "queued" });+ assert.deepEqual(receipt, { sessionId: "ses-3", turnId: "turn-1", status: "queued", duplicate: false });const sent = view.result();assert.equal(sent.isRunning, true);assert.deepEqual(sent.messages, [@@ -387,7 +400,7 @@ test("a send admitted by one session never lands in the session attached later",// A's response lands now: A's caller gets A's receipt, B is untouched.release();const receipt = await sent!;- assert.deepEqual(receipt, { sessionId: "ses-a", turnId: "turn-1", status: "queued" });+ assert.deepEqual(receipt, { sessionId: "ses-a", turnId: "turn-1", status: "queued", duplicate: false });await tick();await tick();assert.equal(latest!.sessionId, "ses-b");@@ -570,7 +583,7 @@ test("create mode still creates the session on the first send and streams the reawait act(async () => {receipt = await view.result().send("Hi");});- assert.deepEqual(receipt, { sessionId: "ses-new", turnId: "t1", status: "queued" });+ assert.deepEqual(receipt, { sessionId: "ses-new", turnId: "t1", status: "queued", duplicate: false });const result = view.result();assert.equal(result.sessionId, "ses-new");assert.equal(result.isRunning, false);@@ -623,6 +636,33 @@ test("send carries a caller-retained key and a payload, and generates a key whenawait view.unmount();});+// The review's receipt case: a retry of a turn that has since completed+// reported `queued`, because every status except `running` was mapped to+// it. The receipt keeps what the platform persisted, and a settled duplicate+// never counts as a pending admission.+test("a retried send returns the turn's persisted status, settled ones included, and does not reopen it", async (t) => {+ const session = fakeSession("ses-receipts");+ const view = mount(t, { sessionId: "ses-receipts", basePath: "/app/agent", fetch: session.fetch, pollIntervalMs: 5 });+ await view.render();+ await view.until((result) => !result.isReplaying, "replay");+ let first: SendReceipt | undefined;+ await act(async () => {+ first = await view.result().send("Fix the login page", { idempotencyKey: "task-1/start" });+ });+ assert.deepEqual(first, { sessionId: "ses-receipts", turnId: "turn-1", status: "queued", duplicate: false });+ session.append({ turnId: "turn-1", type: "message.completed", data: { text: "Done." } });+ session.append({ turnId: "turn-1", type: "turn.completed", data: {} });+ await view.until((result) => !result.isRunning, "turn settled");+ let again: SendReceipt | undefined;+ await act(async () => {+ again = await view.result().send("Fix the login page", { idempotencyKey: "task-1/start" });+ });+ assert.deepEqual(again, { sessionId: "ses-receipts", turnId: "turn-1", status: "completed", duplicate: true });+ assert.equal(view.result().isRunning, false);+ assert.equal(view.result().turns.length, 1);+ await view.unmount();+});+test("attach exposes turns with their tool activity and result, the same after a replay", async (t) => {const session = fakeSession("ses-turns");session.append({ turnId: "t0", type: "message.received", data: { input: "Clone and report" } });diff --git a/sdks/typescript/src/managed-agents/client.test.ts b/sdks/typescript/src/managed-agents/client.test.tsindex d7320a43..6994d66a 100644--- a/sdks/typescript/src/managed-agents/client.test.ts+++ b/sdks/typescript/src/managed-agents/client.test.ts@@ -268,12 +268,24 @@ describe("OpenComputer client", () => {expect(await client.sessions.get("extra")).toEqual({ ...session, nextThing: { added: true } });});- it("accepts every persisted turn status on an admission receipt", async () => {+ // The API answers a repeated key with the turn's persisted status. A+ // retry of a turn that has since completed, failed or been cancelled must+ // say so; a receipt that read "queued" for a completed turn was the+ // review's reproduction.+ it("keeps the persisted status on a duplicate admission receipt: completed, failed and cancelled included", async () => {+ let status = "completed";const api = fakeApi({- "POST /api/managed-agents/sessions/ses_1/turns": () => Response.json({ turnId: "turn_1", status: "completed", duplicate: true }),+ "POST /api/managed-agents/sessions/ses_1/turns": () => Response.json({ turnId: "turn_1", status, duplicate: true }),});- const receipt = await oc(api).sessions.turns.send("ses_1", { input: "again", idempotencyKey: "task_1/start" });- expect(receipt).toMatchObject({ turnId: "turn_1", duplicate: true });+ const client = oc(api);+ for (status of ["completed", "failed", "cancelled", "running", "queued"]) {+ expect(await client.sessions.turns.send("ses_1", { input: "again", idempotencyKey: "task_1/start" })).toEqual({+ turnId: "turn_1", status, duplicate: true,+ });+ }+ // A status the API adds later reaches the caller as itself.+ status = "stopping";+ expect((await client.sessions.turns.send("ses_1", { input: "again" })).status).toBe("stopping");});it("honours a custom base URL and requires a key", () => {diff --git a/sdks/typescript/src/managed-agents/client.ts b/sdks/typescript/src/managed-agents/client.tsindex 1a16b67a..d4736b63 100644--- a/sdks/typescript/src/managed-agents/client.ts+++ b/sdks/typescript/src/managed-agents/client.ts@@ -96,9 +96,12 @@ export class Turns {body,signal: options.signal,});+ // The receipt says what the platform persisted. A repeated key answers+ // with the existing turn, which may have settled since; mapping that to+ // "queued" told a retrying caller its finished work was waiting.return {turnId: answer.body.turnId,- status: answer.body.status === "running" ? "running" : "queued",+ status: answer.body.status,duplicate: answer.body.duplicate ?? answer.status === 200,};}diff --git a/sdks/typescript/src/managed-agents/types.ts b/sdks/typescript/src/managed-agents/types.tsindex 18e1e682..55415405 100644--- a/sdks/typescript/src/managed-agents/types.ts+++ b/sdks/typescript/src/managed-agents/types.ts@@ -134,8 +134,13 @@ export interface CreateSessionParams {/** Turn admission, as `POST /sessions/<id>/turns` answers it. */export interface TurnReceipt {turnId: string;- /** `queued` behind earlier turns, or `running` at once. */- status: "queued" | "running";+ /**+ * The turn's persisted status: `queued` behind earlier turns or `running`+ * at once for a new turn; for a repeated key, whatever the existing turn+ * has reached, `completed`, `failed` or `cancelled` included. Nothing is+ * mapped, so a status the API adds reaches the caller as itself.+ */+ status: TurnStatus;/** `true` when the `idempotencyKey` had already created the turn. */duplicate: boolean;}