Skip to content

An open-source, faster Devin alternative

TypeScript

docs+dashboard: structured turn payload and request-keyed idempotency

Igor Zalutski6a9bb008f8e8
diff --git a/cloudflare-workers/api-edge/src/managed_agents.test.ts b/cloudflare-workers/api-edge/src/managed_agents.test.ts
index 762e4092..9920ce70 100644
--- a/cloudflare-workers/api-edge/src/managed_agents.test.ts
+++ b/cloudflare-workers/api-edge/src/managed_agents.test.ts
@@ -1858,6 +1858,167 @@ describe("managed agents proxy", () => {
});
});
+ it("forwards a turn payload unchanged and passes admission conflicts through", async () => {
+ const payload = {
+ taskId: "01J9Z6QX4M5N7P8R9S0T1V2W3X",
+ repo: "acme/widgets",
+ ref: "main",
+ actor: { login: "octocat", id: 583231 },
+ note: " keep this spacing ",
+ empty: null,
+ };
+ const body = {
+ input: "Fix the flaky test.",
+ idempotencyKey: "01J9Z6QX4M5N7P8R9S0T1V2W3X/start",
+ payload,
+ };
+ const fetchSpy = vi.fn(async () =>
+ Response.json(
+ { turnId: "turn-3", status: "queued", duplicate: false },
+ { status: 202 },
+ ),
+ );
+ vi.stubGlobal("fetch", fetchSpy);
+
+ 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(body),
+ },
+ ),
+ {
+ OC_MANAGED_AGENTS_SECRET: "test-secret",
+ MANAGED_AGENTS_API_URL: "https://managedagents.test",
+ },
+ { orgID: "org_test", userID: "user_test" },
+ "/api/managed-agents",
+ );
+
+ expect(response.status).toBe(202);
+ const [, init] = fetchSpy.mock.calls[0] as unknown as [URL, RequestInit];
+ // Byte for byte: the backend fingerprints this body, so the proxy must
+ // neither drop fields nor reserialize them.
+ expect(await new Response(init.body).text()).toBe(JSON.stringify(body));
+
+ vi.stubGlobal(
+ "fetch",
+ vi.fn(async () =>
+ Response.json(
+ {
+ error: {
+ code: "idempotency_conflict",
+ message: "idempotencyKey was already used with different input, payload, or mode",
+ },
+ },
+ { status: 409 },
+ ),
+ ),
+ );
+ const conflict = 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({ ...body, input: "Something else" }),
+ },
+ ),
+ {
+ OC_MANAGED_AGENTS_SECRET: "test-secret",
+ MANAGED_AGENTS_API_URL: "https://managedagents.test",
+ },
+ { orgID: "org_test", userID: "user_test" },
+ "/api/managed-agents",
+ );
+ expect(conflict.status).toBe(409);
+ expect(await conflict.json()).toMatchObject({
+ error: { code: "idempotency_conflict" },
+ });
+
+ vi.stubGlobal(
+ "fetch",
+ vi.fn(async () =>
+ Response.json(
+ { error: { code: "invalid_payload", message: "payload cannot exceed 32 KB of JSON" } },
+ { status: 400 },
+ ),
+ ),
+ );
+ const oversize = 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({ ...body, payload: "x".repeat(40_000) }),
+ },
+ ),
+ {
+ OC_MANAGED_AGENTS_SECRET: "test-secret",
+ MANAGED_AGENTS_API_URL: "https://managedagents.test",
+ },
+ { orgID: "org_test", userID: "user_test" },
+ "/api/managed-agents",
+ );
+ expect(oversize.status).toBe(400);
+ expect(await oversize.json()).toMatchObject({
+ error: { code: "invalid_payload" },
+ });
+ });
+
+ it("keeps the payload on public message.received events", async () => {
+ vi.stubGlobal(
+ "fetch",
+ vi.fn(async () =>
+ Response.json({
+ events: [
+ {
+ id: "event-1",
+ seq: 1,
+ timestamp: "2026-09-15T00:00:00.000Z",
+ sessionId: "session-1",
+ turnId: "turn-1",
+ type: "message.received",
+ data: {
+ input: "Fix the flaky test.",
+ mode: "queue",
+ payload: { repo: "acme/widgets", ref: "main" },
+ accountId: "acct_private",
+ },
+ },
+ ],
+ }),
+ ),
+ );
+ const response = await proxyManagedAgents(
+ new Request(
+ "https://app.opencomputer.dev/api/managed-agents/sessions/session-1/events?after=0",
+ ),
+ {
+ OC_MANAGED_AGENTS_SECRET: "test-secret",
+ MANAGED_AGENTS_API_URL: "https://managedagents.test",
+ },
+ { orgID: "org_test", userID: "user_test" },
+ "/api/managed-agents",
+ );
+ expect(response.status).toBe(200);
+ expect(await response.json()).toEqual({
+ events: [
+ expect.objectContaining({
+ type: "message.received",
+ data: {
+ input: "Fix the flaky test.",
+ mode: "queue",
+ payload: { repo: "acme/widgets", ref: "main" },
+ },
+ }),
+ ],
+ });
+ });
+
it("interrupts a session's running turn and returns the sanitized snapshot", async () => {
const fetchSpy = vi.fn(async () =>
Response.json({
diff --git a/docs/agents/api.mdx b/docs/agents/api.mdx
index 30f95856..801a4940 100644
--- a/docs/agents/api.mdx
+++ b/docs/agents/api.mdx
@@ -137,26 +137,61 @@ curl -X POST 'https://app.opencomputer.dev/api/managed-agents/sessions/<session-
-d '{
"input": "Plan the workshop.",
"idempotencyKey": "message-42",
- "mode": "queue"
+ "mode": "queue",
+ "payload": { "workshopId": "ws_812", "audience": "backend" }
}'
```
| Field | Meaning |
| --- | --- |
| `input` | The user text for this turn. Required, not empty. |
-| `idempotencyKey` | Optional. The same key returns the existing turn; without one every request starts a turn. |
+| `idempotencyKey` | Optional. Identifies this request: a repeat returns the existing turn, a different request under the same key is refused (below). Without one every request starts a turn. |
| `mode` | `queue` (default): run after earlier turns. `steer`: deliver into the running turn when the runtime supports it, otherwise queue. `interrupt`: cancel running turns and run next. |
+| `payload` | Optional. A JSON value for the agent, at most 32 KB encoded. It reaches the agent as [`useInput().payload`](/agents/inputs) with `source: "user"`, next to the text, and is recorded on the turn's `message.received` event. The text stays the message; the payload is structured context the agent reads. |
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.
-Codes: `400 invalid_turn`, `402 insufficient_credits`,
+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 the
+payload does not matter, an omitted `mode` means `queue`, and whitespace in
+the text counts. The same key with anything else is `409
+idempotency_conflict` and admits nothing. A retry after a lost reply is
+therefore safe with the same body, and a different request never lands on
+another request's key.
+
+Codes: `400 invalid_turn`, `400 invalid_payload` (over 32 KB),
+`402 insufficient_credits`, `409 idempotency_conflict`,
`409 memory_admission_pending` (retry the session creation with its key
first), `409 memory_admission_rejected` (the session is ended; create a new
one).
+### Start work from an application
+
+An application that turns a form submission into agent work makes two calls,
+each with its own key, and keeps what it sent until the second one is
+acknowledged:
+
+1. Resolve the deployment once, where the submission is composed (for
+ example when the form opens), and pin it: `POST /sessions` with
+ `Idempotency-Key: <submission-id>`, the `deploymentId` and `environment`.
+ A retry then carries the deployment the submission was composed against,
+ even if the alias has moved since.
+2. `POST /sessions/<id>/turns` with `idempotencyKey: <submission-id>/start`,
+ the text and the `payload`.
+
+Keep the submission (its id, the pinned deployment, the text and the
+payload) until the turns call answers, with `duplicate: false` or `true`.
+A lost reply at either step is retried with the same body and the same key:
+the first step returns the same session, the second the same turn. A
+session that exists without a turn is work that was never admitted; only the
+holder of the submission can retry it. A `409 idempotency_conflict` from
+either call means a different request already used that id; show it, keep
+the draft, and do not append the submission to a session it did not create.
+Each later message is its own submission with its own key.
+
## Events
```bash
diff --git a/docs/agents/events.mdx b/docs/agents/events.mdx
index 4ea9656d..5f0fa03c 100644
--- a/docs/agents/events.mdx
+++ b/docs/agents/events.mdx
@@ -51,7 +51,7 @@ unknown type as informational and keep reading.
| Type | When | `data` |
| --- | --- | --- |
-| `message.received` | A turn was accepted; its input is recorded before anything runs | `input`: the user text; `mode`: `queue`, `steer` or `interrupt` |
+| `message.received` | A turn was accepted; its input is recorded before anything runs | `input`: the user text; `mode`: `queue`, `steer` or `interrupt`; `payload`: the structured value the turn was sent with, when there was one |
| `turn.queued` | The turn waits for earlier turns | `mode` |
| `turn.steered` | The input was delivered into the running turn | `activeTurnId` |
| `turn.interrupted` | This turn cancelled the turns that were running | `interruptedTurnIds` |
diff --git a/docs/agents/inputs.mdx b/docs/agents/inputs.mdx
index a88f7d7c..d4b58ed1 100644
--- a/docs/agents/inputs.mdx
+++ b/docs/agents/inputs.mdx
@@ -40,6 +40,12 @@ interface AgentInput {
string, array, or object. Both `text` and `payload` are optional, so check them
before use.
+A payload comes from whatever started the turn. An application sends one on
+the [turns route](/agents/api#turns) next to the text, and the agent reads it
+with `source: "user"`; a [webhook](/agents/webhooks) delivers its body as the
+payload; a [schedule](/agents/schedules) dispatches the payload it was
+configured with. The agent reads all of them the same way.
+
## Adapt to the source
The current direct and delegated flows can share one agent definition:
diff --git a/web/src/managed-agents/Session.tsx b/web/src/managed-agents/Session.tsx
index 17460ec0..ef68ec4d 100644
--- a/web/src/managed-agents/Session.tsx
+++ b/web/src/managed-agents/Session.tsx
@@ -19,7 +19,11 @@ import {
getManagedProject,
} from './api'
import { AgentMarkdown } from './AgentMarkdown'
-import { turnAssistantText, turnFailureReason } from './session-history'
+import {
+ turnAssistantText,
+ turnFailureReason,
+ turnPayload,
+} from './session-history'
function formatDate(value: string) {
return new Date(value).toLocaleString()
@@ -222,6 +226,7 @@ export default function ManagedSessionDetail() {
turn.status === 'failed'
? turnFailureReason(events.data ?? [], turn.id)
: undefined
+ const payload = turnPayload(events.data ?? [], turn.id)
const running = !['completed', 'failed'].includes(turn.status)
return (
<div key={turn.id} className="space-y-6">
@@ -232,6 +237,16 @@ export default function ManagedSessionDetail() {
<p className="bg-muted ml-auto max-w-2xl rounded-xl rounded-br-sm px-3.5 py-2.5 text-sm leading-6 whitespace-pre-wrap">
{turn.input}
</p>
+ {payload !== undefined ? (
+ <details className="ml-auto mt-2 max-w-2xl">
+ <summary className="text-muted-foreground cursor-pointer text-xs">
+ Payload
+ </summary>
+ <pre className="bg-muted mt-1.5 overflow-x-auto rounded-xl px-3.5 py-2.5 font-mono text-xs leading-5">
+ {JSON.stringify(payload, null, 2)}
+ </pre>
+ </details>
+ ) : null}
</div>
<div className="max-w-3xl">
<p className="text-muted-foreground mb-1.5 flex items-center gap-1.5 text-[10px] font-semibold tracking-wider uppercase">
diff --git a/web/src/managed-agents/session-history.test.ts b/web/src/managed-agents/session-history.test.ts
index de5e96c8..54c2d36d 100644
--- a/web/src/managed-agents/session-history.test.ts
+++ b/web/src/managed-agents/session-history.test.ts
@@ -10,6 +10,7 @@ import {
sessionsForEnvironment,
turnAssistantText,
turnFailureReason,
+ turnPayload,
} from './session-history'
function deployment(
@@ -158,3 +159,35 @@ describe('turnFailureReason', () => {
expect(turnFailureReason(events, 'turn-3')).toBeUndefined()
})
})
+
+describe('turnPayload', () => {
+ it('reads the payload the turn was admitted with and nothing for a text-only turn', () => {
+ const payload = { repo: 'acme/widgets', ref: 'main', actor: { id: 583231 } }
+ const events: ManagedAgentEvent[] = [
+ {
+ id: 'e1',
+ seq: 1,
+ turnId: 'turn-1',
+ type: 'message.received',
+ data: { input: 'Fix the flaky test.', mode: 'queue', payload },
+ },
+ {
+ id: 'e2',
+ seq: 2,
+ turnId: 'turn-2',
+ type: 'message.received',
+ data: { input: 'Follow up', mode: 'queue' },
+ },
+ {
+ id: 'e3',
+ seq: 3,
+ turnId: 'turn-1',
+ type: 'message.completed',
+ data: { text: 'Done', payload: 'not an admission' },
+ },
+ ]
+ expect(turnPayload(events, 'turn-1')).toEqual(payload)
+ expect(turnPayload(events, 'turn-2')).toBeUndefined()
+ expect(turnPayload(events, 'turn-3')).toBeUndefined()
+ })
+})
diff --git a/web/src/managed-agents/session-history.ts b/web/src/managed-agents/session-history.ts
index f7dd7172..8196a467 100644
--- a/web/src/managed-agents/session-history.ts
+++ b/web/src/managed-agents/session-history.ts
@@ -55,3 +55,16 @@ export function turnFailureReason(events: ManagedAgentEvent[], turnId: string) {
}
return undefined
}
+
+/**
+ * The structured value a turn was sent with, as its `message.received` event
+ * recorded it at admission; undefined when the turn carried only text.
+ */
+export function turnPayload(events: ManagedAgentEvent[], turnId: string) {
+ for (const event of events) {
+ if (event.turnId === turnId && event.type === 'message.received') {
+ return event.data.payload
+ }
+ }
+ return undefined
+}