From 50998de093a03880ce5de019d215689c577313cd Mon Sep 17 00:00:00 2001 From: Brian Love Date: Tue, 17 Nov 2026 20:12:05 -0800 Subject: [PATCH 1/4] feat(core): add typed application state to the session contract AgentSession and AgentSnapshot take a second type parameter for application state. The snapshot gains an optional, deeply readonly `state`, and `submit` accepts `{ message, state }` with a partial state as well as plain text. A session is told its state type by one declaration: `type()` for the type alone, or any Standard Schema value to also check each state as it arrives. `readState` runs that check for session implementations. The fake session holds, sets and validates state the same way. No backend session supplies `state` yet; LangGraph and AG-UI follow. --- .../ag-ui-candidate/installed-types.ts | 4 +- fixtures/react-parity/runtime/README.md | 2 +- .../react-parity/runtime/installed-types.ts | 3 +- .../src/runtime/submit-input.type-test.ts | 4 +- libs/core/README.md | 19 +- libs/core/src/contracts/agent-session.ts | 20 +- libs/core/src/contracts/agent-snapshot.ts | 11 +- libs/core/src/contracts/state.spec.ts | 103 +++++++++++ libs/core/src/contracts/state.ts | 173 ++++++++++++++++++ libs/core/src/contracts/state.type-test.ts | 108 +++++++++++ libs/core/src/index.ts | 11 ++ .../src/testing/fake-agent-session.spec.ts | 107 ++++++++++- libs/core/src/testing/fake-agent-session.ts | 121 +++++++++--- .../testing/fake-agent-session.type-test.ts | 39 ++++ .../src/runtime/submit-input.type-test.ts | 4 +- 15 files changed, 685 insertions(+), 44 deletions(-) create mode 100644 libs/core/src/contracts/state.spec.ts create mode 100644 libs/core/src/contracts/state.ts create mode 100644 libs/core/src/contracts/state.type-test.ts diff --git a/fixtures/react-parity/ag-ui-candidate/installed-types.ts b/fixtures/react-parity/ag-ui-candidate/installed-types.ts index ec917feab..cdeb54b57 100644 --- a/fixtures/react-parity/ag-ui-candidate/installed-types.ts +++ b/fixtures/react-parity/ag-ui-candidate/installed-types.ts @@ -103,8 +103,10 @@ export function checkCandidate(signal: AbortSignal) { const agent: AgentSession = createAgentSession(session); const core: AgentSnapshot = agent.getSnapshot(); void agent.submit('Hello', { signal }); - // @ts-expect-error The core view submits text only; state goes through the native session. void agent.submit({ message: 'Hello' }); + void agent.submit({ message: 'Hello', state: { topic: 'x' } }); + // @ts-expect-error The core view takes a message and state only. + void agent.submit({ message: 'Hello', messages: [] }); // @ts-expect-error Native resume stays on the native session. void agent.resume; // @ts-expect-error The view wraps a session, not its options. diff --git a/fixtures/react-parity/runtime/README.md b/fixtures/react-parity/runtime/README.md index 2f54b4617..3d58ff665 100644 --- a/fixtures/react-parity/runtime/README.md +++ b/fixtures/react-parity/runtime/README.md @@ -263,7 +263,7 @@ Application fields go directly into the initial run's input. They are not resent on tool continuations, owned-run reconnect, or subsequent independent submits: server reducers may accumulate repeated values. Input state never changes snapshot `values` optimistically; only backend observations do. Core sessions -remain text-only, while the private backend method accepts this extension. +accept the same `{ message, state }` input, typed by their state declaration. Tool and Drop in the review apps send fixed model, reasoning, UI-mode and itinerary choices. The strict fixture requires them on those initial requests diff --git a/fixtures/react-parity/runtime/installed-types.ts b/fixtures/react-parity/runtime/installed-types.ts index b4652c1d0..6e399becd 100644 --- a/fixtures/react-parity/runtime/installed-types.ts +++ b/fixtures/react-parity/runtime/installed-types.ts @@ -104,8 +104,9 @@ export function assertCore( const snapshot: AgentSnapshot = session.getSnapshot(); assertSnapshot(snapshot); void session.submit('Hello', { signal }); - // @ts-expect-error The neutral session does not acquire backend application input. void session.submit({ message: 'Hello', state: { model: 'gpt-5-mini' } }); + // @ts-expect-error The neutral session takes plain data as state. + void session.submit({ message: 'Hello', state: { at: new Date() } }); const tool: FunctionTool<{ values: readonly string[] }, number> = { description: 'Count values', handler: ({ values }, context) => { diff --git a/libs/ag-ui/src/runtime/submit-input.type-test.ts b/libs/ag-ui/src/runtime/submit-input.type-test.ts index 723e8c1c3..dd63a8992 100644 --- a/libs/ag-ui/src/runtime/submit-input.type-test.ts +++ b/libs/ag-ui/src/runtime/submit-input.type-test.ts @@ -42,5 +42,7 @@ void owner.submit({ message: 'text', tools: [] }); void owner.submit({ message: 'text', signal: new AbortController().signal }); // @ts-expect-error captured authored state is readonly patch['settings'] = {}; -// @ts-expect-error core intentionally retains its string-only submit contract +// The neutral core accepts the same text-with-state input. void core.submit({ message: 'text', state: {} }); +// @ts-expect-error the neutral core still rejects fields outside message and state +void core.submit({ message: 'text', messages: [] }); diff --git a/libs/core/README.md b/libs/core/README.md index 287415bdd..43667ada3 100644 --- a/libs/core/README.md +++ b/libs/core/README.md @@ -11,13 +11,30 @@ acquire/settle invocation-ownership contract. `@threadplane/core/testing` export `createFakeAgentSession`, a transport-free session whose test controls publish frozen snapshots, stream assistant text and record submit, stop and dispose calls. -Sessions accept text and an optional standard `AbortSignal`. Read and subscribe are +Sessions accept text, optionally with a partial state, and an optional standard `AbortSignal`. Read and subscribe are inert; subscribe notifies changes only. Implementations must publish owned, deeply readonly plain snapshot data and keep references stable between changes. Raw errors, causes, controllers, SDK instances and arbitrary extras belong to effect boundaries. `projectAgentError` copies already classified display fields; it does not classify transport failures. Tool failures carry a plain error string instead. +`AgentSession` carries an optional application state type. The +snapshot's `state` is deeply readonly, and absent until the backend reports one. A +session is told its state type by one declaration: `type()` for the type alone, or +any Standard Schema value, such as a Zod object, to also check each state as it +arrives. `InferState` reads the type from either form. `type()` rejects functions, +class instances, arrays and primitives with a sentence naming the problem. A typed +session is still assignable wherever an untyped `AgentSession` is expected, and +without a declaration `state` is plain data. + +`submit` takes the message text, or `{ message, state }` where `state` is a partial +state the backend merges before the run: the declared keys for a typed session, any +plain record otherwise. `readState(declaration, value)` is for session +implementations. It returns the schema's output or the issue messages, never throws, +and treats a schema that validates asynchronously as invalid because a snapshot is +published synchronously. This package defines the contract; whether a backend session +supplies `state` is that session's choice. + `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 f73e0ecc7..d1fa14d92 100644 --- a/libs/core/src/contracts/agent-session.ts +++ b/libs/core/src/contracts/agent-session.ts @@ -1,9 +1,18 @@ import type { AgentSnapshot } from './agent-snapshot.js'; import type { CompleteOutcome } from './delivery.js'; +import type { AgentStateUpdate } from './state.js'; import type { PlainValue, ToolContract } from './tool.js'; -/** The initial neutral session supports text submission only. */ -export type AgentSubmitInput = string; +/** + * What a caller submits: the message text, or the text with a partial state the + * backend merges before the run. A session that holds no state ignores `state`. + */ +export type AgentSubmitInput = + | string + | { + readonly message: string; + readonly state?: AgentStateUpdate; + }; /** Per-submission cancellation signal supplied by the caller. */ export interface AgentSubmitOptions { @@ -27,10 +36,11 @@ export type AgentSession< TTools extends { [K in keyof TTools]: ToolContract } = Record< string, ToolContract - > + >, + TState = unknown > = TTools extends unknown ? { - getSnapshot(): AgentSnapshot; + getSnapshot(): AgentSnapshot; /** Changes only. Read the initial aggregate through getSnapshot. */ subscribe(notify: () => void): () => void; /** @@ -42,7 +52,7 @@ export type AgentSession< listener: (event: AgentSessionCustomEvent) => void ): () => void; submit( - input: AgentSubmitInput, + input: AgentSubmitInput, options?: AgentSubmitOptions ): Promise; stop(): Promise; diff --git a/libs/core/src/contracts/agent-snapshot.ts b/libs/core/src/contracts/agent-snapshot.ts index 8cfdb81cf..03c39aa18 100644 --- a/libs/core/src/contracts/agent-snapshot.ts +++ b/libs/core/src/contracts/agent-snapshot.ts @@ -1,6 +1,6 @@ import type { AgentError } from './error.js'; import type { Message } from './message.js'; -import type { ToolCall, ToolContract } from './tool.js'; +import type { DeepReadonly, ToolCall, ToolContract } from './tool.js'; import type { AgentPlanStep } from './plan.js'; /** @@ -34,7 +34,8 @@ export type AgentSnapshot< TTools extends { [K in keyof TTools]: ToolContract } = Record< string, ToolContract - > + >, + TState = unknown > = TTools extends unknown ? { readonly status: AgentStatus; @@ -45,5 +46,11 @@ export type AgentSnapshot< readonly plan?: readonly AgentPlanStep[]; /** Token usage the runtime reported for the most recent settled run; absent while one runs or when none was reported. */ readonly usage?: AgentUsage; + /** + * Application state the backend last reported, as frozen plain data. + * Typed by the session's state declaration, and plain data without one. + * Absent until the backend reports a state, and on sessions that hold none. + */ + readonly state?: DeepReadonly; } : never; diff --git a/libs/core/src/contracts/state.spec.ts b/libs/core/src/contracts/state.spec.ts new file mode 100644 index 000000000..8791a0fbb --- /dev/null +++ b/libs/core/src/contracts/state.spec.ts @@ -0,0 +1,103 @@ +import { describe, expect, it } from 'vitest'; +import { readState, type, type StandardSchemaV1 } from '../index'; + +interface Board { + count: number; +} + +function schema( + validate: StandardSchemaV1['~standard']['validate'] +): StandardSchemaV1 { + return { '~standard': { version: 1, vendor: 'test', validate } }; +} + +const counted = schema((value) => + typeof (value as Board | null)?.count === 'number' + ? { value: value as Board } + : { issues: [{ message: 'count must be a number' }] } +); + +describe('type', () => { + it('returns one frozen marker that holds no value and is not a schema', () => { + const declared = type(); + expect(declared).toBe(type<{ other: string }>()); + expect(Object.isFrozen(declared)).toBe(true); + expect('~standard' in declared).toBe(false); + expect('~type' in declared).toBe(false); + }); +}); + +describe('readState', () => { + it('accepts every value as given when nothing checks it', () => { + const value = { anything: [1, 'two'] }; + expect(readState(undefined, value)).toEqual({ valid: true, value }); + expect(readState(type(), value)).toEqual({ valid: true, value }); + expect(readState(type(), value)).toHaveProperty('value', value); + }); + + it('returns what a schema accepts', () => { + const value = { count: 2 }; + const reading = readState(counted, value); + expect(reading).toEqual({ valid: true, value }); + }); + + it('returns the schema output, not the input, when the schema transforms', () => { + const doubled = schema((value) => ({ + value: { count: (value as Board).count * 2 }, + })); + expect(readState(doubled, { count: 2 })).toEqual({ + valid: true, + value: { count: 4 }, + }); + }); + + it('reports each issue message for a value the schema rejects', () => { + expect(readState(counted, { count: 'two' })).toEqual({ + valid: false, + issues: ['count must be a number'], + }); + const several = schema(() => ({ + issues: [{ message: 'first' }, { message: 'second' }], + })); + expect(readState(several, {})).toEqual({ + valid: false, + issues: ['first', 'second'], + }); + }); + + it('reports a schema that throws instead of throwing', () => { + const throwing = schema(() => { + throw new Error('broken schema'); + }); + expect(readState(throwing, {})).toEqual({ + valid: false, + issues: ['broken schema'], + }); + }); + + it('reports an asynchronous schema as invalid and leaves no unhandled rejection', async () => { + const resolving = schema(async (value) => ({ + value: value as Board, + })); + expect(readState(resolving, { count: 1 })).toEqual({ + valid: false, + issues: ['State schemas must validate synchronously.'], + }); + const rejecting = schema(() => Promise.reject(new Error('late'))); + expect(readState(rejecting, { count: 1 }).valid).toBe(false); + await new Promise((resolve) => setTimeout(resolve, 0)); + }); + + it('reports a malformed schema result as invalid', () => { + const empty = schema(() => undefined as never); + expect(readState(empty, {})).toEqual({ + valid: false, + issues: ['The schema returned no result.'], + }); + const odd = schema(() => ({ issues: [null, {}] } as never)); + expect(readState(odd, {})).toEqual({ + valid: false, + issues: ['Invalid state.', 'Invalid state.'], + }); + }); +}); diff --git a/libs/core/src/contracts/state.ts b/libs/core/src/contracts/state.ts new file mode 100644 index 000000000..0c2e1fad8 --- /dev/null +++ b/libs/core/src/contracts/state.ts @@ -0,0 +1,173 @@ +import type { PlainValue } from './tool.js'; + +/** + * The part of Standard Schema v1 a session reads. Zod, Valibot, ArkType and any + * other library that implements the standard produce values of this shape, so a + * session needs no schema dependency of its own. + */ +export interface StandardSchemaV1 { + readonly '~standard': { + readonly version: 1; + readonly vendor: string; + readonly validate: ( + value: unknown + ) => StandardSchemaResult | Promise>; + readonly types?: { readonly input: Input; readonly output: Output }; + }; +} + +/** What a Standard Schema reports for one value. */ +export type StandardSchemaResult = + | { readonly value: Output; readonly issues?: undefined } + | { readonly issues: readonly { readonly message: string }[] }; + +const witness = '~threadplane.state'; + +/** + * A state type declared without a schema. It holds no value: the session trusts + * that the backend sends this shape and checks nothing at runtime. + */ +export interface StateWitness { + readonly [witness]: 'type'; + /** Never present. It only carries the declared type. */ + readonly '~type'?: TState; +} + +/** How a session is told its state type: a type alone, or a schema that also checks it. */ +export type StateDeclaration = + | StateWitness + | StandardSchemaV1; + +/** The state type a declaration stands for; `unknown` when there is none. */ +export type InferState = TDeclaration extends StateWitness< + infer TState +> + ? TState + : TDeclaration extends StandardSchemaV1 + ? TState + : unknown; + +type Portable = T extends string | number | boolean | null | undefined + ? T + : T extends (...args: never[]) => unknown + ? never + : T extends object + ? { [K in keyof T]: Portable } + : never; + +/** + * Resolves to `unknown` for a state type a session can hold, and to a sentence + * naming the problem for one it cannot. Used as a constraint so the sentence is + * what the compiler reports. `any` satisfies every constraint, so it is the one + * unusable type this cannot reject. + */ +export type StateTypeCheck = unknown extends TState + ? 'State needs a declared shape. Leave the state type out to keep it untyped.' + : [TState] extends [object] + ? [TState] extends [readonly unknown[]] + ? 'State must be an object, not an array.' + : [TState] extends [Portable] + ? unknown + : 'State must be plain data. Functions and class instances such as Date cannot be held in a snapshot.' + : 'State must be an object.'; + +/** + * Declares a session's state type without a schema. + * + * @example + * ```ts + * const session = createSession({ + * ...options, + * stateType: type<{ todos: Todo[]; draft?: string }>(), + * }); + * session.getSnapshot().state?.todos; // readonly Todo[] + * ``` + * + * The session does not check what the backend sends. Pass a Standard Schema, + * such as a Zod object, in place of `type()` to have each state checked as it + * arrives. + */ +export function type< + TState extends TCheck, + TCheck = StateTypeCheck +>(): StateWitness { + return typeOnly as StateWitness; +} +const typeOnly: StateWitness = Object.freeze({ [witness]: 'type' }); + +/** + * A partial state a caller sends with a submission. Typed sessions accept the + * keys of their declared state; untyped sessions accept any plain record. + */ +export type AgentStateUpdate = unknown extends TState + ? Readonly> + : Partial; + +/** The outcome of checking one state a backend reported. */ +export type StateReading = + | { readonly valid: true; readonly value: unknown } + | { readonly valid: false; readonly issues: readonly string[] }; + +function isSchema(value: unknown): value is StandardSchemaV1 { + if (value === null || typeof value !== 'object') return false; + const standard = (value as { readonly '~standard'?: unknown })['~standard']; + return ( + standard !== null && + typeof standard === 'object' && + typeof (standard as { readonly validate?: unknown }).validate === 'function' + ); +} + +/** + * Checks a state a backend reported against a session's declaration. For + * session implementations. + * + * With no declaration, or a `type()` declaration, every value is valid and + * returned as given. With a schema, the value is the schema's output, so a + * transformed field holds its transformed value. A schema that validates + * asynchronously is reported as invalid: a snapshot is published synchronously + * and cannot wait for it. + */ +export function readState( + declaration: StateDeclaration | undefined, + value: unknown +): StateReading { + if (!isSchema(declaration)) return { valid: true, value }; + let result: unknown; + try { + result = declaration['~standard'].validate(value); + } catch (error) { + return { + valid: false, + issues: [error instanceof Error ? error.message : 'Validation threw.'], + }; + } + if (result === null || typeof result !== 'object') + return { valid: false, issues: ['The schema returned no result.'] }; + if (typeof (result as { readonly then?: unknown }).then === 'function') { + // The validation is abandoned, so its rejection must not surface as unhandled. + (result as Promise).then(undefined, () => undefined); + return { + valid: false, + issues: ['State schemas must validate synchronously.'], + }; + } + const { issues, value: output } = result as { + readonly issues?: unknown; + readonly value?: unknown; + }; + if (issues === undefined || issues === null) + return { valid: true, value: output }; + return { + valid: false, + issues: Array.isArray(issues) + ? issues.map((issue: unknown) => + issue !== null && + typeof issue === 'object' && + typeof (issue as { readonly message?: unknown }).message === 'string' + ? (issue as { readonly message: string }).message + : 'Invalid state.' + ) + : ['Invalid state.'], + }; +} diff --git a/libs/core/src/contracts/state.type-test.ts b/libs/core/src/contracts/state.type-test.ts new file mode 100644 index 000000000..b652ce627 --- /dev/null +++ b/libs/core/src/contracts/state.type-test.ts @@ -0,0 +1,108 @@ +import { + type, + type AgentSession, + type AgentSnapshot, + type InferState, + type PlainValue, + type StandardSchemaV1, + type StateDeclaration, +} from '../index'; + +interface Todo { + id: string; + done: boolean; + tags?: string[]; +} +interface Board { + todos: Todo[]; + draft?: string; + owner: { name: string } | null; +} +type Tools = { weather: { args: { city: string }; result: { temp: number } } }; + +// A declaration carries its state type, whichever form it takes. +const declared = type(); +const fromWitness: InferState = { + todos: [], + owner: null, +}; +declare const schema: StandardSchemaV1; +const fromSchema: InferState = { todos: [], owner: null }; +const untypedDeclaration: unknown = null as InferState; +const either: StateDeclaration[] = [declared, schema]; +// @ts-expect-error a declaration for another shape is not this state's declaration +const wrongDeclaration: StateDeclaration = type<{ count: number }>(); +void [fromWitness, fromSchema, untypedDeclaration, either, wrongDeclaration]; + +// State must be a plain object with a declared shape. +// @ts-expect-error functions cannot be held in a snapshot +type<{ save: () => void }>(); +// @ts-expect-error class instances cannot be held in a snapshot +type<{ at: Date }>(); +// @ts-expect-error state is an object, not an array +type(); +// @ts-expect-error state is an object, not a primitive +type(); +// @ts-expect-error `unknown` declares nothing +type(); +type<{ [key: string]: number }>(); +type>(); + +// The snapshot reads the declared state, deeply readonly. +declare const typed: AgentSession; +const state = typed.getSnapshot().state; +const draft: string | undefined = state?.draft; +const firstTag: string | undefined = state?.todos[0]?.tags?.[0]; +const owner: string | undefined = state?.owner?.name; +// @ts-expect-error state is absent until the backend reports one +const eager: string = typed.getSnapshot().state.draft; +// @ts-expect-error undeclared keys are not state +const missing = state?.archived; +// @ts-expect-error declared fields keep their type +const wrongType: number | undefined = state?.draft; +if (state) { + // @ts-expect-error state cannot be replaced + typed.getSnapshot().state = state; + // @ts-expect-error state fields are readonly + state.draft = 'changed'; + // @ts-expect-error nested collections are readonly + state.todos.push({ id: 't', done: false }); + // @ts-expect-error nested fields are readonly + state.todos[0].done = true; +} +void [draft, firstTag, owner, eager, missing, wrongType]; + +// A submission may carry part of the declared state. +void typed.submit('hello'); +void typed.submit({ message: 'hello' }); +void typed.submit({ message: 'hello', state: { draft: 'x' } }); +void typed.submit({ message: 'hello', state: { todos: [], owner: null } }); +// @ts-expect-error undeclared keys are not state +void typed.submit({ message: 'hello', state: { archived: true } }); +// @ts-expect-error declared fields keep their type +void typed.submit({ message: 'hello', state: { draft: 1 } }); +// @ts-expect-error a submission needs its message +void typed.submit({ state: { draft: 'x' } }); + +// Without a declaration, state is plain data and submissions take any plain record. +declare const untyped: AgentSession; +const plain: PlainValue = untyped.getSnapshot().state; +// @ts-expect-error untyped state has no known fields +const guessed: string = untyped.getSnapshot().state?.draft; +void untyped.submit({ message: 'hello', state: { anything: [1, 'two'] } }); +// @ts-expect-error submitted state is plain data +void untyped.submit({ message: 'hello', state: { run: () => 1 } }); +void [plain, guessed]; + +// A typed session is still a session: consumers that take any session accept it. +const observer: AgentSession = typed; +const toolObserver: AgentSession = typed; +const snapshotObserver: AgentSnapshot = typed.getSnapshot(); +declare const aliasTyped: AgentSession< + Tools, + { count: number; label?: string } +>; +const aliasObserver: AgentSession = aliasTyped; +// @ts-expect-error an untyped session does not promise a declared state +const narrowed: AgentSession = untyped as AgentSession; +void [observer, toolObserver, snapshotObserver, aliasObserver, narrowed]; diff --git a/libs/core/src/index.ts b/libs/core/src/index.ts index 9694d8dc4..532090b42 100644 --- a/libs/core/src/index.ts +++ b/libs/core/src/index.ts @@ -10,6 +10,17 @@ export type { AgentUsage, AgentUsageEntry, } from './contracts/agent-snapshot.js'; +export { readState, type } from './contracts/state.js'; +export type { + AgentStateUpdate, + InferState, + StandardSchemaResult, + StandardSchemaV1, + StateDeclaration, + StateReading, + StateTypeCheck, + StateWitness, +} from './contracts/state.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 187bdfff9..eaddf47bf 100644 --- a/libs/core/src/testing/fake-agent-session.spec.ts +++ b/libs/core/src/testing/fake-agent-session.spec.ts @@ -1,5 +1,11 @@ import { describe, expect, it, vi } from 'vitest'; -import { completeDelivery, staticDelivery, streamingDelivery } from '../index'; +import { + completeDelivery, + staticDelivery, + streamingDelivery, + type, + type StandardSchemaV1, +} from '../index'; import { createFakeAgentSession } from './index'; describe('createFakeAgentSession', () => { @@ -90,7 +96,7 @@ describe('createFakeAgentSession', () => { content: 'You said ', delivery: streamingDelivery('r'), }); - reply.append(input); + reply.append(typeof input === 'string' ? input : input.message); reply.complete(); reply.append(' ignored'); }, @@ -204,4 +210,101 @@ describe('createFakeAgentSession', () => { const call = fake.session.getSnapshot().toolCalls[0]; expect(call.name === 'weather' && call.args.city).toBe('Oslo'); }); + + it('holds no state until one is set, then publishes an owned frozen copy', () => { + const fake = createFakeAgentSession({ + stateType: type<{ todos: string[]; draft?: string }>(), + }); + expect('state' in fake.session.getSnapshot()).toBe(false); + const notify = vi.fn(); + fake.session.subscribe(notify); + const authored = { todos: ['a'] }; + fake.setState(authored); + const state = fake.session.getSnapshot().state; + expect(state).toEqual({ todos: ['a'] }); + expect(state).not.toBe(authored); + expect(Object.isFrozen(state)).toBe(true); + expect(Object.isFrozen(state?.todos)).toBe(true); + expect(notify).toHaveBeenCalledTimes(1); + fake.push({ role: 'assistant', content: 'Later' }); + expect(fake.session.getSnapshot().state).toBe(state); + fake.setState(undefined); + expect('state' in fake.session.getSnapshot()).toBe(false); + }); + + it('starts with an initial state and replaces it whole through set', () => { + const fake = createFakeAgentSession({ + stateType: type<{ count: number; label?: string }>(), + state: { count: 1, label: 'one' }, + }); + expect(fake.session.getSnapshot().state).toEqual({ + count: 1, + label: 'one', + }); + fake.set({ state: { count: 2 } }); + expect(fake.session.getSnapshot().state).toEqual({ count: 2 }); + }); + + it('merges submitted state into the snapshot and records the input as passed', async () => { + const inputs: unknown[] = []; + const fake = createFakeAgentSession({ + stateType: type<{ count: number; label?: string }>(), + state: { count: 1 }, + onSubmit: (input, session) => { + inputs.push(input, session.session.getSnapshot().state); + }, + }); + await fake.session.submit({ message: 'Go', state: { label: 'one' } }); + const snapshot = fake.session.getSnapshot(); + expect(snapshot.state).toEqual({ count: 1, label: 'one' }); + expect(snapshot.messages.map((m) => [m.role, m.content])).toEqual([ + ['user', 'Go'], + ]); + expect(fake.submits).toEqual([ + { input: { message: 'Go', state: { label: 'one' } } }, + ]); + expect(inputs).toEqual([ + { message: 'Go', state: { label: 'one' } }, + { count: 1, label: 'one' }, + ]); + const before = snapshot.state; + await fake.session.submit({ message: 'Again' }); + await fake.session.submit('Text'); + expect(fake.session.getSnapshot().state).toBe(before); + }); + + it('creates state from a submission when none was held', async () => { + const fake = createFakeAgentSession(); + await fake.session.submit({ message: 'Go', state: { topic: 'x' } }); + expect(fake.session.getSnapshot().state).toEqual({ topic: 'x' }); + }); + + it('checks every state against a schema declaration', async () => { + const stateType: StandardSchemaV1 = { + '~standard': { + version: 1, + vendor: 'test', + validate: (value) => + typeof (value as { count?: unknown } | null)?.count === 'number' + ? { value: { count: (value as { count: number }).count } } + : { issues: [{ message: 'count must be a number' }] }, + }, + }; + expect(() => + createFakeAgentSession({ stateType, state: { count: 'x' } as never }) + ).toThrow(/does not match its schema: count must be a number/); + const fake = createFakeAgentSession({ stateType, state: { count: 1 } }); + const notify = vi.fn(); + fake.session.subscribe(notify); + expect(() => fake.setState({ count: 'x' } as never)).toThrow(TypeError); + expect(fake.session.getSnapshot().state).toEqual({ count: 1 }); + expect(notify).not.toHaveBeenCalled(); + // The schema's output is what the snapshot holds: extra keys it drops are gone. + fake.setState({ count: 2, stray: true } as never); + expect(fake.session.getSnapshot().state).toEqual({ count: 2 }); + await expect( + fake.session.submit({ message: 'Go', state: { count: 'x' } as never }) + ).rejects.toThrow(/does not match its schema/); + expect(fake.session.getSnapshot().messages).toHaveLength(0); + }); }); diff --git a/libs/core/src/testing/fake-agent-session.ts b/libs/core/src/testing/fake-agent-session.ts index ab03e85ae..4e660045f 100644 --- a/libs/core/src/testing/fake-agent-session.ts +++ b/libs/core/src/testing/fake-agent-session.ts @@ -14,7 +14,16 @@ import { import { projectAgentError, type AgentError } from '../contracts/error.js'; import type { Message } from '../contracts/message.js'; import type { AgentPlanStep } from '../contracts/plan.js'; -import type { ToolCall, ToolContract } from '../contracts/tool.js'; +import { + readState, + type AgentStateUpdate, + type StateDeclaration, +} from '../contracts/state.js'; +import type { + DeepReadonly, + ToolCall, + ToolContract, +} from '../contracts/tool.js'; /** A message to place in a fake snapshot. The id defaults to a generated one * and the delivery to a complete, successful static delivery. */ @@ -24,28 +33,34 @@ export type FakeMessageInput = Omit & { }; /** Snapshot fields a test may replace. Omitted fields keep their value; an - * explicit `error: undefined` or `plan: undefined` removes the field. */ + * explicit `error: undefined`, `plan: undefined` or `state: undefined` 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< string, ToolContract - > + >, + TState = unknown > { readonly status?: AgentStatus; readonly messages?: readonly FakeMessageInput[]; readonly toolCalls?: readonly ToolCall[]; readonly error?: AgentError; readonly plan?: readonly AgentPlanStep[]; + readonly state?: NoInfer | DeepReadonly>; } /** One recorded call to `session.submit`. */ -export interface FakeSubmitCall { - readonly input: AgentSubmitInput; +export interface FakeSubmitCall { + readonly input: AgentSubmitInput; readonly options?: AgentSubmitOptions; } /** - * Runs after the fake appends the user message for a submission. Return the + * Runs after the fake appends the user message for a submission and merges any + * state it carried. `input` is what the caller passed: the text, or an object + * with `message` and `state`. Return the * outcome `submit` resolves with; nothing means `'success'`. Throwing rejects * `submit` with that error. */ @@ -53,21 +68,28 @@ export type FakeSubmitHandler< TTools extends { [K in keyof TTools]: ToolContract } = Record< string, ToolContract - > + >, + TState = unknown > = ( - input: AgentSubmitInput, - fake: FakeAgentSession, + input: AgentSubmitInput, + fake: FakeAgentSession, options?: AgentSubmitOptions ) => CompleteOutcome | void | PromiseLike; -/** Initial snapshot fields plus an optional submit handler. */ +/** Initial snapshot fields, an optional state declaration and an optional submit handler. */ export interface FakeAgentSessionInit< TTools extends { [K in keyof TTools]: ToolContract } = Record< string, ToolContract - > -> extends FakeAgentSnapshotPatch { - readonly onSubmit?: FakeSubmitHandler; + >, + TState = unknown +> extends FakeAgentSnapshotPatch { + /** + * Types `state`, the way a real session's `stateType` does: `type()` for + * the type alone, or a Standard Schema to also check every state a test sets. + */ + readonly stateType?: StateDeclaration; + readonly onSubmit?: FakeSubmitHandler; } /** An assistant message that receives text until it completes. */ @@ -85,16 +107,17 @@ export interface FakeAgentSession< TTools extends { [K in keyof TTools]: ToolContract } = Record< string, ToolContract - > + >, + TState = unknown > { /** Pass this to `Chat`, `useAgent`, or any other session consumer. */ - readonly session: AgentSession; + readonly session: AgentSession; /** Submissions in call order, including ones the handler rejected. */ - readonly submits: readonly FakeSubmitCall[]; + readonly submits: readonly FakeSubmitCall[]; readonly stopCount: number; readonly disposed: boolean; /** Replaces the listed snapshot fields and notifies subscribers once. */ - set(patch: FakeAgentSnapshotPatch): void; + set(patch: FakeAgentSnapshotPatch): void; /** Appends one message and returns the owned, frozen copy. */ push(message: FakeMessageInput): Message; setStatus(status: AgentStatus): void; @@ -102,13 +125,15 @@ export interface FakeAgentSession< * returns an errored session to `'idle'`. */ setError(error: AgentError | undefined): void; setToolCalls(toolCalls: readonly ToolCall[]): void; + /** Replaces the state; `undefined` removes it. Throws when a schema `stateType` rejects it. */ + setState(state: NoInfer | undefined): void; /** Starts a streaming assistant message and sets status `'running'`. */ stream(options?: { readonly id?: string; readonly text?: string; }): FakeAssistantStream; /** Replaces the handler used by later submissions. */ - onSubmit(handler: FakeSubmitHandler | undefined): void; + onSubmit(handler: FakeSubmitHandler | undefined): void; } const owned = new WeakSet(); @@ -138,8 +163,9 @@ function own(value: T, ancestors = new Set()): T { * Subscribers are notified synchronously, so React tests wrap control calls in * `act`. * - * By default `submit` records the call, appends a user message, and resolves - * `'success'`. Pass `onSubmit` to stream a reply or return another outcome. + * By default `submit` records the call, appends a user message, merges any + * submitted state into the snapshot's state, and resolves `'success'`. Pass + * `onSubmit` to stream a reply or return another outcome. * * @example * ```ts @@ -157,14 +183,26 @@ export function createFakeAgentSession< TTools extends { [K in keyof TTools]: ToolContract } = Record< string, ToolContract - > ->(init: FakeAgentSessionInit = {}): FakeAgentSession { + >, + TState = unknown +>( + init: FakeAgentSessionInit = {} +): FakeAgentSession { type Snapshot = { readonly status: AgentStatus; readonly messages: readonly Message[]; readonly toolCalls: readonly ToolCall[]; readonly error?: AgentError; readonly plan?: readonly AgentPlanStep[]; + readonly state?: DeepReadonly; + }; + const checkState = (value: unknown): DeepReadonly => { + const reading = readState(init.stateType as StateDeclaration, value); + if (!reading.valid) + throw new TypeError( + `The fake state does not match its schema: ${reading.issues.join('; ')}` + ); + return own(reading.value) as DeepReadonly; }; let sequence = 0; const nextId = (prefix: string) => `fake-${prefix}-${++sequence}`; @@ -179,7 +217,7 @@ export function createFakeAgentSession< }; const build = ( base: Snapshot | undefined, - patch: FakeAgentSnapshotPatch + patch: FakeAgentSnapshotPatch ): Snapshot => { const next: { status: AgentStatus; @@ -187,6 +225,7 @@ export function createFakeAgentSession< toolCalls: readonly ToolCall[]; error?: AgentError; plan?: readonly AgentPlanStep[]; + state?: DeepReadonly; } = { status: patch.status ?? base?.status ?? 'idle', messages: patch.messages @@ -203,18 +242,25 @@ export function createFakeAgentSession< if (error) next.error = error; const plan = 'plan' in patch ? patch.plan : base?.plan; if (plan) next.plan = own(plan); + const state = + 'state' in patch + ? patch.state === undefined + ? undefined + : checkState(patch.state) + : base?.state; + if (state !== undefined) next.state = state; return Object.freeze(next); }; let snapshot = build(undefined, init); let handler = init.onSubmit; const listeners = new Set<() => void>(); - const submits: FakeSubmitCall[] = []; + const submits: FakeSubmitCall[] = []; const streams = new Set<() => void>(); let stopCount = 0; let disposed = false; - const publish = (patch: FakeAgentSnapshotPatch) => { + const publish = (patch: FakeAgentSnapshotPatch) => { snapshot = build(snapshot, patch); for (const notify of [...listeners]) notify(); }; @@ -236,12 +282,28 @@ export function createFakeAgentSession< }; }, async submit( - input: AgentSubmitInput, + input: AgentSubmitInput, options?: AgentSubmitOptions ): Promise { submits.push(Object.freeze(options ? { input, options } : { input })); if (disposed) throw new Error('The fake agent session is disposed.'); - fake.push({ role: 'user', content: input }); + const update: AgentStateUpdate | undefined = + typeof input === 'string' ? undefined : input.state; + publish({ + messages: [ + ...snapshot.messages, + ownMessage({ + role: 'user', + content: typeof input === 'string' ? input : input.message, + }), + ], + ...(update !== undefined && { + state: { + ...(snapshot.state as object | undefined), + ...(update as object), + } as NoInfer, + }), + }); const outcome = await handler?.(input, fake, options); return outcome ?? 'success'; }, @@ -256,8 +318,8 @@ export function createFakeAgentSession< }, }; - const fake: FakeAgentSession = { - session: session as unknown as AgentSession, + const fake: FakeAgentSession = { + session: session as unknown as AgentSession, submits, get stopCount() { return stopCount; @@ -282,6 +344,7 @@ export function createFakeAgentSession< } ), setToolCalls: (toolCalls) => publish({ toolCalls }), + setState: (state) => publish({ state }), stream(options = {}) { const id = options.id ?? nextId('assistant'); let open = true; 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 4f70624e8..2b4c93037 100644 --- a/libs/core/src/testing/fake-agent-session.type-test.ts +++ b/libs/core/src/testing/fake-agent-session.type-test.ts @@ -1,4 +1,5 @@ import type { AgentSession, AgentSnapshot } from '../index.js'; +import { type } from '../index.js'; import { createFakeAgentSession } from './index.js'; interface Catalog { @@ -21,3 +22,41 @@ createFakeAgentSession({ createFakeAgentSession().session.getSnapshot().messages.push(); void [untyped, widened, snapshot]; + +// A state declaration types the fake's state, its controls and its submissions. +interface Board { + todos: string[]; + draft?: string; +} +const stateful = createFakeAgentSession({ + stateType: type(), + state: { todos: [] }, + onSubmit: (input) => { + if (typeof input !== 'string') { + const sent: Partial | undefined = input.state; + void sent; + } + }, +}); +const statefulSession: AgentSession< + Record, + Board +> = stateful.session as AgentSession, Board>; +const todos: readonly string[] | undefined = + stateful.session.getSnapshot().state?.todos; +stateful.setState({ todos: ['a'], draft: 'b' }); +stateful.setState(undefined); +stateful.set({ state: { todos: [] } }); +// @ts-expect-error the declaration decides the state type, not the value set +stateful.setState({ count: 1 }); +// @ts-expect-error a whole state needs its required fields +stateful.setState({ draft: 'b' }); +// @ts-expect-error the initial state must match the declaration +createFakeAgentSession({ stateType: type(), state: { todos: 1 } }); +// @ts-expect-error fake state is readonly +stateful.session.getSnapshot().state?.todos.push('b'); +const explicit = createFakeAgentSession(); +const explicitDraft: string | undefined = + explicit.session.getSnapshot().state?.draft; +const anySession: AgentSession = stateful.session; +void [statefulSession, todos, explicitDraft, anySession]; diff --git a/libs/langgraph/src/runtime/submit-input.type-test.ts b/libs/langgraph/src/runtime/submit-input.type-test.ts index f80d238c1..22b74ec70 100644 --- a/libs/langgraph/src/runtime/submit-input.type-test.ts +++ b/libs/langgraph/src/runtime/submit-input.type-test.ts @@ -40,8 +40,10 @@ void session.submit({ message: 'Text', state: { value: new Date() } }); void session.submit('Text', { state }); void session.submit('Text', { config: {} }); const observer: AgentSession = session; -// @ts-expect-error The neutral core still accepts text only. +// The neutral core accepts the same text-with-state input. void observer.submit(input); +// @ts-expect-error The neutral core still takes plain data only. +void observer.submit({ message: 'Text', state: { value: new Date() } }); interface ItineraryStop { readonly city: string; readonly day: number; From 72675d93a165fc95d5e18e32d52990bdc304484f Mon Sep 17 00:00:00 2001 From: Brian Love Date: Thu, 19 Nov 2026 08:49:57 -0800 Subject: [PATCH 2/4] feat(core): add interrupts, resume and child agents to the session contract The snapshot gains optional interrupts and subagents, and the session an optional resume(responses) that answers pending interrupts by id. The fake session publishes both fields and records resume calls. --- libs/core/README.md | 18 ++ libs/core/src/contracts/agent-session.ts | 14 ++ libs/core/src/contracts/agent-snapshot.ts | 12 ++ .../core/src/contracts/contracts.type-test.ts | 84 ++++++++++ libs/core/src/contracts/interrupt.ts | 38 +++++ libs/core/src/contracts/plan.spec.ts | 9 +- libs/core/src/contracts/subagent.ts | 31 ++++ libs/core/src/index.ts | 8 + .../src/testing/fake-agent-session.spec.ts | 155 ++++++++++++++++++ libs/core/src/testing/fake-agent-session.ts | 122 +++++++++++++- .../testing/fake-agent-session.type-test.ts | 25 +++ libs/core/src/testing/index.ts | 3 + 12 files changed, 514 insertions(+), 5 deletions(-) create mode 100644 libs/core/src/contracts/interrupt.ts create mode 100644 libs/core/src/contracts/subagent.ts diff --git a/libs/core/README.md b/libs/core/README.md index 43667ada3..ad334ef8d 100644 --- a/libs/core/README.md +++ b/libs/core/README.md @@ -35,6 +35,24 @@ and treats a schema that validates asynchronously as invalid because a snapshot published synchronously. This package defines the contract; whether a backend session supplies `state` is that session's choice. +A run that pauses for a person settles with the `'paused'` outcome and lists what it +waits on in the snapshot's `interrupts`. Each `AgentInterrupt` has an `id`, and may +carry the backend's `value`, a `reason`, display `message` and the `toolCallId` it is +about. `resume(responses)` answers them: each `AgentInterruptResponse` names one +pending interrupt and is `resolved`, optionally with a `value`, or `cancelled`. A +session rejects a response that names an interrupt that is not pending, names one +twice, or uses a status its backend cannot express. `interrupts` and `resume` are +optional: a session that cannot pause supplies neither. + +The snapshot's optional `subagents` lists the child agents the root agent started, in +start order. An `AgentSubagent` has an `id`, a `status` of `running`, `complete`, +`error` or `unknown`, and its own `messages` and `toolCalls`, which are not repeated +in the root transcript. `unknown` means the child started, no ending was seen, and +no run is active that could still report one. `toolCallId` relates a child to the +root tool call that started it, and `parentId` to the child that did. The fake +session in `@threadplane/core/testing` publishes both fields and records `resume` +calls. + `Message.citations` optionally contains readonly `Citation` source metadata: stable IDs/order, title, URL, snippet, source type, icon URL, primitive publication time, and deeply readonly plain provider extras. These strings are authored display data; diff --git a/libs/core/src/contracts/agent-session.ts b/libs/core/src/contracts/agent-session.ts index d1fa14d92..5b2b4ccdb 100644 --- a/libs/core/src/contracts/agent-session.ts +++ b/libs/core/src/contracts/agent-session.ts @@ -1,5 +1,6 @@ import type { AgentSnapshot } from './agent-snapshot.js'; import type { CompleteOutcome } from './delivery.js'; +import type { AgentInterruptResponse } from './interrupt.js'; import type { AgentStateUpdate } from './state.js'; import type { PlainValue, ToolContract } from './tool.js'; @@ -67,6 +68,19 @@ export type AgentSession< messageId: string, options?: AgentSubmitOptions ): Promise; + /** + * Optional: answers interrupts the snapshot lists and continues the + * paused work, resolving with the continued run's outcome. Each response + * names one pending interrupt by `id`. Rejects without sending when a + * response names an interrupt that is not pending, names one twice, or + * uses a status the backend cannot express; whether every pending + * interrupt must be answered at once is the backend's rule. A session + * that cannot pause leaves the command undefined. + */ + resume?( + responses: readonly AgentInterruptResponse[], + options?: AgentSubmitOptions + ): Promise; /** Read-only reconciliation; never retries an uncertain submission. */ checkStatus?(): Promise; dispose(): Promise; diff --git a/libs/core/src/contracts/agent-snapshot.ts b/libs/core/src/contracts/agent-snapshot.ts index 03c39aa18..da8d5f00b 100644 --- a/libs/core/src/contracts/agent-snapshot.ts +++ b/libs/core/src/contracts/agent-snapshot.ts @@ -2,6 +2,8 @@ import type { AgentError } from './error.js'; import type { Message } from './message.js'; import type { DeepReadonly, ToolCall, ToolContract } from './tool.js'; import type { AgentPlanStep } from './plan.js'; +import type { AgentInterrupt } from './interrupt.js'; +import type { AgentSubagent } from './subagent.js'; /** * Token counts for one model in one run, as the runtime reported them. Absent @@ -52,5 +54,15 @@ export type AgentSnapshot< * Absent until the backend reports a state, and on sessions that hold none. */ readonly state?: DeepReadonly; + /** + * What a paused run is waiting on. Empty or absent when nothing is + * pending, and always absent on sessions that cannot pause. + */ + readonly interrupts?: readonly AgentInterrupt[]; + /** + * Child agents the root agent started, in start order. Absent on + * sessions that report none. + */ + readonly subagents?: readonly AgentSubagent[]; } : never; diff --git a/libs/core/src/contracts/contracts.type-test.ts b/libs/core/src/contracts/contracts.type-test.ts index b2521d847..5beebdc26 100644 --- a/libs/core/src/contracts/contracts.type-test.ts +++ b/libs/core/src/contracts/contracts.type-test.ts @@ -1,7 +1,11 @@ import type { AgentError, + AgentInterrupt, + AgentInterruptResponse, AgentSession, AgentSnapshot, + AgentSubagent, + AgentSubagentStatus, AgentUsage, Citation, CompleteOutcome, @@ -222,3 +226,83 @@ const usage: AgentUsage | undefined = snapshot.usage; // @ts-expect-error usage entries are readonly usage?.entries.push({ inputTokens: 1 }); void [retried, retriedText, usage]; + +// Interrupts: optional on the snapshot, readonly, and answered through resume. +const interrupts: readonly AgentInterrupt[] | undefined = snapshot.interrupts; +const interruptValue: PlainValue = interrupts?.[0]?.value; +// @ts-expect-error pending interrupts are readonly +interrupts?.push({ id: 'i' }); +// @ts-expect-error an interrupt's fields are readonly +if (interrupts?.[0]) interrupts[0].id = 'other'; +const resolved: AgentInterruptResponse = { + interruptId: 'i', + status: 'resolved', + value: { approved: true }, +}; +const cancelled: AgentInterruptResponse = { + interruptId: 'i', + status: 'cancelled', +}; +// @ts-expect-error a cancelled response carries no value +const cancelledWithValue: AgentInterruptResponse = { + interruptId: 'i', + status: 'cancelled', + value: 1, +}; +// @ts-expect-error a response names its interrupt +const unnamed: AgentInterruptResponse = { status: 'resolved' }; +const unsendable: AgentInterruptResponse = { + interruptId: 'i', + status: 'resolved', + // @ts-expect-error a response value is plain data + value: new Date(), +}; +// resume is optional and reports the continued run's outcome, like submit. +const resumed: Promise | undefined = session.resume?.( + [resolved, cancelled], + { signal: new AbortController().signal } +); +// @ts-expect-error resume takes the responses as a list +session.resume?.(resolved); +// A session with no resume command is still an AgentSession. +const cannotPause: AgentSession = { + getSnapshot: () => snapshot, + subscribe: () => () => undefined, + submit: async () => 'success', + stop: async () => undefined, + dispose: async () => undefined, +}; +void [ + interruptValue, + cancelledWithValue, + unnamed, + unsendable, + resumed, + cannotPause, +]; + +// Child agents: optional on the snapshot, each with its own readonly transcript. +const subagents: readonly AgentSubagent[] | undefined = snapshot.subagents; +const childMessages: readonly Message[] | undefined = subagents?.[0]?.messages; +const childCalls: readonly ToolCall[] | undefined = subagents?.[0]?.toolCalls; +const childStatus: AgentSubagentStatus | undefined = subagents?.[0]?.status; +// @ts-expect-error pending is a tool call status, not a child agent status +const invalidChildStatus: AgentSubagentStatus = 'pending'; +// @ts-expect-error a child's messages are readonly +subagents?.[0]?.messages.push(); +// @ts-expect-error a child agent needs its transcript +const bare: AgentSubagent = { id: 'c', status: 'running' }; +// A session typed with authored tools reports the same child shape. +declare const authored: AgentSnapshot<{ + weather: { args: { city: string }; result: { temp: number } }; +}>; +const authoredChildren: readonly AgentSubagent[] | undefined = + authored.subagents; +void [ + childMessages, + childCalls, + childStatus, + invalidChildStatus, + bare, + authoredChildren, +]; diff --git a/libs/core/src/contracts/interrupt.ts b/libs/core/src/contracts/interrupt.ts new file mode 100644 index 000000000..274c34f6a --- /dev/null +++ b/libs/core/src/contracts/interrupt.ts @@ -0,0 +1,38 @@ +import type { PlainValue } from './tool.js'; + +/** + * One thing a paused run is waiting on, such as an approval or a missing + * answer. A run that paused reports its interrupts in the snapshot and settles + * with the `'paused'` outcome; `resume` answers them. + */ +export interface AgentInterrupt { + /** Names this interrupt in a response. Unique among the pending interrupts. */ + readonly id: string; + /** + * What the backend sent with the pause, as frozen plain data. Its shape + * belongs to the agent that paused, so a view narrows it before rendering. + */ + readonly value?: PlainValue; + /** The kind of pause in the backend's own words, such as `tool_approval`. */ + readonly reason?: string; + /** Display text the backend supplied for the person answering. */ + readonly message?: string; + /** The tool call this pause is about, when the backend relates the two. */ + readonly toolCallId?: string; +} + +/** + * The answer to one pending interrupt. `resolved` continues the paused work + * with `value`; `cancelled` declines it and carries no value. + */ +export type AgentInterruptResponse = + | { + readonly interruptId: string; + readonly status: 'resolved'; + readonly value?: PlainValue; + } + | { + readonly interruptId: string; + readonly status: 'cancelled'; + readonly value?: never; + }; diff --git a/libs/core/src/contracts/plan.spec.ts b/libs/core/src/contracts/plan.spec.ts index fa69fb6d6..42c282254 100644 --- a/libs/core/src/contracts/plan.spec.ts +++ b/libs/core/src/contracts/plan.spec.ts @@ -18,7 +18,10 @@ describe('agentPlanFromState', () => { { label: 'Write', status: 'pending' }, ]); }); - it.each([undefined, null, 'x', {}, { todos: 'no' }])('is undefined without a todos list (%s)', (state) => { - expect(agentPlanFromState(state)).toBeUndefined(); - }); + it.each([undefined, null, 'x', {}, { todos: 'no' }])( + 'is undefined without a todos list (%s)', + (state) => { + expect(agentPlanFromState(state)).toBeUndefined(); + } + ); }); diff --git a/libs/core/src/contracts/subagent.ts b/libs/core/src/contracts/subagent.ts new file mode 100644 index 000000000..582f970db --- /dev/null +++ b/libs/core/src/contracts/subagent.ts @@ -0,0 +1,31 @@ +import type { Message } from './message.js'; +import type { ToolCall } from './tool.js'; + +/** + * Where a child agent stands. `unknown` means the session saw it start and saw + * no ending, and no run is active that could still report one. + */ +export type AgentSubagentStatus = 'running' | 'complete' | 'error' | 'unknown'; + +/** + * A child agent the root agent started, with the transcript it produced. Its + * messages and tool calls are held here and are not repeated in the root + * snapshot's `messages` and `toolCalls`. + */ +export interface AgentSubagent { + /** Stable for the life of the session. */ + readonly id: string; + readonly name?: string; + /** The task the child was given, in the root agent's words. */ + readonly description?: string; + /** The root tool call that started this child, when the backend relates the two. */ + readonly toolCallId?: string; + /** The `id` of the child that started this one; absent for a child of the root agent. */ + readonly parentId?: string; + readonly status: AgentSubagentStatus; + readonly messages: readonly Message[]; + /** The child's own tool calls, referenced by `Message.toolCallIds` in `messages`. */ + readonly toolCalls: readonly ToolCall[]; + /** Display text for the failure when `status` is `'error'` and the backend gave one. */ + readonly error?: string; +} diff --git a/libs/core/src/index.ts b/libs/core/src/index.ts index 532090b42..9493f3851 100644 --- a/libs/core/src/index.ts +++ b/libs/core/src/index.ts @@ -21,6 +21,14 @@ export type { StateTypeCheck, StateWitness, } from './contracts/state.js'; +export type { + AgentInterrupt, + AgentInterruptResponse, +} from './contracts/interrupt.js'; +export type { + AgentSubagent, + AgentSubagentStatus, +} from './contracts/subagent.js'; export type { AgentPlanStep } from './contracts/plan.js'; export { agentPlanFromState } from './contracts/plan.js'; export type { Message, Role } from './contracts/message.js'; diff --git a/libs/core/src/testing/fake-agent-session.spec.ts b/libs/core/src/testing/fake-agent-session.spec.ts index eaddf47bf..c5c57fd87 100644 --- a/libs/core/src/testing/fake-agent-session.spec.ts +++ b/libs/core/src/testing/fake-agent-session.spec.ts @@ -307,4 +307,159 @@ describe('createFakeAgentSession', () => { ).rejects.toThrow(/does not match its schema/); expect(fake.session.getSnapshot().messages).toHaveLength(0); }); + + it('publishes interrupts and removes the ones a resume answers', async () => { + const fake = createFakeAgentSession(); + expect('interrupts' in fake.session.getSnapshot()).toBe(false); + const value = { tool: 'send_email', args: { to: 'ada@example.com' } }; + fake.setInterrupts([ + { id: 'i1', value, reason: 'tool_approval', toolCallId: 'c1' }, + { id: 'i2', message: 'Which account?' }, + ]); + const pending = fake.session.getSnapshot().interrupts; + expect(pending).toEqual([ + { id: 'i1', value, reason: 'tool_approval', toolCallId: 'c1' }, + { id: 'i2', message: 'Which account?' }, + ]); + expect(Object.isFrozen(pending)).toBe(true); + expect(pending?.[0].value).not.toBe(value); + expect(Object.isFrozen(pending?.[0].value)).toBe(true); + + const notify = vi.fn(); + fake.session.subscribe(notify); + const signal = new AbortController().signal; + await expect( + fake.session.resume?.( + [{ interruptId: 'i1', status: 'resolved', value: { approved: true } }], + { signal } + ) + ).resolves.toBe('paused'); + expect(notify).toHaveBeenCalledTimes(1); + expect(fake.session.getSnapshot().interrupts).toEqual([ + { id: 'i2', message: 'Which account?' }, + ]); + await expect( + fake.session.resume?.([{ interruptId: 'i2', status: 'cancelled' }]) + ).resolves.toBe('success'); + expect(fake.session.getSnapshot().interrupts).toEqual([]); + expect(fake.resumes).toEqual([ + { + responses: [ + { interruptId: 'i1', status: 'resolved', value: { approved: true } }, + ], + options: { signal }, + }, + { responses: [{ interruptId: 'i2', status: 'cancelled' }] }, + ]); + fake.setInterrupts(undefined); + expect('interrupts' in fake.session.getSnapshot()).toBe(false); + }); + + it('rejects a resume that names no pending interrupt, or one twice', async () => { + const fake = createFakeAgentSession({ interrupts: [{ id: 'i1' }] }); + const before = fake.session.getSnapshot(); + await expect( + fake.session.resume?.([{ interruptId: 'other', status: 'resolved' }]) + ).rejects.toThrow('No pending interrupt has the id "other".'); + await expect( + fake.session.resume?.([ + { interruptId: 'i1', status: 'resolved' }, + { interruptId: 'i1', status: 'cancelled' }, + ]) + ).rejects.toThrow('The interrupt "i1" is answered twice.'); + expect(fake.session.getSnapshot()).toBe(before); + expect(fake.resumes).toHaveLength(2); + await fake.session.dispose(); + await expect( + fake.session.resume?.([{ interruptId: 'i1', status: 'resolved' }]) + ).rejects.toThrow(/disposed/); + }); + + it('lets a resume handler continue the run and choose the outcome', async () => { + const fake = createFakeAgentSession({ + interrupts: [{ id: 'i1' }], + onResume: (responses, controls) => { + controls.push({ role: 'assistant', content: responses[0].status }); + return 'error'; + }, + }); + await expect( + fake.session.resume?.([{ interruptId: 'i1', status: 'resolved' }]) + ).resolves.toBe('error'); + expect(fake.session.getSnapshot().messages.at(-1)?.content).toBe( + 'resolved' + ); + fake.setInterrupts([{ id: 'i2' }]); + fake.onResume(() => { + throw new Error('refused'); + }); + await expect( + fake.session.resume?.([{ interruptId: 'i2', status: 'resolved' }]) + ).rejects.toThrow('refused'); + fake.setInterrupts([{ id: 'i3' }]); + fake.onResume(undefined); + await expect( + fake.session.resume?.([{ interruptId: 'i3', status: 'resolved' }]) + ).resolves.toBe('success'); + }); + + it('publishes child agents with owned transcripts', () => { + const fake = createFakeAgentSession(); + expect('subagents' in fake.session.getSnapshot()).toBe(false); + fake.setSubagents([ + { + id: 'child-1', + name: 'researcher', + description: 'Find three sources', + toolCallId: 'c1', + status: 'running', + messages: [ + { role: 'assistant', content: 'Searching', toolCallIds: ['s1'] }, + ], + toolCalls: [ + { id: 's1', name: 'search', args: { q: 'tides' }, status: 'running' }, + ], + }, + { id: 'child-2', parentId: 'child-1' }, + ]); + const [first, second] = fake.session.getSnapshot().subagents ?? []; + expect(first).toMatchObject({ + id: 'child-1', + name: 'researcher', + description: 'Find three sources', + toolCallId: 'c1', + status: 'running', + }); + expect(first.messages).toEqual([ + { + id: 'fake-assistant-1', + role: 'assistant', + content: 'Searching', + toolCallIds: ['s1'], + delivery: { + generation: 'fake-assistant-1', + phase: 'complete', + outcome: 'success', + }, + }, + ]); + expect(first.toolCalls).toEqual([ + { id: 's1', name: 'search', args: { q: 'tides' }, status: 'running' }, + ]); + expect(second).toEqual({ + id: 'child-2', + parentId: 'child-1', + status: 'complete', + messages: [], + toolCalls: [], + }); + expect(Object.isFrozen(first)).toBe(true); + expect(Object.isFrozen(first.messages)).toBe(true); + // Root changes keep the children by reference. + fake.push({ role: 'assistant', content: 'Done' }); + expect(fake.session.getSnapshot().subagents?.[0]).toBe(first); + expect(fake.session.getSnapshot().messages).toHaveLength(1); + fake.set({ subagents: undefined }); + expect('subagents' in fake.session.getSnapshot()).toBe(false); + }); }); diff --git a/libs/core/src/testing/fake-agent-session.ts b/libs/core/src/testing/fake-agent-session.ts index 4e660045f..6d244f75d 100644 --- a/libs/core/src/testing/fake-agent-session.ts +++ b/libs/core/src/testing/fake-agent-session.ts @@ -13,7 +13,15 @@ import { } from '../contracts/delivery.js'; import { projectAgentError, type AgentError } from '../contracts/error.js'; import type { Message } from '../contracts/message.js'; +import type { + AgentInterrupt, + AgentInterruptResponse, +} from '../contracts/interrupt.js'; import type { AgentPlanStep } from '../contracts/plan.js'; +import type { + AgentSubagent, + AgentSubagentStatus, +} from '../contracts/subagent.js'; import { readState, type AgentStateUpdate, @@ -32,9 +40,20 @@ export type FakeMessageInput = Omit & { readonly delivery?: MessageDelivery; }; +/** A child agent to place in a fake snapshot. The status defaults to + * `'complete'`, and its messages take the same defaults as root messages. */ +export type FakeSubagentInput = Omit< + AgentSubagent, + 'status' | 'messages' | 'toolCalls' +> & { + readonly status?: AgentSubagentStatus; + readonly messages?: readonly FakeMessageInput[]; + readonly toolCalls?: readonly ToolCall[]; +}; + /** Snapshot fields a test may replace. Omitted fields keep their value; an - * explicit `error: undefined`, `plan: undefined` or `state: undefined` removes - * the field. `state` replaces the whole state and is checked against the + * explicit `undefined` for `error`, `plan`, `state`, `interrupts` or + * `subagents` removes the field. `state` replaces the whole state and is checked against the * session's `stateType` when that is a schema. */ export interface FakeAgentSnapshotPatch< TTools extends { [K in keyof TTools]: ToolContract } = Record< @@ -49,8 +68,34 @@ export interface FakeAgentSnapshotPatch< readonly error?: AgentError; readonly plan?: readonly AgentPlanStep[]; readonly state?: NoInfer | DeepReadonly>; + readonly interrupts?: readonly AgentInterrupt[]; + readonly subagents?: readonly FakeSubagentInput[]; } +/** One recorded call to `session.resume`. */ +export interface FakeResumeCall { + readonly responses: readonly AgentInterruptResponse[]; + readonly options?: AgentSubmitOptions; +} + +/** + * Runs after the fake removes the answered interrupts from the snapshot. + * Return the outcome `resume` resolves with; nothing means `'paused'` while + * interrupts remain and `'success'` otherwise. Throwing rejects `resume` with + * that error. + */ +export type FakeResumeHandler< + TTools extends { [K in keyof TTools]: ToolContract } = Record< + string, + ToolContract + >, + TState = unknown +> = ( + responses: readonly AgentInterruptResponse[], + fake: FakeAgentSession, + options?: AgentSubmitOptions +) => CompleteOutcome | void | PromiseLike; + /** One recorded call to `session.submit`. */ export interface FakeSubmitCall { readonly input: AgentSubmitInput; @@ -90,6 +135,7 @@ export interface FakeAgentSessionInit< */ readonly stateType?: StateDeclaration; readonly onSubmit?: FakeSubmitHandler; + readonly onResume?: FakeResumeHandler; } /** An assistant message that receives text until it completes. */ @@ -114,6 +160,8 @@ export interface FakeAgentSession< readonly session: AgentSession; /** Submissions in call order, including ones the handler rejected. */ readonly submits: readonly FakeSubmitCall[]; + /** Resumes in call order, including ones the fake or the handler rejected. */ + readonly resumes: readonly FakeResumeCall[]; readonly stopCount: number; readonly disposed: boolean; /** Replaces the listed snapshot fields and notifies subscribers once. */ @@ -127,6 +175,10 @@ export interface FakeAgentSession< setToolCalls(toolCalls: readonly ToolCall[]): void; /** Replaces the state; `undefined` removes it. Throws when a schema `stateType` rejects it. */ setState(state: NoInfer | undefined): void; + /** Replaces the pending interrupts; `undefined` removes the field. */ + setInterrupts(interrupts: readonly AgentInterrupt[] | undefined): void; + /** Replaces the child agents; `undefined` removes the field. */ + setSubagents(subagents: readonly FakeSubagentInput[] | undefined): void; /** Starts a streaming assistant message and sets status `'running'`. */ stream(options?: { readonly id?: string; @@ -134,6 +186,8 @@ export interface FakeAgentSession< }): FakeAssistantStream; /** Replaces the handler used by later submissions. */ onSubmit(handler: FakeSubmitHandler | undefined): void; + /** Replaces the handler used by later resumes. */ + onResume(handler: FakeResumeHandler | undefined): void; } const owned = new WeakSet(); @@ -167,6 +221,10 @@ function own(value: T, ancestors = new Set()): T { * submitted state into the snapshot's state, and resolves `'success'`. Pass * `onSubmit` to stream a reply or return another outcome. * + * `resume` records the call, removes the interrupts it answers and resolves + * `'success'`, or `'paused'` while others remain. It rejects a response that + * names an interrupt the snapshot does not list, or names one twice. + * * @example * ```ts * const fake = createFakeAgentSession({ @@ -195,6 +253,8 @@ export function createFakeAgentSession< readonly error?: AgentError; readonly plan?: readonly AgentPlanStep[]; readonly state?: DeepReadonly; + readonly interrupts?: readonly AgentInterrupt[]; + readonly subagents?: readonly AgentSubagent[]; }; const checkState = (value: unknown): DeepReadonly => { const reading = readState(init.stateType as StateDeclaration, value); @@ -215,6 +275,15 @@ export function createFakeAgentSession< delivery: input.delivery ?? staticDelivery(id), }); }; + const ownSubagent = (input: FakeSubagentInput): AgentSubagent => { + if (owned.has(input)) return input as AgentSubagent; + return own({ + ...input, + status: input.status ?? 'complete', + messages: (input.messages ?? []).map(ownMessage), + toolCalls: input.toolCalls ?? [], + }); + }; const build = ( base: Snapshot | undefined, patch: FakeAgentSnapshotPatch @@ -226,6 +295,8 @@ export function createFakeAgentSession< error?: AgentError; plan?: readonly AgentPlanStep[]; state?: DeepReadonly; + interrupts?: readonly AgentInterrupt[]; + subagents?: readonly AgentSubagent[]; } = { status: patch.status ?? base?.status ?? 'idle', messages: patch.messages @@ -249,13 +320,23 @@ export function createFakeAgentSession< : checkState(patch.state) : base?.state; if (state !== undefined) next.state = state; + const interrupts = + 'interrupts' in patch ? patch.interrupts : base?.interrupts; + if (interrupts) next.interrupts = own(interrupts); + const subagents = + 'subagents' in patch + ? patch.subagents && own(patch.subagents.map(ownSubagent)) + : base?.subagents; + if (subagents) next.subagents = subagents; return Object.freeze(next); }; let snapshot = build(undefined, init); let handler = init.onSubmit; const listeners = new Set<() => void>(); + let resumeHandler = init.onResume; const submits: FakeSubmitCall[] = []; + const resumes: FakeResumeCall[] = []; const streams = new Set<() => void>(); let stopCount = 0; let disposed = false; @@ -307,6 +388,37 @@ export function createFakeAgentSession< const outcome = await handler?.(input, fake, options); return outcome ?? 'success'; }, + async resume( + responses: readonly AgentInterruptResponse[], + options?: AgentSubmitOptions + ): Promise { + const answers = own([...responses]); + resumes.push( + Object.freeze( + options ? { responses: answers, options } : { responses: answers } + ) + ); + if (disposed) throw new Error('The fake agent session is disposed.'); + const pending = snapshot.interrupts ?? []; + const answered = new Set(); + for (const { interruptId } of answers) { + if (!pending.some((interrupt) => interrupt.id === interruptId)) + throw new TypeError( + `No pending interrupt has the id "${interruptId}".` + ); + if (answered.has(interruptId)) + throw new TypeError( + `The interrupt "${interruptId}" is answered twice.` + ); + answered.add(interruptId); + } + const remaining = pending.filter( + (interrupt) => !answered.has(interrupt.id) + ); + if (answered.size > 0) publish({ interrupts: remaining }); + const outcome = await resumeHandler?.(answers, fake, options); + return outcome ?? (remaining.length > 0 ? 'paused' : 'success'); + }, async stop() { stopCount++; for (const abort of [...streams]) abort(); @@ -321,6 +433,7 @@ export function createFakeAgentSession< const fake: FakeAgentSession = { session: session as unknown as AgentSession, submits, + resumes, get stopCount() { return stopCount; }, @@ -345,6 +458,8 @@ export function createFakeAgentSession< ), setToolCalls: (toolCalls) => publish({ toolCalls }), setState: (state) => publish({ state }), + setInterrupts: (interrupts) => publish({ interrupts }), + setSubagents: (subagents) => publish({ subagents }), stream(options = {}) { const id = options.id ?? nextId('assistant'); let open = true; @@ -386,6 +501,9 @@ export function createFakeAgentSession< onSubmit(next) { handler = next; }, + onResume(next) { + resumeHandler = next; + }, }; return fake; } diff --git a/libs/core/src/testing/fake-agent-session.type-test.ts b/libs/core/src/testing/fake-agent-session.type-test.ts index 2b4c93037..0e7ba5258 100644 --- a/libs/core/src/testing/fake-agent-session.type-test.ts +++ b/libs/core/src/testing/fake-agent-session.type-test.ts @@ -60,3 +60,28 @@ const explicitDraft: string | undefined = explicit.session.getSnapshot().state?.draft; const anySession: AgentSession = stateful.session; void [statefulSession, todos, explicitDraft, anySession]; + +// Interrupts, child agents and resume use the core shapes. +const pausing = createFakeAgentSession({ + interrupts: [{ id: 'i1', value: { tool: 'send' } }], + subagents: [ + { id: 'child', messages: [{ role: 'assistant', content: 'Hi' }] }, + ], + onResume: (responses, fake) => { + const first: string = responses[0].interruptId; + fake.setInterrupts(undefined); + void first; + return 'success'; + }, +}); +pausing.setInterrupts([{ id: 'i2' }]); +// @ts-expect-error an interrupt needs an id +pausing.setInterrupts([{ value: 1 }]); +pausing.setSubagents([{ id: 'child', status: 'unknown' }]); +// @ts-expect-error a child agent status is one of the four contract values +pausing.setSubagents([{ id: 'child', status: 'pending' }]); +// @ts-expect-error a resume handler returns an outcome +pausing.onResume(() => 'done'); +const firstResume: string | undefined = + pausing.resumes[0]?.responses[0]?.interruptId; +void firstResume; diff --git a/libs/core/src/testing/index.ts b/libs/core/src/testing/index.ts index fb3da6906..51cb7df39 100644 --- a/libs/core/src/testing/index.ts +++ b/libs/core/src/testing/index.ts @@ -5,6 +5,9 @@ export type { FakeAgentSnapshotPatch, FakeAssistantStream, FakeMessageInput, + FakeResumeCall, + FakeResumeHandler, + FakeSubagentInput, FakeSubmitCall, FakeSubmitHandler, } from './fake-agent-session.js'; From d6662338b5a6c2ffa4afcf58ca6a3b1938959255 Mon Sep 17 00:00:00 2001 From: Brian Love Date: Thu, 19 Nov 2026 08:49:58 -0800 Subject: [PATCH 3/4] feat(langgraph): answer interrupts by id through the core resume command Every published interrupt has an id, and resume takes the core contract's responses in place of a bare value. One pending interrupt receives its response's value; several are answered as one map keyed by backend id. Callers in the cockpit examples, the native conversation example and the parity fixtures move to the new command. --- cockpit/chat/debug/react/src/application.ts | 6 +- .../interrupts/react/src/application.spec.ts | 2 +- .../chat/interrupts/react/src/application.ts | 25 ++- .../chat/interrupts/react/src/authority.ts | 9 +- cockpit/chat/subagents/react/src/authority.ts | 9 +- cockpit/chat/threads/react/src/authority.ts | 4 +- .../chat/tool-calls/react/src/authority.ts | 9 +- .../filesystem/react/src/application.ts | 17 +- .../angular/e2e/checkpoint-session.spec.ts | 4 +- .../interrupts/react/src/app.spec.tsx | 12 +- .../interrupts/react/src/application.spec.ts | 30 ++- .../interrupts/react/src/application.ts | 29 ++- .../shared/application-approval.spec.ts | 19 +- examples/chat/native/shared/application.ts | 8 +- .../tooling/approval-provider-consumer.ts | 22 +- .../chat/native/tooling/approval-provider.ts | 14 +- .../native/tooling/backup-provider.spec.ts | 2 +- .../chat/native/tooling/backup-provider.ts | 6 +- .../chat/native/tooling/browser-proof.mjs | 2 +- fixtures/react-parity/README.md | 4 +- .../ag-ui-candidate/installed-types.ts | 4 +- .../langgraph-candidate/installed-types.ts | 24 ++- fixtures/react-parity/runtime/README.md | 22 +- .../react-parity/runtime/runtime-entry.ts | 4 +- fixtures/react-parity/runtime/scenarios.ts | 24 ++- libs/langgraph/src/runtime/README.md | 14 ++ .../src/runtime/checkpoint-execution.spec.ts | 17 +- .../src/runtime/checkpoint-history.spec.ts | 5 +- .../runtime/checkpoint-persistence.spec.ts | 3 +- .../runtime/checkpoint-tool-evidence.spec.ts | 9 +- libs/langgraph/src/runtime/create-session.ts | 48 +++-- .../src/runtime/history-projection.ts | 4 +- .../src/runtime/interrupt-projection.spec.ts | 141 +++++++++++++ .../src/runtime/interrupt-projection.ts | 83 +++++++- .../runtime/interrupt-projection.type-test.ts | 16 +- .../src/runtime/interruption-recovery.spec.ts | 57 +++-- libs/langgraph/src/runtime/interrupts.spec.ts | 4 +- .../src/runtime/langgraph-snapshot.ts | 18 +- .../runtime/owned-checkpoint-stream.spec.ts | 5 +- libs/langgraph/src/runtime/ownership.ts | 9 +- libs/langgraph/src/runtime/reasoning.spec.ts | 3 +- libs/langgraph/src/runtime/reconnect.spec.ts | 13 +- .../src/runtime/response-identity.spec.ts | 5 +- libs/langgraph/src/runtime/resume.spec.ts | 199 ++++++++++++++---- .../langgraph/src/runtime/resume.type-test.ts | 35 ++- libs/langgraph/src/runtime/retry.spec.ts | 43 ++-- .../langgraph/src/runtime/run-options.spec.ts | 13 +- .../src/runtime/run-options.type-test.ts | 7 +- .../session-invocation-identity.spec.ts | 5 +- libs/langgraph/src/runtime/subgraphs.spec.ts | 7 +- .../src/runtime/testing/answer-pending.ts | 20 ++ .../src/runtime/tool-claim-ownership.spec.ts | 3 +- .../runtime/tool-write-serialization.spec.ts | 5 +- .../src/runtime/transport.integration.spec.ts | 15 +- libs/langgraph/src/runtime/values.spec.ts | 8 +- .../src/runtime/visible-text.spec.ts | 5 +- scripts/react-parity/dispositions.json | 11 + scripts/react-parity/runtime-consumer.mjs | 24 ++- .../react-parity/runtime-consumer.spec.mjs | 15 +- 59 files changed, 916 insertions(+), 264 deletions(-) create mode 100644 libs/langgraph/src/runtime/testing/answer-pending.ts diff --git a/cockpit/chat/debug/react/src/application.ts b/cockpit/chat/debug/react/src/application.ts index c582118e5..64007d5d4 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[], values: 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 7b3535bce..0bdd4ed28 100644 --- a/cockpit/deep-agents/filesystem/react/src/application.ts +++ b/cockpit/deep-agents/filesystem/react/src/application.ts @@ -1,4 +1,5 @@ import type { + AgentInterruptResponse, AgentSession, AgentSnapshot, CompleteOutcome, @@ -37,11 +38,12 @@ import { type FilesystemSnapshot, type Turn, } from './authority'; -export interface FilesystemSession extends Omit { +export interface FilesystemSession + extends Omit { getSnapshot(): AgentSnapshot & FilesystemSnapshot; load(options?: { readonly signal?: AbortSignal }): Promise; resume( - value: PlainValue, + responses: readonly AgentInterruptResponse[], options?: { readonly signal?: AbortSignal } ): Promise; } @@ -497,11 +499,16 @@ export function createFilesystemApplication(client: FilesystemClient) { (snapshot as FilesystemApplicationSnapshot).phase !== 'confirming' ) throw Error('Unavailable whole batch'); + // The whole batch is one interrupt; its id names the response. + const interruptId = selected.session.getSnapshot().interrupts[0]?.id; + if (typeof interruptId !== 'string') + throw Error('Unavailable whole batch'); publish({ phase: 'working', approval: null, decisionToken: null }); if (!current(run)) return false; - outcome = await selected.session.resume(decision, { - signal: run.controller.signal, - }); + outcome = await selected.session.resume( + [{ interruptId, status: 'resolved', value: decision }], + { signal: run.controller.signal } + ); if (!current(run)) return false; observe(run); if (!current(run)) return false; diff --git a/cockpit/langgraph/interrupts/angular/e2e/checkpoint-session.spec.ts b/cockpit/langgraph/interrupts/angular/e2e/checkpoint-session.spec.ts index 926bd198d..f1943ae95 100644 --- a/cockpit/langgraph/interrupts/angular/e2e/checkpoint-session.spec.ts +++ b/cockpit/langgraph/interrupts/angular/e2e/checkpoint-session.spec.ts @@ -133,7 +133,7 @@ for (const consumed of [false, true]) { const unsubscribe = session.subscribe(() => publications.push(session.getSnapshot())); let rejected = false; try { - await session.resume({ approved: false }); + await session.resume([{ interruptId: session.getSnapshot().interrupts[0]?.id ?? 'consumed', status: 'resolved', value: { approved: false } }]); } catch { rejected = true; } finally { @@ -159,7 +159,7 @@ for (const consumed of [false, true]) { expect(position((await api.threads.getState(threadId)).checkpoint)).toEqual(position(approved.checkpoint)); const stillPaused = await api.threads.getState(threadId, pausedPosition); expect(stillPaused.tasks).toEqual([expect.objectContaining({ id: task.id, result: null, interrupts: task.interrupts })]); - expect(await session.resume({ approved: false })).toBe('success'); + expect(await session.resume([{ interruptId: session.getSnapshot().interrupts[0].id, status: 'resolved', value: { approved: false } }])).toBe('success'); expect(transport.creations).toBe(beforeCreations + 1); const exact = transport.finalPosition(); const rejected = await api.threads.getState(threadId, exact); diff --git a/cockpit/langgraph/interrupts/react/src/app.spec.tsx b/cockpit/langgraph/interrupts/react/src/app.spec.tsx index a2c5bed4e..f23d5503c 100644 --- a/cockpit/langgraph/interrupts/react/src/app.spec.tsx +++ b/cockpit/langgraph/interrupts/react/src/app.spec.tsx @@ -29,7 +29,7 @@ function setup( finish = resolve; }); const batch = Object.freeze([{ id: 'refund', value: payload }]); - let interrupts: readonly { value: unknown }[] = batch; + let interrupts: readonly { id: string; value: unknown }[] = batch; const session: InterruptSession = { getSnapshot: () => ({ status: 'idle', @@ -121,7 +121,7 @@ describe('native React refund approval', () => { await s.pause(); fireEvent.click(s.view.getByRole('button', { name: label })); expect(s.session.resume).toHaveBeenCalledWith( - { approved }, + [{ interruptId: 'refund', status: 'resolved', value: { approved } }], expect.any(Object) ); expect(s.session.submit).toHaveBeenCalledTimes(1); @@ -185,7 +185,13 @@ describe('native React refund approval', () => { s.view.getByRole('button', { name: 'Approve edited amount' }) ); expect(s.session.resume).toHaveBeenCalledWith( - { approved: true, amount: 0 }, + [ + { + interruptId: 'refund', + status: 'resolved', + value: { approved: true, amount: 0 }, + }, + ], expect.any(Object) ); }); diff --git a/cockpit/langgraph/interrupts/react/src/application.spec.ts b/cockpit/langgraph/interrupts/react/src/application.spec.ts index e55742b79..6bc940d6e 100644 --- a/cockpit/langgraph/interrupts/react/src/application.spec.ts +++ b/cockpit/langgraph/interrupts/react/src/application.spec.ts @@ -33,13 +33,14 @@ function setup() { const creation = deferred(); const run = deferred(); const resumed = deferred(); - let snapshot: AgentSnapshot & { interrupts: readonly { value?: unknown }[] } = - Object.freeze({ - status: 'idle', - messages: [], - toolCalls: [], - interrupts: Object.freeze([]), - }); + let snapshot: AgentSnapshot & { + interrupts: readonly { id: string; value?: unknown }[]; + } = Object.freeze({ + status: 'idle', + messages: [], + toolCalls: [], + interrupts: Object.freeze([]), + }); const observers = new Set<() => void>(); const release = vi.fn(); const session: InterruptSession = { @@ -142,9 +143,10 @@ describe('public interrupts owner', () => { await s.application.decide(required(decision), response); await s.application.submit('Duplicate text'); expect(s.session.resume).toHaveBeenCalledTimes(1); - expect(s.session.resume).toHaveBeenCalledWith(response, { - signal: expect.any(AbortSignal), - }); + expect(s.session.resume).toHaveBeenCalledWith( + [{ interruptId: 'reused-id', status: 'resolved', value: response }], + { signal: expect.any(AbortSignal) } + ); expect(s.application.getSnapshot().busy).toBe(true); expect(s.application.getSnapshot().decision).toBeNull(); expect(s.session.submit).toHaveBeenCalledTimes(1); @@ -244,7 +246,13 @@ describe('public interrupts owner', () => { const pending = s.application.decide(required(decision), response); response.amount = 100; expect(s.session.resume).toHaveBeenCalledWith( - { approved: true, amount: 25 }, + [ + { + interruptId: 'reused-id', + status: 'resolved', + value: { approved: true, amount: 25 }, + }, + ], expect.any(Object) ); s.resumed.reject(new Error('PRIVATE credential')); diff --git a/cockpit/langgraph/interrupts/react/src/application.ts b/cockpit/langgraph/interrupts/react/src/application.ts index b76d2fe02..835275190 100644 --- a/cockpit/langgraph/interrupts/react/src/application.ts +++ b/cockpit/langgraph/interrupts/react/src/application.ts @@ -1,4 +1,5 @@ import type { + AgentInterruptResponse, AgentSession, AgentSnapshot, CompleteOutcome, @@ -8,12 +9,16 @@ import { type MessageRow, } from '@threadplane/content/messages'; -export interface InterruptSession extends Omit { +export interface InterruptSession + extends Omit { getSnapshot(): AgentSnapshot & { - readonly interrupts: readonly { readonly value?: unknown }[]; + readonly interrupts: readonly { + readonly id: string; + readonly value?: unknown; + }[]; }; resume( - value: RefundResponse, + responses: readonly AgentInterruptResponse[], options?: { readonly signal?: AbortSignal } ): Promise; } @@ -112,6 +117,8 @@ export function createInterruptsApplication(options: { let capturedBatch: | ReturnType['interrupts'] | undefined; + /** The id of the one interrupt behind the projected decision. */ + let capturedId: string | undefined; let operation: AbortController | undefined; let disposed = false; let disposal: Promise | undefined; @@ -126,8 +133,13 @@ export function createInterruptsApplication(options: { if (interrupts === capturedBatch) return; capturedBatch = interrupts; const root = - interrupts.length === 1 ? ownData(interrupts[0], ['value']) : undefined; - const refund = root && refundPayload(root['value']); + interrupts.length === 1 + ? ownData(interrupts[0], ['id', 'value']) + : undefined; + const id = root?.['id']; + const refund = + root && typeof id === 'string' ? refundPayload(root['value']) : undefined; + capturedId = refund && typeof id === 'string' ? id : undefined; publish({ decision: refund ? Object.freeze({ refund }) : null, canSubmit: false, @@ -234,12 +246,17 @@ export function createInterruptsApplication(options: { ) return; const admittedBatch = capturedBatch; + const interruptId = capturedId; + if (interruptId === undefined) return; await perform('decision', (owned, signal) => { // Publishing pending state can synchronously replace the observed batch. // Reproject that pause without dispatching the superseded decision. if (owned.getSnapshot().interrupts !== admittedBatch) return Promise.resolve('paused'); - return owned.resume(captured, { signal }); + return owned.resume( + [{ interruptId, status: 'resolved', value: captured }], + { signal } + ); }); } async function stop() { diff --git a/examples/chat/native/shared/application-approval.spec.ts b/examples/chat/native/shared/application-approval.spec.ts index 5cfa11079..9dbd91c88 100644 --- a/examples/chat/native/shared/application-approval.spec.ts +++ b/examples/chat/native/shared/application-approval.spec.ts @@ -96,7 +96,8 @@ const resume = (thread: string, answer = 'approved', extra = {}) => ({ payload: { assistant_id: 'assistant', input: null, - command: { resume: { [id]: answer } }, + // One pending approval: the answer is the plain resume value. + command: { resume: answer }, stream_mode: ['values', 'messages-tuple', 'updates', 'custom', 'checkpoints'], stream_subgraphs: true, stream_resumable: true, @@ -452,8 +453,8 @@ test('approval rejected completion suppresses a real replacement pause even when const actual = o.sessionFactory!(thread); return { ...actual, - async resume(value, options) { - assert.equal(await actual.resume(value, options), 'paused'); + async resume(responses, options) { + assert.equal(await actual.resume(responses, options), 'paused'); throw new Error('completion delivery failed'); }, }; @@ -495,10 +496,10 @@ for (const action of ['stop', 'select', 'dispose'] as const) { const actual = o.sessionFactory!(thread); return { ...actual, - resume(value, options) { + resume(responses, options) { invocations++; aborted = options?.signal?.aborted ?? false; - return actual.resume(value, options); + return actual.resume(responses, options); }, }; }, @@ -554,8 +555,8 @@ test('approval held resume Stop closes HTTP but cannot release the shared slot b const actual = o.sessionFactory!(thread); return { ...actual, - async resume(value, options) { - const result = await actual.resume(value, options); + async resume(responses, options) { + const result = await actual.resume(responses, options); settled.release(); await gate.promise; return result; @@ -654,8 +655,8 @@ for (const rejection of [false, true]) { first = false; return { ...actual, - async resume(value, options) { - const result = await actual.resume(value, options); + async resume(responses, options) { + const result = await actual.resume(responses, options); if (delay) { settled.release(); await gate.promise; diff --git a/examples/chat/native/shared/application.ts b/examples/chat/native/shared/application.ts index 0a622df57..1b406e3d5 100644 --- a/examples/chat/native/shared/application.ts +++ b/examples/chat/native/shared/application.ts @@ -1788,10 +1788,12 @@ function createApplicationOwner( ) return false; const response = { - [decision.approval.id]: action === 'approve' ? 'approved' : 'denied', - }; + interruptId: decision.approval.id, + status: 'resolved', + value: action === 'approve' ? 'approved' : 'denied', + } as const; return execute('decision', (runtimeSession, signal) => - runtimeSession.resume(response, { signal }) + runtimeSession.resume([response], { signal }) ); } diff --git a/examples/chat/native/tooling/approval-provider-consumer.ts b/examples/chat/native/tooling/approval-provider-consumer.ts index 73f3dc837..93b68557c 100644 --- a/examples/chat/native/tooling/approval-provider-consumer.ts +++ b/examples/chat/native/tooling/approval-provider-consumer.ts @@ -167,14 +167,26 @@ 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, so the ID-keyed command goes through + // the provider client. const session = own(thread.thread_id); assert.ok(session.load); - await session.load({ signal }); - assert.equal( - await session.resume({ [unmatched]: 'denied' }, { signal }), - 'paused' + await assert.rejects( + session.resume( + [{ interruptId: unmatched, status: 'resolved', value: 'denied' }], + { signal } + ), + TypeError ); + 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.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 c9d78d05a..f6707277a 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 cdeb54b57..26880f73a 100644 --- a/fixtures/react-parity/ag-ui-candidate/installed-types.ts +++ b/fixtures/react-parity/ag-ui-candidate/installed-types.ts @@ -107,8 +107,8 @@ export function checkCandidate(signal: AbortSignal) { void agent.submit({ message: 'Hello', state: { topic: 'x' } }); // @ts-expect-error The core view takes a message and state only. void agent.submit({ message: 'Hello', messages: [] }); - // @ts-expect-error Native resume stays on the native session. - void agent.resume; + // @ts-expect-error The core contract's resume is optional, and this view does not supply it. + void agent.resume([]); // @ts-expect-error The view wraps a session, not its options. createAgentSession(options); return { session, snapshot, rows, stable, messages, toolCalls, agent, core }; diff --git a/fixtures/react-parity/langgraph-candidate/installed-types.ts b/fixtures/react-parity/langgraph-candidate/installed-types.ts index d8e116323..a109384d0 100644 --- a/fixtures/react-parity/langgraph-candidate/installed-types.ts +++ b/fixtures/react-parity/langgraph-candidate/installed-types.ts @@ -52,8 +52,19 @@ export function checkCandidate(signal: AbortSignal) { ); void session.submit('Hello', { signal }); void session.load?.({ signal }); - void session.resume({ approval: true }, options); - void session.resume(null); + void session.resume( + [ + { + interruptId: 'approval', + status: 'resolved', + value: { approval: true }, + }, + ], + options + ); + void session.resume([ + { interruptId: 'approval', status: 'resolved', value: null }, + ]); void session.reconnect({ signal }); const snapshot = session.getSnapshot(); const values: Readonly> | undefined = @@ -101,8 +112,13 @@ export function checkCandidate(signal: AbortSignal) { void session.submit({ message: '', state: { date: new Date() } }); // @ts-expect-error Run options cannot route another thread. void session.submit('', { config: { configurable: { thread_id: 'other' } } }); - // @ts-expect-error Resume cannot override transport commands. - void session.resume(true, { command: { goto: 'other' } }); + void session.resume( + [{ interruptId: 'approval', status: 'resolved', value: true }], + // @ts-expect-error Resume cannot override transport commands. + { command: { goto: 'other' } } + ); + // @ts-expect-error A bare value does not name the interrupt it answers. + void session.resume(true); // @ts-expect-error Fork requires the actual checkpoint shape. void session.fork('checkpoint', 'Branch'); // @ts-expect-error Observed state cannot be replaced by a consumer. diff --git a/fixtures/react-parity/runtime/README.md b/fixtures/react-parity/runtime/README.md index 3d58ff665..5b84e7c10 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. @@ -565,7 +570,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, @@ -598,7 +603,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 294f7c5bc..49e1b459f 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/langgraph/src/runtime/README.md b/libs/langgraph/src/runtime/README.md index d59fae0d2..3600068e3 100644 --- a/libs/langgraph/src/runtime/README.md +++ b/libs/langgraph/src/runtime/README.md @@ -250,6 +250,20 @@ stream modes produce. ## 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 23657e254..3d7b6e8f3 100644 --- a/libs/langgraph/src/runtime/create-session.ts +++ b/libs/langgraph/src/runtime/create-session.ts @@ -2,6 +2,7 @@ import { agentPlanFromState, completeDelivery, type AgentError, + type AgentInterruptResponse, type AgentSession, type AgentSessionCustomEvent, type CompleteOutcome, @@ -30,14 +31,16 @@ import { } from './history-projection.js'; import { projectCheckpointHistory } from './checkpoint-history.js'; import type { - LangGraphInterrupt, + LangGraphWireInterrupt, LangGraphSnapshot, LangGraphValues, } 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 { @@ -54,7 +57,10 @@ import { type LangGraphInputState, type LangGraphSubmitInput, } from './submit-input.js'; -export type { LangGraphInputState, LangGraphSubmitInput } from './submit-input.js'; +export type { + LangGraphInputState, + LangGraphSubmitInput, +} from './submit-input.js'; import { captureRunOptions, type CapturedRunOptions, @@ -129,7 +135,7 @@ export type LangGraphSession< string, ToolContract > -> = Omit, 'getSnapshot' | 'submit'> & { +> = Omit, 'getSnapshot' | 'submit' | 'resume'> & { getSnapshot(): LangGraphSnapshot; submit( input: LangGraphSubmitInput, @@ -143,8 +149,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; @@ -177,7 +189,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 { @@ -219,11 +231,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))); @@ -367,7 +379,7 @@ export function createSession( let state = initialMessageState(); const reasoningTimer = createReasoningTimer(); let values: LangGraphValues | undefined; - let interrupts: readonly LangGraphInterrupt[] = + let interrupts: readonly LangGraphWireInterrupt[] = publication.getSnapshot().interrupts; let owner: Attempt | undefined; let recoveryAttempt: Attempt | undefined; @@ -476,7 +488,7 @@ export function createSession( history: historyPage, values, ...(plan ? { plan } : {}), - interrupts, + interrupts: identifyInterrupts(interrupts), subgraphs: subgraphs.subgraphs, ...(retained?.run.evidence.runId ? { reconnect: { runId: retained.run.evidence.runId } } @@ -835,8 +847,7 @@ export function createSession( return ( message && (message['type'] === 'ai' || - (attempt.handoffIds.length === 0 && - message['type'] === 'tool') || + (attempt.handoffIds.length === 0 && message['type'] === 'tool') || message['role'] === 'assistant') && typeof message['id'] === 'string' ); @@ -1665,7 +1676,7 @@ export function createSession( } function resume( - value?: PlainValue, + responses: readonly AgentInterruptResponse[], options?: LangGraphRunOptions ): Promise { let attempt: Attempt | undefined; @@ -1703,6 +1714,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); @@ -2162,7 +2174,9 @@ export function createSession( ); // The transcript may have moved on while history was read. if (select().id !== prompt.id) - throw new Error('The conversation changed before it could be regenerated.'); + throw new Error( + 'The conversation changed before it could be regenerated.' + ); const holds = (saved: ThreadState) => { const values = saved.values as { messages?: unknown } | null | undefined; return ( @@ -2182,7 +2196,11 @@ export function createSession( throw new Error( 'The checkpoint before that prompt is not in the loaded history.' ); - return fork(source.checkpoint as CheckpointReference, prompt.content, options); + return fork( + source.checkpoint as CheckpointReference, + prompt.content, + options + ); } const canRegenerate = !!getHistory && 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 eae727e8f..ae7e3dd05 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 045204ffd..b90a7f2ab 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 bdf3b5014..40a47bfc2 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; /** Observed backend application data, not a validated application schema. */ export type LangGraphValues = Readonly>; @@ -25,7 +35,7 @@ export interface LangGraphSubgraph { readonly namespace: readonly string[]; readonly messages: readonly Message[]; readonly values: LangGraphValues | undefined; - readonly interrupts: readonly LangGraphInterrupt[]; + readonly interrupts: readonly LangGraphWireInterrupt[]; readonly error?: AgentError; } @@ -35,7 +45,7 @@ export type LangGraphSnapshot< string, ToolContract > -> = AgentSnapshot & { +> = Omit, 'interrupts'> & { /** Last explicit history page; undefined until loaded. Not a live branch tree. */ readonly history: readonly LangGraphHistoryEntry[] | undefined; readonly values: LangGraphValues | undefined; 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 712d6f639..1d3629fe5 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, LangGraphValues, @@ -336,9 +337,9 @@ export function ownLangGraphSnapshot( | LangGraphValues | 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 @@ -389,7 +390,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 600ab9bd6..dc3fe4f51 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 96fb8c102..6bb9e2edd 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().values).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 d72ae2349..227c093c5 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().values; 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 0e461d8d5..28b91c6ae 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 4b385c8c0..3429bcd1b 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 cd215ba12..f13d67a61 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 588c3ba77..dade65b9b 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().values).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().values).toEqual({ count: 3 }); - expect(f.snapshot().interrupts).toEqual([{ when: 'breakpoint' }]); + expect(f.snapshot().interrupts).toEqual([ + { id: 'breakpoint', when: 'breakpoint' }, + ]); expect(f.snapshot().messages.at(-1)?.delivery).toMatchObject({ outcome: 'paused', }); diff --git a/libs/langgraph/src/runtime/visible-text.spec.ts b/libs/langgraph/src/runtime/visible-text.spec.ts index 08508ad6c..24b0fb6a1 100644 --- a/libs/langgraph/src/runtime/visible-text.spec.ts +++ b/libs/langgraph/src/runtime/visible-text.spec.ts @@ -3,6 +3,7 @@ import { createSession } from './create-session'; import type { AgentTransport, StreamEvent } from './transport.types'; import { controlledSession } from './testing/controlled-session'; import { saved } from './testing/checkpoint-fixture'; +import { answerPending } from './testing/answer-pending'; const cleanups: (() => Promise)[] = []; afterEach(async () => { @@ -210,7 +211,9 @@ describe('visible text through actual session ownership', () => { await session.load!(); const paused = session.getSnapshot(); expect(paused.messages.at(-1)?.content).toBe('Waiting'); - expect(await session.resume(true)).toBe('success'); + expect(await session.resume(answerPending(session, true))).toBe( + 'success' + ); expect( session.getSnapshot().messages.filter((m) => m.role === 'assistant') ).toMatchObject([ diff --git a/scripts/react-parity/dispositions.json b/scripts/react-parity/dispositions.json index e4a5a99cd..f8e0dddd8 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": [ diff --git a/scripts/react-parity/runtime-consumer.mjs b/scripts/react-parity/runtime-consumer.mjs index b4a42887f..10df1d3cd 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']]) { From 50984f8eae36e0f05b542df8827be9f5d04c80e7 Mon Sep 17 00:00:00 2001 From: Brian Love Date: Thu, 19 Nov 2026 09:31:18 -0800 Subject: [PATCH 4/4] test(native-conversation): send the unmatched-id diagnostic through the client only The raw session has loaded nothing at that point, so its resume rejects for a missing pause, not for the unmatched id. The session's own specs cover the rejection; the diagnostic keeps the provider routing evidence. --- .../chat/native/tooling/approval-provider-consumer.ts | 11 ++--------- 1 file changed, 2 insertions(+), 9 deletions(-) diff --git a/examples/chat/native/tooling/approval-provider-consumer.ts b/examples/chat/native/tooling/approval-provider-consumer.ts index 93b68557c..a4f143b87 100644 --- a/examples/chat/native/tooling/approval-provider-consumer.ts +++ b/examples/chat/native/tooling/approval-provider-consumer.ts @@ -168,17 +168,10 @@ try { const before = await journal(); // Provider routing diagnostic only; application decisions never accept // an arbitrary ID or raw resume value. The session rejects an ID that - // is not pending before sending, so the ID-keyed command goes through - // the provider client. + // 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); - await assert.rejects( - session.resume( - [{ interruptId: unmatched, status: 'resolved', value: 'denied' }], - { signal } - ), - TypeError - ); for await (const event of api.runs.stream(thread.thread_id, 'chat', { input: null, command: { resume: { [unmatched]: 'denied' } },