An open-source, faster Devin alternative
TypeScript
api-edge, sdk, react: held receipts reach callers intact
Igor Zalutskic7f064854ba5
diff --git a/cloudflare-workers/api-edge/src/managed_agents.test.ts b/cloudflare-workers/api-edge/src/managed_agents.test.tsindex a66de293..e1cccb67 100644--- a/cloudflare-workers/api-edge/src/managed_agents.test.ts+++ b/cloudflare-workers/api-edge/src/managed_agents.test.ts@@ -4175,6 +4175,37 @@ describe("managed agents proxy", () => {});});+ it("passes a held receipt through with its question and no turn", async () => {+ vi.stubGlobal(+ "fetch",+ vi.fn(async () =>+ Response.json(+ { status: "held", questionId: question.id, duplicate: false, accountId: "acct_private" },+ { status: 202 },+ ),+ ),+ );+ const response = await proxyManagedAgents(+ new Request(+ "https://app.opencomputer.dev/api/managed-agents/sessions/session-1/turns",+ {+ method: "POST",+ headers: { "content-type": "application/json" },+ body: JSON.stringify({ input: "Keep the old endpoint" }),+ },+ ),+ env,+ caller,+ "/api/managed-agents",+ );+ expect(response.status).toBe(202);+ expect(await response.json()).toEqual({+ status: "held",+ questionId: question.id,+ duplicate: false,+ });+ });+it("passes the open question and a turn's outcome through the session snapshot", async () => {vi.stubGlobal("fetch",diff --git a/cloudflare-workers/api-edge/src/managed_agents.ts b/cloudflare-workers/api-edge/src/managed_agents.tsindex 43f8e609..f359395f 100644--- a/cloudflare-workers/api-edge/src/managed_agents.ts+++ b/cloudflare-workers/api-edge/src/managed_agents.ts@@ -2109,10 +2109,13 @@ function publicSuccessBody(};}if (method === "POST" && /\/turns$/.test(suffix)) {+ // An input held behind an open question has no turn yet: its receipt+ // names the question instead (status "held", or "discarded" after a stop).return {- turnId: body.turnId,+ ...(typeof body.turnId === "string" ? { turnId: body.turnId } : {}),status: body.status,duplicate: body.duplicate,+ ...(typeof body.questionId === "string" ? { questionId: body.questionId } : {}),};}if (method === "GET" && suffix === "/billing/sessions") {diff --git a/docs/agents/react.mdx b/docs/agents/react.mdxindex 7a22c0d1..daa4a41d 100644--- a/docs/agents/react.mdx+++ b/docs/agents/react.mdx@@ -271,6 +271,10 @@ log records `question.answered` or `question.closed` for it. Answering aquestion that is no longer open rejects with a `SendError` whose code is`question_stale`; the hook's `question` shows the current one.+While a question is open, `send` without `answers` resolves with a held+receipt, `{ status: "held", questionId }` and no `turnId`: the message stays+in `messages` and reaches the agent with the answer.+## Stop and reopen`stop()` requests an interrupt without spending a model turn. It resolvesdiff --git a/docs/reference/typescript-sdk/agents.mdx b/docs/reference/typescript-sdk/agents.mdxindex b47bb29c..d1287d94 100644--- a/docs/reference/typescript-sdk/agents.mdx+++ b/docs/reference/typescript-sdk/agents.mdx@@ -128,7 +128,10 @@ the key as the `Idempotency-Key` header. The receipt carries the turn'spersisted `status`: `queued` or `running` for a new turn, and for a repeatedkey the existing turn's status, `completed`, `failed` or `cancelled` once ithas settled, with `duplicate: true`. The client maps nothing, so a retry-after a lost reply learns what became of the turn. `list` takes the exact+after a lost reply learns what became of the turn. An input sent while a+question is open, without `answers`, runs no turn: its receipt is+`{ status: "held", questionId, duplicate }` with no `turnId` (`"discarded"`+once a stop ended the question). `list` takes the exactfilters of [`GET /sessions`](/agents/api#get-and-list): `project` or`projectId`, `environment`, `agent` or `agentId`, `status`, `deploymentId`,`externalReference`, `createdAfter`, `createdBefore`, `updatedAfter`,diff --git a/react/src/index.ts b/react/src/index.tsindex 2df12b36..ea044bb8 100644--- a/react/src/index.ts+++ b/react/src/index.ts@@ -80,10 +80,17 @@ export interface AttachAgentOptions extends CommonOptions {export type UseAgentOptions = CreateAgentOptions | AttachAgentOptions;-/** What `send` resolves with: the platform admitted the input as a turn. */+/**+ * What `send` resolves with: the platform admitted the input as a turn, or,+ * while the agent's question is open, held it (`status: "held"`, no `turnId`,+ * `questionId` set) to reach the agent with the answer.+ */export interface SendReceipt {sessionId: string;- turnId: string;+ /** Absent when the input was held behind an open question. */+ turnId?: string;+ /** Set when the input was held: the question it waits on. */+ questionId?: string;/*** 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@@ -212,18 +219,26 @@ function asSendError(cause: unknown): SendError {}/** 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;+function turnAdmission(+ body: unknown,+): { turnId?: string; questionId?: string; status: TurnStatus; duplicate: boolean } {+ const reply = body as { turnId?: unknown; questionId?: unknown; status?: unknown; duplicate?: unknown } | null;+ if (!reply || typeof reply.status !== "string" || !reply.status) {+ throw new SendError("The admission reply was not a turn receipt.", "invalid_response");+ }+ const duplicate = reply.duplicate === true;+ if (typeof reply.turnId === "string" && reply.turnId) {+ return { turnId: reply.turnId, status: reply.status as TurnStatus, duplicate };+ }+ // Held behind the open question: no turn, the question instead.if (- !reply ||- typeof reply.turnId !== "string" ||- !reply.turnId ||- typeof reply.status !== "string" ||- !reply.status+ (reply.status === "held" || reply.status === "discarded") &&+ typeof reply.questionId === "string" &&+ reply.questionId) {- throw new SendError("The admission reply was not a turn receipt.", "invalid_response");+ return { questionId: reply.questionId, status: reply.status as TurnStatus, duplicate };}- return { turnId: reply.turnId, status: reply.status as TurnStatus, duplicate: reply.duplicate === true };+ throw new SendError("The admission reply was not a turn receipt.", "invalid_response");}export function useAgent(@@ -421,7 +436,23 @@ export function useAgent(setError(undefined);try {const receipt = await admitTurn(activeSession, prompt, sendOptions);- if (current()) {+ if (current() && receipt.turnId === undefined) {+ // Held behind the open question: no turn will echo it back, so the+ // message stays in the conversation as sent. It reaches the agent+ // with the answer.+ const timeline = timelineRef.current;+ commit({+ ...timeline,+ messages: upsert(timeline.messages, {+ id: `held:${receipt.questionId}:${timeline.messages.length}`,+ role: "user",+ text: prompt,+ }),+ });+ return receipt;+ }+ if (current() && receipt.turnId !== undefined) {+ const turnId = receipt.turnId;// The log's message.received for this turn carries the same id,// so it confirms this message instead of duplicating it. Whether// the turn is still running is the log's call, not this reply's.@@ -429,22 +460,22 @@ export function useAgent(commit({...timeline,messages: upsert(timeline.messages, {- id: inputMessageId(receipt.turnId),+ id: inputMessageId(turnId),role: "user",text: prompt,- turnId: receipt.turnId,+ 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)+ !isSettledTurn(timelineRef.current, turnId)) {setAdmitted((pending) =>- pending.includes(receipt.turnId)+ pending.includes(turnId)? pending- : [...pending, receipt.turnId],+ : [...pending, turnId],);}}@@ -564,6 +595,10 @@ export function useAgent(// The placeholders belong to the admitted turn from here on, so the// turn's messages are its own.const { turnId } = receipt;+ if (!turnId) {+ // A new session has no question, so nothing can be held.+ throw new SendError("The admission reply was not a turn receipt.", "invalid_response");+ }updateMessages((messages) =>messages.map((message) =>message.id === userMessage.id || message.id === assistantIddiff --git a/react/src/use-agent.test.ts b/react/src/use-agent.test.tsindex 64da0f96..a30e6d37 100644--- a/react/src/use-agent.test.ts+++ b/react/src/use-agent.test.ts@@ -758,3 +758,29 @@ test("attach exposes turns with their tool activity and result, the same after aawait again.unmount();await view.unmount();});++test("attach keeps a message held behind an open question in the conversation", async (t) => {+ const fetch: typeof globalThis.fetch = async (input, init) => {+ const url = new URL(String(input), "http://app.test");+ if ((init?.method ?? "GET") === "GET" && url.pathname.endsWith("/events")) {+ return Response.json({ events: [] });+ }+ if (init?.method === "POST" && url.pathname.endsWith("/turns")) {+ return Response.json({ status: "held", questionId: "q-1", duplicate: false }, { status: 202 });+ }+ return Response.json({}, { status: 404 });+ };+ const view = mount(t, { sessionId: "ses-held", basePath: "/app/agent", fetch, pollIntervalMs: 5 });+ await view.render();+ await view.until((result) => !result.isReplaying, "empty history");++ let receipt: SendReceipt | undefined;+ await act(async () => {+ receipt = await view.result().send("Keep the old endpoint");+ });+ assert.deepEqual(receipt, { sessionId: "ses-held", questionId: "q-1", status: "held", duplicate: false });+ const held = view.result();+ assert.equal(held.isRunning, false);+ assert.deepEqual(held.messages, [{ id: "held:q-1:0", role: "user", text: "Keep the old endpoint" }]);+ await view.unmount();+});diff --git a/sdks/typescript/src/agents/client.test.ts b/sdks/typescript/src/agents/client.test.tsindex 7b387d29..fcb28217 100644--- a/sdks/typescript/src/agents/client.test.ts+++ b/sdks/typescript/src/agents/client.test.ts@@ -216,6 +216,21 @@ describe("OpenComputer client", () => {expect(api.last().body).toEqual({ input: "go", answers: "q_1" });});+ it("returns a held receipt, without a turn, for input sent while a question is open", async () => {+ let body: Record<string, unknown> = { status: "held", questionId: "q_1", duplicate: false };+ const api = fakeApi({+ "POST /api/managed-agents/sessions/ses_1/turns": () => Response.json(body, { status: 202 }),+ });+ const client = oc(api);+ expect(await client.sessions.turns.send("ses_1", { input: "Keep the old endpoint." })).toEqual({+ status: "held",+ questionId: "q_1",+ duplicate: false,+ });+ body = { status: "held", duplicate: false };+ await expect(client.sessions.turns.send("ses_1", { input: "again" })).rejects.toThrow();+ });+it("reads the event log from a cursor", async () => {const events = [{ id: "e1", seq: 1, timestamp: "t", sessionId: "ses_1", type: "session.created", data: { agentId: "worker", deploymentId: "dep_1" } }];const api = fakeApi({ "GET /api/managed-agents/sessions/ses_1/events": () => Response.json({ events }) });diff --git a/sdks/typescript/src/agents/client.ts b/sdks/typescript/src/agents/client.tsindex 050fec11..93e3888d 100644--- a/sdks/typescript/src/agents/client.ts+++ b/sdks/typescript/src/agents/client.ts@@ -107,10 +107,15 @@ export class Turns {// 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.+ const duplicate = answer.body.duplicate ?? answer.status === 200;+ if (answer.body.turnId !== undefined) {+ return { turnId: answer.body.turnId, status: answer.body.status, duplicate };+ }+ // Held behind the open question: no turn, the question instead (the shape checked it).return {- turnId: answer.body.turnId,- status: answer.body.status,- duplicate: answer.body.duplicate ?? answer.status === 200,+ status: answer.body.status as "held" | "discarded",+ questionId: answer.body.questionId as string,+ duplicate,};}}diff --git a/sdks/typescript/src/agents/shapes.ts b/sdks/typescript/src/agents/shapes.tsindex 90976416..4644d4a5 100644--- a/sdks/typescript/src/agents/shapes.ts+++ b/sdks/typescript/src/agents/shapes.ts@@ -314,12 +314,23 @@ export const sessionPage: Shape<SessionPage> = (value, path) => {return { sessions: page.sessions, nextCursor: page.nextCursor ?? null };};-export const turnReceipt = object({- turnId: string,+const turnReceiptFields = object({+ turnId: optional(string),status: nonEmptyString,duplicate: optional(boolean),+ questionId: optional(string),});+/** A turn, or an input held behind an open question (`held` / `discarded` with `questionId`, no turn). */+export const turnReceipt: Shape<ReturnType<typeof turnReceiptFields>> = (value, path) => {+ const receipt = turnReceiptFields(value, path);+ const held = (receipt.status === "held" || receipt.status === "discarded") && !!receipt.questionId;+ if (receipt.turnId === undefined && !held) {+ throw new ShapeError(at(path, "turnId"), "a string, or a held receipt with questionId");+ }+ return receipt;+};+/*** One log entry. `seq`, `type` and `data` are what a reader keys on and are* required; the identity fields are checked when present.diff --git a/sdks/typescript/src/agents/types.ts b/sdks/typescript/src/agents/types.tsindex ca407940..7493edb7 100644--- a/sdks/typescript/src/agents/types.ts+++ b/sdks/typescript/src/agents/types.ts@@ -178,8 +178,27 @@ export interface CreateSessionParams {externalReference?: string;}-/** Turn admission, as `POST /sessions/<id>/turns` answers it. */-export interface TurnReceipt {+/**+ * Turn admission, as `POST /sessions/<id>/turns` answers it: a turn, or an+ * input held behind the session's open question.+ */+export type TurnReceipt = AdmittedTurnReceipt | HeldTurnReceipt;++/**+ * An input sent while a question was open, without `answers`. It runs no turn+ * of its own: it reaches the agent with the answer, as `steering`. `discarded`+ * when a stop ended the question first.+ */+export interface HeldTurnReceipt {+ status: "held" | "discarded";+ /** The question the input is waiting on. */+ questionId: string;+ /** `true` when the `idempotencyKey` had already been received. */+ duplicate: boolean;+ turnId?: undefined;+}++export interface AdmittedTurnReceipt {turnId: string;/*** The turn's persisted status: `queued` behind earlier turns or `running`