diff --git a/cockpit/chat/debug/react/src/application.ts b/cockpit/chat/debug/react/src/application.ts index 3fd23ec6a..4050fd461 100644 --- a/cockpit/chat/debug/react/src/application.ts +++ b/cockpit/chat/debug/react/src/application.ts @@ -1,4 +1,4 @@ -import type { AgentSnapshot, Message } from '@threadplane/core'; +import type { AgentInterrupt, AgentSnapshot, Message } from '@threadplane/core'; import { createMessageContent, type MessageRow, @@ -140,7 +140,9 @@ function captureNative( toolCalls: captureData( ownField(raw, 'toolCalls') ) as AgentSnapshot['toolCalls'], - interrupts: captureData(ownField(raw, 'interrupts')) as readonly unknown[], + interrupts: captureData( + ownField(raw, 'interrupts') + ) as unknown as readonly AgentInterrupt[], subgraphs: captureData(ownField(raw, 'subgraphs')) as readonly unknown[], state: values.kind === 'available' ? values.values : undefined, history, diff --git a/cockpit/chat/interrupts/react/src/application.spec.ts b/cockpit/chat/interrupts/react/src/application.spec.ts index 6506249ba..56acb154a 100644 --- a/cockpit/chat/interrupts/react/src/application.spec.ts +++ b/cockpit/chat/interrupts/react/src/application.spec.ts @@ -225,7 +225,7 @@ it.each(['confirm', 'cancel'] as const)( await h.app.submit('Forbidden while paused'); expect(h.session.resume).toHaveBeenCalledTimes(1); expect(h.session.resume).toHaveBeenCalledWith( - value, + [{ interruptId: 'approval', status: 'resolved', value }], expect.objectContaining({ signal: expect.any(AbortSignal) }) ); h.result(); diff --git a/cockpit/chat/interrupts/react/src/application.ts b/cockpit/chat/interrupts/react/src/application.ts index b41dab753..e13811511 100644 --- a/cockpit/chat/interrupts/react/src/application.ts +++ b/cockpit/chat/interrupts/react/src/application.ts @@ -1,4 +1,5 @@ import type { + AgentInterruptResponse, AgentSession, CompleteOutcome, Message, @@ -18,11 +19,12 @@ import { type PauseAuthority, } from './authority'; -export interface InterruptsSession extends Omit { +export interface InterruptsSession + extends Omit { getSnapshot(): InterruptsState; load(options?: { readonly signal?: AbortSignal }): Promise; resume( - value: 'confirm' | 'cancel', + responses: readonly AgentInterruptResponse[], options?: { readonly signal?: AbortSignal } ): Promise; } @@ -387,9 +389,26 @@ export function createInterruptsApplication(options: { blocked(); return; } + // A decision answers the one interrupt its authority was captured from. + const interruptId = + 'text' in input ? undefined : dispatch.interrupts[0]?.id; + if (!('text' in input) && typeof interruptId !== 'string') { + selected.unsafe = true; + blocked(); + return; + } const outcome = await ('text' in input ? selected.session.submit(input.text, { signal: admitted.signal }) - : selected.session.resume(input.value, { signal: admitted.signal })); + : selected.session.resume( + [ + { + interruptId: interruptId as string, + status: 'resolved', + value: input.value, + }, + ], + { signal: admitted.signal } + )); if (!valid()) return; const live = read(selected, valid), turn = selected.turn; diff --git a/cockpit/chat/interrupts/react/src/authority.ts b/cockpit/chat/interrupts/react/src/authority.ts index c5e5c729f..b2356d483 100644 --- a/cockpit/chat/interrupts/react/src/authority.ts +++ b/cockpit/chat/interrupts/react/src/authority.ts @@ -1,7 +1,12 @@ -import type { AgentSnapshot, Message, ToolCall } from '@threadplane/core'; +import type { + AgentInterrupt, + AgentSnapshot, + Message, + ToolCall, +} from '@threadplane/core'; export interface InterruptsState extends AgentSnapshot { - readonly interrupts: readonly unknown[]; + readonly interrupts: readonly AgentInterrupt[]; readonly subgraphs: readonly unknown[]; readonly history: | readonly { diff --git a/cockpit/chat/subagents/react/src/authority.ts b/cockpit/chat/subagents/react/src/authority.ts index 917345230..5458ec1ab 100644 --- a/cockpit/chat/subagents/react/src/authority.ts +++ b/cockpit/chat/subagents/react/src/authority.ts @@ -1,7 +1,12 @@ -import type { AgentSnapshot, Message, ToolCall } from '@threadplane/core'; +import type { + AgentInterrupt, + AgentSnapshot, + Message, + ToolCall, +} from '@threadplane/core'; export interface SubagentsState extends AgentSnapshot { - readonly interrupts: readonly unknown[]; + readonly interrupts: readonly AgentInterrupt[]; readonly subgraphs: readonly unknown[]; readonly history: | readonly { diff --git a/cockpit/chat/threads/react/src/authority.ts b/cockpit/chat/threads/react/src/authority.ts index faa0bd9a2..094ba6901 100644 --- a/cockpit/chat/threads/react/src/authority.ts +++ b/cockpit/chat/threads/react/src/authority.ts @@ -1,6 +1,6 @@ -import type { AgentSnapshot, Message } from '@threadplane/core'; +import type { AgentInterrupt, AgentSnapshot, Message } from '@threadplane/core'; export interface ThreadsState extends AgentSnapshot { - readonly interrupts: readonly unknown[]; + readonly interrupts: readonly AgentInterrupt[]; readonly subgraphs: readonly unknown[]; readonly history: | readonly { diff --git a/cockpit/chat/tool-calls/react/src/authority.ts b/cockpit/chat/tool-calls/react/src/authority.ts index 6fdbe9e6f..bcfabce1e 100644 --- a/cockpit/chat/tool-calls/react/src/authority.ts +++ b/cockpit/chat/tool-calls/react/src/authority.ts @@ -1,7 +1,12 @@ -import type { AgentSnapshot, Message, ToolCall } from '@threadplane/core'; +import type { + AgentInterrupt, + AgentSnapshot, + Message, + ToolCall, +} from '@threadplane/core'; export interface ToolCallsState extends AgentSnapshot { - readonly interrupts: readonly unknown[]; + readonly interrupts: readonly AgentInterrupt[]; readonly subgraphs: readonly unknown[]; readonly history: | readonly { diff --git a/cockpit/deep-agents/filesystem/react/src/application.ts b/cockpit/deep-agents/filesystem/react/src/application.ts index 7b7b8faf3..b19c02ef8 100644 --- a/cockpit/deep-agents/filesystem/react/src/application.ts +++ b/cockpit/deep-agents/filesystem/react/src/application.ts @@ -1,4 +1,5 @@ import type { + AgentInterruptResponse, AgentSession, AgentSnapshot, CompleteOutcome, @@ -37,11 +38,12 @@ import { type FilesystemSnapshot, type Turn, } from './authority'; -export interface FilesystemSession extends Omit { +export interface FilesystemSession + extends Omit { getSnapshot(): AgentSnapshot & FilesystemSnapshot; load(options?: { readonly signal?: AbortSignal }): Promise; resume( - value: PlainValue, + responses: readonly AgentInterruptResponse[], options?: { readonly signal?: AbortSignal } ): Promise; } @@ -497,11 +499,16 @@ export function createFilesystemApplication(client: FilesystemClient) { (snapshot as FilesystemApplicationSnapshot).phase !== 'confirming' ) throw Error('Unavailable whole batch'); + // The whole batch is one interrupt; its id names the response. + const interruptId = selected.session.getSnapshot().interrupts[0]?.id; + if (typeof interruptId !== 'string') + throw Error('Unavailable whole batch'); publish({ phase: 'working', approval: null, decisionToken: null }); if (!current(run)) return false; - outcome = await selected.session.resume(decision, { - signal: run.controller.signal, - }); + outcome = await selected.session.resume( + [{ interruptId, status: 'resolved', value: decision }], + { signal: run.controller.signal } + ); if (!current(run)) return false; observe(run); if (!current(run)) return false; diff --git a/cockpit/langgraph/interrupts/angular/e2e/checkpoint-session.spec.ts b/cockpit/langgraph/interrupts/angular/e2e/checkpoint-session.spec.ts index 926bd198d..f1943ae95 100644 --- a/cockpit/langgraph/interrupts/angular/e2e/checkpoint-session.spec.ts +++ b/cockpit/langgraph/interrupts/angular/e2e/checkpoint-session.spec.ts @@ -133,7 +133,7 @@ for (const consumed of [false, true]) { const unsubscribe = session.subscribe(() => publications.push(session.getSnapshot())); let rejected = false; try { - await session.resume({ approved: false }); + await session.resume([{ interruptId: session.getSnapshot().interrupts[0]?.id ?? 'consumed', status: 'resolved', value: { approved: false } }]); } catch { rejected = true; } finally { @@ -159,7 +159,7 @@ for (const consumed of [false, true]) { expect(position((await api.threads.getState(threadId)).checkpoint)).toEqual(position(approved.checkpoint)); const stillPaused = await api.threads.getState(threadId, pausedPosition); expect(stillPaused.tasks).toEqual([expect.objectContaining({ id: task.id, result: null, interrupts: task.interrupts })]); - expect(await session.resume({ approved: false })).toBe('success'); + expect(await session.resume([{ interruptId: session.getSnapshot().interrupts[0].id, status: 'resolved', value: { approved: false } }])).toBe('success'); expect(transport.creations).toBe(beforeCreations + 1); const exact = transport.finalPosition(); const rejected = await api.threads.getState(threadId, exact); diff --git a/cockpit/langgraph/interrupts/react/src/app.spec.tsx b/cockpit/langgraph/interrupts/react/src/app.spec.tsx index a2c5bed4e..f23d5503c 100644 --- a/cockpit/langgraph/interrupts/react/src/app.spec.tsx +++ b/cockpit/langgraph/interrupts/react/src/app.spec.tsx @@ -29,7 +29,7 @@ function setup( finish = resolve; }); const batch = Object.freeze([{ id: 'refund', value: payload }]); - let interrupts: readonly { value: unknown }[] = batch; + let interrupts: readonly { id: string; value: unknown }[] = batch; const session: InterruptSession = { getSnapshot: () => ({ status: 'idle', @@ -121,7 +121,7 @@ describe('native React refund approval', () => { await s.pause(); fireEvent.click(s.view.getByRole('button', { name: label })); expect(s.session.resume).toHaveBeenCalledWith( - { approved }, + [{ interruptId: 'refund', status: 'resolved', value: { approved } }], expect.any(Object) ); expect(s.session.submit).toHaveBeenCalledTimes(1); @@ -185,7 +185,13 @@ describe('native React refund approval', () => { s.view.getByRole('button', { name: 'Approve edited amount' }) ); expect(s.session.resume).toHaveBeenCalledWith( - { approved: true, amount: 0 }, + [ + { + interruptId: 'refund', + status: 'resolved', + value: { approved: true, amount: 0 }, + }, + ], expect.any(Object) ); }); diff --git a/cockpit/langgraph/interrupts/react/src/application.spec.ts b/cockpit/langgraph/interrupts/react/src/application.spec.ts index e55742b79..6bc940d6e 100644 --- a/cockpit/langgraph/interrupts/react/src/application.spec.ts +++ b/cockpit/langgraph/interrupts/react/src/application.spec.ts @@ -33,13 +33,14 @@ function setup() { const creation = deferred(); const run = deferred(); const resumed = deferred(); - let snapshot: AgentSnapshot & { interrupts: readonly { value?: unknown }[] } = - Object.freeze({ - status: 'idle', - messages: [], - toolCalls: [], - interrupts: Object.freeze([]), - }); + let snapshot: AgentSnapshot & { + interrupts: readonly { id: string; value?: unknown }[]; + } = Object.freeze({ + status: 'idle', + messages: [], + toolCalls: [], + interrupts: Object.freeze([]), + }); const observers = new Set<() => void>(); const release = vi.fn(); const session: InterruptSession = { @@ -142,9 +143,10 @@ describe('public interrupts owner', () => { await s.application.decide(required(decision), response); await s.application.submit('Duplicate text'); expect(s.session.resume).toHaveBeenCalledTimes(1); - expect(s.session.resume).toHaveBeenCalledWith(response, { - signal: expect.any(AbortSignal), - }); + expect(s.session.resume).toHaveBeenCalledWith( + [{ interruptId: 'reused-id', status: 'resolved', value: response }], + { signal: expect.any(AbortSignal) } + ); expect(s.application.getSnapshot().busy).toBe(true); expect(s.application.getSnapshot().decision).toBeNull(); expect(s.session.submit).toHaveBeenCalledTimes(1); @@ -244,7 +246,13 @@ describe('public interrupts owner', () => { const pending = s.application.decide(required(decision), response); response.amount = 100; expect(s.session.resume).toHaveBeenCalledWith( - { approved: true, amount: 25 }, + [ + { + interruptId: 'reused-id', + status: 'resolved', + value: { approved: true, amount: 25 }, + }, + ], expect.any(Object) ); s.resumed.reject(new Error('PRIVATE credential')); diff --git a/cockpit/langgraph/interrupts/react/src/application.ts b/cockpit/langgraph/interrupts/react/src/application.ts index b76d2fe02..835275190 100644 --- a/cockpit/langgraph/interrupts/react/src/application.ts +++ b/cockpit/langgraph/interrupts/react/src/application.ts @@ -1,4 +1,5 @@ import type { + AgentInterruptResponse, AgentSession, AgentSnapshot, CompleteOutcome, @@ -8,12 +9,16 @@ import { type MessageRow, } from '@threadplane/content/messages'; -export interface InterruptSession extends Omit { +export interface InterruptSession + extends Omit { getSnapshot(): AgentSnapshot & { - readonly interrupts: readonly { readonly value?: unknown }[]; + readonly interrupts: readonly { + readonly id: string; + readonly value?: unknown; + }[]; }; resume( - value: RefundResponse, + responses: readonly AgentInterruptResponse[], options?: { readonly signal?: AbortSignal } ): Promise; } @@ -112,6 +117,8 @@ export function createInterruptsApplication(options: { let capturedBatch: | ReturnType['interrupts'] | undefined; + /** The id of the one interrupt behind the projected decision. */ + let capturedId: string | undefined; let operation: AbortController | undefined; let disposed = false; let disposal: Promise | undefined; @@ -126,8 +133,13 @@ export function createInterruptsApplication(options: { if (interrupts === capturedBatch) return; capturedBatch = interrupts; const root = - interrupts.length === 1 ? ownData(interrupts[0], ['value']) : undefined; - const refund = root && refundPayload(root['value']); + interrupts.length === 1 + ? ownData(interrupts[0], ['id', 'value']) + : undefined; + const id = root?.['id']; + const refund = + root && typeof id === 'string' ? refundPayload(root['value']) : undefined; + capturedId = refund && typeof id === 'string' ? id : undefined; publish({ decision: refund ? Object.freeze({ refund }) : null, canSubmit: false, @@ -234,12 +246,17 @@ export function createInterruptsApplication(options: { ) return; const admittedBatch = capturedBatch; + const interruptId = capturedId; + if (interruptId === undefined) return; await perform('decision', (owned, signal) => { // Publishing pending state can synchronously replace the observed batch. // Reproject that pause without dispatching the superseded decision. if (owned.getSnapshot().interrupts !== admittedBatch) return Promise.resolve('paused'); - return owned.resume(captured, { signal }); + return owned.resume( + [{ interruptId, status: 'resolved', value: captured }], + { signal } + ); }); } async function stop() { diff --git a/examples/chat/native/shared/application-approval.spec.ts b/examples/chat/native/shared/application-approval.spec.ts index 5cfa11079..9dbd91c88 100644 --- a/examples/chat/native/shared/application-approval.spec.ts +++ b/examples/chat/native/shared/application-approval.spec.ts @@ -96,7 +96,8 @@ const resume = (thread: string, answer = 'approved', extra = {}) => ({ payload: { assistant_id: 'assistant', input: null, - command: { resume: { [id]: answer } }, + // One pending approval: the answer is the plain resume value. + command: { resume: answer }, stream_mode: ['values', 'messages-tuple', 'updates', 'custom', 'checkpoints'], stream_subgraphs: true, stream_resumable: true, @@ -452,8 +453,8 @@ test('approval rejected completion suppresses a real replacement pause even when const actual = o.sessionFactory!(thread); return { ...actual, - async resume(value, options) { - assert.equal(await actual.resume(value, options), 'paused'); + async resume(responses, options) { + assert.equal(await actual.resume(responses, options), 'paused'); throw new Error('completion delivery failed'); }, }; @@ -495,10 +496,10 @@ for (const action of ['stop', 'select', 'dispose'] as const) { const actual = o.sessionFactory!(thread); return { ...actual, - resume(value, options) { + resume(responses, options) { invocations++; aborted = options?.signal?.aborted ?? false; - return actual.resume(value, options); + return actual.resume(responses, options); }, }; }, @@ -554,8 +555,8 @@ test('approval held resume Stop closes HTTP but cannot release the shared slot b const actual = o.sessionFactory!(thread); return { ...actual, - async resume(value, options) { - const result = await actual.resume(value, options); + async resume(responses, options) { + const result = await actual.resume(responses, options); settled.release(); await gate.promise; return result; @@ -654,8 +655,8 @@ for (const rejection of [false, true]) { first = false; return { ...actual, - async resume(value, options) { - const result = await actual.resume(value, options); + async resume(responses, options) { + const result = await actual.resume(responses, options); if (delay) { settled.release(); await gate.promise; diff --git a/examples/chat/native/shared/application.ts b/examples/chat/native/shared/application.ts index 0a622df57..1b406e3d5 100644 --- a/examples/chat/native/shared/application.ts +++ b/examples/chat/native/shared/application.ts @@ -1788,10 +1788,12 @@ function createApplicationOwner( ) return false; const response = { - [decision.approval.id]: action === 'approve' ? 'approved' : 'denied', - }; + interruptId: decision.approval.id, + status: 'resolved', + value: action === 'approve' ? 'approved' : 'denied', + } as const; return execute('decision', (runtimeSession, signal) => - runtimeSession.resume(response, { signal }) + runtimeSession.resume([response], { signal }) ); } diff --git a/examples/chat/native/tooling/approval-provider-consumer.ts b/examples/chat/native/tooling/approval-provider-consumer.ts index 73f3dc837..a4f143b87 100644 --- a/examples/chat/native/tooling/approval-provider-consumer.ts +++ b/examples/chat/native/tooling/approval-provider-consumer.ts @@ -167,14 +167,19 @@ try { original.id === '0'.repeat(32) ? '1'.repeat(32) : '0'.repeat(32); const before = await journal(); // Provider routing diagnostic only; application decisions never accept - // an arbitrary ID or raw resume value. + // an arbitrary ID or raw resume value. The session rejects an ID that + // is not pending before sending (its own specs cover that), so the + // ID-keyed command goes through the provider client. const session = own(thread.thread_id); assert.ok(session.load); + for await (const event of api.runs.stream(thread.thread_id, 'chat', { + input: null, + command: { resume: { [unmatched]: 'denied' } }, + streamMode: ['values', 'updates'], + signal, + })) + assert.notEqual(event.event, 'error', JSON.stringify(event.data)); await session.load({ signal }); - assert.equal( - await session.resume({ [unmatched]: 'denied' }, { signal }), - 'paused' - ); assert.deepEqual(pause(session.getSnapshot()), original); assert.deepEqual( await journal(), diff --git a/examples/chat/native/tooling/approval-provider.ts b/examples/chat/native/tooling/approval-provider.ts index 947bba5c2..70484e045 100644 --- a/examples/chat/native/tooling/approval-provider.ts +++ b/examples/chat/native/tooling/approval-provider.ts @@ -69,9 +69,9 @@ export function acceptApprovalCapture( 'POST /runs/:id', 'GET /runs/:id', ...(item.scenario === 'loaded' ? ['GET ', 'POST /history'] : []), - ...(item.unmatched - ? ['POST /history', 'POST /runs/:id', 'GET /runs/:id'] - : []), + // The unmatched-ID diagnostic posts its command through the provider + // client, then a raw session loads the saved pause. + ...(item.unmatched ? ['POST /runs/:id', 'POST /history'] : []), 'POST /runs/:id', 'GET /runs/:id', 'GET /state', @@ -123,7 +123,9 @@ export function acceptApprovalCapture( responses.map((q) => q.command), [ ...(item.unmatched ? [{ resume: { [item.unmatched]: 'denied' } }] : []), - { resume: { [item.interrupt.id]: item.answer } }, + // One pending approval: the session sends the answer as the plain + // resume value. + { resume: item.answer }, ] ); for (const body of responses) assert.equal(body.input, null); @@ -143,14 +145,14 @@ export function acceptApprovalCapture( ); assert.equal( capture.requests.length, - 46, + 45, 'Exact canonical application request footprint' ); const result = { ...capture, accepted: true as const, limits: [ - 'Normal submit and decision commands use the installed default application/session factory and real directory/history admission. The unmatched-ID raw-session substep is provider routing evidence, not application decision authority.', + 'Normal submit and decision commands use the installed default application/session factory and real directory/history admission. The unmatched-ID substep posts an ID-keyed resume command through the provider client, because the session rejects an ID that is not pending before sending; it is provider routing evidence, not application decision authority.', 'Cleanup acknowledges synchronous application retirement, awaited raw-probe disposal and completed known-thread deletions. The private application dispose contract does not await its internal session disposal promise.', 'A task may reuse its interrupt ID for successive pauses: the separate direct-graph feasibility probe establishes this limitation, not this HTTP proof. No remote atomicity or pause-occurrence identity is inferred from interrupt IDs.', ], diff --git a/examples/chat/native/tooling/backup-provider.spec.ts b/examples/chat/native/tooling/backup-provider.spec.ts index 0e59ba719..3bbfddc56 100644 --- a/examples/chat/native/tooling/backup-provider.spec.ts +++ b/examples/chat/native/tooling/backup-provider.spec.ts @@ -211,7 +211,7 @@ function candidate() { assistant_id: 'chat', input: null, command: { - resume: { [id]: scenario === 'decline' ? 'denied' : 'approved' }, + resume: scenario === 'decline' ? 'denied' : 'approved', }, ...stream, }); diff --git a/examples/chat/native/tooling/backup-provider.ts b/examples/chat/native/tooling/backup-provider.ts index 0eb812c60..0e156c801 100644 --- a/examples/chat/native/tooling/backup-provider.ts +++ b/examples/chat/native/tooling/backup-provider.ts @@ -286,11 +286,9 @@ export function acceptBackupCapture( assert.deepEqual(request.body, { assistant_id: 'chat', input: null, + // One pending approval: the answer is the plain resume value. command: { - resume: { - [item.interrupt.id]: - scenario === 'decline' ? 'denied' : 'approved', - }, + resume: scenario === 'decline' ? 'denied' : 'approved', }, ...streamOptions, }); diff --git a/examples/chat/native/tooling/browser-proof.mjs b/examples/chat/native/tooling/browser-proof.mjs index 48f2ba7f7..6451c9fa2 100644 --- a/examples/chat/native/tooling/browser-proof.mjs +++ b/examples/chat/native/tooling/browser-proof.mjs @@ -249,7 +249,7 @@ const resume = (id, answer, events, extra = {}) => ({ payload: { assistant_id: 'assistant', input: null, - command: { resume: { [approvalId]: answer } }, + command: { resume: answer }, stream_mode: ['values', 'messages-tuple', 'updates', 'custom', 'checkpoints'], stream_subgraphs: true, stream_resumable: true, diff --git a/fixtures/react-parity/README.md b/fixtures/react-parity/README.md index 2d5379751..5d70fe8c8 100644 --- a/fixtures/react-parity/README.md +++ b/fixtures/react-parity/README.md @@ -111,8 +111,8 @@ catalog retain ownership of their input fields. Submitted state does not optimistically change observed values. The input contract is broad plain data, not an inferred or validated application schema. -Explicit `resume()` sends an authored response for observed interrupts without a -synthetic human message. `reconnect()` joins the latest retained owned physical +Explicit `resume(responses)` answers observed interrupts by id with authored +values, without a synthetic human message. `reconnect()` joins the latest retained owned physical run only with safe cursor evidence. Captured run identity requires exact-run status confirmation before successful completion or tool execution; known-run uncertainty cannot fall back to thread history. Reconnection preserves anonymous diff --git a/fixtures/react-parity/ag-ui-candidate/installed-types.ts b/fixtures/react-parity/ag-ui-candidate/installed-types.ts index 389b9a86a..a6e86bb1a 100644 --- a/fixtures/react-parity/ag-ui-candidate/installed-types.ts +++ b/fixtures/react-parity/ag-ui-candidate/installed-types.ts @@ -108,8 +108,8 @@ export function checkCandidate(signal: AbortSignal) { void agent.submit({ message: 'Hello', state: { topic: 'x' } }); // @ts-expect-error The core view takes a message and state only. void agent.submit({ message: 'Hello', messages: [] }); - // @ts-expect-error Native resume stays on the native session. - void agent.resume; + // @ts-expect-error The core contract's resume is optional, and this view does not supply it. + void agent.resume([]); const regenerated: Promise | undefined = session.regenerate?.('assistant-id', { signal }); void regenerated; diff --git a/fixtures/react-parity/langgraph-candidate/installed-types.ts b/fixtures/react-parity/langgraph-candidate/installed-types.ts index 90f47b6ec..c14cc1b26 100644 --- a/fixtures/react-parity/langgraph-candidate/installed-types.ts +++ b/fixtures/react-parity/langgraph-candidate/installed-types.ts @@ -52,8 +52,19 @@ export function checkCandidate(signal: AbortSignal) { ); void session.submit('Hello', { signal }); void session.load?.({ signal }); - void session.resume({ approval: true }, options); - void session.resume(null); + void session.resume( + [ + { + interruptId: 'approval', + status: 'resolved', + value: { approval: true }, + }, + ], + options + ); + void session.resume([ + { interruptId: 'approval', status: 'resolved', value: null }, + ]); void session.reconnect({ signal }); const snapshot = session.getSnapshot(); const values: Readonly> | undefined = @@ -101,8 +112,13 @@ export function checkCandidate(signal: AbortSignal) { void session.submit({ message: '', state: { date: new Date() } }); // @ts-expect-error Run options cannot route another thread. void session.submit('', { config: { configurable: { thread_id: 'other' } } }); - // @ts-expect-error Resume cannot override transport commands. - void session.resume(true, { command: { goto: 'other' } }); + void session.resume( + [{ interruptId: 'approval', status: 'resolved', value: true }], + // @ts-expect-error Resume cannot override transport commands. + { command: { goto: 'other' } } + ); + // @ts-expect-error A bare value does not name the interrupt it answers. + void session.resume(true); // @ts-expect-error Fork requires the actual checkpoint shape. void session.fork('checkpoint', 'Branch'); // @ts-expect-error Observed state cannot be replaced by a consumer. diff --git a/fixtures/react-parity/runtime/README.md b/fixtures/react-parity/runtime/README.md index 42fa3a06e..47bd7e7cc 100644 --- a/fixtures/react-parity/runtime/README.md +++ b/fixtures/react-parity/runtime/README.md @@ -273,12 +273,17 @@ responses demonstrate the distinction between submitted and observed state. ## Explicit resume contract The private development session exposes -`resume(value?: PlainValue, options?: LangGraphRunOptions)`. Supply the -application's response for a dynamic interrupt, including an interrupt-ID map -when responding to several interrupts. Omit the response to continue a static -breakpoint. `false`, `0`, `''`, and `null` are responses and are preserved. The -runtime owns a plain-data copy; it does not validate an application schema, -select interrupt targets, or transform arguments. +`resume(responses: readonly AgentInterruptResponse[], options?: LangGraphRunOptions)`. +Each response names one pending interrupt by the `id` the snapshot publishes +and has the status `resolved` with an optional `value`. When one interrupt is +pending, its response's value is sent as the resume value as is. When several +are pending, the answered ones are sent as an interrupt-ID map, so each needs a +backend id and a defined value. Answer the `breakpoint` interrupt without a +value to continue a static breakpoint. `false`, `0`, `''`, and `null` are +values and are preserved. A response that names an interrupt that is not +pending, names one twice, or has the status `cancelled` rejects before +anything is sent. The runtime owns a plain-data copy; it does not validate an +application schema, choose which interrupts to answer, or transform arguments. Resume requires an observed pause and no active run, history load, unresolved submission recovery, retained reconnect ownership, or unsettled tool results. @@ -567,7 +572,7 @@ Chromium: inert mount, explicit history load, equal history refresh, empty histo replacement, successful text, a real local tool handler and exact two-request result continuation, protected visible server error, held streaming DOM updates and Stop, the full pause batch retained after Stop, an explicit response -map and second pause, same-message resume completion, known-run premature EOF, +map and second pause answered by a single plain value, same-message resume completion, known-run premature EOF, explicit cursor join with exact-run completion, reuse after Stop, then unmount/dispose/post-disposal commands. The separate thread view adds six scenario groups covering explicit selection/load, switching during streaming, @@ -600,7 +605,8 @@ makes three. History fixtures contain two separate task payloads and show paused delivery. The Pause button sends two separate root controls and renders both payloads; Stop retains them without another request. Resume clears the old batch and observes a new pause, then a second explicit resume completes without adding -human messages. Both null inputs and exact response maps are asserted server-side. +human messages. Both null inputs, the exact response map for the two-interrupt +batch and the plain value for the single final interrupt are asserted server-side. Drop captures its run identity from `Content-Location` and ends with a committed cursor. Its assistant frames omit message IDs, proving that fallback message identity survives the fresh delivery generation used by reconnect. Its clean diff --git a/fixtures/react-parity/runtime/runtime-entry.ts b/fixtures/react-parity/runtime/runtime-entry.ts index 521557cc3..14a60b717 100644 --- a/fixtures/react-parity/runtime/runtime-entry.ts +++ b/fixtures/react-parity/runtime/runtime-entry.ts @@ -1,7 +1,7 @@ import type { + AgentInterruptResponse, AgentSession, CompleteOutcome, - PlainValue, } from '@threadplane/core'; // eslint-disable-next-line @nx/enforce-module-boundaries -- This development-only entry composes private source into a temporary fixture bundle, never a package export. import { createSession } from '../../../libs/langgraph/src/runtime/create-session'; @@ -32,7 +32,7 @@ export function createFixtureSession( ): Promise; load?: (options?: { signal?: AbortSignal }) => Promise; resume( - value?: PlainValue, + responses: readonly AgentInterruptResponse[], options?: FixtureRunOptions ): Promise; reconnect(options?: { diff --git a/fixtures/react-parity/runtime/scenarios.ts b/fixtures/react-parity/runtime/scenarios.ts index 73c9358d9..47c8977c9 100644 --- a/fixtures/react-parity/runtime/scenarios.ts +++ b/fixtures/react-parity/runtime/scenarios.ts @@ -1,4 +1,5 @@ import type { + AgentInterruptResponse, AgentSession, AgentSnapshot, AgentError, @@ -74,12 +75,21 @@ export function reviewRunOptions(label: string) { } /** Application-authored choices for this fixture, not a library targeting helper. */ -export function reviewResponse(snapshot: FixtureSnapshot): PlainValue { +export function reviewResponse( + snapshot: FixtureSnapshot +): readonly AgentInterruptResponse[] { return snapshot.interrupts.some( (interrupt) => interrupt.id === 'final-approval' ) - ? { 'final-approval': true } - : { 'live-approval': 'yes', 'live-confirmation': false }; + ? [{ interruptId: 'final-approval', status: 'resolved', value: true }] + : [ + { interruptId: 'live-approval', status: 'resolved', value: 'yes' }, + { + interruptId: 'live-confirmation', + status: 'resolved', + value: false, + }, + ]; } export interface FixtureTools { @@ -222,7 +232,9 @@ export function display(snapshot: FixtureSnapshot) { /** Owner controls deliberately survive framework teardown. */ export function attachOwner( session: AgentSession & { - resume(value?: PlainValue): Promise; + resume( + responses: readonly AgentInterruptResponse[] + ): Promise; reconnect(): Promise; }, unmount: () => void @@ -261,7 +273,9 @@ export function attachOwner( }); button('Resume after dispose', async () => { status.textContent = 'resuming'; - status.textContent = await session.resume(true); + status.textContent = await session.resume([ + { interruptId: 'final-approval', status: 'resolved', value: true }, + ]); }); button('Reconnect after dispose', async () => { status.textContent = 'reconnecting'; diff --git a/libs/core/README.md b/libs/core/README.md index 43667ada3..ad334ef8d 100644 --- a/libs/core/README.md +++ b/libs/core/README.md @@ -35,6 +35,24 @@ and treats a schema that validates asynchronously as invalid because a snapshot published synchronously. This package defines the contract; whether a backend session supplies `state` is that session's choice. +A run that pauses for a person settles with the `'paused'` outcome and lists what it +waits on in the snapshot's `interrupts`. Each `AgentInterrupt` has an `id`, and may +carry the backend's `value`, a `reason`, display `message` and the `toolCallId` it is +about. `resume(responses)` answers them: each `AgentInterruptResponse` names one +pending interrupt and is `resolved`, optionally with a `value`, or `cancelled`. A +session rejects a response that names an interrupt that is not pending, names one +twice, or uses a status its backend cannot express. `interrupts` and `resume` are +optional: a session that cannot pause supplies neither. + +The snapshot's optional `subagents` lists the child agents the root agent started, in +start order. An `AgentSubagent` has an `id`, a `status` of `running`, `complete`, +`error` or `unknown`, and its own `messages` and `toolCalls`, which are not repeated +in the root transcript. `unknown` means the child started, no ending was seen, and +no run is active that could still report one. `toolCallId` relates a child to the +root tool call that started it, and `parentId` to the child that did. The fake +session in `@threadplane/core/testing` publishes both fields and records `resume` +calls. + `Message.citations` optionally contains readonly `Citation` source metadata: stable IDs/order, title, URL, snippet, source type, icon URL, primitive publication time, and deeply readonly plain provider extras. These strings are authored display data; diff --git a/libs/core/src/contracts/agent-session.ts b/libs/core/src/contracts/agent-session.ts index d1fa14d92..5b2b4ccdb 100644 --- a/libs/core/src/contracts/agent-session.ts +++ b/libs/core/src/contracts/agent-session.ts @@ -1,5 +1,6 @@ import type { AgentSnapshot } from './agent-snapshot.js'; import type { CompleteOutcome } from './delivery.js'; +import type { AgentInterruptResponse } from './interrupt.js'; import type { AgentStateUpdate } from './state.js'; import type { PlainValue, ToolContract } from './tool.js'; @@ -67,6 +68,19 @@ export type AgentSession< messageId: string, options?: AgentSubmitOptions ): Promise; + /** + * Optional: answers interrupts the snapshot lists and continues the + * paused work, resolving with the continued run's outcome. Each response + * names one pending interrupt by `id`. Rejects without sending when a + * response names an interrupt that is not pending, names one twice, or + * uses a status the backend cannot express; whether every pending + * interrupt must be answered at once is the backend's rule. A session + * that cannot pause leaves the command undefined. + */ + resume?( + responses: readonly AgentInterruptResponse[], + options?: AgentSubmitOptions + ): Promise; /** Read-only reconciliation; never retries an uncertain submission. */ checkStatus?(): Promise; dispose(): Promise; diff --git a/libs/core/src/contracts/agent-snapshot.ts b/libs/core/src/contracts/agent-snapshot.ts index 03c39aa18..da8d5f00b 100644 --- a/libs/core/src/contracts/agent-snapshot.ts +++ b/libs/core/src/contracts/agent-snapshot.ts @@ -2,6 +2,8 @@ import type { AgentError } from './error.js'; import type { Message } from './message.js'; import type { DeepReadonly, ToolCall, ToolContract } from './tool.js'; import type { AgentPlanStep } from './plan.js'; +import type { AgentInterrupt } from './interrupt.js'; +import type { AgentSubagent } from './subagent.js'; /** * Token counts for one model in one run, as the runtime reported them. Absent @@ -52,5 +54,15 @@ export type AgentSnapshot< * Absent until the backend reports a state, and on sessions that hold none. */ readonly state?: DeepReadonly; + /** + * What a paused run is waiting on. Empty or absent when nothing is + * pending, and always absent on sessions that cannot pause. + */ + readonly interrupts?: readonly AgentInterrupt[]; + /** + * Child agents the root agent started, in start order. Absent on + * sessions that report none. + */ + readonly subagents?: readonly AgentSubagent[]; } : never; diff --git a/libs/core/src/contracts/contracts.type-test.ts b/libs/core/src/contracts/contracts.type-test.ts index b2521d847..5beebdc26 100644 --- a/libs/core/src/contracts/contracts.type-test.ts +++ b/libs/core/src/contracts/contracts.type-test.ts @@ -1,7 +1,11 @@ import type { AgentError, + AgentInterrupt, + AgentInterruptResponse, AgentSession, AgentSnapshot, + AgentSubagent, + AgentSubagentStatus, AgentUsage, Citation, CompleteOutcome, @@ -222,3 +226,83 @@ const usage: AgentUsage | undefined = snapshot.usage; // @ts-expect-error usage entries are readonly usage?.entries.push({ inputTokens: 1 }); void [retried, retriedText, usage]; + +// Interrupts: optional on the snapshot, readonly, and answered through resume. +const interrupts: readonly AgentInterrupt[] | undefined = snapshot.interrupts; +const interruptValue: PlainValue = interrupts?.[0]?.value; +// @ts-expect-error pending interrupts are readonly +interrupts?.push({ id: 'i' }); +// @ts-expect-error an interrupt's fields are readonly +if (interrupts?.[0]) interrupts[0].id = 'other'; +const resolved: AgentInterruptResponse = { + interruptId: 'i', + status: 'resolved', + value: { approved: true }, +}; +const cancelled: AgentInterruptResponse = { + interruptId: 'i', + status: 'cancelled', +}; +// @ts-expect-error a cancelled response carries no value +const cancelledWithValue: AgentInterruptResponse = { + interruptId: 'i', + status: 'cancelled', + value: 1, +}; +// @ts-expect-error a response names its interrupt +const unnamed: AgentInterruptResponse = { status: 'resolved' }; +const unsendable: AgentInterruptResponse = { + interruptId: 'i', + status: 'resolved', + // @ts-expect-error a response value is plain data + value: new Date(), +}; +// resume is optional and reports the continued run's outcome, like submit. +const resumed: Promise | undefined = session.resume?.( + [resolved, cancelled], + { signal: new AbortController().signal } +); +// @ts-expect-error resume takes the responses as a list +session.resume?.(resolved); +// A session with no resume command is still an AgentSession. +const cannotPause: AgentSession = { + getSnapshot: () => snapshot, + subscribe: () => () => undefined, + submit: async () => 'success', + stop: async () => undefined, + dispose: async () => undefined, +}; +void [ + interruptValue, + cancelledWithValue, + unnamed, + unsendable, + resumed, + cannotPause, +]; + +// Child agents: optional on the snapshot, each with its own readonly transcript. +const subagents: readonly AgentSubagent[] | undefined = snapshot.subagents; +const childMessages: readonly Message[] | undefined = subagents?.[0]?.messages; +const childCalls: readonly ToolCall[] | undefined = subagents?.[0]?.toolCalls; +const childStatus: AgentSubagentStatus | undefined = subagents?.[0]?.status; +// @ts-expect-error pending is a tool call status, not a child agent status +const invalidChildStatus: AgentSubagentStatus = 'pending'; +// @ts-expect-error a child's messages are readonly +subagents?.[0]?.messages.push(); +// @ts-expect-error a child agent needs its transcript +const bare: AgentSubagent = { id: 'c', status: 'running' }; +// A session typed with authored tools reports the same child shape. +declare const authored: AgentSnapshot<{ + weather: { args: { city: string }; result: { temp: number } }; +}>; +const authoredChildren: readonly AgentSubagent[] | undefined = + authored.subagents; +void [ + childMessages, + childCalls, + childStatus, + invalidChildStatus, + bare, + authoredChildren, +]; diff --git a/libs/core/src/contracts/interrupt.ts b/libs/core/src/contracts/interrupt.ts new file mode 100644 index 000000000..274c34f6a --- /dev/null +++ b/libs/core/src/contracts/interrupt.ts @@ -0,0 +1,38 @@ +import type { PlainValue } from './tool.js'; + +/** + * One thing a paused run is waiting on, such as an approval or a missing + * answer. A run that paused reports its interrupts in the snapshot and settles + * with the `'paused'` outcome; `resume` answers them. + */ +export interface AgentInterrupt { + /** Names this interrupt in a response. Unique among the pending interrupts. */ + readonly id: string; + /** + * What the backend sent with the pause, as frozen plain data. Its shape + * belongs to the agent that paused, so a view narrows it before rendering. + */ + readonly value?: PlainValue; + /** The kind of pause in the backend's own words, such as `tool_approval`. */ + readonly reason?: string; + /** Display text the backend supplied for the person answering. */ + readonly message?: string; + /** The tool call this pause is about, when the backend relates the two. */ + readonly toolCallId?: string; +} + +/** + * The answer to one pending interrupt. `resolved` continues the paused work + * with `value`; `cancelled` declines it and carries no value. + */ +export type AgentInterruptResponse = + | { + readonly interruptId: string; + readonly status: 'resolved'; + readonly value?: PlainValue; + } + | { + readonly interruptId: string; + readonly status: 'cancelled'; + readonly value?: never; + }; diff --git a/libs/core/src/contracts/plan.spec.ts b/libs/core/src/contracts/plan.spec.ts index fa69fb6d6..42c282254 100644 --- a/libs/core/src/contracts/plan.spec.ts +++ b/libs/core/src/contracts/plan.spec.ts @@ -18,7 +18,10 @@ describe('agentPlanFromState', () => { { label: 'Write', status: 'pending' }, ]); }); - it.each([undefined, null, 'x', {}, { todos: 'no' }])('is undefined without a todos list (%s)', (state) => { - expect(agentPlanFromState(state)).toBeUndefined(); - }); + it.each([undefined, null, 'x', {}, { todos: 'no' }])( + 'is undefined without a todos list (%s)', + (state) => { + expect(agentPlanFromState(state)).toBeUndefined(); + } + ); }); diff --git a/libs/core/src/contracts/subagent.ts b/libs/core/src/contracts/subagent.ts new file mode 100644 index 000000000..582f970db --- /dev/null +++ b/libs/core/src/contracts/subagent.ts @@ -0,0 +1,31 @@ +import type { Message } from './message.js'; +import type { ToolCall } from './tool.js'; + +/** + * Where a child agent stands. `unknown` means the session saw it start and saw + * no ending, and no run is active that could still report one. + */ +export type AgentSubagentStatus = 'running' | 'complete' | 'error' | 'unknown'; + +/** + * A child agent the root agent started, with the transcript it produced. Its + * messages and tool calls are held here and are not repeated in the root + * snapshot's `messages` and `toolCalls`. + */ +export interface AgentSubagent { + /** Stable for the life of the session. */ + readonly id: string; + readonly name?: string; + /** The task the child was given, in the root agent's words. */ + readonly description?: string; + /** The root tool call that started this child, when the backend relates the two. */ + readonly toolCallId?: string; + /** The `id` of the child that started this one; absent for a child of the root agent. */ + readonly parentId?: string; + readonly status: AgentSubagentStatus; + readonly messages: readonly Message[]; + /** The child's own tool calls, referenced by `Message.toolCallIds` in `messages`. */ + readonly toolCalls: readonly ToolCall[]; + /** Display text for the failure when `status` is `'error'` and the backend gave one. */ + readonly error?: string; +} diff --git a/libs/core/src/index.ts b/libs/core/src/index.ts index 532090b42..9493f3851 100644 --- a/libs/core/src/index.ts +++ b/libs/core/src/index.ts @@ -21,6 +21,14 @@ export type { StateTypeCheck, StateWitness, } from './contracts/state.js'; +export type { + AgentInterrupt, + AgentInterruptResponse, +} from './contracts/interrupt.js'; +export type { + AgentSubagent, + AgentSubagentStatus, +} from './contracts/subagent.js'; export type { AgentPlanStep } from './contracts/plan.js'; export { agentPlanFromState } from './contracts/plan.js'; export type { Message, Role } from './contracts/message.js'; diff --git a/libs/core/src/testing/fake-agent-session.spec.ts b/libs/core/src/testing/fake-agent-session.spec.ts index eaddf47bf..c5c57fd87 100644 --- a/libs/core/src/testing/fake-agent-session.spec.ts +++ b/libs/core/src/testing/fake-agent-session.spec.ts @@ -307,4 +307,159 @@ describe('createFakeAgentSession', () => { ).rejects.toThrow(/does not match its schema/); expect(fake.session.getSnapshot().messages).toHaveLength(0); }); + + it('publishes interrupts and removes the ones a resume answers', async () => { + const fake = createFakeAgentSession(); + expect('interrupts' in fake.session.getSnapshot()).toBe(false); + const value = { tool: 'send_email', args: { to: 'ada@example.com' } }; + fake.setInterrupts([ + { id: 'i1', value, reason: 'tool_approval', toolCallId: 'c1' }, + { id: 'i2', message: 'Which account?' }, + ]); + const pending = fake.session.getSnapshot().interrupts; + expect(pending).toEqual([ + { id: 'i1', value, reason: 'tool_approval', toolCallId: 'c1' }, + { id: 'i2', message: 'Which account?' }, + ]); + expect(Object.isFrozen(pending)).toBe(true); + expect(pending?.[0].value).not.toBe(value); + expect(Object.isFrozen(pending?.[0].value)).toBe(true); + + const notify = vi.fn(); + fake.session.subscribe(notify); + const signal = new AbortController().signal; + await expect( + fake.session.resume?.( + [{ interruptId: 'i1', status: 'resolved', value: { approved: true } }], + { signal } + ) + ).resolves.toBe('paused'); + expect(notify).toHaveBeenCalledTimes(1); + expect(fake.session.getSnapshot().interrupts).toEqual([ + { id: 'i2', message: 'Which account?' }, + ]); + await expect( + fake.session.resume?.([{ interruptId: 'i2', status: 'cancelled' }]) + ).resolves.toBe('success'); + expect(fake.session.getSnapshot().interrupts).toEqual([]); + expect(fake.resumes).toEqual([ + { + responses: [ + { interruptId: 'i1', status: 'resolved', value: { approved: true } }, + ], + options: { signal }, + }, + { responses: [{ interruptId: 'i2', status: 'cancelled' }] }, + ]); + fake.setInterrupts(undefined); + expect('interrupts' in fake.session.getSnapshot()).toBe(false); + }); + + it('rejects a resume that names no pending interrupt, or one twice', async () => { + const fake = createFakeAgentSession({ interrupts: [{ id: 'i1' }] }); + const before = fake.session.getSnapshot(); + await expect( + fake.session.resume?.([{ interruptId: 'other', status: 'resolved' }]) + ).rejects.toThrow('No pending interrupt has the id "other".'); + await expect( + fake.session.resume?.([ + { interruptId: 'i1', status: 'resolved' }, + { interruptId: 'i1', status: 'cancelled' }, + ]) + ).rejects.toThrow('The interrupt "i1" is answered twice.'); + expect(fake.session.getSnapshot()).toBe(before); + expect(fake.resumes).toHaveLength(2); + await fake.session.dispose(); + await expect( + fake.session.resume?.([{ interruptId: 'i1', status: 'resolved' }]) + ).rejects.toThrow(/disposed/); + }); + + it('lets a resume handler continue the run and choose the outcome', async () => { + const fake = createFakeAgentSession({ + interrupts: [{ id: 'i1' }], + onResume: (responses, controls) => { + controls.push({ role: 'assistant', content: responses[0].status }); + return 'error'; + }, + }); + await expect( + fake.session.resume?.([{ interruptId: 'i1', status: 'resolved' }]) + ).resolves.toBe('error'); + expect(fake.session.getSnapshot().messages.at(-1)?.content).toBe( + 'resolved' + ); + fake.setInterrupts([{ id: 'i2' }]); + fake.onResume(() => { + throw new Error('refused'); + }); + await expect( + fake.session.resume?.([{ interruptId: 'i2', status: 'resolved' }]) + ).rejects.toThrow('refused'); + fake.setInterrupts([{ id: 'i3' }]); + fake.onResume(undefined); + await expect( + fake.session.resume?.([{ interruptId: 'i3', status: 'resolved' }]) + ).resolves.toBe('success'); + }); + + it('publishes child agents with owned transcripts', () => { + const fake = createFakeAgentSession(); + expect('subagents' in fake.session.getSnapshot()).toBe(false); + fake.setSubagents([ + { + id: 'child-1', + name: 'researcher', + description: 'Find three sources', + toolCallId: 'c1', + status: 'running', + messages: [ + { role: 'assistant', content: 'Searching', toolCallIds: ['s1'] }, + ], + toolCalls: [ + { id: 's1', name: 'search', args: { q: 'tides' }, status: 'running' }, + ], + }, + { id: 'child-2', parentId: 'child-1' }, + ]); + const [first, second] = fake.session.getSnapshot().subagents ?? []; + expect(first).toMatchObject({ + id: 'child-1', + name: 'researcher', + description: 'Find three sources', + toolCallId: 'c1', + status: 'running', + }); + expect(first.messages).toEqual([ + { + id: 'fake-assistant-1', + role: 'assistant', + content: 'Searching', + toolCallIds: ['s1'], + delivery: { + generation: 'fake-assistant-1', + phase: 'complete', + outcome: 'success', + }, + }, + ]); + expect(first.toolCalls).toEqual([ + { id: 's1', name: 'search', args: { q: 'tides' }, status: 'running' }, + ]); + expect(second).toEqual({ + id: 'child-2', + parentId: 'child-1', + status: 'complete', + messages: [], + toolCalls: [], + }); + expect(Object.isFrozen(first)).toBe(true); + expect(Object.isFrozen(first.messages)).toBe(true); + // Root changes keep the children by reference. + fake.push({ role: 'assistant', content: 'Done' }); + expect(fake.session.getSnapshot().subagents?.[0]).toBe(first); + expect(fake.session.getSnapshot().messages).toHaveLength(1); + fake.set({ subagents: undefined }); + expect('subagents' in fake.session.getSnapshot()).toBe(false); + }); }); diff --git a/libs/core/src/testing/fake-agent-session.ts b/libs/core/src/testing/fake-agent-session.ts index 4e660045f..6d244f75d 100644 --- a/libs/core/src/testing/fake-agent-session.ts +++ b/libs/core/src/testing/fake-agent-session.ts @@ -13,7 +13,15 @@ import { } from '../contracts/delivery.js'; import { projectAgentError, type AgentError } from '../contracts/error.js'; import type { Message } from '../contracts/message.js'; +import type { + AgentInterrupt, + AgentInterruptResponse, +} from '../contracts/interrupt.js'; import type { AgentPlanStep } from '../contracts/plan.js'; +import type { + AgentSubagent, + AgentSubagentStatus, +} from '../contracts/subagent.js'; import { readState, type AgentStateUpdate, @@ -32,9 +40,20 @@ export type FakeMessageInput = Omit & { readonly delivery?: MessageDelivery; }; +/** A child agent to place in a fake snapshot. The status defaults to + * `'complete'`, and its messages take the same defaults as root messages. */ +export type FakeSubagentInput = Omit< + AgentSubagent, + 'status' | 'messages' | 'toolCalls' +> & { + readonly status?: AgentSubagentStatus; + readonly messages?: readonly FakeMessageInput[]; + readonly toolCalls?: readonly ToolCall[]; +}; + /** Snapshot fields a test may replace. Omitted fields keep their value; an - * explicit `error: undefined`, `plan: undefined` or `state: undefined` removes - * the field. `state` replaces the whole state and is checked against the + * explicit `undefined` for `error`, `plan`, `state`, `interrupts` or + * `subagents` removes the field. `state` replaces the whole state and is checked against the * session's `stateType` when that is a schema. */ export interface FakeAgentSnapshotPatch< TTools extends { [K in keyof TTools]: ToolContract } = Record< @@ -49,8 +68,34 @@ export interface FakeAgentSnapshotPatch< readonly error?: AgentError; readonly plan?: readonly AgentPlanStep[]; readonly state?: NoInfer | DeepReadonly>; + readonly interrupts?: readonly AgentInterrupt[]; + readonly subagents?: readonly FakeSubagentInput[]; } +/** One recorded call to `session.resume`. */ +export interface FakeResumeCall { + readonly responses: readonly AgentInterruptResponse[]; + readonly options?: AgentSubmitOptions; +} + +/** + * Runs after the fake removes the answered interrupts from the snapshot. + * Return the outcome `resume` resolves with; nothing means `'paused'` while + * interrupts remain and `'success'` otherwise. Throwing rejects `resume` with + * that error. + */ +export type FakeResumeHandler< + TTools extends { [K in keyof TTools]: ToolContract } = Record< + string, + ToolContract + >, + TState = unknown +> = ( + responses: readonly AgentInterruptResponse[], + fake: FakeAgentSession, + options?: AgentSubmitOptions +) => CompleteOutcome | void | PromiseLike; + /** One recorded call to `session.submit`. */ export interface FakeSubmitCall { readonly input: AgentSubmitInput; @@ -90,6 +135,7 @@ export interface FakeAgentSessionInit< */ readonly stateType?: StateDeclaration; readonly onSubmit?: FakeSubmitHandler; + readonly onResume?: FakeResumeHandler; } /** An assistant message that receives text until it completes. */ @@ -114,6 +160,8 @@ export interface FakeAgentSession< readonly session: AgentSession; /** Submissions in call order, including ones the handler rejected. */ readonly submits: readonly FakeSubmitCall[]; + /** Resumes in call order, including ones the fake or the handler rejected. */ + readonly resumes: readonly FakeResumeCall[]; readonly stopCount: number; readonly disposed: boolean; /** Replaces the listed snapshot fields and notifies subscribers once. */ @@ -127,6 +175,10 @@ export interface FakeAgentSession< setToolCalls(toolCalls: readonly ToolCall[]): void; /** Replaces the state; `undefined` removes it. Throws when a schema `stateType` rejects it. */ setState(state: NoInfer | undefined): void; + /** Replaces the pending interrupts; `undefined` removes the field. */ + setInterrupts(interrupts: readonly AgentInterrupt[] | undefined): void; + /** Replaces the child agents; `undefined` removes the field. */ + setSubagents(subagents: readonly FakeSubagentInput[] | undefined): void; /** Starts a streaming assistant message and sets status `'running'`. */ stream(options?: { readonly id?: string; @@ -134,6 +186,8 @@ export interface FakeAgentSession< }): FakeAssistantStream; /** Replaces the handler used by later submissions. */ onSubmit(handler: FakeSubmitHandler | undefined): void; + /** Replaces the handler used by later resumes. */ + onResume(handler: FakeResumeHandler | undefined): void; } const owned = new WeakSet(); @@ -167,6 +221,10 @@ function own(value: T, ancestors = new Set()): T { * submitted state into the snapshot's state, and resolves `'success'`. Pass * `onSubmit` to stream a reply or return another outcome. * + * `resume` records the call, removes the interrupts it answers and resolves + * `'success'`, or `'paused'` while others remain. It rejects a response that + * names an interrupt the snapshot does not list, or names one twice. + * * @example * ```ts * const fake = createFakeAgentSession({ @@ -195,6 +253,8 @@ export function createFakeAgentSession< readonly error?: AgentError; readonly plan?: readonly AgentPlanStep[]; readonly state?: DeepReadonly; + readonly interrupts?: readonly AgentInterrupt[]; + readonly subagents?: readonly AgentSubagent[]; }; const checkState = (value: unknown): DeepReadonly => { const reading = readState(init.stateType as StateDeclaration, value); @@ -215,6 +275,15 @@ export function createFakeAgentSession< delivery: input.delivery ?? staticDelivery(id), }); }; + const ownSubagent = (input: FakeSubagentInput): AgentSubagent => { + if (owned.has(input)) return input as AgentSubagent; + return own({ + ...input, + status: input.status ?? 'complete', + messages: (input.messages ?? []).map(ownMessage), + toolCalls: input.toolCalls ?? [], + }); + }; const build = ( base: Snapshot | undefined, patch: FakeAgentSnapshotPatch @@ -226,6 +295,8 @@ export function createFakeAgentSession< error?: AgentError; plan?: readonly AgentPlanStep[]; state?: DeepReadonly; + interrupts?: readonly AgentInterrupt[]; + subagents?: readonly AgentSubagent[]; } = { status: patch.status ?? base?.status ?? 'idle', messages: patch.messages @@ -249,13 +320,23 @@ export function createFakeAgentSession< : checkState(patch.state) : base?.state; if (state !== undefined) next.state = state; + const interrupts = + 'interrupts' in patch ? patch.interrupts : base?.interrupts; + if (interrupts) next.interrupts = own(interrupts); + const subagents = + 'subagents' in patch + ? patch.subagents && own(patch.subagents.map(ownSubagent)) + : base?.subagents; + if (subagents) next.subagents = subagents; return Object.freeze(next); }; let snapshot = build(undefined, init); let handler = init.onSubmit; const listeners = new Set<() => void>(); + let resumeHandler = init.onResume; const submits: FakeSubmitCall[] = []; + const resumes: FakeResumeCall[] = []; const streams = new Set<() => void>(); let stopCount = 0; let disposed = false; @@ -307,6 +388,37 @@ export function createFakeAgentSession< const outcome = await handler?.(input, fake, options); return outcome ?? 'success'; }, + async resume( + responses: readonly AgentInterruptResponse[], + options?: AgentSubmitOptions + ): Promise { + const answers = own([...responses]); + resumes.push( + Object.freeze( + options ? { responses: answers, options } : { responses: answers } + ) + ); + if (disposed) throw new Error('The fake agent session is disposed.'); + const pending = snapshot.interrupts ?? []; + const answered = new Set(); + for (const { interruptId } of answers) { + if (!pending.some((interrupt) => interrupt.id === interruptId)) + throw new TypeError( + `No pending interrupt has the id "${interruptId}".` + ); + if (answered.has(interruptId)) + throw new TypeError( + `The interrupt "${interruptId}" is answered twice.` + ); + answered.add(interruptId); + } + const remaining = pending.filter( + (interrupt) => !answered.has(interrupt.id) + ); + if (answered.size > 0) publish({ interrupts: remaining }); + const outcome = await resumeHandler?.(answers, fake, options); + return outcome ?? (remaining.length > 0 ? 'paused' : 'success'); + }, async stop() { stopCount++; for (const abort of [...streams]) abort(); @@ -321,6 +433,7 @@ export function createFakeAgentSession< const fake: FakeAgentSession = { session: session as unknown as AgentSession, submits, + resumes, get stopCount() { return stopCount; }, @@ -345,6 +458,8 @@ export function createFakeAgentSession< ), setToolCalls: (toolCalls) => publish({ toolCalls }), setState: (state) => publish({ state }), + setInterrupts: (interrupts) => publish({ interrupts }), + setSubagents: (subagents) => publish({ subagents }), stream(options = {}) { const id = options.id ?? nextId('assistant'); let open = true; @@ -386,6 +501,9 @@ export function createFakeAgentSession< onSubmit(next) { handler = next; }, + onResume(next) { + resumeHandler = next; + }, }; return fake; } diff --git a/libs/core/src/testing/fake-agent-session.type-test.ts b/libs/core/src/testing/fake-agent-session.type-test.ts index 2b4c93037..0e7ba5258 100644 --- a/libs/core/src/testing/fake-agent-session.type-test.ts +++ b/libs/core/src/testing/fake-agent-session.type-test.ts @@ -60,3 +60,28 @@ const explicitDraft: string | undefined = explicit.session.getSnapshot().state?.draft; const anySession: AgentSession = stateful.session; void [statefulSession, todos, explicitDraft, anySession]; + +// Interrupts, child agents and resume use the core shapes. +const pausing = createFakeAgentSession({ + interrupts: [{ id: 'i1', value: { tool: 'send' } }], + subagents: [ + { id: 'child', messages: [{ role: 'assistant', content: 'Hi' }] }, + ], + onResume: (responses, fake) => { + const first: string = responses[0].interruptId; + fake.setInterrupts(undefined); + void first; + return 'success'; + }, +}); +pausing.setInterrupts([{ id: 'i2' }]); +// @ts-expect-error an interrupt needs an id +pausing.setInterrupts([{ value: 1 }]); +pausing.setSubagents([{ id: 'child', status: 'unknown' }]); +// @ts-expect-error a child agent status is one of the four contract values +pausing.setSubagents([{ id: 'child', status: 'pending' }]); +// @ts-expect-error a resume handler returns an outcome +pausing.onResume(() => 'done'); +const firstResume: string | undefined = + pausing.resumes[0]?.responses[0]?.interruptId; +void firstResume; diff --git a/libs/core/src/testing/index.ts b/libs/core/src/testing/index.ts index fb3da6906..51cb7df39 100644 --- a/libs/core/src/testing/index.ts +++ b/libs/core/src/testing/index.ts @@ -5,6 +5,9 @@ export type { FakeAgentSnapshotPatch, FakeAssistantStream, FakeMessageInput, + FakeResumeCall, + FakeResumeHandler, + FakeSubagentInput, FakeSubmitCall, FakeSubmitHandler, } from './fake-agent-session.js'; diff --git a/libs/langgraph/src/runtime/README.md b/libs/langgraph/src/runtime/README.md index 47eec1866..25922cba9 100644 --- a/libs/langgraph/src/runtime/README.md +++ b/libs/langgraph/src/runtime/README.md @@ -339,6 +339,20 @@ Disposal releases every listener and later subscriptions are inert. ## Dynamic pauses +Every interrupt in the snapshot's `interrupts` has the `id` a response names: the +backend's id when it sent one, `breakpoint` for a static breakpoint, and the +position (`interrupt-0`) otherwise. The wire metadata stays alongside. Child +observations in `subgraphs` keep the wire shape, where `id` is optional. + +`resume(responses)` is the core contract's command. Each response names one pending +interrupt and has the status `resolved`. With one interrupt pending, its response's +`value` is sent as the resume value, and a response with no value sends no command. +With several pending, the answered ones are sent as one map keyed by backend id, so +each needs an id the backend sent and a value; the others stay pending. `resume` +rejects without sending when a response names an interrupt that is not pending, +names one twice, or is `cancelled`: LangGraph has no cancelled response, so a +refusal is a value the graph reads. + Branch resume reads the exact retained pause before sending a decision. Task and interrupt identities, payloads and unconsumed task results must match. Undefined does not mean replay; pass an explicit defined response, including null where diff --git a/libs/langgraph/src/runtime/checkpoint-execution.spec.ts b/libs/langgraph/src/runtime/checkpoint-execution.spec.ts index a8ae80b6e..6e2282e83 100644 --- a/libs/langgraph/src/runtime/checkpoint-execution.spec.ts +++ b/libs/langgraph/src/runtime/checkpoint-execution.spec.ts @@ -11,6 +11,7 @@ import { position, saved, } from './testing/checkpoint-fixture'; +import { answerPending } from './testing/answer-pending'; describe('checkpoint execution', () => { it.each([ @@ -121,7 +122,7 @@ describe('checkpoint execution', () => { }); expect(await session.fork(position('a'), 'Run')).toBe('paused'); expect(handler).toHaveBeenCalledOnce(); - expect(await session.resume(null)).toBe('success'); + expect(await session.resume(answerPending(session, null))).toBe('success'); expect(vi.mocked(f.transport.stream).mock.calls[1][4]?.checkpoint).toEqual( position('tools') ); @@ -356,7 +357,7 @@ describe('checkpoint execution', () => { expect(await session.fork(position('a'), 'Pause')).toBe('paused'); const before = session.getSnapshot(); const reads = vi.mocked(f.transport.getState!).mock.calls.length; - await expect(session.resume()).rejects.toThrow(); + await expect(session.resume(answerPending(session))).rejects.toThrow(); expect(f.transport.getState).toHaveBeenCalledTimes(reads); f.states.set( 'pause', @@ -365,7 +366,9 @@ describe('checkpoint execution', () => { tasks: [{ ...tasks[0], result: { decision: true } }], }) ); - await expect(session.resume(null)).rejects.toThrow(); + await expect( + session.resume(answerPending(session, null)) + ).rejects.toThrow(); expect(session.getSnapshot()).toBe(before); expect(f.transport.stream).toHaveBeenCalledTimes(1); }); @@ -399,9 +402,11 @@ describe('checkpoint execution', () => { }); expect(await session.fork(position('a'), 'Pause')).toBe('paused'); const external = new AbortController(); - expect(await session.resume(null, { signal: external.signal })).toBe( - 'success' - ); + expect( + await session.resume(answerPending(session, null), { + signal: external.signal, + }) + ).toBe('success'); const stream = vi.mocked(f.transport.stream).mock.calls[1]; expect(stream[2]).toBeNull(); expect(stream[4]).toMatchObject({ diff --git a/libs/langgraph/src/runtime/checkpoint-history.spec.ts b/libs/langgraph/src/runtime/checkpoint-history.spec.ts index e658d80c1..d86358e3c 100644 --- a/libs/langgraph/src/runtime/checkpoint-history.spec.ts +++ b/libs/langgraph/src/runtime/checkpoint-history.spec.ts @@ -3,6 +3,7 @@ import { assert, describe, expect, it, vi } from 'vitest'; import { createSession } from './create-session'; import type { AgentTransport } from './transport.types'; import { deferred } from './testing/deferred'; +import { answerPending } from './testing/answer-pending'; function checkpoint(id: string | null = 'latest'): ThreadState { return { @@ -59,7 +60,9 @@ describe('explicit checkpoint history observation', () => { }); expect(await f.session.submit('Go')).toBe('paused'); await f.session.stop(); - expect(await f.session.resume(true)).toBe('success'); + expect(await f.session.resume(answerPending(f.session, true))).toBe( + 'success' + ); await f.session.dispose(); expect(snapshots.length).toBeGreaterThan(2); expect(snapshots.every((snapshot) => snapshot.history === page)).toBe(true); diff --git a/libs/langgraph/src/runtime/checkpoint-persistence.spec.ts b/libs/langgraph/src/runtime/checkpoint-persistence.spec.ts index 4545d2646..3a60fc29a 100644 --- a/libs/langgraph/src/runtime/checkpoint-persistence.spec.ts +++ b/libs/langgraph/src/runtime/checkpoint-persistence.spec.ts @@ -12,6 +12,7 @@ import { position, saved, } from './testing/checkpoint-fixture'; +import { answerPending } from './testing/answer-pending'; const drain = () => new Promise((resolve) => setImmediate(resolve)); function persistenceFixture() { @@ -139,7 +140,7 @@ describe('checkpoint persistence', () => { for (const command of [ () => f.session.submit('Next'), () => f.session.fork(position('a'), 'Fork'), - () => f.session.resume(null), + () => f.session.resume(answerPending(f.session, null)), () => f.session.load?.(), () => f.session.checkStatus?.(), () => f.session.reconnect(), diff --git a/libs/langgraph/src/runtime/checkpoint-tool-evidence.spec.ts b/libs/langgraph/src/runtime/checkpoint-tool-evidence.spec.ts index b16180e01..6bbfb0b28 100644 --- a/libs/langgraph/src/runtime/checkpoint-tool-evidence.spec.ts +++ b/libs/langgraph/src/runtime/checkpoint-tool-evidence.spec.ts @@ -7,6 +7,7 @@ import { position, saved, } from './testing/checkpoint-fixture'; +import { answerPending } from './testing/answer-pending'; const call = { type: 'ai', @@ -254,7 +255,9 @@ describe('branch-owned local tool settlement', () => { content: 'ACTUAL RESULT', }); if (load) await session.load?.(); - expect(await session.resume(null)).toBe('success'); + expect(await session.resume(answerPending(session, null))).toBe( + 'success' + ); expect(handler).toHaveBeenCalledOnce(); expect(f.transport.stream).toHaveBeenCalledTimes(3); await session.dispose(); @@ -322,7 +325,9 @@ describe('branch-owned local tool settlement', () => { }); expect(await session.fork(position('a'), 'Run')).toBe('paused'); await session.load?.(); - expect(await session.resume(null)).toBe('interrupted'); + expect(await session.resume(answerPending(session, null))).toBe( + 'interrupted' + ); expect(session.getSnapshot().error?.message).toContain( 'identity conflict' ); diff --git a/libs/langgraph/src/runtime/create-session.ts b/libs/langgraph/src/runtime/create-session.ts index 56ee861d3..f0b282841 100644 --- a/libs/langgraph/src/runtime/create-session.ts +++ b/libs/langgraph/src/runtime/create-session.ts @@ -5,6 +5,7 @@ import { type InferState, type StateDeclaration, type AgentError, + type AgentInterruptResponse, type AgentSession, type AgentSessionCustomEvent, type CompleteOutcome, @@ -37,15 +38,17 @@ import { } from './history-projection.js'; import { projectCheckpointHistory } from './checkpoint-history.js'; import type { - LangGraphInterrupt, + LangGraphWireInterrupt, LangGraphSnapshot, LangGraphState, LangGraphSubgraph, } from './langgraph-snapshot.js'; import { projectHistoryValues, projectValues } from './values-projection.js'; import { + identifyInterrupts, projectHistoryInterrupts, projectInterrupts, + resumeValue, } from './interrupt-projection.js'; import { ownMessage, ownValue } from './ownership.js'; import { @@ -158,7 +161,7 @@ export type LangGraphSession< ToolContract >, TState = unknown -> = Omit, 'getSnapshot' | 'submit'> & { +> = Omit, 'getSnapshot' | 'submit' | 'resume'> & { getSnapshot(): LangGraphSnapshot; /** The session's thread: the given `threadId`, or the thread it created on * the first submit. Undefined until that thread exists. */ @@ -175,8 +178,14 @@ export type LangGraphSession< reconnect(options?: { readonly signal?: AbortSignal; }): Promise; + /** + * Answers pending interrupts and continues the paused graph. One pending + * interrupt receives its response's value as the resume value. Several are + * answered by backend id, each with a value. LangGraph has no cancelled + * response: a refusal is a value the graph reads. + */ resume( - value?: PlainValue, + responses: readonly AgentInterruptResponse[], options?: LangGraphRunOptions ): Promise; load?(options?: { readonly signal?: AbortSignal }): Promise; @@ -211,7 +220,7 @@ type AttemptInput = readonly kind: 'resume'; readonly value: PlainValue | undefined; /** The pending interrupts this decision answers, for history reconciliation. */ - readonly interrupts: readonly LangGraphInterrupt[]; + readonly interrupts: readonly LangGraphWireInterrupt[]; }; interface PhysicalRun { @@ -253,11 +262,11 @@ interface Attempt { * by id and payload. Ids alone are not enough: a node that pauses again can * reuse its deterministic id with a different question. */ function sameInterrupts( - current: readonly LangGraphInterrupt[], - answered: readonly LangGraphInterrupt[] + current: readonly LangGraphWireInterrupt[], + answered: readonly LangGraphWireInterrupt[] ): boolean { if (current.length !== answered.length) return false; - const key = (interrupt: LangGraphInterrupt) => + const key = (interrupt: LangGraphWireInterrupt) => JSON.stringify([interrupt.id ?? null, interrupt.value ?? null]); const keys = answered.map(key); return current.every((interrupt) => keys.includes(key(interrupt))); @@ -489,7 +498,7 @@ export function createSession( } const lifecycle = createLifecycleRecorder(); let values: LangGraphState | undefined; - let interrupts: readonly LangGraphInterrupt[] = + let interrupts: readonly LangGraphWireInterrupt[] = publication.getSnapshot().interrupts; let owner: Attempt | undefined; let recoveryAttempt: Attempt | undefined; @@ -671,7 +680,7 @@ export function createSession( state: reading.state, ...(reading.issues ? { stateIssues: reading.issues } : {}), ...(plan ? { plan } : {}), - interrupts, + interrupts: identifyInterrupts(interrupts), subgraphs: timedSubgraphs(subgraphs.subgraphs), ...(retained?.run.evidence.runId ? { reconnect: { runId: retained.run.evidence.runId } } @@ -1878,7 +1887,7 @@ export function createSession( } function resume( - value?: PlainValue, + responses: readonly AgentInterruptResponse[], options?: LangGraphRunOptions ): Promise { let attempt: Attempt | undefined; @@ -1916,6 +1925,7 @@ export function createSession( throw new Error('Resume requires an observed interrupt.'); }; admit(); + const value = resumeValue(responses, interrupts); if (branch && value === undefined) throw new Error('Branch resume requires a defined response value.'); const captured = ownValue(value); diff --git a/libs/langgraph/src/runtime/history-projection.ts b/libs/langgraph/src/runtime/history-projection.ts index 3efde3b98..79742eb9d 100644 --- a/libs/langgraph/src/runtime/history-projection.ts +++ b/libs/langgraph/src/runtime/history-projection.ts @@ -15,7 +15,7 @@ import { } from './ownership.js'; import { record, roleOf, textContent } from './wire-message.js'; import { projectHistoryInterrupts } from './interrupt-projection.js'; -import type { LangGraphInterrupt } from './langgraph-snapshot.js'; +import type { LangGraphWireInterrupt } from './langgraph-snapshot.js'; import { observeInvocation, type ToolInvocation } from './tool-invocations.js'; import { projectCitations } from './citation-projection.js'; import { projectReasoning } from './reasoning-projection.js'; @@ -26,7 +26,7 @@ export interface HistoryProjectionOptions { readonly registeredTools?: ReadonlySet; /** An aggregate caller supplies its already-owned candidate to avoid reading * transport-owned interrupt getters a second time. */ - readonly interrupts?: readonly LangGraphInterrupt[]; + readonly interrupts?: readonly LangGraphWireInterrupt[]; } function sameEntries(left: readonly unknown[], right: readonly unknown[]) { diff --git a/libs/langgraph/src/runtime/interrupt-projection.spec.ts b/libs/langgraph/src/runtime/interrupt-projection.spec.ts index c6c2115f5..f5db44908 100644 --- a/libs/langgraph/src/runtime/interrupt-projection.spec.ts +++ b/libs/langgraph/src/runtime/interrupt-projection.spec.ts @@ -1,8 +1,10 @@ import type { ThreadState } from '@langchain/langgraph-sdk'; import { describe, expect, it } from 'vitest'; import { + identifyInterrupts, projectHistoryInterrupts, projectInterrupts, + resumeValue, } from './interrupt-projection'; import type { StreamEvent } from './transport.types'; @@ -384,3 +386,142 @@ describe('interrupt projection', () => { expect(Object.isFrozen(value)).toBe(false); }); }); + +describe('published interrupt ids', () => { + it('keeps backend ids and names the rest by breakpoint or position', () => { + const wire = projectInterrupts( + [], + control([ + { id: 'approve', value: 'Proceed?', namespace: ['task'] }, + { value: 'No id' }, + { id: 'interrupt-1', value: 'Taken name' }, + ]) + ); + const published = identifyInterrupts(wire); + expect(published).toEqual([ + { id: 'approve', value: 'Proceed?', namespace: ['task'] }, + { id: 'interrupt-1-1', value: 'No id' }, + { id: 'interrupt-1', value: 'Taken name' }, + ]); + expect(published[0]).toBe(wire[0]); + expect(Object.isFrozen(published)).toBe(true); + expect(Object.isFrozen(published[1])).toBe(true); + // One wire batch has one published list. + expect(identifyInterrupts(wire)).toBe(published); + expect(identifyInterrupts(projectInterrupts([], control([])))).toEqual([ + { id: 'breakpoint', when: 'breakpoint' }, + ]); + expect( + identifyInterrupts(projectInterrupts([], control([{ value: 0 }]))) + ).toEqual([{ id: 'interrupt-0', value: 0 }]); + }); +}); + +describe('resume value', () => { + const one = projectInterrupts([], control([{ id: 'approve', value: 'Q' }])); + const several = projectInterrupts( + [], + control([{ id: 'a', value: 1 }, { id: 'b', value: 2 }, { value: 3 }]) + ); + + it('sends the response value as is for one pending interrupt', () => { + for (const value of [undefined, null, false, 0, '', { approve: true }]) + expect( + resumeValue( + [{ interruptId: 'approve', status: 'resolved', value }], + one + ) + ).toBe(value); + const breakpoint = projectInterrupts([], control([])); + expect( + resumeValue( + [{ interruptId: 'breakpoint', status: 'resolved' }], + breakpoint + ) + ).toBeUndefined(); + const unnamed = projectInterrupts([], control([{ value: 'Q' }])); + expect( + resumeValue( + [{ interruptId: 'interrupt-0', status: 'resolved', value: 'yes' }], + unnamed + ) + ).toBe('yes'); + }); + + it('answers several pending interrupts by backend id, all or some', () => { + expect( + resumeValue( + [ + { interruptId: 'b', status: 'resolved', value: { ok: true } }, + { interruptId: 'a', status: 'resolved', value: null }, + ], + several + ) + ).toEqual({ b: { ok: true }, a: null }); + expect( + resumeValue( + [{ interruptId: 'a', status: 'resolved', value: 'only' }], + several + ) + ).toEqual({ a: 'only' }); + }); + + it.each([ + [undefined, /at least one/], + [[], /at least one/], + [[null], /names its interrupt by id/], + [[{ status: 'resolved' }], /names its interrupt by id/], + [ + [{ interruptId: 'other', status: 'resolved' }], + /No pending interrupt has the id "other"/, + ], + [ + [ + { interruptId: 'approve', status: 'resolved' }, + { interruptId: 'approve', status: 'resolved' }, + ], + /"approve" is answered twice/, + ], + [ + [{ interruptId: 'approve', status: 'cancelled' }], + /cannot cancel an interrupt/, + ], + [[{ interruptId: 'approve', status: 'done' }], /status "resolved"/], + [[{ interruptId: 'approve' }], /status "resolved"/], + ])('rejects %j', (responses, message) => { + expect(() => resumeValue(responses, one)).toThrow(TypeError); + expect(() => resumeValue(responses, one)).toThrow(message); + }); + + it('rejects what a batch answered by id cannot express', () => { + expect(() => + resumeValue( + [{ interruptId: 'interrupt-2', status: 'resolved', value: 1 }], + several + ) + ).toThrow(/has no backend id/); + expect(() => + resumeValue([{ interruptId: 'a', status: 'resolved' }], several) + ).toThrow(/needs a value while several interrupts are pending/); + }); + + it('reads each response field once', () => { + const reads: string[] = []; + const response = { + get interruptId() { + reads.push('interruptId'); + return 'approve'; + }, + get status() { + reads.push('status'); + return 'resolved'; + }, + get value() { + reads.push('value'); + return 1; + }, + }; + expect(resumeValue([response], one)).toBe(1); + expect(reads).toEqual(['interruptId', 'status', 'value']); + }); +}); diff --git a/libs/langgraph/src/runtime/interrupt-projection.ts b/libs/langgraph/src/runtime/interrupt-projection.ts index 6c0294cf5..4984d9e38 100644 --- a/libs/langgraph/src/runtime/interrupt-projection.ts +++ b/libs/langgraph/src/runtime/interrupt-projection.ts @@ -1,11 +1,14 @@ import type { ThreadState } from '@langchain/langgraph-sdk'; import type { PlainValue } from '@threadplane/core'; -import type { LangGraphInterrupt } from './langgraph-snapshot.js'; +import type { + LangGraphInterrupt, + LangGraphWireInterrupt, +} from './langgraph-snapshot.js'; import { ownValue, ownValueWithSharing } from './ownership.js'; import type { StreamEvent } from './transport.types.js'; import { record } from './wire-message.js'; -type Interrupts = readonly LangGraphInterrupt[]; +type Interrupts = readonly LangGraphWireInterrupt[]; const breakpoint: Interrupts = ownValue([{ when: 'breakpoint' }]) as Interrupts; @@ -124,3 +127,79 @@ export function projectHistoryInterrupts( const latest = record(history[0]); return replace(previous, latest ? checkpointInterrupts(latest) : []); } + +const identified = new WeakMap(); + +/** The published form of a pending batch: every interrupt has the id a + * response names. A backend id is kept; a static breakpoint is `breakpoint`; + * anything else is named by position. One wire batch maps to one list. */ +export function identifyInterrupts( + interrupts: Interrupts +): readonly LangGraphInterrupt[] { + const known = identified.get(interrupts); + if (known) return known; + const taken = new Set( + interrupts.flatMap(({ id }) => (typeof id === 'string' ? [id] : [])) + ); + const published = ownValue( + interrupts.map((interrupt, index) => { + if (typeof interrupt.id === 'string') return interrupt; + let id = + interrupt.when === 'breakpoint' ? 'breakpoint' : `interrupt-${index}`; + while (taken.has(id)) id = `${id}-${index}`; + taken.add(id); + return { ...interrupt, id }; + }) as PlainValue + ) as unknown as readonly LangGraphInterrupt[]; + identified.set(interrupts, published); + return published; +} + +/** + * The value a resume command carries for these responses. One pending + * interrupt takes its response's value as is. Several are answered by backend + * id, so each answered interrupt needs an id the backend sent and a value. + */ +export function resumeValue( + responses: unknown, + pending: Interrupts +): PlainValue | undefined { + if (!Array.isArray(responses) || responses.length === 0) + throw new TypeError('Resume requires at least one interrupt response.'); + const published = identifyInterrupts(pending); + const answers = new Map(); + const length = responses.length; + for (let index = 0; index < length; index++) { + const response = record(responses[index]); + // Response getters are caller effects; read each field once. + const interruptId = response?.['interruptId']; + const status = response?.['status']; + const value = response?.['value'] as PlainValue | undefined; + if (typeof interruptId !== 'string') + throw new TypeError('An interrupt response names its interrupt by id.'); + const position = published.findIndex(({ id }) => id === interruptId); + if (position < 0) + throw new TypeError(`No pending interrupt has the id "${interruptId}".`); + if (answers.has(interruptId)) + throw new TypeError(`The interrupt "${interruptId}" is answered twice.`); + if (status === 'cancelled') + throw new TypeError( + 'LangGraph cannot cancel an interrupt. Resolve it with a value the graph reads as a refusal.' + ); + if (status !== 'resolved') + throw new TypeError('An interrupt response has the status "resolved".'); + if (pending.length > 1) { + if (pending[position].id !== interruptId) + throw new TypeError( + `The interrupt "${interruptId}" has no backend id, so it cannot be answered while others are pending.` + ); + if (value === undefined) + throw new TypeError( + `The response to "${interruptId}" needs a value while several interrupts are pending.` + ); + } + answers.set(interruptId, value); + } + if (pending.length === 1) return answers.values().next().value; + return Object.fromEntries(answers); +} diff --git a/libs/langgraph/src/runtime/interrupt-projection.type-test.ts b/libs/langgraph/src/runtime/interrupt-projection.type-test.ts index 47b0134c8..6cc0c3def 100644 --- a/libs/langgraph/src/runtime/interrupt-projection.type-test.ts +++ b/libs/langgraph/src/runtime/interrupt-projection.type-test.ts @@ -1,7 +1,10 @@ import type { Interrupt } from '@langchain/langgraph-sdk'; import type { DeepReadonly, PlainValue } from '@threadplane/core'; -import type { LangGraphInterrupt } from './langgraph-snapshot'; -import { projectInterrupts } from './interrupt-projection'; +import type { + LangGraphInterrupt, + LangGraphWireInterrupt, +} from './langgraph-snapshot'; +import { identifyInterrupts, projectInterrupts } from './interrupt-projection'; const wire: Interrupt = { id: 'approval', @@ -12,7 +15,12 @@ const wire: Interrupt = { resumable: false, }; const batch = projectInterrupts([], { type: 'interrupt', interrupt: wire }); -const interrupt: LangGraphInterrupt = batch[0]; +const interrupt: LangGraphWireInterrupt = batch[0]; +// The published form always has the id a response names. +const published: LangGraphInterrupt = identifyInterrupts(batch)[0]; +const publishedId: string = published.id; +// @ts-expect-error A wire interrupt may have no id. +const wireId: string = interrupt.id; const sdkShape: DeepReadonly = interrupt; const payload: PlainValue = interrupt.value; const metadata: readonly string[] | undefined = interrupt.namespace; @@ -34,4 +42,4 @@ if ( // @ts-expect-error Nested payload fields remain readonly. interrupt.value['changed'] = true; } -void [sdkShape, payload, metadata, request]; +void [sdkShape, payload, metadata, request, publishedId, wireId]; diff --git a/libs/langgraph/src/runtime/interruption-recovery.spec.ts b/libs/langgraph/src/runtime/interruption-recovery.spec.ts index 132567acf..defe27cc8 100644 --- a/libs/langgraph/src/runtime/interruption-recovery.spec.ts +++ b/libs/langgraph/src/runtime/interruption-recovery.spec.ts @@ -3,6 +3,7 @@ import type { Run, ThreadState } from '@langchain/langgraph-sdk'; import { createSession } from './create-session'; import { RECOVERY_COPY, failureProjection } from './stream-projection'; import type { AgentTransport, StreamEvent } from './transport.types'; +import { answerPending } from './testing/answer-pending'; const chunk = (content: string, sseId = '1'): StreamEvent => ({ type: 'messages', @@ -354,7 +355,9 @@ describe('read-only recovery for a resume attempt', () => { it('offers a status check for a dropped decision on a run still in flight and resolves it once the run ends', async () => { const f = await resumeFixture({ status: 'running' }); - expect(await f.session.resume(true)).toBe('interrupted'); + expect(await f.session.resume(answerPending(f.session, true))).toBe( + 'interrupted' + ); expect(f.getHistory).not.toHaveBeenCalled(); expect(f.session.getSnapshot()).toMatchObject({ status: 'error', @@ -384,7 +387,9 @@ describe('read-only recovery for a resume attempt', () => { it('treats the same pause with no new activity as inconclusive and lets the decision be sent again', async () => { const f = await resumeFixture({ exact: false }); - expect(await f.session.resume(true)).toBe('interrupted'); + expect(await f.session.resume(answerPending(f.session, true))).toBe( + 'interrupted' + ); expect(f.getHistory).toHaveBeenCalledTimes(1); const original = f.session.getSnapshot(); expect(original.error).toMatchObject({ recovery: 'check' }); @@ -404,7 +409,9 @@ describe('read-only recovery for a resume attempt', () => { f.stream.mockImplementation(async function* () { yield { type: 'values', data: { messages: [user, waiting, answer] } }; }); - expect(await f.session.resume(true)).toBe('success'); + expect(await f.session.resume(answerPending(f.session, true))).toBe( + 'success' + ); expect(f.session.getSnapshot().messages.at(-1)).toMatchObject({ id: 'resumed-answer', delivery: { outcome: 'success' }, @@ -415,7 +422,9 @@ describe('read-only recovery for a resume attempt', () => { it('settles as paused on a different pending interrupt reached after the decision landed', async () => { const f = await resumeFixture({ exact: false }); f.getHistory.mockResolvedValue([paused([user, waiting, answer], [again])]); - expect(await f.session.resume(true)).toBe('paused'); + expect(await f.session.resume(answerPending(f.session, true))).toBe( + 'paused' + ); expect(f.getHistory).toHaveBeenCalledTimes(1); expect(f.session.getSnapshot()).toMatchObject({ status: 'idle', @@ -432,7 +441,9 @@ describe('read-only recovery for a resume attempt', () => { f.getHistory.mockResolvedValue([ paused([user, waiting, answer], [approve]), ]); - expect(await f.session.resume(true)).toBe('paused'); + expect(await f.session.resume(answerPending(f.session, true))).toBe( + 'paused' + ); expect(f.session.getSnapshot().interrupts).toEqual([approve]); expect(f.session.getSnapshot().messages.at(-1)).toMatchObject({ id: 'resumed-answer', @@ -444,7 +455,9 @@ describe('read-only recovery for a resume attempt', () => { f.getHistory.mockResolvedValue([ paused([user, waiting], [{ id: 'approve', value: 'Really proceed?' }]), ]); - expect(await f.session.resume(true)).toBe('paused'); + expect(await f.session.resume(answerPending(f.session, true))).toBe( + 'paused' + ); expect(f.session.getSnapshot().interrupts).toEqual([ { id: 'approve', value: 'Really proceed?' }, ]); @@ -462,7 +475,9 @@ describe('read-only recovery for a resume attempt', () => { settings?.onRunCreated?.({ run_id: 'run-1', thread_id: 't' }); yield { type: 'updates', data: { __interrupt__: [again] } }; }); - expect(await f.session.resume(true)).toBe('interrupted'); + expect(await f.session.resume(answerPending(f.session, true))).toBe( + 'interrupted' + ); expect(f.session.getSnapshot()).toMatchObject({ status: 'error', error: { recovery: 'check' }, @@ -471,7 +486,9 @@ describe('read-only recovery for a resume attempt', () => { f.stream.mockImplementationOnce(async function* () { yield { type: 'values', data: { messages: [user, waiting, answer] } }; }); - expect(await f.session.resume(false)).toBe('success'); + expect(await f.session.resume(answerPending(f.session, false))).toBe( + 'success' + ); expect(f.session.getSnapshot().interrupts).toEqual([]); expect(f.stream).toHaveBeenCalledTimes(2); }); @@ -479,7 +496,9 @@ describe('read-only recovery for a resume attempt', () => { it('keeps an idle thread with no pending interrupt and no new activity inconclusive', async () => { const f = await resumeFixture({ exact: false }); f.getHistory.mockResolvedValue([paused([user, waiting], [])]); - expect(await f.session.resume(true)).toBe('interrupted'); + expect(await f.session.resume(answerPending(f.session, true))).toBe( + 'interrupted' + ); const original = f.session.getSnapshot(); expect(original.error).toMatchObject({ recovery: 'check' }); await f.session.checkStatus?.(); @@ -491,7 +510,9 @@ describe('read-only recovery for a resume attempt', () => { f.getHistory.mockResolvedValue([ paused([user, waiting, answer], [], ['generate']), ]); - expect(await f.session.resume(true)).toBe('interrupted'); + expect(await f.session.resume(answerPending(f.session, true))).toBe( + 'interrupted' + ); expect(f.session.getSnapshot().error).toMatchObject({ recovery: 'check' }); f.getHistory.mockResolvedValue([paused([user, waiting, answer], [])]); await f.session.checkStatus?.(); @@ -507,7 +528,9 @@ describe('read-only recovery for a resume attempt', () => { f.getHistory.mockResolvedValue([ paused([user, waiting, answer, newer], [], ['analyze']), ]); - expect(await f.session.resume(true)).toBe('success'); + expect(await f.session.resume(answerPending(f.session, true))).toBe( + 'success' + ); expect(f.session.getSnapshot().messages.at(-1)).toMatchObject({ id: 'resumed-answer', delivery: { outcome: 'success' }, @@ -517,7 +540,9 @@ describe('read-only recovery for a resume attempt', () => { it('disambiguates an exact interrupted status on a resumed run through history', async () => { const f = await resumeFixture({ status: 'interrupted' }); f.getHistory.mockResolvedValue([paused([user, waiting, answer], [again])]); - expect(await f.session.resume(true)).toBe('paused'); + expect(await f.session.resume(answerPending(f.session, true))).toBe( + 'paused' + ); expect(f.getHistory).toHaveBeenCalledTimes(1); expect(f.session.getSnapshot().interrupts).toEqual([again]); expect(f.session.getSnapshot().reconnect).toBeUndefined(); @@ -528,7 +553,9 @@ describe('read-only recovery for a resume attempt', () => { f.getHistory.mockResolvedValue([ paused([{ ...user, id: 'other-user' }, answer], [again]), ]); - expect(await f.session.resume(true)).toBe('interrupted'); + expect(await f.session.resume(answerPending(f.session, true))).toBe( + 'interrupted' + ); expect(f.session.getSnapshot().interrupts).toEqual([]); expect(f.session.getSnapshot().error).toMatchObject({ recovery: 'check' }); }); @@ -676,7 +703,9 @@ describe('automatic read-only recovery when the stream throws', () => { ], }, ]); - expect(await f.session.resume(true)).toBe('paused'); + expect(await f.session.resume(answerPending(f.session, true))).toBe( + 'paused' + ); expect(f.session.getSnapshot()).toMatchObject({ status: 'idle', error: undefined, diff --git a/libs/langgraph/src/runtime/interrupts.spec.ts b/libs/langgraph/src/runtime/interrupts.spec.ts index e6a389fcf..5f409c752 100644 --- a/libs/langgraph/src/runtime/interrupts.spec.ts +++ b/libs/langgraph/src/runtime/interrupts.spec.ts @@ -235,7 +235,9 @@ describe('session interrupt observation', () => { await f.emit(control([])); f.streams[0].finish(); expect(await run).toBe('paused'); - expect(f.snapshot().interrupts).toEqual([{ when: 'breakpoint' }]); + expect(f.snapshot().interrupts).toEqual([ + { id: 'breakpoint', when: 'breakpoint' }, + ]); expect(f.history).not.toHaveBeenCalled(); expect(f.acquire).not.toHaveBeenCalled(); expect(f.write).not.toHaveBeenCalled(); diff --git a/libs/langgraph/src/runtime/langgraph-snapshot.ts b/libs/langgraph/src/runtime/langgraph-snapshot.ts index eb2f9b937..1393ead24 100644 --- a/libs/langgraph/src/runtime/langgraph-snapshot.ts +++ b/libs/langgraph/src/runtime/langgraph-snapshot.ts @@ -1,4 +1,5 @@ import type { + AgentInterrupt, AgentSnapshot, AgentError, DeepReadonly, @@ -13,9 +14,18 @@ export type LangGraphHistoryEntry = DeepReadonly< Pick >; -/** Backend wire metadata and a plain payload. DeepReadonly maps the SDK's +/** An interrupt as the backend sent it: wire metadata and a plain payload, + * with an id only when the backend supplied one. DeepReadonly maps the SDK's * unknown payload to PlainValue without recursively re-mapping PlainValue. */ -export type LangGraphInterrupt = DeepReadonly; +export type LangGraphWireInterrupt = DeepReadonly; + +/** + * A pending root interrupt. `id` is the name a `resume` response uses: the + * backend's id when it sent one, `breakpoint` for a static breakpoint, and the + * position (`interrupt-0`) otherwise. The wire metadata is kept alongside. + */ +export type LangGraphInterrupt = AgentInterrupt & + Omit; /** Graph state as the backend reported it, for a session that declares no state type. */ export type LangGraphState = Readonly>; @@ -31,7 +41,7 @@ export interface LangGraphSubgraph { readonly messages: readonly Message[]; /** A child graph's state. It is never checked against the session's declaration. */ readonly state: LangGraphState | undefined; - readonly interrupts: readonly LangGraphInterrupt[]; + readonly interrupts: readonly LangGraphWireInterrupt[]; readonly error?: AgentError; } @@ -42,7 +52,7 @@ export type LangGraphSnapshot< ToolContract >, TState = unknown -> = AgentSnapshot & { +> = Omit, 'interrupts'> & { /** Last explicit history page; undefined until loaded. Not a live branch tree. */ readonly history: readonly LangGraphHistoryEntry[] | undefined; /** diff --git a/libs/langgraph/src/runtime/lazy-thread.spec.ts b/libs/langgraph/src/runtime/lazy-thread.spec.ts index a1ca40933..8c96153e2 100644 --- a/libs/langgraph/src/runtime/lazy-thread.spec.ts +++ b/libs/langgraph/src/runtime/lazy-thread.spec.ts @@ -1,6 +1,7 @@ import { afterEach, describe, expect, it, vi } from 'vitest'; import type { Run } from '@langchain/langgraph-sdk'; import { createSession } from './create-session'; +import { answerPending } from './testing/answer-pending'; import { deferred } from './testing/deferred'; import type { AgentTransport, StreamEvent } from './transport.types'; @@ -96,9 +97,9 @@ describe('a session without a thread', () => { await expect(f.session.reconnect()).rejects.toThrow( 'Reconnect requires an idle retained run' ); - await expect(f.session.resume(true)).rejects.toThrow( - 'Resume requires an observed interrupt.' - ); + await expect( + f.session.resume(answerPending(f.session, true)) + ).rejects.toThrow('Resume requires an observed interrupt.'); await expect( f.session.fork( { @@ -142,7 +143,9 @@ describe('a session without a thread', () => { f.stream.mock.invocationCallOrder[0] ); expect( - f.session.getSnapshot().messages.map(({ role, content }) => [role, content]) + f.session + .getSnapshot() + .messages.map(({ role, content }) => [role, content]) ).toEqual([ ['user', 'Hello'], ['assistant', 'Done'], @@ -247,7 +250,9 @@ describe('a session without a thread', () => { expect(f.session.threadId).toBe('second'); expect(f.onThreadId).toHaveBeenCalledWith('second'); expect( - f.session.getSnapshot().messages.map(({ role, content }) => [role, content]) + f.session + .getSnapshot() + .messages.map(({ role, content }) => [role, content]) ).toEqual([ ['user', 'Hello'], ['assistant', 'Done'], diff --git a/libs/langgraph/src/runtime/lifecycle.spec.ts b/libs/langgraph/src/runtime/lifecycle.spec.ts index c5adbe191..452ae92df 100644 --- a/libs/langgraph/src/runtime/lifecycle.spec.ts +++ b/libs/langgraph/src/runtime/lifecycle.spec.ts @@ -3,6 +3,7 @@ import type { AgentError } from '@threadplane/core'; import { afterEach, describe, expect, it, vi } from 'vitest'; import { createLifecycleRecorder } from './lifecycle'; import type { StreamEvent } from './transport.types'; +import { answerPending } from './testing/answer-pending'; import { controlledSession } from './testing/controlled-session'; import { saved } from './testing/checkpoint-fixture'; @@ -222,7 +223,7 @@ describe('lifecycle through the session', () => { }); f.at(30); f.getHistory.mockResolvedValueOnce([paused()]); - const run = f.session.resume(true); + const run = f.session.resume(answerPending(f.session, true)); await f.started(); expect(f.lifecycle().interruptResolvedAt).toBe(30); f.at(40); diff --git a/libs/langgraph/src/runtime/owned-checkpoint-stream.spec.ts b/libs/langgraph/src/runtime/owned-checkpoint-stream.spec.ts index 0d67c642f..4810d993d 100644 --- a/libs/langgraph/src/runtime/owned-checkpoint-stream.spec.ts +++ b/libs/langgraph/src/runtime/owned-checkpoint-stream.spec.ts @@ -2,6 +2,7 @@ import { afterEach, describe, expect, it, vi } from 'vitest'; import { FetchStreamTransport } from '../lib/transport/fetch-stream.transport'; import { createSession } from './create-session'; import type { AgentTransport } from './transport.types'; +import { answerPending } from './testing/answer-pending'; const modes = ['values', 'messages-tuple', 'updates', 'custom', 'checkpoints']; const legacyModes = modes.slice(0, -1); @@ -233,7 +234,9 @@ describe('owned native checkpoint stream through the real SDK', () => { const requests = server({ pause: true }); const session = native(); expect(await session.submit('Question')).toBe('paused'); - expect(await session.resume({ approve: false })).toBe('success'); + expect( + await session.resume(answerPending(session, { approve: false })) + ).toBe('success'); const posts = requests.filter((r) => r.method === 'POST'); expect(posts).toHaveLength(2); expect(posts.map((r) => r.body?.['stream_mode'])).toEqual([modes, modes]); diff --git a/libs/langgraph/src/runtime/ownership.ts b/libs/langgraph/src/runtime/ownership.ts index 33cada80e..6a6dabf7d 100644 --- a/libs/langgraph/src/runtime/ownership.ts +++ b/libs/langgraph/src/runtime/ownership.ts @@ -10,6 +10,7 @@ import { } from '@threadplane/core'; import type { LangGraphInterrupt, + LangGraphWireInterrupt, LangGraphSnapshot, LangGraphSubgraph, LangGraphState, @@ -336,9 +337,9 @@ export function ownLangGraphSnapshot( | LangGraphState | undefined; const interrupts = ownValueWithSharing( - input.interrupts, - previous?.interrupts - ) as readonly LangGraphInterrupt[]; + input.interrupts as unknown as PlainValue, + previous?.interrupts as unknown as PlainValue + ) as unknown as readonly LangGraphInterrupt[]; const reconnect = ownValueWithSharing( input.reconnect, previous?.reconnect @@ -395,7 +396,7 @@ export function ownSubgraph( const interrupts = ownValueWithSharing( input.interrupts, previous?.interrupts - ) as readonly LangGraphInterrupt[]; + ) as readonly LangGraphWireInterrupt[]; const error = sameError(input.error, previous?.error) ? previous?.error : input.error && ownError(input.error); diff --git a/libs/langgraph/src/runtime/reasoning.spec.ts b/libs/langgraph/src/runtime/reasoning.spec.ts index 462589d40..04226580f 100644 --- a/libs/langgraph/src/runtime/reasoning.spec.ts +++ b/libs/langgraph/src/runtime/reasoning.spec.ts @@ -9,6 +9,7 @@ import { position, saved, } from './testing/checkpoint-fixture'; +import { answerPending } from './testing/answer-pending'; const ai = (reasoning?: unknown, content = 'Answer') => ({ type: 'ai', @@ -201,7 +202,7 @@ describe('reasoning through actual session ownership', () => { await f.session.load!(); const paused = f.session.getSnapshot(); expect(paused.messages[0].reasoning).toBe('Paused'); - const run = f.session.resume(true); + const run = f.session.resume(answerPending(f.session, true)); await f.started(); await f.emit(delta(undefined, 'Resumed')); const current = f.session.getSnapshot().messages[0]; diff --git a/libs/langgraph/src/runtime/reconnect.spec.ts b/libs/langgraph/src/runtime/reconnect.spec.ts index 1bdedccce..702ef8258 100644 --- a/libs/langgraph/src/runtime/reconnect.spec.ts +++ b/libs/langgraph/src/runtime/reconnect.spec.ts @@ -7,6 +7,7 @@ import type { import { createSession } from './create-session'; import type { AgentTransport, StreamEvent } from './transport.types'; import { deferred } from './testing/deferred'; +import { answerPending } from './testing/answer-pending'; const chunk = (content: string, sseId?: string): StreamEvent => ({ type: 'messages', @@ -274,7 +275,9 @@ describe('owned run reconnect', () => { }; }); f.getRunStatus.mockResolvedValue('running'); - expect(await f.session.resume(null)).toBe('interrupted'); + expect(await f.session.resume(answerPending(f.session, null))).toBe( + 'interrupted' + ); const anonymous = f.session .getSnapshot() .messages.find((message) => message.content === 'Foreign'); @@ -538,7 +541,9 @@ describe('owned run reconnect', () => { const f = fixture(); await f.session.submit('Question'); await expect(f.session.load?.()).rejects.toThrow(); - await expect(f.session.resume(true)).rejects.toThrow(); + await expect( + f.session.resume(answerPending(f.session, true)) + ).rejects.toThrow(); const wait = deferred>(); const started = deferred(); f.joinStream.mockImplementation(() => ({ @@ -929,7 +934,9 @@ describe('owned run reconnect', () => { yield chunk('Resumed', 'resume-1'); }); f.getRunStatus.mockResolvedValue('running'); - expect(await f.session.resume({ approval: null })).toBe('interrupted'); + expect( + await f.session.resume(answerPending(f.session, { approval: null })) + ).toBe('interrupted'); expect(f.stream.mock.calls[1][2]).toBeNull(); expect(f.stream.mock.calls[1][4]?.command).toEqual({ resume: { approval: null }, diff --git a/libs/langgraph/src/runtime/response-identity.spec.ts b/libs/langgraph/src/runtime/response-identity.spec.ts index af6dc3285..94b7115e9 100644 --- a/libs/langgraph/src/runtime/response-identity.spec.ts +++ b/libs/langgraph/src/runtime/response-identity.spec.ts @@ -12,6 +12,7 @@ import { } from './stream-projection'; import type { StreamEvent } from './transport.types'; import { initialSubgraphs, projectSubgraphs } from './subgraph-projection'; +import { answerPending } from './testing/answer-pending'; const projection = (): StreamProjection => ({ generation: 'physical-run', @@ -611,7 +612,9 @@ it('keeps pause/resume, the next turn and fresh history on canonical IDs', async .messages.filter((m) => m.role === 'assistant') .map((m) => m.id) ).toEqual([first.id]); - await expect(session.resume({ pause: 'approved' })).resolves.toBe('success'); + await expect( + session.resume(answerPending(session, { pause: 'approved' })) + ).resolves.toBe('success'); expect( session .getSnapshot() diff --git a/libs/langgraph/src/runtime/resume.spec.ts b/libs/langgraph/src/runtime/resume.spec.ts index 1d7401945..d5ee4e23a 100644 --- a/libs/langgraph/src/runtime/resume.spec.ts +++ b/libs/langgraph/src/runtime/resume.spec.ts @@ -5,6 +5,7 @@ import { createSession, type SessionOptions } from './create-session'; import type { AgentTransport, StreamEvent } from './transport.types'; import { controlledTransport } from './testing/controlled-transport'; import { deferred } from './testing/deferred'; +import { answerPending } from './testing/answer-pending'; const human = { type: 'human', id: 'saved-user', content: 'Question' }; const saved = { type: 'ai', id: 'saved-answer', content: 'Waiting' }; @@ -105,9 +106,11 @@ describe('explicit interrupt resume', () => { const external = new AbortController(); const seen: unknown[] = []; f.session.subscribe(() => seen.push(f.session.getSnapshot())); - expect(await f.session.resume(value, { signal: external.signal })).toBe( - 'success' - ); + expect( + await f.session.resume(answerPending(f.session, value), { + signal: external.signal, + }) + ).toBe('success'); expect(f.stream).toHaveBeenCalledTimes(1); expect(f.stream.mock.calls[0].slice(0, 3)).toEqual(['a', 't', null]); expect(f.stream.mock.calls[0][3]).not.toBe(external.signal); @@ -133,10 +136,76 @@ describe('explicit interrupt resume', () => { } ); + it('publishes the id a response names and rejects responses it cannot send', async () => { + const f = await fixture(); + const before = f.session.getSnapshot(); + expect(before.interrupts).toEqual([{ id: 'approve', value: 'Proceed?' }]); + await expect( + f.session.resume([{ interruptId: 'other', status: 'resolved' }]) + ).rejects.toThrow('No pending interrupt has the id "other".'); + await expect( + f.session.resume([{ interruptId: 'approve', status: 'cancelled' }]) + ).rejects.toThrow(/cannot cancel an interrupt/); + await expect(f.session.resume([])).rejects.toThrow(/at least one/); + expect(f.session.getSnapshot()).toBe(before); + expect(f.stream).not.toHaveBeenCalled(); + expect( + await f.session.resume([ + { interruptId: 'approve', status: 'resolved', value: { ok: true } }, + ]) + ).toBe('success'); + expect(f.stream.mock.calls[0][4]).toEqual({ + command: { resume: { ok: true } }, + }); + }); + + it('answers several pending interrupts by id in one command', async () => { + const [state] = history(); + const stream = vi.fn(async function* () { + yield final; + }); + const session = createSession({ + assistantId: 'a', + threadId: 't', + transport: { + stream, + getHistory: async () => [ + { + ...state, + tasks: [ + { + ...state.tasks[0], + interrupts: [ + { id: 'first', value: 'One?' }, + { id: 'second', value: 'Two?' }, + ], + }, + ], + }, + ], + }, + }); + await session.load?.(); + expect(session.getSnapshot().interrupts.map(({ id }) => id)).toEqual([ + 'first', + 'second', + ]); + expect( + await session.resume([ + { interruptId: 'second', status: 'resolved', value: false }, + { interruptId: 'first', status: 'resolved', value: 'yes' }, + ]) + ).toBe('success'); + expect(stream.mock.calls[0][4]).toEqual({ + command: { resume: { second: false, first: 'yes' } }, + }); + await session.dispose(); + }); + it('owns nested response data before dispatch without freezing caller objects', async () => { const f = await fixture(); const value = { approve: { choices: ['first'] } }; - const done = f.session.resume(value); + const done = f.session.resume(answerPending(f.session, value)); value.approve.choices.push('later'); await done; const command = f.stream.mock.calls[0][4]?.command; @@ -153,7 +222,9 @@ describe('explicit interrupt resume', () => { yield pause; }, }); - expect(await f.session.resume(true)).toBe('paused'); + expect(await f.session.resume(answerPending(f.session, true))).toBe( + 'paused' + ); expect(f.session.getSnapshot().interrupts).toEqual([ { id: 'next', value: 'Again?' }, ]); @@ -171,7 +242,7 @@ describe('explicit interrupt resume', () => { yield { type: 'error', data: { message: 'failed' } }; }, }); - expect(await f.session.resume(true)).toBe( + expect(await f.session.resume(answerPending(f.session, true))).toBe( kind === 'error' ? 'error' : 'interrupted' ); // History is readable, so the check is offered, but the old checkpoint @@ -206,7 +277,7 @@ describe('explicit interrupt resume', () => { }, }); const before = f.session.getSnapshot().messages; - expect(await f.session.resume()).toBe('success'); + expect(await f.session.resume(answerPending(f.session))).toBe('success'); expect(f.session.getSnapshot().messages).toBe(before); }); @@ -217,7 +288,7 @@ describe('explicit interrupt resume', () => { yield { type: 'values', data: { stage: 'done' } }; }, }); - expect(await f.session.resume()).toBe('success'); + expect(await f.session.resume(answerPending(f.session))).toBe('success'); expect(f.session.getSnapshot().messages).toEqual([]); expect(f.session.getSnapshot().state).toEqual({ stage: 'done' }); }); @@ -225,13 +296,17 @@ describe('explicit interrupt resume', () => { it('rejects absent pause without effects and keeps disposed/pre-aborted calls inert', async () => { const f = await fixture(); const before = f.session.getSnapshot(); - expect(await f.session.resume(true, { signal: AbortSignal.abort() })).toBe( - 'aborted' - ); + expect( + await f.session.resume(answerPending(f.session, true), { + signal: AbortSignal.abort(), + }) + ).toBe('aborted'); expect(f.session.getSnapshot()).toBe(before); await f.session.dispose(); const disposed = f.session.getSnapshot(); - expect(await f.session.resume(true)).toBe('aborted'); + expect(await f.session.resume(answerPending(f.session, true))).toBe( + 'aborted' + ); expect(f.session.getSnapshot()).toBe(disposed); expect(f.stream).not.toHaveBeenCalled(); const fresh = createSession({ @@ -239,21 +314,27 @@ describe('explicit interrupt resume', () => { threadId: 't', transport: { stream: f.stream }, }); - await expect(fresh.resume()).rejects.toThrow(/interrupt|pause/i); + await expect(fresh.resume(answerPending(fresh))).rejects.toThrow( + /interrupt|pause/i + ); expect(fresh.getSnapshot().status).toBe('idle'); }); it('admits only one concurrent resume and rejects during an active load', async () => { const controlled = controlledTransport(); const f = await fixture({ stream: () => controlled.stream }); - const first = f.session.resume(true); - await expect(f.session.resume(false)).rejects.toThrow(/active|request/i); + const first = f.session.resume(answerPending(f.session, true)); + await expect( + f.session.resume(answerPending(f.session, false)) + ).rejects.toThrow(/active|request/i); await f.session.stop(); expect(await first).toBe('aborted'); const read = deferred(); f.getHistory.mockImplementation(() => read.promise); const loading = f.session.load?.(); - await expect(f.session.resume()).rejects.toThrow(/active|load|history/i); + await expect(f.session.resume(answerPending(f.session))).rejects.toThrow( + /active|load|history/i + ); read.resolve(history()); await loading; expect(f.stream).toHaveBeenCalledTimes(1); @@ -273,7 +354,9 @@ describe('explicit interrupt resume', () => { return true; }, }; - expect(await f.session.resume(response)).toBe('aborted'); + expect(await f.session.resume(answerPending(f.session, response))).toBe( + 'aborted' + ); await nested; expect(f.stream).toHaveBeenCalledTimes(command === 'submit' ? 1 : 0); if (command === 'submit') @@ -298,7 +381,9 @@ describe('explicit interrupt resume', () => { async (value) => { const f = await fixture(); const before = f.session.getSnapshot(); - await expect(f.session.resume(value() as PlainValue)).rejects.toThrow(); + await expect( + f.session.resume(answerPending(f.session, value() as PlainValue)) + ).rejects.toThrow(); expect(f.session.getSnapshot()).toBe(before); expect(f.stream).not.toHaveBeenCalled(); } @@ -312,7 +397,7 @@ describe('explicit interrupt resume', () => { if (f.session.getSnapshot().status === 'running') void f.session[command](); }); - expect(await f.session.resume()).toBe('aborted'); + expect(await f.session.resume(answerPending(f.session))).toBe('aborted'); expect(f.stream).not.toHaveBeenCalled(); } ); @@ -332,7 +417,9 @@ describe('explicit interrupt resume', () => { }), }); const external = new AbortController(); - const pending = f.session.resume(true, { signal: external.signal }); + const pending = f.session.resume(answerPending(f.session, true), { + signal: external.signal, + }); await opened.promise; external.abort(); expect(await pending).toBe('aborted'); @@ -360,7 +447,9 @@ describe('explicit interrupt resume', () => { else yield final; }, }); - expect(await f.session.resume({ approve: true })).toBe('success'); + expect( + await f.session.resume(answerPending(f.session, { approve: true })) + ).toBe('success'); expect(f.handler).toHaveBeenCalledExactlyOnceWith( { amount: 3 }, expect.anything() @@ -407,7 +496,7 @@ describe('explicit interrupt resume', () => { }; }, }); - expect(await f.session.resume()).toBe('success'); + expect(await f.session.resume(answerPending(f.session))).toBe('success'); expect(f.handler).not.toHaveBeenCalled(); expect(f.stream).toHaveBeenCalledTimes(1); }); @@ -425,7 +514,7 @@ describe('explicit interrupt resume', () => { yield { type: 'error', data: { message: 'failed' } }; }, }); - expect(await f.session.resume(true)).toBe( + expect(await f.session.resume(answerPending(f.session, true))).toBe( failure === 'error' ? 'error' : 'interrupted' ); expect(f.session.getSnapshot().error).toMatchObject({ @@ -436,7 +525,9 @@ describe('explicit interrupt resume', () => { expect(f.getHistory).not.toHaveBeenCalled(); await f.session.checkStatus?.(); await expect(f.session.load?.()).rejects.toThrow(/unsettled/i); - await expect(f.session.resume(true)).rejects.toThrow(/unsettled/i); + await expect( + f.session.resume(answerPending(f.session, true)) + ).rejects.toThrow(/unsettled/i); f.stream.mockImplementation(async function* () { yield final; }); @@ -465,7 +556,7 @@ it('never re-enables a later-turn call when subsequent terminal data omits its h yield { type: 'values', data: { messages: [later] } }; }, }); - expect(await f.session.resume()).toBe('success'); + expect(await f.session.resume(answerPending(f.session))).toBe('success'); expect(f.handler).not.toHaveBeenCalled(); expect(f.stream).toHaveBeenCalledTimes(1); }); @@ -483,7 +574,7 @@ it('retracts tool eligibility when a later terminal batch reveals its foreign us }; }, }); - expect(await f.session.resume()).toBe('success'); + expect(await f.session.resume(answerPending(f.session))).toBe('success'); expect(f.handler).not.toHaveBeenCalled(); }); @@ -500,7 +591,7 @@ it('does not attribute an unseen assistant after an observed later user to the r }; }, }); - expect(await f.session.resume()).toBe('success'); + expect(await f.session.resume(answerPending(f.session))).toBe('success'); expect(f.handler).not.toHaveBeenCalled(); }); @@ -518,7 +609,7 @@ it('allows finalized anonymous assistant tools after a message-less pause', asyn : final; }, }); - expect(await f.session.resume()).toBe('success'); + expect(await f.session.resume(answerPending(f.session))).toBe('success'); expect(f.handler).toHaveBeenCalledExactlyOnceWith( { amount: 4 }, expect.anything() @@ -535,9 +626,11 @@ it('an abort during listener registration cannot publish stale running state', a external.abort(); } ); - expect(await f.session.resume(true, { signal: external.signal })).toBe( - 'aborted' - ); + expect( + await f.session.resume(answerPending(f.session, true), { + signal: external.signal, + }) + ).toBe('aborted'); expect(f.session.getSnapshot().status).toBe('idle'); expect(f.stream).not.toHaveBeenCalled(); }); @@ -553,7 +646,9 @@ it('blocks resume while an uncertain normal submit still owns history recovery', expect(f.session.getSnapshot().interrupts.length).toBeGreaterThan(0); expect(f.session.getSnapshot().error?.recovery).toBe('check'); const before = f.session.getSnapshot(); - await expect(f.session.resume(true)).rejects.toThrow(/recovery/i); + await expect( + f.session.resume(answerPending(f.session, true)) + ).rejects.toThrow(/recovery/i); expect(f.session.getSnapshot()).toBe(before); expect(f.stream).toHaveBeenCalledTimes(1); }); @@ -592,7 +687,7 @@ it.each(['acquire', 'settle', 'write'] as const)( writeStarted.resolve(); return written.promise; }); - const resumed = f.session.resume(true); + const resumed = f.session.resume(answerPending(f.session, true)); await (phase === 'acquire' ? claimStarted.promise : phase === 'settle' @@ -600,11 +695,15 @@ it.each(['acquire', 'settle', 'write'] as const)( : writeStarted.promise); await f.session.stop(); expect(await resumed).toBe('aborted'); - await expect(f.session.resume(true)).rejects.toThrow(/unsettled/i); + await expect( + f.session.resume(answerPending(f.session, true)) + ).rejects.toThrow(/unsettled/i); acquire.resolve({ status: 'acquired' as const, token: 'owner' }); recorded.resolve(); await writeStarted.promise; - await expect(f.session.resume(true)).rejects.toThrow(/unsettled/i); + await expect( + f.session.resume(answerPending(f.session, true)) + ).rejects.toThrow(/unsettled/i); written.resolve(); // Drain acknowledged cleanup without depending on its promise-chain depth. await new Promise((resolve) => setImmediate(resolve)); @@ -612,7 +711,9 @@ it.each(['acquire', 'settle', 'write'] as const)( f.stream.mockImplementation(async function* () { yield final; }); - expect(await f.session.resume(true)).toBe('success'); + expect(await f.session.resume(answerPending(f.session, true))).toBe( + 'success' + ); expect(f.stream).toHaveBeenCalledTimes(2); } ); @@ -632,13 +733,17 @@ it('preserves durable completed facts and local resolved IDs across explicit rel : final; }, }); - expect(await f.session.resume(true)).toBe('success'); + expect(await f.session.resume(answerPending(f.session, true))).toBe( + 'success' + ); expect(f.session.getSnapshot().toolCalls[0]).toMatchObject({ status: 'complete', result: { doubled: 12 }, }); await f.session.load?.(); - expect(await f.session.resume(true)).toBe('success'); + expect(await f.session.resume(answerPending(f.session, true))).toBe( + 'success' + ); expect(acquire).toHaveBeenCalledTimes(1); expect(settle).not.toHaveBeenCalled(); expect(f.handler).not.toHaveBeenCalled(); @@ -659,11 +764,13 @@ it('keeps sessions independent and observes stale rejected reads after disposal' }), }); const b = await fixture(); - const pending = a.session.resume(true); + const pending = a.session.resume(answerPending(a.session, true)); await entered.promise; await a.session.dispose(); expect(await pending).toBe('aborted'); - expect(await b.session.resume(false)).toBe('success'); + expect(await b.session.resume(answerPending(b.session, false))).toBe( + 'success' + ); const before = a.session.getSnapshot(); next.reject(new Error('Late failure')); await next.promise.catch(() => undefined); @@ -689,7 +796,7 @@ it('retracts an anonymous candidate when a later batch reveals its foreign turn' }; }, }); - expect(await f.session.resume()).toBe('success'); + expect(await f.session.resume(answerPending(f.session))).toBe('success'); expect(f.handler).not.toHaveBeenCalled(); }); @@ -716,7 +823,9 @@ it('retains later-turn evidence across a legitimate current-turn tool follow-up' : final; }, }); - expect(await f.session.resume(true)).toBe('success'); + expect(await f.session.resume(answerPending(f.session, true))).toBe( + 'success' + ); expect(f.handler).toHaveBeenCalledTimes(1); expect(f.stream).toHaveBeenCalledTimes(2); }); @@ -736,12 +845,12 @@ it('admits at most one of two resumes queued by a paused observer', async () => f.session.getSnapshot().interrupts[0]?.id === 'next' ) { queued = Promise.allSettled([ - f.session.resume(true), - f.session.resume(false), + f.session.resume(answerPending(f.session, true)), + f.session.resume(answerPending(f.session, false)), ]); } }); - expect(await f.session.resume()).toBe('paused'); + expect(await f.session.resume(answerPending(f.session))).toBe('paused'); expect(await queued).toEqual([ { status: 'fulfilled', value: 'success' }, { status: 'rejected', reason: expect.any(Error) }, diff --git a/libs/langgraph/src/runtime/resume.type-test.ts b/libs/langgraph/src/runtime/resume.type-test.ts index 00f16cf74..9abe958f5 100644 --- a/libs/langgraph/src/runtime/resume.type-test.ts +++ b/libs/langgraph/src/runtime/resume.type-test.ts @@ -1,4 +1,5 @@ import type { + AgentInterruptResponse, AgentSession, CompleteOutcome, PlainValue, @@ -19,24 +20,36 @@ const response: Readonly> = { first: { approved: false }, second: [0, null], }; -const result: Promise = session.resume(response, { +const interruptId = session.getSnapshot().interrupts[0].id; +const responses: readonly AgentInterruptResponse[] = [ + { interruptId, status: 'resolved', value: response }, +]; +const result: Promise = session.resume(responses, { signal: new AbortController().signal, }); -session.resume(); -session.resume(undefined); -session.resume(null); +session.resume([{ interruptId, status: 'resolved' }]); +session.resume([{ interruptId, status: 'resolved', value: null }]); +session.resume([{ interruptId, status: 'resolved', value: false }]); +// @ts-expect-error Resume takes responses, not a bare value. session.resume(false); +// @ts-expect-error Resume needs its responses. +session.resume(); +// @ts-expect-error A response names its interrupt. +session.resume([{ status: 'resolved', value: true }]); // @ts-expect-error Functions are not plain response values. -session.resume(() => true); +session.resume([{ interruptId, status: 'resolved', value: () => true }]); // @ts-expect-error SDK classes are not plain response values. -session.resume(new Date()); +session.resume([{ interruptId, status: 'resolved', value: new Date() }]); // @ts-expect-error Resume options require AbortSignal. -session.resume(true, { signal: 'wrong' }); +session.resume(responses, { signal: 'wrong' }); // @ts-expect-error Resume does not add arbitrary command options. -session.resume(true, { command: { goto: 'other' } }); +session.resume(responses, { command: { goto: 'other' } }); +// The session's resume is the core contract's command, always present here. const observer: AgentSession = session; -// @ts-expect-error Backend resume is absent from the borrowed core contract. -observer.resume(true); +const viaCore: Promise | undefined = + observer.resume?.(responses); +// @ts-expect-error The core contract makes resume optional. +observer.resume(responses); const values: Readonly> | undefined = session.getSnapshot().state; for (const call of session.getSnapshot().toolCalls) { @@ -47,4 +60,4 @@ for (const call of session.getSnapshot().toolCalls) { void [doubled, wrong]; } } -void [result, values]; +void [result, values, viaCore]; diff --git a/libs/langgraph/src/runtime/retry.spec.ts b/libs/langgraph/src/runtime/retry.spec.ts index e8ed745cf..0db150025 100644 --- a/libs/langgraph/src/runtime/retry.spec.ts +++ b/libs/langgraph/src/runtime/retry.spec.ts @@ -3,6 +3,7 @@ import type { Run } from '@langchain/langgraph-sdk'; import { createSession } from './create-session'; import { deferred } from './testing/deferred'; import type { AgentTransport, StreamEvent } from './transport.types'; +import { answerPending } from './testing/answer-pending'; const partial: StreamEvent = { type: 'messages', @@ -67,24 +68,22 @@ function fixture( /** A completed run that echoes the submitted user message and answers it. */ const answer = (content: string): Script => - (payload) => [ - { - type: 'values', - data: { - messages: [ - ...(payload?.messages ?? []), - { type: 'ai', id: 'answer', content }, - ], + (payload) => + [ + { + type: 'values', + data: { + messages: [ + ...(payload?.messages ?? []), + { type: 'ai', id: 'answer', content }, + ], + }, }, - }, - ]; + ]; describe('retry', () => { it('sends a submission the backend reported failed again, with the same user message', async () => { - const f = fixture( - [() => [partial], answer('Done')], - ['error', 'success'] - ); + const f = fixture([() => [partial], answer('Done')], ['error', 'success']); expect(await f.session.submit('Question')).toBe('error'); expect(f.session.getSnapshot()).toMatchObject({ status: 'error', @@ -171,7 +170,13 @@ describe('retry', () => { it('sends a failed resume again with the same response and no user message', async () => { // Each run is scripted below; run-1, the resume, is the one that fails. const f = fixture([], ['interrupted', 'error', 'success']); - f.stream.mockImplementationOnce(async function* (_a, _t, payload, _s, settings) { + f.stream.mockImplementationOnce(async function* ( + _a, + _t, + payload, + _s, + settings + ) { settings?.onRunCreated?.({ run_id: 'run-0', thread_id: 't' }); yield* answer('Waiting')(payload as Payload) as StreamEvent[]; yield pause; @@ -182,7 +187,9 @@ describe('retry', () => { settings?.onRunCreated?.({ run_id: 'run-1', thread_id: 't' }); yield partial; }); - expect(await f.session.resume({ approved: true })).toBe('error'); + expect( + await f.session.resume(answerPending(f.session, { approved: true })) + ).toBe('error'); expect(f.session.getSnapshot().error).toMatchObject({ recovery: 'retry' }); f.stream.mockImplementationOnce(async function* (_a, _t, _p, _s, settings) { settings?.onRunCreated?.({ run_id: 'run-2', thread_id: 't' }); @@ -210,7 +217,9 @@ describe('retry', () => { ); const snapshot = f.session.getSnapshot(); expect(snapshot.error).toBeUndefined(); - expect(snapshot.messages.filter(({ role }) => role === 'user')).toHaveLength(1); + expect( + snapshot.messages.filter(({ role }) => role === 'user') + ).toHaveLength(1); expect(snapshot.messages.some(({ id }) => id === 'partial')).toBe(false); }); diff --git a/libs/langgraph/src/runtime/run-options.spec.ts b/libs/langgraph/src/runtime/run-options.spec.ts index e9c78c919..ccc41812a 100644 --- a/libs/langgraph/src/runtime/run-options.spec.ts +++ b/libs/langgraph/src/runtime/run-options.spec.ts @@ -2,6 +2,7 @@ import { afterEach, describe, expect, it, vi } from 'vitest'; import { createSession } from './create-session'; import type { AgentTransport, StreamEvent } from './transport.types'; import { deferred } from './testing/deferred'; +import { answerPending } from './testing/answer-pending'; const sessions: ReturnType[] = []; const complete: StreamEvent = { @@ -198,12 +199,16 @@ describe('owned run options', () => { data: { __interrupt__: [{ id: 'second', value: 'Again?' }] }, }; }); - expect(await f.session.resume(false, choices())).toBe('paused'); + expect( + await f.session.resume(answerPending(f.session, false), choices()) + ).toBe('paused'); expect(f.stream.mock.calls[1][4]).toEqual({ ...choices(), command: { resume: false }, }); - expect(await f.session.resume(true)).toBe('success'); + expect(await f.session.resume(answerPending(f.session, true))).toBe( + 'success' + ); expect(f.stream.mock.calls[2][4]).toEqual({ command: { resume: true } }); }); @@ -273,7 +278,7 @@ describe('owned run options', () => { }) ).toBe('aborted'); await expect( - f.session.resume(true, { + f.session.resume(answerPending(f.session, true), { get context() { return poison(); }, @@ -295,7 +300,7 @@ describe('owned run options', () => { }); expect(await f.session.submit('Pause')).toBe('paused'); let replacement: Promise | undefined; - const run = f.session.resume(true, { + const run = f.session.resume(answerPending(f.session, true), { get context() { replacement = command === 'submit' diff --git a/libs/langgraph/src/runtime/run-options.type-test.ts b/libs/langgraph/src/runtime/run-options.type-test.ts index 69cc3f46b..c8f84f65e 100644 --- a/libs/langgraph/src/runtime/run-options.type-test.ts +++ b/libs/langgraph/src/runtime/run-options.type-test.ts @@ -15,7 +15,10 @@ export function assertRunOptions( metadata: { source: 'ui' }, } as const; void session.submit('Hello', options); - void session.resume(false, options); + void session.resume( + [{ interruptId: 'i', status: 'resolved', value: false }], + options + ); // @ts-expect-error Configuration is deeply readonly. options.config?.tags?.push('changed'); if (options.config?.configurable) { @@ -32,7 +35,7 @@ export function assertRunOptions( // @ts-expect-error Thread routing belongs to the session. config: { configurable: { thread_id: 'other' } }, }); - void session.resume(true, { + void session.resume([{ interruptId: 'i', status: 'resolved', value: true }], { // @ts-expect-error Checkpoint execution needs an explicit owner contract. config: { configurable: { checkpoint_id: 'old' } }, }); diff --git a/libs/langgraph/src/runtime/session-invocation-identity.spec.ts b/libs/langgraph/src/runtime/session-invocation-identity.spec.ts index 7b1b1b79d..f7cb84629 100644 --- a/libs/langgraph/src/runtime/session-invocation-identity.spec.ts +++ b/libs/langgraph/src/runtime/session-invocation-identity.spec.ts @@ -4,6 +4,7 @@ import { describe, expect, it, vi } from 'vitest'; import { createSession } from './create-session'; import type { AgentTransport, StreamEvent } from './transport.types'; import { deferred } from './testing/deferred'; +import { answerPending } from './testing/answer-pending'; const original = { id: 'shared-call', @@ -497,7 +498,9 @@ describe('session invocation identity', () => { await expect(f.session.submit('Again')).rejects.toThrow( /identity|conflict/i ); - await expect(f.session.resume()).rejects.toThrow(/identity|conflict/i); + await expect( + f.session.resume(answerPending(f.session)) + ).rejects.toThrow(/identity|conflict/i); await expect(f.session.reconnect()).rejects.toThrow( /identity|conflict/i ); diff --git a/libs/langgraph/src/runtime/subgraphs.spec.ts b/libs/langgraph/src/runtime/subgraphs.spec.ts index 99b463e1c..e8fab8c93 100644 --- a/libs/langgraph/src/runtime/subgraphs.spec.ts +++ b/libs/langgraph/src/runtime/subgraphs.spec.ts @@ -4,6 +4,7 @@ import { createSession } from './create-session'; import type { AgentTransport, StreamEvent } from './transport.types'; import { controlledTransport } from './testing/controlled-transport'; import { deferred } from './testing/deferred'; +import { answerPending } from './testing/answer-pending'; const ai = (content: string, id = 'shared') => ({ type: 'ai', id, content }); const child = (content: string, namespace = ['child']): StreamEvent => ({ @@ -222,7 +223,9 @@ describe('private subgraph observations', () => { f.streams[0].finish(); expect(await run).toBe('interrupted'); expect(f.session.getSnapshot().interrupts).toEqual([]); - await expect(f.session.resume()).rejects.toThrow(); + await expect( + f.session.resume(answerPending(f.session)) + ).rejects.toThrow(); } ); @@ -341,7 +344,7 @@ describe('private subgraph observations', () => { f.streams[0].finish(); expect(await run).toBe('paused'); const before = f.session.getSnapshot(); - const resumed = f.session.resume(true); + const resumed = f.session.resume(answerPending(f.session, true)); await f.started(1); expect(f.session.getSnapshot().subgraphs).toBe(before.subgraphs); await f.emit(child('New'), 1); diff --git a/libs/langgraph/src/runtime/testing/answer-pending.ts b/libs/langgraph/src/runtime/testing/answer-pending.ts new file mode 100644 index 000000000..8e6c0aee1 --- /dev/null +++ b/libs/langgraph/src/runtime/testing/answer-pending.ts @@ -0,0 +1,20 @@ +import type { AgentInterruptResponse, PlainValue } from '@threadplane/core'; + +/** The response a test sends to the first pending interrupt, resolved with + * `value`. With nothing pending it names an interrupt that does not exist, so + * the session's own admission decides the outcome. */ +export function answerPending( + session: { + getSnapshot(): { readonly interrupts: readonly { readonly id: string }[] }; + }, + value?: PlainValue +): readonly AgentInterruptResponse[] { + const [interrupt] = session.getSnapshot().interrupts; + return [ + { + interruptId: interrupt?.id ?? 'none-pending', + status: 'resolved', + ...(value !== undefined && { value }), + }, + ]; +} diff --git a/libs/langgraph/src/runtime/tool-claim-ownership.spec.ts b/libs/langgraph/src/runtime/tool-claim-ownership.spec.ts index dfea0e264..715b2298c 100644 --- a/libs/langgraph/src/runtime/tool-claim-ownership.spec.ts +++ b/libs/langgraph/src/runtime/tool-claim-ownership.spec.ts @@ -5,6 +5,7 @@ import type { ToolExecutionStore } from '@threadplane/core/tools'; import { createSession } from './create-session'; import type { AgentTransport, StreamEvent } from './transport.types'; import { deferred } from './testing/deferred'; +import { answerPending } from './testing/answer-pending'; const key = { threadId: 'thread', toolCallId: 'foreign' }; function call(id: string, messageId = `ai-${id}`): StreamEvent { @@ -88,7 +89,7 @@ describe('tool acquire ownership', () => { await expect(session.submit('Bypass')).rejects.toThrow( /unsettled tool/ ); - await expect(session.resume()).rejects.toThrow(); + await expect(session.resume(answerPending(session))).rejects.toThrow(); await expect(session.reconnect()).rejects.toThrow(); await session.checkStatus?.(); expect(f.getHistory).not.toHaveBeenCalled(); diff --git a/libs/langgraph/src/runtime/tool-write-serialization.spec.ts b/libs/langgraph/src/runtime/tool-write-serialization.spec.ts index 86f98f5a9..e4e9e1988 100644 --- a/libs/langgraph/src/runtime/tool-write-serialization.spec.ts +++ b/libs/langgraph/src/runtime/tool-write-serialization.spec.ts @@ -3,6 +3,7 @@ import type { ToolExecutionStore } from '@threadplane/core/tools'; import { createSession } from './create-session'; import { deferred } from './testing/deferred'; import type { AgentTransport, StreamEvent } from './transport.types'; +import { answerPending } from './testing/answer-pending'; const drain = () => new Promise((resolve) => setImmediate(resolve)); const callIds = ['first', 'second', 'third']; @@ -156,7 +157,9 @@ describe('terminal tool write serialization', () => { await expect( f.session.submit('Cannot overtake queued cleanup') ).rejects.toThrow(); - await expect(f.session.resume()).rejects.toThrow(); + await expect( + f.session.resume(answerPending(f.session)) + ).rejects.toThrow(); await expect(f.session.load?.()).rejects.toThrow(); expect(f.getHistory).not.toHaveBeenCalled(); } diff --git a/libs/langgraph/src/runtime/transport.integration.spec.ts b/libs/langgraph/src/runtime/transport.integration.spec.ts index 64af2338c..95c008cd6 100644 --- a/libs/langgraph/src/runtime/transport.integration.spec.ts +++ b/libs/langgraph/src/runtime/transport.integration.spec.ts @@ -6,6 +6,7 @@ import { FetchStreamTransport } from '../lib/transport/fetch-stream.transport'; import type { StreamEvent } from './transport.types'; import { createSession, type SessionOptions } from './create-session'; import type { ToolExecutionStore } from '@threadplane/core/tools'; +import { answerPending } from './testing/answer-pending'; const textTrace = readFileSync( new URL( @@ -510,7 +511,9 @@ describe('neutral real SDK transport', () => { state: { model: 'initial' }, }) ).toBe('paused'); - expect(await session.resume(value)).toBe('success'); + expect(await session.resume(answerPending(session, value))).toBe( + 'success' + ); expect(bodies[1]['input']).toBeNull(); expect(bodies[1]['command']).toEqual( value === undefined ? undefined : { resume: value } @@ -555,7 +558,7 @@ describe('neutral real SDK transport', () => { apiUrl: 'https://runtime.example', }); expect(await session.submit('Pause')).toBe('paused'); - const pending = session.resume(null); + const pending = session.resume(answerPending(session, null)); await vi.runAllTimersAsync(); expect(await pending).toBe('interrupted'); expect(session.getSnapshot().error).toMatchObject({ @@ -589,7 +592,7 @@ describe('neutral real SDK transport', () => { apiUrl: 'https://runtime.example', }); expect(await session.submit('Pause')).toBe('paused'); - expect(await session.resume()).toBe('paused'); + expect(await session.resume(answerPending(session))).toBe('paused'); expect(session.getSnapshot().interrupts).toEqual([ { id: 'second', value: { confirm: false } }, ]); @@ -625,7 +628,9 @@ describe('neutral real SDK transport', () => { tools: { weather: { description: 'Weather', handler } }, }); expect(await session.submit('Question')).toBe('paused'); - expect(await session.resume({ approval: false })).toBe('success'); + expect( + await session.resume(answerPending(session, { approval: false })) + ).toBe('success'); expect(bodies[1]).toMatchObject({ input: null, command: { resume: { approval: false } }, @@ -662,7 +667,7 @@ describe('neutral real SDK transport', () => { try { expect(await session.submit('Pause')).toBe('paused'); expect(session.getSnapshot().interrupts).toEqual([ - { when: 'breakpoint' }, + { id: 'breakpoint', when: 'breakpoint' }, ]); expect(session.getSnapshot().status).toBe('idle'); expect(session.getSnapshot().messages).toHaveLength(1); diff --git a/libs/langgraph/src/runtime/values.spec.ts b/libs/langgraph/src/runtime/values.spec.ts index f450a1be3..8ed746cd2 100644 --- a/libs/langgraph/src/runtime/values.spec.ts +++ b/libs/langgraph/src/runtime/values.spec.ts @@ -206,7 +206,9 @@ describe('session application values', () => { expect(f.snapshot().state).toEqual({ count: 2 }); f.streams[0].finish(); expect(await run).toBe('paused'); - expect(f.snapshot().interrupts).toEqual([{ when: 'breakpoint' }]); + expect(f.snapshot().interrupts).toEqual([ + { id: 'breakpoint', when: 'breakpoint' }, + ]); }); for (const [label, invalid] of [ @@ -419,7 +421,9 @@ describe('session application values', () => { expect(await run).toBe('paused'); } else await f.session.checkStatus?.(); expect(f.snapshot().state).toEqual({ count: 3 }); - expect(f.snapshot().interrupts).toEqual([{ when: 'breakpoint' }]); + expect(f.snapshot().interrupts).toEqual([ + { id: 'breakpoint', when: 'breakpoint' }, + ]); expect(f.snapshot().messages.at(-1)?.delivery).toMatchObject({ outcome: 'paused', }); diff --git a/libs/langgraph/src/runtime/visible-text.spec.ts b/libs/langgraph/src/runtime/visible-text.spec.ts index 08508ad6c..24b0fb6a1 100644 --- a/libs/langgraph/src/runtime/visible-text.spec.ts +++ b/libs/langgraph/src/runtime/visible-text.spec.ts @@ -3,6 +3,7 @@ import { createSession } from './create-session'; import type { AgentTransport, StreamEvent } from './transport.types'; import { controlledSession } from './testing/controlled-session'; import { saved } from './testing/checkpoint-fixture'; +import { answerPending } from './testing/answer-pending'; const cleanups: (() => Promise)[] = []; afterEach(async () => { @@ -210,7 +211,9 @@ describe('visible text through actual session ownership', () => { await session.load!(); const paused = session.getSnapshot(); expect(paused.messages.at(-1)?.content).toBe('Waiting'); - expect(await session.resume(true)).toBe('success'); + expect(await session.resume(answerPending(session, true))).toBe( + 'success' + ); expect( session.getSnapshot().messages.filter((m) => m.role === 'assistant') ).toMatchObject([ diff --git a/scripts/react-parity/dispositions.json b/scripts/react-parity/dispositions.json index 2f26e047d..36fcdc566 100644 --- a/scripts/react-parity/dispositions.json +++ b/scripts/react-parity/dispositions.json @@ -12840,6 +12840,17 @@ "reason": "Private controlled runtime/binding test helper; excluded from public exports and production packages.", "note": "Bounded runtime proof only; broader task capabilities and final public package cutover remain open." }, + { + "id": "source:libs/langgraph/src/runtime/testing/answer-pending.ts", + "taskIds": [ + "T05", + "T06" + ], + "treatment": "internal", + "status": "in-progress", + "reason": "Private controlled runtime/binding test helper; excluded from public exports and production packages.", + "note": "Bounded runtime proof only; broader task capabilities and final public package cutover remain open." + }, { "id": "source:libs/langgraph/src/runtime/testing/deferred.ts", "taskIds": [ diff --git a/scripts/react-parity/runtime-consumer.mjs b/scripts/react-parity/runtime-consumer.mjs index 731cd456a..a8b4f238a 100644 --- a/scripts/react-parity/runtime-consumer.mjs +++ b/scripts/react-parity/runtime-consumer.mjs @@ -87,7 +87,7 @@ export function runtimeResponse(body) { + sse('updates|review:child', { __interrupt__: [{ id: 'child-final', value: 'Child confirmation' }] }) + sse('updates', { __interrupt__: [{ id: 'final-approval', value: { question: 'Confirm final action?' } }] }); } - assert.deepEqual(response, { 'final-approval': true }, 'exact final response map'); + assert.strictEqual(response, true, 'exact final response value'); return sse('values|review:child', { stage: 'child-approved', messages: [{ type: 'ai', id: 'child-review', content: 'Child approved' }] }) + sse('values', { stage: 'approved', messages: [{ type: 'ai', id: 'resume-answer', content: 'Approvals complete' }] }); } @@ -191,15 +191,15 @@ export function assertTextTranscript(messages: readonly Message[]) { void session.submit({ message: 'Hello', state: { itinerary: stops.map(stop => ({ ...stop })) } }); const runOptions = { config: { tags: ['memory'], recursion_limit: 50, configurable: { user_id: 'user-42' } }, context: { locale: 'en' }, metadata: { source: 'ui' } } as const; void session.submit('Hello', runOptions); - void session.resume(true, runOptions); + void session.resume([{ interruptId: 'final-approval', status: 'resolved', value: true }], runOptions); // @ts-expect-error Configuration cannot change owned thread routing. void session.submit('Hello', { config: { configurable: { thread_id: 'other' } } }); // @ts-expect-error Configuration cannot bypass checkpoint execution ownership. - void session.resume(true, { config: { configurable: { checkpoint_id: 'old' } } }); + void session.resume([{ interruptId: 'final-approval', status: 'resolved', value: true }], { config: { configurable: { checkpoint_id: 'old' } } }); // @ts-expect-error Run context remains plain data. void session.submit('Hello', { context: new Date() }); // @ts-expect-error Metadata cannot contain callbacks. - void session.resume(true, { metadata: { callback: () => true } }); + void session.resume([{ interruptId: 'final-approval', status: 'resolved', value: true }], { metadata: { callback: () => true } }); // @ts-expect-error Object input still requires a message. void session.submit({ state: { model: 'gpt-5-mini' } }); // @ts-expect-error Message text must be a string. @@ -222,7 +222,11 @@ export function assertTextTranscript(messages: readonly Message[]) { void session.submit('Hello', { state: { model: 'gpt-5-mini' } }); // @ts-expect-error Submit does not expose transport command overrides. void session.submit({ message: 'Hello' }, { command: { goto: 'other' } }); + void session.resume([{ interruptId: 'final-approval', status: 'resolved' }]); + // @ts-expect-error Resume requires the responses it sends. void session.resume(); + // @ts-expect-error A bare value does not name the interrupt it answers. + void session.resume(true); const reconnected: Promise = session.reconnect({ signal: new AbortController().signal }); void reconnected; // @ts-expect-error Reconnect cannot attach an arbitrary run. @@ -237,13 +241,13 @@ export function assertTextTranscript(messages: readonly Message[]) { // @ts-expect-error Retained run identity is readonly. snapshot.reconnect.runId = 'changed'; } - void session.resume(false); - void session.resume(null); - void session.resume({ approval: { choice: 'yes' } } as const, { signal: new AbortController().signal }); + void session.resume([{ interruptId: 'final-approval', status: 'resolved', value: false }]); + void session.resume([{ interruptId: 'final-approval', status: 'resolved', value: null }]); + void session.resume([{ interruptId: 'final-approval', status: 'resolved', value: { approval: { choice: 'yes' } } }] as const, { signal: new AbortController().signal }); // @ts-expect-error Responses must be portable authored data, not SDK instances. - void session.resume(new Date()); + void session.resume([{ interruptId: 'final-approval', status: 'resolved', value: new Date() }]); // @ts-expect-error Resume does not expose transport command overrides. - void session.resume(true, { command: { goto: 'other' } }); + void session.resume([{ interruptId: 'final-approval', status: 'resolved', value: true }], { command: { goto: 'other' } }); const direct = session.getSnapshot(); const history = snapshot.history; const directHistory: typeof history = direct.history; @@ -2976,7 +2980,7 @@ export async function runRuntimeScenarios(directory, kind, { a2ui = false } = {} await expect(page.getByTestId('handler-calls')).toHaveText('1'); await expect(page.getByRole('button', { name: 'Resume', exact: true })).toBeDisabled(); assert.equal(server.requests.length, 8); - assert.deepEqual(server.requests[7].command, { resume: { 'final-approval': true } }); + assert.deepEqual(server.requests[7].command, { resume: true }); assert.equal(server.requests[7].input, null); completed.push('same-message resume completion without synthetic input'); diff --git a/scripts/react-parity/runtime-consumer.spec.mjs b/scripts/react-parity/runtime-consumer.spec.mjs index 5a9e21fd0..70441490d 100644 --- a/scripts/react-parity/runtime-consumer.spec.mjs +++ b/scripts/react-parity/runtime-consumer.spec.mjs @@ -124,7 +124,7 @@ test('execution settings are required for configured submits, tool continuations assert.throws(() => runtime.runtimeResponse(missing), /unexpected run fields/); } } - const resume = { ...heldBody, ...runSettings, input: null, command: { resume: { 'final-approval': true } } }; + const resume = { ...heldBody, ...runSettings, input: null, command: { resume: true } }; assert.doesNotThrow(() => runtime.runtimeResponse(resume)); for (const key of Object.keys(runSettings)) { const missing = { ...resume }; delete missing[key]; @@ -170,7 +170,7 @@ test('application state cannot replay on tool continuation, a later Send, or res assert.doesNotThrow(() => runtime.runtimeResponse(body)); assert.throws(() => runtime.runtimeResponse({ ...body, input: { ...applicationState, ...body.input } }), /unexpected run fields/); } - const resume = { ...heldBody, ...runSettings, input: null, command: { resume: { 'final-approval': true } } }; + const resume = { ...heldBody, ...runSettings, input: null, command: { resume: true } }; assert.doesNotThrow(() => runtime.runtimeResponse(resume)); assert.throws(() => runtime.runtimeResponse({ ...resume, state: applicationState }), /exact resume run fields/); assert.throws(() => runtime.runtimeResponse({ ...resume, input: applicationState })); @@ -230,7 +230,7 @@ test('explicit resume maps use null input, re-pause, and complete the same assis assert.match(first, /"id":"final-approval"/); assert.match(first, /"content":"One final approval"/); assert.match(first, /"content":"Child final approval"/); - const second = runtime.runtimeResponse({ ...base, command: { resume: { 'final-approval': true } } }); + const second = runtime.runtimeResponse({ ...base, command: { resume: true } }); assert.match(second, /"content":"Approvals complete"/); assert.match(second, /"stage":"approved"/); assert.match(second, /"content":"Child approved"/); @@ -242,9 +242,10 @@ test('explicit resume maps use null input, re-pause, and complete the same assis assert.ok([...firstMessages, ...secondMessages].every((message) => message.type === 'ai'), 'resume creates no synthetic human message'); for (const body of [ { ...base, command: { resume: { 'live-approval': 'yes' } } }, - { ...base, command: { resume: { 'final-approval': false } } }, - { ...base, command: { resume: { 'final-approval': true }, update: {} } }, - { ...base, input: { messages: [] }, command: { resume: { 'final-approval': true } } }, + { ...base, command: { resume: false } }, + { ...base, command: { resume: { 'final-approval': true } } }, + { ...base, command: { resume: true, update: {} } }, + { ...base, input: { messages: [] }, command: { resume: true } }, ]) assert.throws(() => runtime.runtimeResponse(body)); }); @@ -383,7 +384,7 @@ test('owned runtime accepts exactly five modes and rejects otherwise valid mode const stream_mode = ['values', 'messages-tuple', 'updates', 'custom', 'checkpoints']; const submit = { ...heldBody, stream_mode, input: { ...heldBody.input, messages: [{ id: 'exact-five-user', type: 'human', content: 'Send' }] } }; const continuation = { ...submit, ...runSettings, input: { client_tools: heldBody.input.client_tools, messages: [{ id: 'client-tool-result-call-weather', type: 'tool', role: 'tool', tool_call_id: 'call-weather', content: '{"city":"Paris","temperature":20}' }] } }; - const resume = { ...submit, ...runSettings, input: null, command: { resume: { 'final-approval': true } } }; + const resume = { ...submit, ...runSettings, input: null, command: { resume: true } }; for (const body of [submit, continuation, resume]) { assert.doesNotThrow(() => runtime.runtimeResponse(body), 'exact owned five-mode body'); for (const modes of [stream_mode.slice(0, -1), [...stream_mode.slice(0, -1), 'debug'], [...stream_mode, 'debug']]) {