diff --git a/cockpit/ag-ui/interrupts/react/src/application.spec.ts b/cockpit/ag-ui/interrupts/react/src/application.spec.ts index 1bcfd0e6a..dac3f7ac8 100644 --- a/cockpit/ag-ui/interrupts/react/src/application.spec.ts +++ b/cockpit/ag-ui/interrupts/react/src/application.spec.ts @@ -182,12 +182,11 @@ it.each(['approve', 'edit', 'cancel'] as const)( action === 'edit' ? 20 : undefined ); expect(session.resume).toHaveBeenCalledWith( - approval.pause, [ { interruptId: approval.interruptId, status: 'resolved', - payload: + value: action === 'cancel' ? { approved: false } : action === 'edit' diff --git a/cockpit/ag-ui/interrupts/react/src/application.ts b/cockpit/ag-ui/interrupts/react/src/application.ts index 329040a76..e83f29560 100644 --- a/cockpit/ag-ui/interrupts/react/src/application.ts +++ b/cockpit/ag-ui/interrupts/react/src/application.ts @@ -436,8 +436,13 @@ export function createInterruptsApplication(options: { : { approved: true }; if (selected.unsafe || !ownedValid()) return; const pending = selected.session.resume( - approval.pause, - [{ interruptId: approval.interruptId, status: 'resolved', payload }], + [ + { + interruptId: approval.interruptId, + status: 'resolved', + value: payload, + }, + ], { signal: admitted.signal } ); void pending.catch(() => undefined); diff --git a/cockpit/ag-ui/interrupts/react/src/approval-policy.ts b/cockpit/ag-ui/interrupts/react/src/approval-policy.ts index 4038905be..86ff1059a 100644 --- a/cockpit/ag-ui/interrupts/react/src/approval-policy.ts +++ b/cockpit/ag-ui/interrupts/react/src/approval-policy.ts @@ -1,4 +1,8 @@ -import type { Session, TextTranscriptRow } from '@threadplane/ag-ui'; +import type { + DecisionState, + Session, + TextTranscriptRow, +} from '@threadplane/ag-ui'; export type NativeSnapshot = ReturnType; export interface OwnedTurn { readonly threadId: string; @@ -9,7 +13,7 @@ export interface OwnedTurn { export interface RefundApproval { readonly threadId: string; readonly sourceRunId: string; - readonly pause: Parameters[0]; + readonly pause: Extract['id']; readonly interruptId: string; readonly amount: number; readonly customerId: string; 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/cockpit/runtimes/aws-strands/react/src/application.spec.ts b/cockpit/runtimes/aws-strands/react/src/application.spec.ts index 2b41a301e..19a5a6bcb 100644 --- a/cockpit/runtimes/aws-strands/react/src/application.spec.ts +++ b/cockpit/runtimes/aws-strands/react/src/application.spec.ts @@ -690,12 +690,11 @@ it.each([true, false])( void h.app.decide(a, 'approve', 0); expect(h.session.resume).toHaveBeenCalledTimes(1); expect(h.session.resume).toHaveBeenCalledWith( - a.pause, [ { interruptId: 'opaque-native-interrupt', status: 'resolved', - payload: { approved }, + value: { approved }, }, ], expect.anything() @@ -822,7 +821,7 @@ it('Stop during resume aborts and makes late completion powerless', async () => const h = harness(), a = await h.pause(), pending = h.app.decide(a, 'approve', 0); - const options = vi.mocked(h.session.resume).mock.calls[0][2]; + const options = vi.mocked(h.session.resume).mock.calls[0][1]; const stopped = h.app.stop(); expect(options?.signal?.aborted).toBe(true); expect(h.app.getSnapshot().approval).toBeUndefined(); diff --git a/cockpit/runtimes/aws-strands/react/src/application.ts b/cockpit/runtimes/aws-strands/react/src/application.ts index ed4117105..abeb09e29 100644 --- a/cockpit/runtimes/aws-strands/react/src/application.ts +++ b/cockpit/runtimes/aws-strands/react/src/application.ts @@ -547,12 +547,11 @@ export function createStrandsApplication(options: { p.approved = action === 'approve'; const pending = p.methods.resume.call( p.candidate, - approval.pause, [ { interruptId: approval.interruptId, status: 'resolved', - payload: { approved: p.approved }, + value: { approved: p.approved }, }, ], { signal: controller.signal } diff --git a/cockpit/runtimes/aws-strands/react/src/approval-policy.ts b/cockpit/runtimes/aws-strands/react/src/approval-policy.ts index 2edafe727..cb28d2c43 100644 --- a/cockpit/runtimes/aws-strands/react/src/approval-policy.ts +++ b/cockpit/runtimes/aws-strands/react/src/approval-policy.ts @@ -1,4 +1,4 @@ -import type { Session } from '@threadplane/ag-ui'; +import type { DecisionState, Session } from '@threadplane/ag-ui'; export type NativeSnapshot = ReturnType; type Transcript = NativeSnapshot['transcript']; export interface Meeting { @@ -15,7 +15,7 @@ export interface MeetingApproval { readonly threadId: string; readonly sourceRunId: string; /** Keep the original opaque branded occurrence, never decode an interrupt identifier. */ - readonly pause: Parameters[0]; + readonly pause: Extract['id']; readonly interruptId: string; readonly toolCallId: string; readonly meeting: Meeting; @@ -383,9 +383,10 @@ export function captureApproval( if (!valid()) return; const pause = original && - (Object.getOwnPropertyDescriptor(original, 'id')?.value as Parameters< - Session['resume'] - >[0]); + (Object.getOwnPropertyDescriptor(original, 'id')?.value as Extract< + DecisionState, + { kind: 'native' } + >['id']); if (!valid() || pause !== d.id) return; return Object.freeze({ threadId: turn.threadId, diff --git a/cockpit/runtimes/mastra/react/src/application.spec.ts b/cockpit/runtimes/mastra/react/src/application.spec.ts index ef4b443a3..7dcd88c08 100644 --- a/cockpit/runtimes/mastra/react/src/application.spec.ts +++ b/cockpit/runtimes/mastra/react/src/application.spec.ts @@ -180,15 +180,12 @@ it.each(['approve', 'decline'] as const)( const pending = h.app.decide(approval, action); await h.app.decide(approval, action === 'approve' ? 'decline' : 'approve'); expect(h.session.resume).toHaveBeenCalledTimes(1); - expect(vi.mocked(h.session.resume).mock.calls[0].slice(0, 2)).toEqual([ - 'opaque-pause', - [ - { - interruptId: 'opaque-interrupt', - status: 'resolved', - payload: { approved: action === 'approve' }, - }, - ], + expect(vi.mocked(h.session.resume).mock.calls[0][0]).toEqual([ + { + interruptId: 'opaque-interrupt', + status: 'resolved', + value: { approved: action === 'approve' }, + }, ]); h.finish(completed(action === 'approve'), 'success'); await pending; diff --git a/cockpit/runtimes/mastra/react/src/application.ts b/cockpit/runtimes/mastra/react/src/application.ts index 3aba18f10..31530dfe9 100644 --- a/cockpit/runtimes/mastra/react/src/application.ts +++ b/cockpit/runtimes/mastra/react/src/application.ts @@ -425,12 +425,11 @@ export function createMastraApplication(options: { if (!ownedValid() || p.unsafe) return; const pending = method.call( p.session, - approval.pause, [ { interruptId: approval.interruptId, status: 'resolved', - payload: { approved: p.approved }, + value: { approved: p.approved }, }, ], { signal: controller.signal } diff --git a/cockpit/runtimes/mastra/react/src/approval-policy.ts b/cockpit/runtimes/mastra/react/src/approval-policy.ts index cce0dd5ab..e1bd47d5f 100644 --- a/cockpit/runtimes/mastra/react/src/approval-policy.ts +++ b/cockpit/runtimes/mastra/react/src/approval-policy.ts @@ -1,4 +1,4 @@ -import type { Session } from '@threadplane/ag-ui'; +import type { DecisionState, Session } from '@threadplane/ag-ui'; export type NativeSnapshot = ReturnType; type Transcript = NativeSnapshot['transcript']; export interface OwnedTurn { @@ -10,7 +10,7 @@ export interface OwnedTurn { export interface ReservationApproval { readonly threadId: string; readonly sourceRunId: string; - readonly pause: Parameters[0]; + readonly pause: Extract['id']; readonly interruptId: string; readonly toolCallId: string; readonly site: string; diff --git a/cockpit/runtimes/microsoft-agent-framework/react/src/application.spec.ts b/cockpit/runtimes/microsoft-agent-framework/react/src/application.spec.ts index 864b14e42..5513bcbb1 100644 --- a/cockpit/runtimes/microsoft-agent-framework/react/src/application.spec.ts +++ b/cockpit/runtimes/microsoft-agent-framework/react/src/application.spec.ts @@ -634,8 +634,7 @@ it.each([true, false])( void h.app.decide(a, 'approve', 0); expect(h.session.resume).toHaveBeenCalledTimes(1); expect(h.session.resume).toHaveBeenCalledWith( - a.pause, - [{ interruptId: 'call', status: 'resolved', payload: { approved } }], + [{ interruptId: 'call', status: 'resolved', value: { approved } }], expect.anything() ); h.update(completed(approved)); diff --git a/cockpit/runtimes/microsoft-agent-framework/react/src/application.ts b/cockpit/runtimes/microsoft-agent-framework/react/src/application.ts index 77535a8f5..cc17d7be3 100644 --- a/cockpit/runtimes/microsoft-agent-framework/react/src/application.ts +++ b/cockpit/runtimes/microsoft-agent-framework/react/src/application.ts @@ -548,12 +548,11 @@ export function createMafApplication(options: { p.approved = action === 'approve'; const pending = p.methods.resume.call( p.candidate, - approval.pause, [ { interruptId: approval.interruptId, status: 'resolved', - payload: { approved: p.approved }, + value: { approved: p.approved }, }, ], { signal: controller.signal } diff --git a/cockpit/runtimes/microsoft-agent-framework/react/src/approval-policy.ts b/cockpit/runtimes/microsoft-agent-framework/react/src/approval-policy.ts index 82294173e..9e3924dff 100644 --- a/cockpit/runtimes/microsoft-agent-framework/react/src/approval-policy.ts +++ b/cockpit/runtimes/microsoft-agent-framework/react/src/approval-policy.ts @@ -1,4 +1,4 @@ -import type { Session } from '@threadplane/ag-ui'; +import type { DecisionState, Session } from '@threadplane/ag-ui'; export type NativeSnapshot = ReturnType; type Transcript = NativeSnapshot['transcript']; export interface Expense { @@ -17,7 +17,7 @@ export interface ExpenseApproval { readonly threadId: string; readonly sourceRunId: string; /** Original opaque native occurrence; never reconstruct from observation data. */ - readonly pause: Parameters[0]; + readonly pause: Extract['id']; readonly interruptId: string; readonly toolCallId: string; readonly expense: Expense; @@ -432,7 +432,7 @@ export function captureApproval( const pause = originalDecision && (Object.getOwnPropertyDescriptor(originalDecision, 'id') - ?.value as Parameters[0]); + ?.value as Extract['id']); if (!valid() || pause !== d.id) return; return Object.freeze({ threadId: turn.threadId, 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 456009832..0cd259fd6 100644 --- a/fixtures/react-parity/ag-ui-candidate/installed-types.ts +++ b/fixtures/react-parity/ag-ui-candidate/installed-types.ts @@ -22,7 +22,7 @@ import type { Message, ToolCall, } from '@threadplane/core'; -export type NativeResponse = Parameters[1][number]; +export type NativeResponse = Parameters[0][number]; export function checkCandidate(signal: AbortSignal) { const options: SessionOptions = { threadId: 'candidate', @@ -51,7 +51,7 @@ export function checkCandidate(signal: AbortSignal) { const resolved: NativeResponse = { interruptId: 'backend-id', status: 'resolved', - payload: null, + value: null, metadata: { reviewed: true }, }; const cancelled: NativeResponse = { @@ -59,13 +59,17 @@ export function checkCandidate(signal: AbortSignal) { status: 'cancelled', }; if (snapshot.decision?.kind === 'native') { - void session.resume(snapshot.decision.id, [resolved], { signal }); - void session.resume(snapshot.decision.id, [cancelled]); - // @ts-expect-error Pause generations are branded, not arbitrary strings. - void session.resume('backend-id', [resolved]); - void session.resume(snapshot.decision.id, [ - // @ts-expect-error Cancelled native responses cannot carry a payload. - { interruptId: 'backend-id', status: 'cancelled', payload: null }, + void session.resume([resolved], { signal }); + void session.resume([cancelled]); + // @ts-expect-error Resume takes the responses alone, with no pause id. + void session.resume(snapshot.decision.id, [resolved]); + void session.resume([ + // @ts-expect-error A cancelled response cannot carry a value. + { interruptId: 'backend-id', status: 'cancelled', value: null }, + ]); + void session.resume([ + // @ts-expect-error The answer is the response's value, not a payload. + { interruptId: 'backend-id', status: 'resolved', payload: null }, ]); // @ts-expect-error Decision evidence is readonly. snapshot.decision.interrupts.push({ id: 'changed' }); @@ -92,7 +96,7 @@ export function checkCandidate(signal: AbortSignal) { void session.addToolResult('id', 'result'); const pending: DecisionState | undefined = decisionState(snapshot); if (pending?.kind === 'native' && pending.phase === 'ready') { - void session.resume(pending.id, [ + void session.resume([ { interruptId: pending.interrupts[0].id, status: 'resolved' }, ]); // @ts-expect-error The pending decision is readonly. @@ -107,8 +111,13 @@ export function checkCandidate(signal: AbortSignal) { void agent.submit({ message: 'Hello', state: { topic: 'x' } }); // @ts-expect-error A submission takes a message and state only. void agent.submit({ message: 'Hello', messages: [] }); - // @ts-expect-error Resume is not part of the core contract. - void agent.resume; + // The session's resume is the core contract's command. + const resumed: Promise | undefined = agent.resume?.([ + { interruptId: 'backend-id', status: 'resolved', value: true }, + ]); + const waiting: string | undefined = core.interrupts?.[0]?.id; + const child: string | undefined = core.subagents?.[0]?.id; + void [resumed, waiting, child]; 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/native-ag-ui-a2ui/installed-types.ts b/fixtures/react-parity/native-ag-ui-a2ui/installed-types.ts index dbcb9c5cd..77b3389cd 100644 --- a/fixtures/react-parity/native-ag-ui-a2ui/installed-types.ts +++ b/fixtures/react-parity/native-ag-ui-a2ui/installed-types.ts @@ -31,8 +31,7 @@ export function checkInstalledA2ui(signal: AbortSignal) { } if (snapshot.decision?.kind === 'native') void owner.resume( - snapshot.decision.id, - [{ interruptId: 'i', status: 'resolved', payload: null }], + [{ interruptId: 'i', status: 'resolved', value: null }], { signal } ); void [snapshot.status, snapshot.state, snapshot.subagents]; diff --git a/fixtures/react-parity/native-ag-ui/README.md b/fixtures/react-parity/native-ag-ui/README.md index 73889fccb..5f14ce315 100644 --- a/fixtures/react-parity/native-ag-ui/README.md +++ b/fixtures/react-parity/native-ag-ui/README.md @@ -53,8 +53,8 @@ Use each enabled control in order: retains the earlier custom notice beside that terminal. 3. **Mount React** reconnects observation without a request and displays both the retained notice and native terminal. -4. **Resume** uses the observed native pause token and an explicit resolved - `approval` response with payload `{ approved: true }`. It sends full prior native +4. **Resume** answers the observed native pause with an explicit resolved + `approval` response whose value is `{ approved: true }`. It sends full prior native history and `count: 2`, adds no user row or settings patch, then shows root `Next answer`. The diagnostic decision contains the captured running attempt. 5. **Remove Angular**, then **Complete resume**. React receives successful @@ -85,7 +85,7 @@ ending at EOF would be `interrupted`; local cancellation can be `aborted` even after terminal evidence was observed. Explicit private `legacy-observation` mode retains the older close-at-notice convention but supplies no resume capability. Any decision blocks ordinary submission. Only a settled unclaimed native pause -can be answered once with its current token; legacy notices cannot be resumed. +can be answered once; legacy notices cannot be resumed. If an invoked resume fails, ends at EOF or is stopped without conclusive native evidence, its retained attempt is uncertain and blocks replay and ordinary bypass. Local stop or reconstructing an owner is not recovery. Separate held HTTP tests diff --git a/fixtures/react-parity/native-ag-ui/browser.tsx b/fixtures/react-parity/native-ag-ui/browser.tsx index abac227fe..c566c9b07 100644 --- a/fixtures/react-parity/native-ag-ui/browser.tsx +++ b/fixtures/react-parity/native-ag-ui/browser.tsx @@ -16,7 +16,11 @@ import { TextTranscriptComponent, ToolObservationComponent, } from '@threadplane/angular/chat'; -import { createSession, projectTextTranscript, type Session } from './backend-binding.js'; +import { + createSession, + projectTextTranscript, + type Session, +} from './backend-binding.js'; const sequence = [ 'First', @@ -249,11 +253,11 @@ function start(session: Session, text: string) { const command = text === 'Resume' ? decision?.kind === 'native' - ? session.resume(decision.id, [ + ? session.resume([ { interruptId: 'approval', status: 'resolved', - payload: { approved: true }, + value: { approved: true }, }, ]) : Promise.reject(new Error('A current native pause is required')) 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/ag-ui/src/runtime/README.md b/libs/ag-ui/src/runtime/README.md index f65253785..96926b977 100644 --- a/libs/ag-ui/src/runtime/README.md +++ b/libs/ag-ui/src/runtime/README.md @@ -140,15 +140,31 @@ const session = createSession({ threadId, url }); ``` - `getSnapshot` returns the core snapshot, - `{ status, messages, toolCalls, error?, plan?, usage?, state?, stateIssues? }`, - together with the protocol evidence behind it: `transcript`, `subagents`, + `{ status, messages, toolCalls, error?, plan?, usage?, state?, stateIssues?, interrupts?, subagents }`, + together with the protocol evidence behind it: `transcript`, `earlierSubagents`, `decision`, `reasoningDurations` and `run`. `messages` and `toolCalls` are what the two selectors above return, and keep their references until they change. One publication always reads as one snapshot. +- `interrupts` lists what a paused run waits on, from the pause until an answer + is sent. Each entry is the protocol's interrupt, so it has the core `id`, + `reason`, `message` and `toolCallId` and any other field the backend sent. It + is absent when nothing is waiting, and for a pause this session cannot answer. +- `subagents` lists the current run's children as core child agents: `id`, + `name`, `description`, `toolCallId`, `parentId`, `status`, and the child's own + `messages` and `toolCalls`, which the root lists do not repeat. The protocol + evidence stays on each child as `started` and `terminal`. A child with + finished evidence is `complete`, one with error evidence is `error` and + carries its message, and one with neither is `running` while the root run is + going and `unknown` after it. A child keeps its reference until its evidence, + status or records change. Children of earlier runs are bare evidence in + `earlierSubagents`. Records are matched by run id, so a later child that + reuses an id also lists the earlier child's records. - Every publication notifies subscribers, including one that changes only protocol evidence such as a decision or a child. -- `submit` takes text, or `{ message, state? }` with a state patch. `resume` - and the client-tool evidence are AG-UI additions to the core contract. +- `submit` takes text, or `{ message, state? }` with a state patch. +- `resume` is the core contract's command: it takes one response for each + pending interrupt, named by `id` (see "Correlated native resume"). +- The client-tool evidence is an AG-UI addition to the core contract. - A failed run becomes `snapshot.error`. A backend `RUN_ERROR` is a `server` error carrying the backend's message. A stream that ended without a terminal is `interrupted`. A response that was not OK carries its HTTP status: 401 and @@ -266,7 +282,7 @@ const pending = decisionState(useAgent(session)); id: 'approve', label: 'Issue refund', onSelect: () => - void session.resume(pending.id, [ + void session.resume([ { interruptId: pending.interrupts[0].id, status: 'resolved' }, ]), }, @@ -287,8 +303,8 @@ const pending = decisionState(useAgent(session)); the answer. An uncertain answer cannot be sent again. - The same decision in the same phase returns the same reference. - `ready` does not look at the clock: an interrupt past its `expiresAt` still - reads `ready`, and `resume` then resolves `error`. -- What the buttons mean, and which payload answers which interrupt, stay with + reads `ready`, and `resume` then rejects. +- What the buttons mean, and which value answers which interrupt, stay with the app. Response schemas are not interpreted. The candidate package entry exports it. The published package root does not. @@ -342,36 +358,44 @@ Child notices do not create root decisions. Duplicate interrupt IDs retain an unsupported blocker. The locked SDK rejects empty wire batches before delivery; that error preserves an existing blocker or claim and invents no terminal. -After the native pause has locally settled, explicitly answer its current token: +After the native pause has locally settled, answer its interrupts with the core +contract's `resume`: ```ts const snapshot = session.getSnapshot(); -if ( - snapshot.decision?.kind === 'native' && - !snapshot.decision.attempt && - snapshot.run?.outcome -) { - await session.resume(snapshot.decision.id, [ - { - interruptId: 'approval', +if (snapshot.interrupts?.length && snapshot.run?.outcome) { + await session.resume( + snapshot.interrupts.map((interrupt) => ({ + interruptId: interrupt.id, status: 'resolved', - payload: { approved: true }, - }, - ]); + value: { approved: true }, + })) + ); } ``` -Every observed interrupt needs exactly one response with its exact ID. Resolved -responses may omit payload; a `null` payload is treated as absent (the AG-UI 1.0 -client omits whole-optional nulls on the wire). Cancelled responses use -`{ interruptId, status: 'cancelled' }` and cannot contain a defined payload. -Optional metadata must be a plain record. Responses and the options signal are +`resume` takes the responses alone and answers the pause that is pending; there +is no pause token to pass. Every pending interrupt needs exactly one response +with its exact ID. A resolved response may omit `value`; a `null` value is +treated as absent (the AG-UI 1.0 client omits whole-optional nulls on the wire). +The request carries the value as the protocol's `payload`, and so does +`decision.attempt.responses`. A cancelled response is +`{ interruptId, status: 'cancelled' }` and cannot carry a value. A response may +also carry the protocol's optional `metadata`, which must be a plain record. + +`resume` rejects with a `TypeError`, sending nothing, when no interrupt is +waiting, the pausing run has not settled, an answer was already sent, a run is +active, an interrupt has expired, the responses are not an array, a response +names an interrupt that is not pending or names one twice, or an interrupt is +left unanswered. It resolves `aborted`, sending nothing, after disposal and when +its signal is already aborted. Once the answer is sent it resolves with that +run's outcome. Responses and the options signal are captured once before queueing; nested data is copied and frozen without freezing the caller. Extra runtime getters are ignored. Response schemas are opaque; this owner neither validates business answers nor guesses defaults or aliases. -Eligibility is checked at invocation and admission. The token must identify the -current unclaimed native generation, the current run must be locally settled, +Eligibility is checked at invocation and admission. The pending decision must be +the current unclaimed native generation, the current run must be locally settled, and every supplied expiry must parse to a time strictly in the future. An observing terminal callback cannot enqueue future resume intent before settlement. Two observers can claim only once. Admission publishes the attempt and new run @@ -389,14 +413,14 @@ controls, not backend rejection or recovery. Each private run result reports `fetchInvoked`, recorded immediately before the captured fetch call. A claim cancelled before that boundary is released and can -be retried with the same token. Once fetch was invoked, failure, EOF or abort +be retried. Once fetch was invoked, failure, EOF or abort without conclusive native evidence retains the attempt and forbids replay or ordinary bypass. `RUN_STARTED`, local promise completion and exception properties do not establish server acknowledgement or socket closure. No retry, reset, session reconstruction or persistence/recovery guarantee is provided. Native success clears the decision at local settlement, even if a terminal -listener selected local `aborted`. A new native pause receives a fresh token even +listener selected local `aborted`. A new native pause is a fresh generation even when backend interrupt IDs repeat; old finalizers cannot clear that generation. Legacy observation has no resume support. Captured Strands replay establishes native response wire shape with synthetic completion only. Captured Mastra and diff --git a/libs/ag-ui/src/runtime/agent-session.ts b/libs/ag-ui/src/runtime/agent-session.ts index cfd13d36c..090f8fbbc 100644 --- a/libs/ag-ui/src/runtime/agent-session.ts +++ b/libs/ag-ui/src/runtime/agent-session.ts @@ -1,6 +1,7 @@ import { readState, type AgentError, + type AgentInterrupt, type AgentSnapshot, type AgentUsage, type AgentUsageEntry, @@ -8,12 +9,11 @@ import { type StateDeclaration, type ToolContract, } from '@threadplane/core'; +import { projectSubagents, type SessionSubagent } from './child-projection.js'; +import type { OwnedInterrupt } from './decision.js'; import { NO_STATE, ownState } from './state.js'; import { projectMessages, projectToolCalls } from './message-projection.js'; -import { - failedWithRunError, - type Observation, -} from './session-observation.js'; +import { failedWithRunError, type Observation } from './session-observation.js'; type Tools = Record; /** @@ -21,8 +21,23 @@ type Tools = Record; * evidence behind it. `state` is the typed state; the literal document a * request sends is not published. */ -export type SessionSnapshot = Omit & - AgentSnapshot & { +export type SessionSnapshot = Omit< + Observation, + 'state' | 'subagents' +> & + Omit, 'interrupts' | 'subagents'> & { + /** + * What a paused run waits on, each with the protocol's own fields. Listed + * from the pause until an answer is sent, and absent otherwise; a pause + * this session cannot answer lists nothing. + */ + readonly interrupts?: readonly SessionInterrupt[]; + /** + * The current root run's children, each with its own messages and tool + * calls and the protocol evidence it was read from. Children of earlier + * runs are in `earlierSubagents`. + */ + readonly subagents: readonly SessionSubagent[]; /** * Why the session's state schema rejected the current state document. * `state` then keeps the last document that passed. Absent while the @@ -31,6 +46,9 @@ export type SessionSnapshot = Omit & readonly stateIssues?: readonly string[]; }; +/** A pending interrupt: the core interrupt, with the protocol's own fields. */ +export type SessionInterrupt = AgentInterrupt & OwnedInterrupt; + /** The state to publish for one state document, and why a schema rejected it. */ interface StateView { readonly source: PlainValue; @@ -99,8 +117,10 @@ function failure( terminal?.type === 'RUN_ERROR' && 'message' in terminal ? terminal.message : undefined; - const interrupted = reported === undefined && native.run?.outcome === 'interrupted'; - const status = reported === undefined ? native.run?.failure?.status : undefined; + const interrupted = + reported === undefined && native.run?.outcome === 'interrupted'; + const status = + reported === undefined ? native.run?.failure?.status : undefined; const auth = status === 401 || status === 403; const kind = interrupted ? 'interrupted' : auth ? 'auth' : 'server'; const message = interrupted @@ -189,11 +209,18 @@ function project( ? failure(native, canRetry, previous?.error) : undefined; const used = usage(native); - const { state: _document, ...evidence } = native; + const { state: _document, subagents: _children, ...evidence } = native; + const decision = native.decision; + const interrupts = + decision?.kind === 'native' && !decision.attempt + ? decision.interrupts + : undefined; return Object.freeze({ ...evidence, messages, toolCalls, + subagents: projectSubagents(native, previous?.subagents), + ...(interrupts && { interrupts }), ...(error && { error }), ...(used && { usage: used }), ...(view.state !== undefined && { state: view.state }), diff --git a/libs/ag-ui/src/runtime/child-projection.spec.ts b/libs/ag-ui/src/runtime/child-projection.spec.ts new file mode 100644 index 000000000..7b8d3e9d0 --- /dev/null +++ b/libs/ag-ui/src/runtime/child-projection.spec.ts @@ -0,0 +1,201 @@ +import type { AgentSession } from '@threadplane/core'; +import { describe, expect, it } from 'vitest'; +import { bindingFixture } from './testing/binding-fixture'; + +describe('core interrupts and child agents on the AG-UI snapshot', () => { + it('publishes each child with its own messages and tool calls', async () => { + const fixture = bindingFixture(); + try { + const run = fixture.session.submit('Research it'); + const exchange = await fixture.started(); + const streamed = fixture.changed( + (snapshot) => + snapshot.subagents[0]?.messages[0]?.content === 'Two sources' + ); + exchange.emit({ + type: 'TEXT_MESSAGE_START', + messageId: 'root', + role: 'assistant', + }); + exchange.emit({ + type: 'TOOL_CALL_START', + toolCallId: 'delegate', + toolCallName: 'task', + parentMessageId: 'root', + }); + exchange.emit({ + type: 'SUBAGENT_STARTED', + subagentRunId: 'child', + name: 'researcher', + description: 'Find the sources', + parentToolCallId: 'delegate', + }); + exchange.emit({ + type: 'TEXT_MESSAGE_START', + messageId: 'finding', + role: 'assistant', + subagentRunId: 'child', + }); + exchange.emit({ + type: 'TEXT_MESSAGE_CONTENT', + messageId: 'finding', + delta: 'Two sources', + }); + exchange.emit({ type: 'TEXT_MESSAGE_END', messageId: 'finding' }); + await streamed; + const running = fixture.session.getSnapshot(); + expect(running.subagents).toHaveLength(1); + const child = running.subagents[0]; + expect(child).toMatchObject({ + id: 'child', + name: 'researcher', + description: 'Find the sources', + toolCallId: 'delegate', + status: 'running', + toolCalls: [], + }); + expect(child.messages.map((message) => message.content)).toEqual([ + 'Two sources', + ]); + // The child's messages are its own: the root transcript does not repeat them. + expect(running.messages.map((message) => message.id)).not.toContain( + 'finding' + ); + // The protocol evidence stays alongside the core fields. + expect(child.started.subagentRunId).toBe('child'); + expect(child.terminal).toBeUndefined(); + + // A publication that does not touch the child keeps its reference. + const worked = fixture.changed((snapshot) => + snapshot.messages.some((message) => message.content === 'Working') + ); + exchange.emit({ + type: 'TEXT_MESSAGE_CONTENT', + messageId: 'root', + delta: 'Working', + }); + await worked; + expect(fixture.session.getSnapshot().subagents).toBe(running.subagents); + + const ended = fixture.changed( + (snapshot) => snapshot.subagents[0]?.terminal !== undefined + ); + exchange.emit({ + type: 'SUBAGENT_ERROR', + subagentRunId: 'child', + message: 'The search failed', + }); + await ended; + const failed = fixture.session.getSnapshot().subagents[0]; + expect(failed).not.toBe(child); + expect(failed).toMatchObject({ + id: 'child', + status: 'error', + error: 'The search failed', + }); + // A child that has ended streams nothing further. + expect(child.messages[0].delivery.phase).toBe('streaming'); + expect(failed.messages[0].delivery.phase).toBe('complete'); + + exchange.emit({ type: 'TOOL_CALL_END', toolCallId: 'delegate' }); + exchange.emit({ type: 'TEXT_MESSAGE_END', messageId: 'root' }); + exchange.emit({ + type: 'RUN_FINISHED', + threadId: exchange.body.threadId, + runId: exchange.body.runId, + }); + await expect(run).resolves.toBe('success'); + // A core observer reads the same children. + const observer: AgentSession = fixture.session; + expect(observer.getSnapshot().subagents?.[0]?.id).toBe('child'); + } finally { + await fixture.cleanup(); + } + }); + + it('reports a child with no ending as unknown once the run settles', async () => { + const fixture = bindingFixture(); + try { + const run = fixture.session.submit('Go'); + const exchange = await fixture.started(); + const seen = fixture.changed( + (snapshot) => snapshot.subagents.length === 1 + ); + exchange.emit({ + type: 'SUBAGENT_STARTED', + subagentRunId: 'open', + name: 'worker', + }); + await seen; + expect(fixture.session.getSnapshot().subagents[0].status).toBe('running'); + exchange.emit({ + type: 'RUN_FINISHED', + threadId: exchange.body.threadId, + runId: exchange.body.runId, + }); + // The protocol requires every child to end before its run does. + await expect(run).resolves.toBe('error'); + expect(fixture.session.getSnapshot().subagents[0].status).toBe('unknown'); + } finally { + await fixture.cleanup(); + } + }); + + it('lists pending interrupts until an answer is sent, and answers them by id', async () => { + const fixture = bindingFixture(); + try { + expect('interrupts' in fixture.session.getSnapshot()).toBe(false); + const run = fixture.session.submit('Refund it'); + const exchange = await fixture.started(); + exchange.emit({ + type: 'RUN_FINISHED', + threadId: exchange.body.threadId, + runId: exchange.body.runId, + outcome: { + type: 'interrupt', + interrupts: [ + { id: 'approval', reason: 'approve', message: 'Refund $20?' }, + ], + }, + }); + await expect(run).resolves.toBe('paused'); + const paused = fixture.session.getSnapshot(); + expect(paused.interrupts).toEqual([ + { id: 'approval', reason: 'approve', message: 'Refund $20?' }, + ]); + // A core observer answers through the core command. + const observer: AgentSession = fixture.session; + await expect( + observer.resume?.([{ interruptId: 'other', status: 'resolved' }]) + ).rejects.toThrow(TypeError); + expect(fixture.session.getSnapshot()).toBe(paused); + const pending = observer.getSnapshot().interrupts ?? []; + const resumed = observer.resume?.( + pending.map((interrupt) => ({ + interruptId: interrupt.id, + status: 'resolved' as const, + value: { approved: true }, + })) + ); + const next = await fixture.started(1); + expect(next.body.resume).toEqual([ + { + interruptId: 'approval', + status: 'resolved', + payload: { approved: true }, + }, + ]); + // The answer is on its way: nothing is waiting on a person now. + expect('interrupts' in fixture.session.getSnapshot()).toBe(false); + next.emit({ + type: 'RUN_FINISHED', + threadId: next.body.threadId, + runId: next.body.runId, + }); + await expect(resumed).resolves.toBe('success'); + expect('interrupts' in fixture.session.getSnapshot()).toBe(false); + } finally { + await fixture.cleanup(); + } + }); +}); diff --git a/libs/ag-ui/src/runtime/child-projection.ts b/libs/ag-ui/src/runtime/child-projection.ts new file mode 100644 index 000000000..e29b602e1 --- /dev/null +++ b/libs/ag-ui/src/runtime/child-projection.ts @@ -0,0 +1,113 @@ +import type { AgentSubagent, Message, ToolCall } from '@threadplane/core'; +import { projectMessages, projectToolCalls } from './message-projection.js'; +import type { Observation } from './session-observation.js'; +import type { SubagentObservation } from './subagents.js'; +import type { Transcript } from './transcript.js'; + +type TranscriptRecord = Transcript[number]; + +/** + * One child of the current root run: the core child, with the protocol + * evidence it was read from. `messages` and `toolCalls` are the child's own + * and are not repeated in the root snapshot's. They are every transcript record + * attributed to the child's run id, so a later child that reuses an id also + * lists the earlier child's records. + */ +export type SessionSubagent = AgentSubagent & SubagentObservation; + +/** A child's records read as a root transcript, so the root selectors apply. */ +const unattributed = new WeakMap(); +function asRoot(record: TranscriptRecord): TranscriptRecord { + let known = unattributed.get(record); + if (!known) { + const { subagentRunId: _child, ...rest } = record as TranscriptRecord & { + subagentRunId?: string; + }; + known = Object.freeze(rest) as TranscriptRecord; + unattributed.set(record, known); + } + return known; +} + +function status( + evidence: SubagentObservation, + running: boolean +): AgentSubagent['status'] { + if (evidence.terminal) + return evidence.terminal.type === 'SUBAGENT_ERROR' ? 'error' : 'complete'; + return running ? 'running' : 'unknown'; +} + +const none: readonly SessionSubagent[] = Object.freeze([]); +const noMessages: readonly Message[] = Object.freeze([]); +const noCalls: readonly ToolCall[] = Object.freeze([]); + +/** + * The current run's children as core children. Each keeps its reference, and + * the list keeps its own, until that child's evidence, status or transcript + * changes. `previous` is the list this function returned last. + */ +export function projectSubagents( + native: Observation, + previous: readonly SessionSubagent[] = none +): readonly SessionSubagent[] { + if (!native.subagents.length) return previous.length ? none : previous; + const records = new Map(); + for (const record of native.transcript) { + const child = (record as { subagentRunId?: unknown }).subagentRunId; + if (typeof child !== 'string') continue; + const own = records.get(child); + if (own) own.push(asRoot(record)); + else records.set(child, [asRoot(record)]); + } + const prior = new Map(previous.map((child) => [child.id, child])); + const running = native.status === 'running'; + let changed = previous.length !== native.subagents.length; + const children = native.subagents.map((evidence, index) => { + const { started, terminal } = evidence; + const id = started.subagentRunId; + const before = prior.get(id); + const state = status(evidence, running); + // A child with terminal evidence streams nothing further. + const view = { + status: state === 'running' ? ('running' as const) : ('idle' as const), + transcript: Object.freeze(records.get(id) ?? []) as Transcript, + reasoningDurations: native.reasoningDurations, + }; + const messages = projectMessages(view, before?.messages ?? noMessages); + const toolCalls = projectToolCalls(view, before?.toolCalls ?? noCalls); + if ( + before && + before.started === started && + before.terminal === terminal && + before.status === state && + before.messages === messages && + before.toolCalls === toolCalls + ) { + if (previous[index] !== before) changed = true; + return before; + } + changed = true; + return Object.freeze({ + id, + ...(typeof started.name === 'string' && { name: started.name }), + ...(typeof started.description === 'string' && { + description: started.description, + }), + ...(typeof started.parentToolCallId === 'string' && { + toolCallId: started.parentToolCallId, + }), + ...(typeof started.parentSubagentRunId === 'string' && { + parentId: started.parentSubagentRunId, + }), + status: state, + messages, + toolCalls, + ...(terminal?.type === 'SUBAGENT_ERROR' && + typeof terminal.message === 'string' && { error: terminal.message }), + started, + ...(terminal && { terminal }), + }) as SessionSubagent; + }); + return changed ? Object.freeze(children) : previous; +} diff --git a/libs/ag-ui/src/runtime/client-tools-session-http.spec.ts b/libs/ag-ui/src/runtime/client-tools-session-http.spec.ts index 5aef450cc..f3b4cbc60 100644 --- a/libs/ag-ui/src/runtime/client-tools-session-http.spec.ts +++ b/libs/ag-ui/src/runtime/client-tools-session-http.spec.ts @@ -187,8 +187,8 @@ describe('native client tools over physical HTTP', () => { const paused = owner.getSnapshot(); if (paused.decision?.kind !== 'native') throw new Error('Missing pause'); - const done = owner.resume(paused.decision.id, [ - { interruptId: 'approve', status: 'resolved', payload: true }, + const done = owner.resume([ + { interruptId: 'approve', status: 'resolved', value: true }, ]); const resumed = await server.next(1); resumed.send( @@ -360,8 +360,8 @@ describe('native client tools over physical HTTP', () => { if (paused.decision?.kind !== 'native') throw new Error('Missing native pause'); expect(paused.run?.id).toBe(continuation.body.runId); - const done = owner.resume(paused.decision.id, [ - { interruptId: 'approve', status: 'resolved', payload: true }, + const done = owner.resume([ + { interruptId: 'approve', status: 'resolved', value: true }, ]); const resumed = await server.next(2); expect(resumed.body.resume).toEqual([ @@ -409,8 +409,8 @@ describe('native client tools over physical HTTP', () => { const paused = owner.getSnapshot(); if (paused.decision?.kind !== 'native') throw new Error('Missing native pause'); - const done = owner.resume(paused.decision.id, [ - { interruptId: 'approve', status: 'resolved', payload: true }, + const done = owner.resume([ + { interruptId: 'approve', status: 'resolved', value: true }, ]); const resumed = await server.next(1); resumed.send(lifecycle(resumed), lifecycle(resumed, 'RUN_FINISHED')); diff --git a/libs/ag-ui/src/runtime/create-session.ts b/libs/ag-ui/src/runtime/create-session.ts index 9e3b87c63..5d40a174c 100644 --- a/libs/ag-ui/src/runtime/create-session.ts +++ b/libs/ag-ui/src/runtime/create-session.ts @@ -53,9 +53,13 @@ import { claimDecision, observeDecision, settleDecision, + type InterruptResponse, type NativeResponse, type PauseId, } from './decision.js'; + +/** Why `resume` rejects while a run is active or the session cannot answer. */ +const NOT_SETTLED = 'Resume needs a settled session with a pending interrupt.'; import { copyData } from '../lib/internal/copy-data.js'; import { captureSubmit, @@ -98,9 +102,18 @@ export interface Session { input: SubmitInput, options?: { readonly signal?: AbortSignal } ): Promise; + /** + * Answers the pending interrupts, as the core contract's `resume`: one + * response for each interrupt in the snapshot's `interrupts`, naming it by + * `id`. A response may also carry the protocol's `metadata`. + * + * Rejects without sending when no interrupt is waiting, a run is active, an + * interrupt has expired, a response names an interrupt that is not pending + * or names one twice, or an interrupt is left unanswered. Resolves `aborted` + * without sending after disposal or when the signal is already aborted. + */ resume( - pause: PauseId, - responses: readonly NativeResponse[], + responses: readonly InterruptResponse[], options?: { readonly signal?: AbortSignal } ): Promise; stop(): Promise; @@ -453,8 +466,8 @@ export function createSession( disposed ? () => undefined : publication.subscribe(notify), onCustomEvent: (listener) => disposed ? () => undefined : publication.onCustomEvent(listener), - resume: (pause, responses, options) => - new Promise((resolve) => { + resume: (responses, options) => + new Promise((resolve, reject) => { const beforeSignal = revision; let signal: AbortSignal | undefined; try { @@ -472,20 +485,17 @@ export function createSession( try { const previous = publication.getObservation(); if (interruptMode !== 'native' || active) - throw new TypeError('Resume requires a settled native owner'); - assertResumeEligible( - previous.decision, - previous.run, - pause, - Date.now() - ); + throw new TypeError(NOT_SETTLED); captured = captureResponses(responses); - } catch { - resolve( - disposed || signal?.aborted || revision !== beforeInput - ? 'aborted' - : 'error' + claimDecision( + assertResumeEligible(previous.decision, previous.run, Date.now()), + captured, + '' ); + } catch (error) { + if (disposed || signal?.aborted || revision !== beforeInput) + resolve('aborted'); + else reject(error); return; } if (disposed || signal?.aborted || revision !== beforeInput) { @@ -503,11 +513,10 @@ export function createSession( try { const previous = publication.getObservation(); if (active || interruptMode !== 'native') - throw new TypeError('Resume requires a settled native owner'); + throw new TypeError(NOT_SETTLED); const decision = assertResumeEligible( previous.decision, previous.run, - pause, Date.now() ); id = crypto.randomUUID(); @@ -518,12 +527,10 @@ export function createSession( ...nextInvocationSubagents(previous), run: Object.freeze({ id }), }); - } catch { - resolve( - disposed || signal?.aborted || revision !== beforeAdmission - ? 'aborted' - : 'error' - ); + } catch (error) { + if (disposed || signal?.aborted || revision !== beforeAdmission) + resolve('aborted'); + else reject(error); return; } if (disposed || signal?.aborted || revision !== beforeAdmission) { @@ -1466,14 +1473,14 @@ function createToolsOwner( } }); }), - resume: (pause, responses, options) => - new Promise((resolve) => { + resume: (responses, options) => + new Promise((resolve, reject) => { if (disposed) { resolve('aborted'); return; } if (active || ledger.snapshot().blocker) { - resolve('error'); + reject(new TypeError(NOT_SETTLED)); return; } const before = revision; @@ -1486,21 +1493,18 @@ function createToolsOwner( return; } if (interruptMode !== 'native') - throw new TypeError('Native resume required'); + throw new TypeError(NOT_SETTLED); const previous = publication.getObservation(); - assertResumeEligible( - previous.decision, - previous.run, - pause, - Date.now() - ); captured = captureResponses(responses); - } catch { - resolve( - disposed || signal?.aborted || revision !== before - ? 'aborted' - : 'error' + claimDecision( + assertResumeEligible(previous.decision, previous.run, Date.now()), + captured, + '' ); + } catch (error) { + if (disposed || signal?.aborted || revision !== before) + resolve('aborted'); + else reject(error); return; } publication.command(() => { @@ -1509,7 +1513,7 @@ function createToolsOwner( return; } if (active || ledger.snapshot().blocker) { - resolve('error'); + reject(new TypeError(NOT_SETTLED)); return; } try { @@ -1517,7 +1521,6 @@ function createToolsOwner( const decision = assertResumeEligible( previous.decision, previous.run, - pause, Date.now() ); const id = crypto.randomUUID(); @@ -1533,8 +1536,8 @@ function createToolsOwner( signal, resolve ); - } catch { - resolve('error'); + } catch (error) { + reject(error); } }); }), diff --git a/libs/ag-ui/src/runtime/decision-state.spec.ts b/libs/ag-ui/src/runtime/decision-state.spec.ts index 3ad1d1946..0c796d3ed 100644 --- a/libs/ag-ui/src/runtime/decision-state.spec.ts +++ b/libs/ag-ui/src/runtime/decision-state.spec.ts @@ -1,9 +1,5 @@ import { describe, expect, it } from 'vitest'; -import { - decisionState, - type NativeDecision, - type PauseId, -} from './decision'; +import { decisionState, type NativeDecision, type PauseId } from './decision'; import { bindingFixture } from './testing/binding-fixture'; const id = '00000000-0000-4000-8000-000000000001' as PauseId; @@ -29,7 +25,9 @@ const claimed: NativeDecision = Object.freeze({ describe('decisionState', () => { it('is absent when nothing is waiting', () => { expect(decisionState({})).toBeUndefined(); - expect(decisionState({ run: { id: 'run', outcome: 'success' } })).toBeUndefined(); + expect( + decisionState({ run: { id: 'run', outcome: 'success' } }) + ).toBeUndefined(); }); it('reads a pause this owner cannot answer as unsupported', () => { @@ -82,13 +80,21 @@ describe('decisionState', () => { expect(await fixture.session.submit('Ignored')).toBe('error'); expect(fixture.exchanges).toHaveLength(1); - const answered = fixture.session.resume(ready.id, [ - { interruptId: 'approval', status: 'resolved', payload: { approved: true } }, + const answered = fixture.session.resume([ + { + interruptId: 'approval', + status: 'resolved', + value: { approved: true }, + }, ]); const next = await fixture.started(1); expect(state()).toMatchObject({ phase: 'answering', id: ready.id }); expect((next.body as { resume?: unknown }).resume).toEqual([ - { interruptId: 'approval', status: 'resolved', payload: { approved: true } }, + { + interruptId: 'approval', + status: 'resolved', + payload: { approved: true }, + }, ]); next.emit({ type: 'RUN_FINISHED', @@ -112,23 +118,26 @@ describe('decisionState', () => { type: 'RUN_FINISHED', threadId: exchange.body.threadId, runId: exchange.body.runId, - outcome: { type: 'interrupt', interrupts: [{ id: 'approval', reason: 'Approve' }] }, + outcome: { + type: 'interrupt', + interrupts: [{ id: 'approval', reason: 'Approve' }], + }, }); await paused; const ready = state(); if (ready?.kind !== 'native') throw new Error('Expected a native pause'); - const answered = fixture.session.resume(ready.id, [ + const answered = fixture.session.resume([ { interruptId: 'approval', status: 'cancelled' }, ]); await fixture.started(1); await fixture.session.stop(); expect(await answered).toBe('aborted'); expect(state()).toMatchObject({ phase: 'uncertain', id: ready.id }); - expect( - await fixture.session.resume(ready.id, [ + await expect( + fixture.session.resume([ { interruptId: 'approval', status: 'cancelled' }, ]) - ).toBe('error'); + ).rejects.toThrow('No interrupt is waiting for an answer.'); expect(fixture.exchanges).toHaveLength(2); } finally { await fixture.cleanup(); diff --git a/libs/ag-ui/src/runtime/decision.spec.ts b/libs/ag-ui/src/runtime/decision.spec.ts index 9aae4ccff..2eb9b5f91 100644 --- a/libs/ag-ui/src/runtime/decision.spec.ts +++ b/libs/ag-ui/src/runtime/decision.spec.ts @@ -9,7 +9,7 @@ import { observeDecision, settleDecision, type NativeDecision, - type NativeResponse, + type InterruptResponse, type PauseId, } from './decision'; @@ -39,7 +39,7 @@ const decision = (): NativeDecision => }); const responses = () => captureResponses([ - { interruptId: 'a', status: 'resolved', payload: null }, + { interruptId: 'a', status: 'resolved', value: null }, { interruptId: 'b', status: 'cancelled' }, ]); @@ -49,7 +49,7 @@ describe('captured native response ownership', () => { const reads = { id: vi.fn(() => 'a'), status: vi.fn(() => 'resolved' as const), - payload: vi.fn(() => graph), + value: vi.fn(() => graph), metadata: vi.fn(() => ({ m: graph })), }; const ignored = vi.fn((): never => { @@ -63,8 +63,8 @@ describe('captured native response ownership', () => { get status() { return reads.status(); }, - get payload() { - return reads.payload(); + get value() { + return reads.value(); }, get metadata() { return reads.metadata(); @@ -100,7 +100,7 @@ describe('captured native response ownership', () => { expect(owned[0]).not.toHaveProperty('payload'); expect( captureResponses([ - { interruptId: 'a', status: 'resolved', payload: undefined }, + { interruptId: 'a', status: 'resolved', value: undefined }, ]) ).toEqual([{ interruptId: 'a', status: 'resolved' }]); }); @@ -109,13 +109,13 @@ describe('captured native response ownership', () => { [{ id: 'a', status: 'resolved' }], [{ interruptId: 1, status: 'resolved' }], [{ interruptId: 'a', status: 'future' }], - [{ interruptId: 'a', status: 'cancelled', payload: null }], - [{ interruptId: 'a', status: 'resolved', payload: new Date() }], + [{ interruptId: 'a', status: 'cancelled', value: null }], + [{ interruptId: 'a', status: 'resolved', value: new Date() }], [{ interruptId: 'a', status: 'resolved', metadata: [] }], - [{ interruptId: 'a', status: 'resolved', payload: () => true }], + [{ interruptId: 'a', status: 'resolved', value: () => true }], ])('rejects unsupported selected decision fields %j', (input) => { expect(() => - captureResponses(input as unknown as readonly NativeResponse[]) + captureResponses(input as unknown as readonly InterruptResponse[]) ).toThrow(); }); }); @@ -160,26 +160,23 @@ describe('pure decision correlation and settlement', () => { ).toEqual({ kind: 'unsupported', sourceRunId: 'source' }); } }); - it('requires current generation and local settlement, then exactly one response per observed ID', () => { + it('requires local settlement and no earlier attempt, then exactly one response per observed ID', () => { const current = decision(); + expect(() => assertResumeEligible(current, { id: 'source' }, 1)).toThrow( + 'No interrupt is waiting for an answer.' + ); expect(() => - assertResumeEligible(current, { id: 'source' }, first, 1) - ).toThrow(); + assertResumeEligible(undefined, { id: 'source', outcome: 'paused' }, 1) + ).toThrow('No interrupt is waiting for an answer.'); expect(() => assertResumeEligible( - current, + { kind: 'unsupported', sourceRunId: 'source' }, { id: 'source', outcome: 'paused' }, - second, 1 ) - ).toThrow(); + ).toThrow('No interrupt is waiting for an answer.'); expect( - assertResumeEligible( - current, - { id: 'source', outcome: 'aborted' }, - first, - 1 - ) + assertResumeEligible(current, { id: 'source', outcome: 'aborted' }, 1) ).toBe(current); for (const input of [ [], @@ -202,13 +199,8 @@ describe('pure decision correlation and settlement', () => { expect(claimed.attempt?.responses).toBe(captured); expect(claimed.interrupts).toBe(current.interrupts); expect(() => - assertResumeEligible( - claimed, - { id: 'resume', outcome: 'aborted' }, - first, - 1 - ) - ).toThrow(); + assertResumeEligible(claimed, { id: 'resume', outcome: 'aborted' }, 1) + ).toThrow('No interrupt is waiting for an answer.'); }); it.each(['invalid', '2020-01-01T00:00:00Z', '2019-01-01T00:00:00Z'])( 'fails closed on expired/invalid date %s', @@ -221,7 +213,6 @@ describe('pure decision correlation and settlement', () => { assertResumeEligible( current, { id: 'source', outcome: 'paused' }, - first, Date.parse('2020-01-01T00:00:00Z') ) ).toThrow(); @@ -238,7 +229,6 @@ describe('pure decision correlation and settlement', () => { assertResumeEligible( current, { id: 'source', outcome: 'paused' }, - first, Date.parse('2020-01-01T00:00:00Z') ) ).toBe(current); @@ -251,12 +241,7 @@ describe('pure decision correlation and settlement', () => { ); expect(released).toEqual(original); expect( - assertResumeEligible( - released, - { id: 'resume', outcome: 'aborted' }, - first, - 1 - ) + assertResumeEligible(released, { id: 'resume', outcome: 'aborted' }, 1) ).toBe(released); expect( settleDecision(claimed, { id: 'resume', outcome: 'aborted' }, true) diff --git a/libs/ag-ui/src/runtime/decision.ts b/libs/ag-ui/src/runtime/decision.ts index 210477078..b827439f8 100644 --- a/libs/ag-ui/src/runtime/decision.ts +++ b/libs/ag-ui/src/runtime/decision.ts @@ -1,5 +1,6 @@ import type { Interrupt } from '@ag-ui/client'; import type { + AgentInterruptResponse, CompleteOutcome, DeepReadonly, PlainValue, @@ -9,6 +10,17 @@ import { copyData } from '../lib/internal/copy-data.js'; declare const pauseId: unique symbol; export type PauseId = string & { readonly [pauseId]: true }; +/** + * One answer for `resume`: the core response, which names a pending interrupt + * and resolves it with an optional `value` or cancels it, plus the protocol's + * optional `metadata`. + */ +export type InterruptResponse = AgentInterruptResponse & { + readonly metadata?: Readonly>; + /** The request's name for the answer. `resume` reads `value`. */ + readonly payload?: never; +}; +/** A response as the protocol carries it, with the value as its `payload`. */ export type NativeResponse = | { readonly interruptId: string; @@ -43,14 +55,14 @@ export interface DecisionRun { } export function captureResponses( - responses: readonly NativeResponse[] + responses: readonly InterruptResponse[] ): readonly NativeResponse[] { if (!Array.isArray(responses)) - throw new TypeError('A native response array is required'); + throw new TypeError('Resume takes an array of responses.'); const length = responses.length; const selected: NativeResponse[] = []; for (let index = 0; index < length; index++) { - const { interruptId, status, payload, metadata } = responses[index]; + const { interruptId, status, value: payload, metadata } = responses[index]; if ( typeof interruptId !== 'string' || (status !== 'resolved' && status !== 'cancelled') @@ -59,7 +71,7 @@ export function captureResponses( 'Explicit interruptId and native status are required' ); if (status === 'cancelled' && payload !== undefined) - throw new TypeError('Cancelled decisions cannot have a payload'); + throw new TypeError('A cancelled response cannot carry a value.'); if ( metadata !== undefined && (metadata === null || @@ -115,19 +127,15 @@ export function observeDecision( export function assertResumeEligible( decision: Decision | undefined, run: DecisionRun | undefined, - pause: PauseId, now: number ): NativeDecision { if ( !decision || decision.kind !== 'native' || - decision.id !== pause || decision.attempt || run?.outcome === undefined ) - throw new TypeError( - 'No settled unclaimed native decision matches this pause' - ); + throw new TypeError('No interrupt is waiting for an answer.'); if (!Number.isFinite(now)) throw new TypeError('A finite admission time is required'); for (const interrupt of decision.interrupts) { @@ -195,7 +203,7 @@ export function settleDecision( * What a view can do about the session's pending decision. * * - `observing`: the pausing run has not settled locally yet; do not answer. - * - `ready`: the pause can be answered with `session.resume(id, responses)`. + * - `ready`: the pause can be answered with `session.resume(responses)`. * - `answering`: an answer was sent and its run is still going. * - `uncertain`: the answering run ended without proof that the backend took * the answer. It cannot be sent again; only a new session can continue. diff --git a/libs/ag-ui/src/runtime/decision.type-test.ts b/libs/ag-ui/src/runtime/decision.type-test.ts index 7bdd99ac5..bfb4fdcfc 100644 --- a/libs/ag-ui/src/runtime/decision.type-test.ts +++ b/libs/ag-ui/src/runtime/decision.type-test.ts @@ -1,30 +1,45 @@ +import type { AgentSession } from '@threadplane/core'; import { captureResponses, type Decision, + type InterruptResponse, type NativeResponse, type PauseId, } from './decision'; import type { Session } from './create-session'; -const resolved: NativeResponse = { +const resolved: InterruptResponse = { interruptId: 'i', status: 'resolved', - payload: null, + value: null, metadata: { nested: [1, undefined] }, }; -const cancelled: NativeResponse = { interruptId: 'i', status: 'cancelled' }; -captureResponses([resolved, cancelled] as const); +const cancelled: InterruptResponse = { interruptId: 'i', status: 'cancelled' }; +// A caller answers with `value`; the captured response carries `payload`. +const captured: readonly NativeResponse[] = captureResponses([ + resolved, + cancelled, +] as const); +void captured; +const wire: NativeResponse = { + interruptId: 'i', + status: 'resolved', + payload: { approved: true }, +}; +void wire; // @ts-expect-error status is mandatory captureResponses([{ interruptId: 'i' }]); // @ts-expect-error no aliases for backend interrupt IDs captureResponses([{ id: 'i', status: 'resolved' }]); -// @ts-expect-error cancelled responses cannot have a defined payload -captureResponses([{ interruptId: 'i', status: 'cancelled', payload: null }]); -// @ts-expect-error functions are not portable payloads -captureResponses([{ interruptId: 'i', status: 'resolved', payload: () => 1 }]); +// @ts-expect-error cancelled responses cannot have a value +captureResponses([{ interruptId: 'i', status: 'cancelled', value: null }]); +// @ts-expect-error the wire name is not a response field +captureResponses([{ interruptId: 'i', status: 'resolved', payload: true }]); +// @ts-expect-error functions are not portable values +captureResponses([{ interruptId: 'i', status: 'resolved', value: () => 1 }]); captureResponses([ // @ts-expect-error Date is not a portable value - { interruptId: 'i', status: 'resolved', payload: new Date() }, + { interruptId: 'i', status: 'resolved', value: new Date() }, ]); // @ts-expect-error metadata must be a plain record captureResponses([{ interruptId: 'i', status: 'resolved', metadata: [] }]); @@ -38,22 +53,49 @@ if (decision.kind === 'native') { // @ts-expect-error snapshots own readonly batches decision.interrupts.push({ id: 'i', reason: 'Approve' }); // @ts-expect-error captured attempt responses are readonly - decision.attempt?.responses.push(resolved); + decision.attempt?.responses.push(wire); void token; } void plain; declare const session: Session; declare const pause: PauseId; -session.resume(pause, [resolved, cancelled] as const, { +session.resume([resolved, cancelled] as const, { signal: new AbortController().signal, }); -// @ts-expect-error a backend ID cannot stand in for a native pause generation +void session.resume([ + { + interruptId: 'i', + status: 'resolved', + value: { approved: true, notes: ['ok'] }, + metadata: { origin: 'review' }, + }, +]); +void session.resume([ + // @ts-expect-error an answer is carried as `value`, not the wire `payload` + { interruptId: 'i', status: 'resolved', payload: { approved: true } }, +]); +// @ts-expect-error there is no pause token: the pending decision is answered +session.resume(pause, [resolved]); +// @ts-expect-error a backend ID cannot stand in for the responses session.resume('backend-id', [resolved]); // @ts-expect-error native resume never accepts a new user message -session.resume(pause, [resolved], { message: 'new intent' }); +session.resume([resolved], { message: 'new intent' }); // @ts-expect-error native resume never accepts a state patch -session.resume(pause, [resolved], { state: {} }); +session.resume([resolved], { state: {} }); // @ts-expect-error transport fields cannot override a correlated native resume -session.resume(pause, [resolved], { runId: 'guessed' }); +session.resume([resolved], { runId: 'guessed' }); // @ts-expect-error an explicit response batch is required -session.resume(pause); +session.resume(); + +// The session is a core session, and a core observer answers through it. +const observer: AgentSession = session; +void observer.resume?.([ + { interruptId: 'i', status: 'resolved', value: { approved: true } }, + { interruptId: 'j', status: 'cancelled' }, +]); +void observer.resume?.([ + // @ts-expect-error the core response has no wire `payload` either + { interruptId: 'i', status: 'resolved', payload: true }, +]); +// @ts-expect-error the core contract has no pause token +void observer.resume?.(pause, [resolved]); diff --git a/libs/ag-ui/src/runtime/resume-http.spec.ts b/libs/ag-ui/src/runtime/resume-http.spec.ts index cea21291f..504405b4a 100644 --- a/libs/ag-ui/src/runtime/resume-http.spec.ts +++ b/libs/ag-ui/src/runtime/resume-http.spec.ts @@ -120,11 +120,11 @@ describe('correlated native resume over held HTTP', () => { { interruptId: 'approval', status: 'resolved' as const, - payload: null, + value: null, metadata: { origin: 'review' }, }, ]; - const done = owner.resume(firstToken, responses); + const done = owner.resume(responses); const second = await server.next(1); expect(second.body).toStrictEqual({ threadId: 'thread', @@ -168,9 +168,8 @@ describe('correlated native resume over held HTTP', () => { expect( next.decision?.kind === 'native' && next.decision.attempt ).toBeUndefined(); - expect(await owner.resume(firstToken, responses)).toBe('error'); expect(server.exchanges).toHaveLength(2); - const cancelled = owner.resume(nextToken, [ + const cancelled = owner.resume([ { interruptId: 'approval', status: 'cancelled' }, ]); const third = await server.next(2); @@ -211,9 +210,8 @@ describe('correlated native resume over held HTTP', () => { const owner = createSession({ threadId: 'thread', url: server.url }); try { await paused(owner, server); - const pause = token(owner); - const done = owner.resume(pause, [ - { interruptId: 'approval', status: 'resolved', payload: true }, + const done = owner.resume([ + { interruptId: 'approval', status: 'resolved', value: true }, ]); const exchange = await server.next(1); const claimed = owner.getSnapshot().decision; @@ -243,11 +241,9 @@ describe('correlated native resume over held HTTP', () => { expect(final.run?.terminal?.type).toBe( ending === 'error' ? 'RUN_ERROR' : undefined ); - expect( - await owner.resume(pause, [ - { interruptId: 'approval', status: 'resolved' }, - ]) - ).toBe('error'); + await expect( + owner.resume([{ interruptId: 'approval', status: 'resolved' }]) + ).rejects.toThrow('No interrupt is waiting for an answer.'); expect(await owner.submit('bypass')).toBe('error'); await owner.stop(); expect(owner.getSnapshot()).toBe(final); @@ -265,7 +261,6 @@ describe('correlated native resume over held HTTP', () => { const owner = createSession({ threadId: 'thread', url: server.url }); try { await paused(owner, server); - const pause = token(owner); let stopped = false; owner.subscribe(() => { const snapshot = owner.getSnapshot(); @@ -279,7 +274,7 @@ describe('correlated native resume over held HTTP', () => { void owner.stop(); } }); - const done = owner.resume(pause, [ + const done = owner.resume([ { interruptId: 'approval', status: 'resolved' }, ]); const exchange = await server.next(1); @@ -305,11 +300,11 @@ describe('correlated native resume over held HTTP', () => { { id: 'approval', reason: 'Approve', expiresAt }, ]); const before = owner.getSnapshot(); - expect( - await owner.resume(token(owner), [ - { interruptId: 'approval', status: 'resolved' }, - ]) - ).toBe('error'); + const refused = owner.resume([ + { interruptId: 'approval', status: 'resolved' }, + ]); + await expect(refused).rejects.toThrow(TypeError); + await expect(refused).rejects.toThrow('The interrupt has expired'); expect(owner.getSnapshot()).toBe(before); expect(server.exchanges).toHaveLength(1); } finally { @@ -345,11 +340,13 @@ describe('correlated native resume over held HTTP', () => { kind: 'unsupported', sourceRunId: exchange.body.runId, }); - expect( - await owner.resume('guessed' as PauseId, [ - { interruptId: 'approval', status: 'resolved' }, - ]) - ).toBe('error'); + await expect( + owner.resume([{ interruptId: 'approval', status: 'resolved' }]) + ).rejects.toThrow( + interruptMode === 'native' + ? 'No interrupt is waiting for an answer.' + : 'Resume needs a settled session with a pending interrupt.' + ); expect(await owner.submit('bypass')).toBe('error'); expect(server.exchanges).toHaveLength(1); } finally { @@ -404,16 +401,15 @@ describe('correlated native resume over held HTTP', () => { exchange.response.write(trace.replaceAll('run-1', exchange.body.runId)); expect(await bounded(first)).toBe('paused'); await bounded(exchange.closed); + const interruptId = + 'v1:tool_call:call_A9ckGX1LrvO82OhqZinzDsom:340a4daa-b874-5aad-8309-a63b92d507dd'; + const value = { chosen_label: 'Tuesday 10:00' }; + // The session takes the answer as `value`; the wire carries `payload`. const responses = [ - { - interruptId: - 'v1:tool_call:call_A9ckGX1LrvO82OhqZinzDsom:340a4daa-b874-5aad-8309-a63b92d507dd', - status: 'resolved' as const, - payload: { chosen_label: 'Tuesday 10:00' }, - }, + { interruptId, status: 'resolved' as const, payload: value }, ]; expect(responses).toStrictEqual(captured.resume); - const done = owner.resume(token(owner), responses); + const done = owner.resume([{ interruptId, status: 'resolved', value }]); const resumed = await server.next(1); expect(resumed.body).toStrictEqual({ threadId: 'th-int-555800', diff --git a/libs/ag-ui/src/runtime/resume.spec.ts b/libs/ag-ui/src/runtime/resume.spec.ts index 403ad6b47..9ddf58452 100644 --- a/libs/ag-ui/src/runtime/resume.spec.ts +++ b/libs/ag-ui/src/runtime/resume.spec.ts @@ -1,7 +1,7 @@ import { PROTOCOL_VERSION } from '@ag-ui/client'; import { describe, expect, it, vi } from 'vitest'; import { bindingFixture } from './testing/binding-fixture'; -import type { NativeResponse, PauseId } from './decision'; +import type { InterruptResponse, PauseId } from './decision'; import type { CompleteOutcome } from '@threadplane/core'; import { createSession } from './create-session'; import type { RunAgentInput } from '@ag-ui/client'; @@ -51,30 +51,6 @@ async function pause(fixture: ReturnType) { } describe('native decision owner', () => { - it('rejects a real foreign owner token without changing either owner', async () => { - const first = bindingFixture(), - second = bindingFixture(); - try { - const firstToken = await pause(first), - secondToken = await pause(second); - expect(firstToken).not.toBe(secondToken); - const before = first.session.getSnapshot(), - other = second.session.getSnapshot(); - expect( - await first.session.resume(secondToken, [ - { interruptId: 'approval', status: 'resolved' }, - ]) - ).toBe('error'); - expect(first.session.getSnapshot()).toBe(before); - expect(second.session.getSnapshot()).toBe(other); - expect(first.exchanges).toHaveLength(1); - expect(second.exchanges).toHaveLength(1); - } finally { - await first.cleanup(); - await second.cleanup(); - } - }); - it('rechecks expiry after selected caller reads and before admission', async () => { const fixture = bindingFixture(); const now = vi.spyOn(Date, 'now').mockReturnValue(1000); @@ -99,18 +75,18 @@ describe('native decision owner', () => { expect(await bounded(first)).toBe('paused'); await bounded(exchange.closed); const before = fixture.session.getSnapshot(); - expect( - await fixture.session.resume(currentPause(fixture), [ - { - interruptId: 'approval', - status: 'resolved', - get payload() { - now.mockReturnValue(2000); - return null; - }, + const expired = fixture.session.resume([ + { + interruptId: 'approval', + status: 'resolved', + get value() { + now.mockReturnValue(2000); + return null; }, - ]) - ).toBe('error'); + }, + ]); + await expect(expired).rejects.toThrow(TypeError); + await expect(expired).rejects.toThrow('The interrupt has expired'); expect(fixture.session.getSnapshot()).toBe(before); expect(fixture.exchanges).toHaveLength(1); } finally { @@ -131,7 +107,6 @@ describe('native decision owner', () => { snapshot.decision?.kind === 'native' ) { pending = fixture.session.resume( - snapshot.decision.id, [{ interruptId: 'approval', status: 'resolved' }], { signal: controller.signal } ); @@ -150,32 +125,40 @@ describe('native decision owner', () => { } }); - it('rejects foreign tokens, invalid batches and pre-aborted input without reads, publication or dispatch', async () => { + it('rejects invalid batches, and aborts pre-aborted input without reads, publication or dispatch', async () => { const fixture = bindingFixture(); try { - const token = await pause(fixture); + await pause(fixture); const before = fixture.session.getSnapshot(); const notify = vi.fn(); fixture.session.subscribe(notify); - for (const responses of [ - [], - [{ interruptId: 'other', status: 'resolved' }], + for (const [responses, message] of [ + [[], 'Exactly one response per interrupt is required'], [ - { interruptId: 'approval', status: 'resolved' }, - { interruptId: 'approval', status: 'cancelled' }, + [{ interruptId: 'other', status: 'resolved' }], + 'Unknown or duplicate interrupt response', ], - [{ interruptId: 'approval', status: 'cancelled', payload: null }], - ] as unknown as readonly NativeResponse[][]) - expect(await fixture.session.resume(token, responses)).toBe('error'); - expect( - await fixture.session.resume('foreign' as PauseId, [ - { interruptId: 'approval', status: 'resolved' }, - ]) - ).toBe('error'); + [ + [ + { interruptId: 'approval', status: 'resolved' }, + { interruptId: 'approval', status: 'cancelled' }, + ], + 'Exactly one response per interrupt is required', + ], + [ + [{ interruptId: 'approval', status: 'cancelled', value: null }], + 'A cancelled response cannot carry a value.', + ], + ['approval', 'Resume takes an array of responses.'], + ] as unknown as readonly [readonly InterruptResponse[], string?][]) { + const refused = fixture.session.resume(responses); + await expect(refused).rejects.toThrow(TypeError); + if (message) await expect(refused).rejects.toThrow(message); + } const unread = vi.fn((): never => { throw new Error('unread'); }); - const responses: readonly NativeResponse[] = [ + const responses: readonly InterruptResponse[] = [ { get interruptId() { return unread(); @@ -184,7 +167,7 @@ describe('native decision owner', () => { }, ]; expect( - await fixture.session.resume(token, responses, { + await fixture.session.resume(responses, { signal: AbortSignal.abort(), }) ).toBe('aborted'); @@ -192,7 +175,7 @@ describe('native decision owner', () => { expect(notify).not.toHaveBeenCalled(); expect(fixture.exchanges).toHaveLength(1); await fixture.session.dispose(); - expect(await fixture.session.resume(token, responses)).toBe('aborted'); + expect(await fixture.session.resume(responses)).toBe('aborted'); expect(unread).not.toHaveBeenCalled(); } finally { await fixture.cleanup(); @@ -202,7 +185,7 @@ describe('native decision owner', () => { it('captures selected option/input getters once and ignores extra getters', async () => { const fixture = bindingFixture(); try { - const token = await pause(fixture); + await pause(fixture); const signal = new AbortController().signal; const selected = vi.fn(() => signal); const ignored = vi.fn((): never => { @@ -219,12 +202,12 @@ describe('native decision owner', () => { const response = { interruptId: 'approval', status: 'resolved' as const, - payload: null, + value: null, get forwardedProps() { return ignored(); }, }; - const done = fixture.session.resume(token, [response], options); + const done = fixture.session.resume([response], options); const exchange = await bounded(fixture.started(1)); // 1.0 client rule: a whole-optional `payload: null` is sent as absent. expect(exchange.body.resume).toStrictEqual([ @@ -242,13 +225,12 @@ describe('native decision owner', () => { it('retains cancellation precedence when a selected signal getter disposes then throws', async () => { const fixture = bindingFixture(); try { - const token = await pause(fixture); + await pause(fixture); const unread = vi.fn((): never => { throw new Error('unread'); }); expect( await fixture.session.resume( - token, [ { get interruptId() { @@ -326,8 +308,8 @@ describe('native decision owner', () => { throw new Error('Missing native decision'); expect( await bounded( - owner.resume(decision.id, [ - { interruptId: 'approval', status: 'resolved', payload: null }, + owner.resume([ + { interruptId: 'approval', status: 'resolved', value: null }, ]) ) ).toBe(action === 'stop' ? 'aborted' : 'error'); @@ -336,11 +318,9 @@ describe('native decision owner', () => { id: decision.id, attempt: { runId: owner.getSnapshot().run?.id }, }); - expect( - await owner.resume(decision.id, [ - { interruptId: 'approval', status: 'resolved' }, - ]) - ).toBe('error'); + await expect( + owner.resume([{ interruptId: 'approval', status: 'resolved' }]) + ).rejects.toThrow('No interrupt is waiting for an answer.'); expect(await owner.submit('bypass')).toBe('error'); expect(calls).toBe(2); } finally { @@ -355,8 +335,8 @@ describe('native decision owner', () => { const token = await pause(fixture); const before = fixture.session.getSnapshot(); const payload = { values: [1] }; - const done = fixture.session.resume(token, [ - { interruptId: 'approval', status: 'resolved', payload }, + const done = fixture.session.resume([ + { interruptId: 'approval', status: 'resolved', value: payload }, ]); payload.values.push(99); const admitted = fixture.session.getSnapshot(); @@ -378,11 +358,13 @@ describe('native decision owner', () => { ], }, }); - expect( - await fixture.session.resume(token, [ + await expect( + fixture.session.resume([ { interruptId: 'approval', status: 'cancelled' }, ]) - ).toBe('error'); + ).rejects.toThrow( + 'Resume needs a settled session with a pending interrupt.' + ); const unread = vi.fn((): never => { throw new Error('unread'); }); @@ -436,15 +418,18 @@ describe('native decision owner', () => { !attempted && snapshot.run?.terminal?.type === 'RUN_FINISHED' && snapshot.decision?.kind === 'native' - ) - attempted = fixture.session.resume(snapshot.decision.id, [ + ) { + attempted = fixture.session.resume([ { interruptId: 'approval', status: 'resolved' }, ]); + // Observed below; the refusal lands before the test awaits it. + attempted.catch(() => undefined); + } }); try { await pause(fixture); if (!attempted) throw new Error('Missing terminal callback attempt'); - expect(await bounded(attempted)).toBe('error'); + await expect(bounded(attempted)).rejects.toThrow(TypeError); expect(fixture.exchanges).toHaveLength(1); expect(fixture.session.getSnapshot().decision?.kind).toBe('native'); } finally { @@ -467,16 +452,18 @@ describe('native decision owner', () => { scheduled = true; const payload = { values: [1] }; attempts.push( - fixture.session.resume(snapshot.decision.id, [ - { interruptId: 'approval', status: 'resolved', payload }, + fixture.session.resume([ + { interruptId: 'approval', status: 'resolved', value: payload }, ]) ); payload.values.push(99); attempts.push( - fixture.session.resume(snapshot.decision.id, [ + fixture.session.resume([ { interruptId: 'approval', status: 'cancelled' }, ]) ); + // Observed below; the refusal lands before the test awaits it. + attempts[1].catch(() => undefined); }); try { await pause(fixture); @@ -488,7 +475,7 @@ describe('native decision owner', () => { payload: { values: [1] }, }, ]); - expect(await bounded(attempts[1])).toBe('error'); + await expect(bounded(attempts[1])).rejects.toThrow(TypeError); await fixture.session.stop(); expect(await bounded(attempts[0])).toBe('aborted'); expect(fixture.exchanges).toHaveLength(2); @@ -503,15 +490,15 @@ describe('native decision owner', () => { const fixture = bindingFixture(); let inner: Promise = Promise.resolve(); try { - const token = await pause(fixture); - const responses: readonly NativeResponse[] = [ + await pause(fixture); + const responses: readonly InterruptResponse[] = [ { interruptId: 'approval', status: 'resolved', - get payload(): never { + get value(): never { inner = command === 'resume' - ? fixture.session.resume(token, [ + ? fixture.session.resume([ { interruptId: 'approval', status: 'cancelled' }, ]) : fixture.session[command](); @@ -519,7 +506,7 @@ describe('native decision owner', () => { }, }, ]; - expect(await fixture.session.resume(token, responses)).toBe('aborted'); + expect(await fixture.session.resume(responses)).toBe('aborted'); if (command === 'resume') { const exchange = await bounded(fixture.started(1)); expect(exchange.body.resume).toEqual([ @@ -550,7 +537,7 @@ describe('native decision owner', () => { } }); expect( - await fixture.session.resume(token, [ + await fixture.session.resume([ { interruptId: 'approval', status: 'resolved' }, ]) ).toBe('aborted'); @@ -563,7 +550,7 @@ describe('native decision owner', () => { expect(fixture.session.getSnapshot().run?.id).not.toBe( decision.sourceRunId ); - const retry = fixture.session.resume(token, [ + const retry = fixture.session.resume([ { interruptId: 'approval', status: 'resolved' }, ]); await bounded(fixture.started(1)); diff --git a/libs/ag-ui/src/runtime/session-http.spec.ts b/libs/ag-ui/src/runtime/session-http.spec.ts index 05b8cb4d5..ef29ccec0 100644 --- a/libs/ag-ui/src/runtime/session-http.spec.ts +++ b/libs/ag-ui/src/runtime/session-http.spec.ts @@ -296,8 +296,8 @@ describe('composed private session over held HTTP', () => { expect(settled.state).toEqual({ count: 2 }); if (settled.decision?.kind !== 'native') throw new Error('Missing native pause'); - second = owner.resume(settled.decision.id, [ - { interruptId: 'approval', status: 'resolved', payload: true }, + second = owner.resume([ + { interruptId: 'approval', status: 'resolved', value: true }, ]); const next = await server.next(1); expect(next.body).toStrictEqual({ @@ -323,12 +323,14 @@ describe('composed private session over held HTTP', () => { expect(owner.getSnapshot().subagents).toEqual([]); expect(settled).not.toHaveProperty('earlierSubagents'); expect(settled.subagents[0].terminal?.type).toBe('SUBAGENT_FINISHED'); + // History keeps the child's protocol evidence, by reference, without + // the core child fields the current run's list adds. + const { started, terminal: finished } = settled.subagents[0]; expect(owner.getSnapshot().earlierSubagents).toStrictEqual([ - settled.subagents[0], + { started, terminal: finished }, ]); - expect(owner.getSnapshot().earlierSubagents?.[0]).toBe( - settled.subagents[0] - ); + expect(owner.getSnapshot().earlierSubagents?.[0].started).toBe(started); + expect(owner.getSnapshot().earlierSubagents?.[0].terminal).toBe(finished); expect(owner.getSnapshot().run?.terminal).toBeUndefined(); next.send(lifecycle(next), lifecycle(next, 'RUN_FINISHED')); expect(await bounded(second)).toBe('success'); @@ -351,20 +353,29 @@ describe('composed private session over held HTTP', () => { expect(await bounded(third)).toBe('success'); expect(owner.getSnapshot().earlierSubagents).toBe(history); const latest = owner.getSnapshot().subagents; - expect(latest).toStrictEqual([ - { - started: { - type: 'SUBAGENT_STARTED', - subagentRunId: 'child', - name: 'again', - }, - terminal: { type: 'SUBAGENT_FINISHED', subagentRunId: 'child' }, + const reused = { + started: { + type: 'SUBAGENT_STARTED', + subagentRunId: 'child', + name: 'again', }, + terminal: { type: 'SUBAGENT_FINISHED', subagentRunId: 'child' }, + }; + // This turn asserts the child's identity and evidence, not its own + // messages and tool calls. + expect(latest).toHaveLength(1); + expect(latest).toMatchObject([ + { id: 'child', name: 'again', status: 'complete', ...reused }, ]); + expect(latest[0].started).toStrictEqual(reused.started); + expect(latest[0].terminal).toStrictEqual(reused.terminal); const fourth = owner.submit('once more'); const last = await server.next(3); expect(owner.getSnapshot().subagents).toEqual([]); - expect(owner.getSnapshot().earlierSubagents).toStrictEqual(latest); + expect(owner.getSnapshot().earlierSubagents).toStrictEqual([reused]); + expect(owner.getSnapshot().earlierSubagents?.[0].started).toBe( + latest[0].started + ); last.send(lifecycle(last), lifecycle(last, 'RUN_FINISHED')); expect(await bounded(fourth)).toBe('success'); } finally { @@ -481,6 +492,11 @@ describe('composed private session over held HTTP', () => { if (ending === 'EOF' || ending === 'error') expect(owner.getSnapshot().subagents).toEqual([ { + id: 'open', + name: 'worker', + status: 'unknown', + messages: [], + toolCalls: [], started: { type: 'SUBAGENT_STARTED', subagentRunId: 'open', diff --git a/libs/angular/src/observe-agent.ag-ui.spec.ts b/libs/angular/src/observe-agent.ag-ui.spec.ts index 296e93214..e85b62563 100644 --- a/libs/angular/src/observe-agent.ag-ui.spec.ts +++ b/libs/angular/src/observe-agent.ag-ui.spec.ts @@ -128,6 +128,11 @@ describe('observeAgent native AG-UI owner', () => { }); expect(second.snapshot().subagents).toEqual([ { + id: 'child', + name: 'worker', + status: 'complete', + messages: [], + toolCalls: [], started: { type: 'SUBAGENT_STARTED', subagentRunId: 'child', @@ -178,8 +183,8 @@ describe('observeAgent native AG-UI owner', () => { expect(second.snapshot().run?.outcome).toBe('paused'); const decision = second.snapshot().decision; if (decision?.kind !== 'native') throw new Error('Missing observed pause'); - const nextRun = f.session.resume(decision.id, [ - { interruptId: 'approval', status: 'resolved', payload: 'yes' }, + const nextRun = f.session.resume([ + { interruptId: 'approval', status: 'resolved', value: 'yes' }, ]); const next = await f.started(1); expect(next.body).toEqual({ 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 a87468258..9bcff8be1 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 ad2f952a5..2ff51505c 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 27171d2a1..0890c6dc7 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 { @@ -165,7 +168,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. */ @@ -182,8 +185,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; @@ -218,7 +227,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 { @@ -260,11 +269,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))); @@ -496,7 +505,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; @@ -678,7 +687,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 } } @@ -1885,7 +1894,7 @@ export function createSession( } function resume( - value?: PlainValue, + responses: readonly AgentInterruptResponse[], options?: LangGraphRunOptions ): Promise { let attempt: Attempt | undefined; @@ -1923,6 +1932,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/libs/react/src/chat/ag-ui-session.spec.tsx b/libs/react/src/chat/ag-ui-session.spec.tsx index 471185731..0e1ba5dae 100644 --- a/libs/react/src/chat/ag-ui-session.spec.tsx +++ b/libs/react/src/chat/ag-ui-session.spec.tsx @@ -45,7 +45,11 @@ describe('Chat over a native AG-UI session', () => { toolCallName: 'search', parentMessageId: 'a1', }); - exchange.emit({ type: 'TOOL_CALL_ARGS', toolCallId: 'c1', delta: '{"q":"tea"}' }); + exchange.emit({ + type: 'TOOL_CALL_ARGS', + toolCallId: 'c1', + delta: '{"q":"tea"}', + }); exchange.emit({ type: 'TOOL_CALL_END', toolCallId: 'c1' }); exchange.emit({ type: 'TOOL_CALL_RESULT', @@ -53,8 +57,16 @@ describe('Chat over a native AG-UI session', () => { messageId: 't1', content: '{"hits":2}', }); - exchange.emit({ type: 'TEXT_MESSAGE_START', messageId: 'a2', role: 'assistant' }); - exchange.emit({ type: 'TEXT_MESSAGE_CONTENT', messageId: 'a2', delta: 'Two teas found.' }); + exchange.emit({ + type: 'TEXT_MESSAGE_START', + messageId: 'a2', + role: 'assistant', + }); + exchange.emit({ + type: 'TEXT_MESSAGE_CONTENT', + messageId: 'a2', + delta: 'Two teas found.', + }); exchange.emit({ type: 'TEXT_MESSAGE_END', messageId: 'a2' }); exchange.emit({ type: 'RUN_FINISHED', @@ -97,7 +109,13 @@ describe('Chat over a native AG-UI session', () => { ], state: { citations: { - a: [{ id: 'doc', title: 'Signals guide', url: 'https://example.test/signals' }], + a: [ + { + id: 'doc', + title: 'Signals guide', + url: 'https://example.test/signals', + }, + ], }, }, }); @@ -132,11 +150,10 @@ describe('Chat over a native AG-UI session', () => { label: 'Issue refund', onSelect: () => void native.resume( - pending.id, pending.interrupts.map((interrupt) => ({ interruptId: interrupt.id, status: 'resolved' as const, - payload: { approved: true }, + value: { approved: true }, })) ), }, @@ -178,15 +195,30 @@ describe('Chat over a native AG-UI session', () => { fireEvent.click(approve); const next = await act(() => fixture.started(1)); expect((next.body as { resume?: unknown }).resume).toEqual([ - { interruptId: 'approval', status: 'resolved', payload: { approved: true } }, + { + interruptId: 'approval', + status: 'resolved', + payload: { approved: true }, + }, ]); expect( - (view.getByRole('button', { name: 'Issue refund' }) as HTMLButtonElement) - .disabled + ( + view.getByRole('button', { + name: 'Issue refund', + }) as HTMLButtonElement + ).disabled ).toBe(true); await act(async () => { - next.emit({ type: 'TEXT_MESSAGE_START', messageId: 'a', role: 'assistant' }); - next.emit({ type: 'TEXT_MESSAGE_CONTENT', messageId: 'a', delta: 'Refund issued.' }); + next.emit({ + type: 'TEXT_MESSAGE_START', + messageId: 'a', + role: 'assistant', + }); + next.emit({ + type: 'TEXT_MESSAGE_CONTENT', + messageId: 'a', + delta: 'Refund issued.', + }); next.emit({ type: 'TEXT_MESSAGE_END', messageId: 'a' }); next.emit({ type: 'RUN_FINISHED', diff --git a/libs/react/src/use-agent.ag-ui.spec.tsx b/libs/react/src/use-agent.ag-ui.spec.tsx index d1816cfa4..660f10e0c 100644 --- a/libs/react/src/use-agent.ag-ui.spec.tsx +++ b/libs/react/src/use-agent.ag-ui.spec.tsx @@ -118,6 +118,11 @@ describe('useAgent native AG-UI owner', () => { }); expect(second.result.current.subagents).toEqual([ { + id: 'child', + name: 'worker', + status: 'complete', + messages: [], + toolCalls: [], started: { type: 'SUBAGENT_STARTED', subagentRunId: 'child', @@ -174,8 +179,8 @@ describe('useAgent native AG-UI owner', () => { const decision = second.result.current.decision; if (decision?.kind !== 'native') throw new Error('Missing observed pause'); await act(async () => { - run = f.session.resume(decision.id, [ - { interruptId: 'approval', status: 'resolved', payload: 'yes' }, + run = f.session.resume([ + { interruptId: 'approval', status: 'resolved', value: 'yes' }, ]); await f.started(1); }); diff --git a/scripts/react-cockpit/native-strands-fixture.spec.mjs b/scripts/react-cockpit/native-strands-fixture.spec.mjs index cfb428b90..0844d17c2 100644 --- a/scripts/react-cockpit/native-strands-fixture.spec.mjs +++ b/scripts/react-cockpit/native-strands-fixture.spec.mjs @@ -109,11 +109,10 @@ for (const scenario of ['approval', 'batch']) ); const outcome = await bounded( session.resume( - decision.id, decision.interrupts.map((i) => ({ interruptId: i.id, status: 'resolved', - payload: { approved }, + value: { approved }, })) ) ); @@ -207,11 +206,10 @@ test( assert.equal(d.kind, 'native'); await bounded( session.resume( - d.id, d.interrupts.map((i) => ({ interruptId: i.id, status: 'resolved', - payload: { approved }, + value: { approved }, })) ) ); @@ -254,11 +252,10 @@ test( assert.equal( await bounded( session.resume( - d.id, d.interrupts.map((i) => ({ interruptId: i.id, status: 'resolved', - payload: { approved: approve }, + value: { approved: approve }, })) ) ), @@ -399,11 +396,10 @@ for (const scenario of [ const d = session.getSnapshot().decision; await bounded( session.resume( - d.id, d.interrupts.map((i) => ({ interruptId: i.id, status: 'resolved', - payload: { approved: true }, + value: { approved: true }, })) ) ); diff --git a/scripts/react-parity/ag-ui-candidate-package.mjs b/scripts/react-parity/ag-ui-candidate-package.mjs index cc87d8c8a..5dffbed5e 100644 --- a/scripts/react-parity/ag-ui-candidate-package.mjs +++ b/scripts/react-parity/ag-ui-candidate-package.mjs @@ -36,6 +36,7 @@ export const reviewedSources = [ ...[ 'activity-messages', 'agent-session', + 'child-projection', 'client-tool-ledger', 'client-tools', 'create-http-request', diff --git a/scripts/react-parity/dispositions.json b/scripts/react-parity/dispositions.json index 7c40941c0..ed2e0e46a 100644 --- a/scripts/react-parity/dispositions.json +++ b/scripts/react-parity/dispositions.json @@ -12822,6 +12822,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": [ @@ -19218,6 +19229,18 @@ "reason": "Private core AgentSession view of the native owner: a snapshot derived from the native one with the message and tool-call selectors, change-only notification, a display error for a failed run, and text submit, stop and dispose forwarded to the owner.", "note": "Covered by runtime specs and a React Chat integration spec over the real owner. Exported from the test-only candidate package entry and checked from installed tarballs; not exported from the published package root. A rejected credential (401 or 403) is an auth error and another HTTP status is carried on a server error. State patches, native resume, client-tool evidence, a status check and a failure without a response are not represented." }, + { + "id": "source:libs/ag-ui/src/runtime/child-projection.ts", + "taskIds": [ + "T12", + "T14", + "T23" + ], + "treatment": "internal", + "status": "in-progress", + "reason": "Private projection of the current run's child evidence into the core contract's child agents: each child's id, name, task, status and its own messages and tool calls, with the protocol evidence kept alongside.", + "note": "Covered by runtime specs over the real owner. Children of earlier runs stay bare evidence in earlierSubagents, and a child that reuses a run id also lists the earlier child's records." + }, { "id": "source:libs/ag-ui/src/runtime/message-projection.ts", "taskIds": [ diff --git a/scripts/react-parity/native-mastra-runner.ts b/scripts/react-parity/native-mastra-runner.ts index a742dae63..02fb56d47 100644 --- a/scripts/react-parity/native-mastra-runner.ts +++ b/scripts/react-parity/native-mastra-runner.ts @@ -9,9 +9,11 @@ import { import { PROTOCOL_VERSION, type RunAgentInput } from '@ag-ui/client'; // eslint-disable-next-line @nx/enforce-module-boundaries -- Explicit fixture binding preserves the source or installed owner. import { createSession } from '../../fixtures/react-parity/native-ag-ui/mastra-backend.js'; -type NativeResponse = Parameters< - ReturnType['resume'] ->[1][number]; +type Answer = Parameters['resume']>[0][number]; +/** An answer as the request carries it. */ +type NativeResponse = + | { interruptId: string; status: 'resolved'; payload?: unknown } + | { interruptId: string; status: 'cancelled' }; // eslint-disable-next-line @nx/enforce-module-boundaries -- Test-only local service composition; no package API is introduced. import { bounded, @@ -293,7 +295,7 @@ async function verifyCase( assert.equal(owner.getSnapshot(), paused); assert.equal(proxy.posts(), pendingPosts); assert.equal(service.stats().length, providerPosts); - const pauseId = paused.decision.id; + // The request carries the answer as `payload`; the command takes `value`. scenario.response = name === 'cancel' ? { interruptId: interrupt.id, status: 'cancelled' } @@ -302,16 +304,21 @@ async function verifyCase( status: 'resolved', payload: { approved: name !== 'decline' }, }; - const done = owner.resume(pauseId, [scenario.response]); + const answer: Answer = + name === 'cancel' + ? { interruptId: interrupt.id, status: 'cancelled' } + : { + interruptId: interrupt.id, + status: 'resolved', + value: { approved: name !== 'decline' }, + }; + const done = owner.resume([answer]); const claimed = owner.getSnapshot(); assert.equal(claimed.transcript, paused.transcript); assert.equal(claimed.state, paused.state); - assert.equal( - await bounded( - owner.resume(pauseId, [scenario.response]), - 'duplicate active claim' - ), - 'error' + await assert.rejects( + bounded(owner.resume([answer]), 'duplicate active claim'), + TypeError ); assert.equal(owner.getSnapshot(), claimed); const outcome = await bounded(done, `${name} resume`); @@ -370,12 +377,9 @@ async function verifyCase( assert.equal(second.suppressed, 0); assert.equal(final.decision, undefined); } - assert.equal( - await bounded( - owner.resume(pauseId, [scenario.response]), - 'stale or uncertain resume' - ), - 'error' + await assert.rejects( + bounded(owner.resume([answer]), 'stale or uncertain resume'), + TypeError ); assert.equal(owner.getSnapshot(), final); assert.equal(proxy.posts(), pendingPosts + 1); 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']]) {