From 50998de093a03880ce5de019d215689c577313cd Mon Sep 17 00:00:00 2001 From: Brian Love Date: Tue, 17 Nov 2026 20:12:05 -0800 Subject: [PATCH 01/18] 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 bf1780da2aadf16d61232672d0c66ad36da613b8 Mon Sep 17 00:00:00 2001 From: Brian Love Date: Wed, 18 Nov 2026 12:58:07 -0800 Subject: [PATCH 02/18] feat(ag-ui): type the session's state and publish it in the core view createSession takes a stateType, either type() or a Standard Schema. createAgentSession publishes the state document as the typed state of the core snapshot, checks it once per document when a schema is declared, and reports a rejected document in stateIssues without failing the run. A session created without a state reports none until one is supplied. --- .../ag-ui-candidate/installed-types.ts | 9 + libs/ag-ui/src/runtime/README.md | 51 ++++- .../src/runtime/agent-session-state.spec.ts | 205 ++++++++++++++++++ libs/ag-ui/src/runtime/agent-session.spec.ts | 1 - libs/ag-ui/src/runtime/agent-session.ts | 129 +++++++++-- .../src/runtime/agent-session.type-test.ts | 80 +++++++ libs/ag-ui/src/runtime/create-session.ts | 42 +++- libs/ag-ui/src/runtime/session-observation.ts | 6 +- libs/ag-ui/src/runtime/state.ts | 7 + libs/ag-ui/src/runtime/submit-input.ts | 15 +- .../src/runtime/testing/binding-fixture.ts | 6 +- 11 files changed, 505 insertions(+), 46 deletions(-) create mode 100644 libs/ag-ui/src/runtime/agent-session-state.spec.ts create mode 100644 libs/ag-ui/src/runtime/agent-session.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 cdeb54b57..e31eb3000 100644 --- a/fixtures/react-parity/ag-ui-candidate/installed-types.ts +++ b/fixtures/react-parity/ag-ui-candidate/installed-types.ts @@ -15,6 +15,7 @@ import { type ClientToolBlocker, } from '@threadplane/ag-ui'; import type { CheckedTools, ToolContracts } from '@threadplane/core/tools'; +import { type } from '@threadplane/core'; import type { AgentSession, AgentSnapshot, @@ -111,6 +112,14 @@ export function checkCandidate(signal: AbortSignal) { void agent.resume; // @ts-expect-error The view wraps a session, not its options. createAgentSession(options); + const typed = createAgentSession( + createSession({ ...options, stateType: type<{ topic: string }>() }) + ); + const topic: string | undefined = typed.getSnapshot().state?.topic; + void topic; + void typed.submit({ message: 'Hello', state: { topic: 'x' } }); + // @ts-expect-error A typed session takes its declared state keys only. + void typed.submit({ message: 'Hello', state: { other: 1 } }); return { session, snapshot, rows, stable, messages, toolCalls, agent, core }; } export function checkClientTools(options: SessionOptions) { diff --git a/libs/ag-ui/src/runtime/README.md b/libs/ag-ui/src/runtime/README.md index 76427d3e6..aff202f3f 100644 --- a/libs/ag-ui/src/runtime/README.md +++ b/libs/ag-ui/src/runtime/README.md @@ -141,11 +141,13 @@ const session = createAgentSession(native); ``` - It is a view, not a second owner. `getSnapshot` derives - `{ status, messages, toolCalls, error?, plan?, usage? }` from the native snapshot with - the two selectors above and keeps its reference until one of those fields - changes. Subscribers hear about those changes only, so a native publication - that touches only state, child evidence or a decision is silent here. -- `submit` takes text and goes straight to the native session, as do `stop` and + `{ status, messages, toolCalls, error?, plan?, usage?, state?, stateIssues? }` + from the native snapshot with the two selectors above and keeps its reference + until one of those fields changes. Subscribers hear about those changes only, + so a native publication that touches only child evidence or a decision is + silent here. +- `submit` takes text, or `{ message, state? }` with a state patch, and goes + straight to the native session, as do `stop` and `dispose`. Disposing the view disposes the session. `retry` goes to the native session too, when it has one (see "Retry" below). - A failed run becomes `snapshot.error`. A backend `RUN_ERROR` is a `server` @@ -171,12 +173,47 @@ const session = createAgentSession(native); labels and finite counts copied. It is absent while a run is going and after a run that reported none, so it never carries over from an earlier run. The native snapshot keeps the event's own `usage` on `run.terminal`. -- A state patch, native resume and client-tool evidence have no core - equivalent. Keep the native session for those; both can be used together. +- Native resume and client-tool evidence have no core equivalent. Keep the + native session for those; both can be used together. While a native decision is waiting, `submit` resolves `error` without sending, and nothing in the core snapshot says why. Show the decision instead, as below. +### State + +The view's `snapshot.state` is the session's state document. Declare its type +with `stateType` when creating the session: + +```ts +import { type } from '@threadplane/core'; + +const native = createSession({ + threadId, + url, + state: { topic: 'billing', notes: [] }, + stateType: type<{ topic: string; notes: string[] }>(), +}); +const session = createAgentSession(native); +session.getSnapshot().state?.topic; // string | undefined +await session.submit({ message: 'Go on', state: { topic: 'refunds' } }); +``` + +- `type()` declares the type and checks nothing. Pass a Standard Schema, such + as a Zod object, to check each document as well: `state` is then the schema's + output, frozen. Each document is checked once, however often it is read. +- A document the schema rejects does not fail the run. `state` keeps the last + document that passed, or stays absent when none has, and `stateIssues` lists + the reasons until a document passes again. A schema must validate + synchronously and produce plain data. +- Without a declaration `state` is plain data and a submitted patch is any plain + record. +- A session created without `state` reports none, and its schema is not asked, + until the application submits a patch or the backend sends a state. The + request still carries `{}` until then. +- The native snapshot's `state` is always the literal document, the one each + request sends, whatever is declared. The schema's output is never sent to the + backend. A typed session's native `submit` accepts the declared keys too. + ### Retry The plain native owner has `retry()`. It sends the last submission again after diff --git a/libs/ag-ui/src/runtime/agent-session-state.spec.ts b/libs/ag-ui/src/runtime/agent-session-state.spec.ts new file mode 100644 index 000000000..45a2ccbe1 --- /dev/null +++ b/libs/ag-ui/src/runtime/agent-session-state.spec.ts @@ -0,0 +1,205 @@ +import { describe, expect, it, vi } from 'vitest'; +import { type, type StandardSchemaV1 } from '@threadplane/core'; +import { createAgentSession, type NativeSession } from './agent-session'; +import { + initialObservation, + type SessionSnapshot, +} from './session-observation'; +import { bindingFixture } from './testing/binding-fixture'; + +interface Counter { + readonly count: number; + readonly label?: string; +} +/** A hand-written Standard Schema: `count` must be a number, and is doubled. */ +function doubling(validate = vi.fn()): StandardSchemaV1 { + return { + '~standard': { + version: 1, + vendor: 'test', + validate(value) { + validate(value); + const count = (value as { count?: unknown } | null)?.count; + return typeof count === 'number' + ? { value: { count: count * 2 } } + : { issues: [{ message: 'count must be a number' }] }; + }, + }, + }; +} +/** A native session whose snapshot the test replaces by hand. */ +function controlled( + first: SessionSnapshot, + stateType?: NativeSession['stateType'] +) { + let snapshot = first; + const listeners = new Set<() => void>(); + const native: NativeSession = { + ...(stateType && { stateType }), + getSnapshot: () => snapshot, + subscribe(notify: () => void) { + listeners.add(notify); + return () => void listeners.delete(notify); + }, + submit: vi.fn(async () => 'success' as const), + stop: vi.fn(async () => undefined), + dispose: vi.fn(async () => undefined), + }; + return { + native, + publish(extra: Partial) { + snapshot = Object.freeze({ ...snapshot, ...extra }); + for (const notify of [...listeners]) notify(); + }, + }; +} + +describe('createAgentSession state', () => { + it('reports no state for a session created without one', () => { + const source = controlled(initialObservation([])); + const session = createAgentSession(source.native); + expect(source.native.getSnapshot().state).toEqual({}); + expect('state' in session.getSnapshot()).toBe(false); + expect('stateIssues' in session.getSnapshot()).toBe(false); + }); + + it('publishes the supplied state document by reference and tells subscribers when it changes', () => { + const source = controlled(initialObservation([], { count: 1 })); + const session = createAgentSession(source.native); + const first = session.getSnapshot(); + expect(first.state).toBe(source.native.getSnapshot().state); + expect(Object.isFrozen(first.state)).toBe(true); + const notify = vi.fn(); + session.subscribe(notify); + source.publish({ reasoningDurations: { missing: 5 } }); + expect(notify).not.toHaveBeenCalled(); + expect(session.getSnapshot()).toBe(first); + const next = Object.freeze({ count: 2 }); + source.publish({ state: next }); + expect(notify).toHaveBeenCalledTimes(1); + expect(session.getSnapshot().state).toBe(next); + // An empty document the backend reported is a state, unlike the default. + const empty = Object.freeze({}); + source.publish({ state: empty }); + expect(session.getSnapshot().state).toBe(empty); + }); + + it('trusts a type() declaration without checking', () => { + const source = controlled( + initialObservation([], { count: 'three' }), + type() + ); + const session = createAgentSession(source.native); + expect(session.getSnapshot().state).toEqual({ count: 'three' }); + expect('stateIssues' in session.getSnapshot()).toBe(false); + }); + + it('checks each document once and publishes the schema output, frozen', () => { + const validate = vi.fn(); + const source = controlled( + initialObservation([], { count: 2 }), + doubling(validate) + ); + const session = createAgentSession(source.native); + const first = session.getSnapshot(); + expect(first.state).toEqual({ count: 4 }); + expect(Object.isFrozen(first.state)).toBe(true); + // The native document, which requests send, is not the schema output. + expect(source.native.getSnapshot().state).toEqual({ count: 2 }); + source.publish({ status: 'running' }); + expect(session.getSnapshot().state).toBe(first.state); + session.getSnapshot(); + expect(validate).toHaveBeenCalledTimes(1); + source.publish({ state: Object.freeze({ count: 5 }) }); + expect(session.getSnapshot().state).toEqual({ count: 10 }); + expect(validate).toHaveBeenCalledTimes(2); + }); + + it('keeps the last valid state and lists the issues when a document is rejected', () => { + const source = controlled( + initialObservation([], { count: 1 }), + doubling() + ); + const session = createAgentSession(source.native); + const valid = session.getSnapshot().state; + const notify = vi.fn(); + session.subscribe(notify); + source.publish({ state: Object.freeze({ count: 'many' }) }); + expect(notify).toHaveBeenCalledTimes(1); + const rejected = session.getSnapshot(); + expect(rejected.state).toBe(valid); + expect(rejected.stateIssues).toEqual(['count must be a number']); + expect(Object.isFrozen(rejected.stateIssues)).toBe(true); + expect(rejected.status).toBe('idle'); + expect('error' in rejected).toBe(false); + source.publish({ state: Object.freeze({ count: 3 }) }); + expect(session.getSnapshot().state).toEqual({ count: 6 }); + expect('stateIssues' in session.getSnapshot()).toBe(false); + }); + + it('has no state while the first document is rejected, and asks nothing about the default', () => { + const validate = vi.fn(); + const untouched = controlled(initialObservation([]), doubling(validate)); + const quiet = createAgentSession(untouched.native).getSnapshot(); + expect('state' in quiet).toBe(false); + expect('stateIssues' in quiet).toBe(false); + expect(validate).not.toHaveBeenCalled(); + const source = controlled(initialObservation([], { count: null }), doubling()); + const snapshot = createAgentSession(source.native).getSnapshot(); + expect('state' in snapshot).toBe(false); + expect(snapshot.stateIssues).toEqual(['count must be a number']); + }); + + it('rejects schema output that is not plain data', () => { + const schema: StandardSchemaV1 = { + '~standard': { + version: 1, + vendor: 'test', + validate: () => ({ value: { at: new Date(0) } }), + }, + }; + const source = controlled(initialObservation([], { at: 0 }), schema); + const snapshot = createAgentSession(source.native).getSnapshot(); + expect('state' in snapshot).toBe(false); + expect(snapshot.stateIssues).toEqual([ + 'The state schema must produce plain data.', + ]); + }); + + it('types and checks the state of a real session across a run', async () => { + const fixture = bindingFixture({ stateType: doubling() }); + try { + const session = createAgentSession(fixture.session); + expect('state' in session.getSnapshot()).toBe(false); + const run = session.submit({ message: 'Go', state: { count: 1 } }); + const exchange = await fixture.started(); + // The request carries the document as submitted, not the schema output. + expect(exchange.body.state).toEqual({ count: 1 }); + expect(session.getSnapshot().state).toEqual({ count: 2 }); + exchange.emit({ type: 'STATE_SNAPSHOT', snapshot: { count: 4 } }); + await fixture.changed((snapshot) => (snapshot.state as { count: unknown }).count === 4); + const count: number | undefined = session.getSnapshot().state?.count; + expect(count).toBe(8); + exchange.emit({ + type: 'STATE_DELTA', + delta: [{ op: 'replace', path: '/count', value: 'lots' }], + }); + await fixture.changed((snapshot) => (snapshot.state as { count: unknown }).count === 'lots'); + expect(session.getSnapshot()).toMatchObject({ + status: 'running', + state: { count: 8 }, + stateIssues: ['count must be a number'], + }); + exchange.emit({ + type: 'RUN_FINISHED', + threadId: exchange.body.threadId, + runId: exchange.body.runId, + }); + exchange.end(); + await expect(run).resolves.toBe('success'); + expect(session.getSnapshot().status).toBe('idle'); + } finally { + await fixture.cleanup(); + } + }); +}); diff --git a/libs/ag-ui/src/runtime/agent-session.spec.ts b/libs/ag-ui/src/runtime/agent-session.spec.ts index 62e3db52b..690ca15c1 100644 --- a/libs/ag-ui/src/runtime/agent-session.spec.ts +++ b/libs/ag-ui/src/runtime/agent-session.spec.ts @@ -68,7 +68,6 @@ describe('createAgentSession', () => { const before = session.getSnapshot(); const notify = vi.fn(); session.subscribe(notify); - source.publish({ state: { model: 'small' } }); source.publish({ reasoningDurations: { missing: 5 } }); expect(notify).not.toHaveBeenCalled(); expect(session.getSnapshot()).toBe(before); diff --git a/libs/ag-ui/src/runtime/agent-session.ts b/libs/ag-ui/src/runtime/agent-session.ts index b06c0d3c8..aabea4d3d 100644 --- a/libs/ag-ui/src/runtime/agent-session.ts +++ b/libs/ag-ui/src/runtime/agent-session.ts @@ -1,12 +1,18 @@ -import type { - AgentError, - AgentSession, - AgentSessionCustomEvent, - AgentSnapshot, - AgentUsage, - AgentUsageEntry, +import { + readState, + type AgentError, + type AgentSession, + type AgentSessionCustomEvent, + type AgentSnapshot, + type AgentUsage, + type AgentUsageEntry, + type PlainValue, + type StateDeclaration, + type ToolContract, } from '@threadplane/core'; import type { Session } from './create-session.js'; +import { NO_STATE, ownState } from './state.js'; +import type { SubmitInput } from './submit-input.js'; import { projectMessages, projectToolCalls } from './message-projection.js'; import { failedWithRunError, @@ -14,11 +20,74 @@ import { } from './session-observation.js'; /** The native owner, with or without a client-tool catalog. */ -export type NativeSession = Pick< - Session, - 'subscribe' | 'submit' | 'stop' | 'dispose' | 'retry' | 'onCustomEvent' +export type NativeSession = Pick< + Session, + | 'stateType' + | 'subscribe' + | 'submit' + | 'stop' + | 'dispose' + | 'retry' + | 'onCustomEvent' > & { getSnapshot(): SessionSnapshot }; +type Tools = Record; +/** The core snapshot of an AG-UI session, with the outcome of its last state check. */ +export type AgUiAgentSnapshot = AgentSnapshot< + Tools, + TState +> & { + /** + * Why the session's state schema rejected the current state document. + * `state` then keeps the last document that passed. Absent while the + * document passes, and always absent without a schema. + */ + readonly stateIssues?: readonly string[]; +}; +/** A core `AgentSession` over an AG-UI session. */ +export type AgUiAgentSession = Omit< + AgentSession, + 'getSnapshot' +> & { getSnapshot(): AgUiAgentSnapshot }; + +/** The state to publish for one state document, and why a schema rejected it. */ +interface StateView { + readonly source: PlainValue; + readonly state?: PlainValue; + readonly issues?: readonly string[]; +} +const NOT_PLAIN = Object.freeze(['The state schema must produce plain data.']); + +/** + * Checks each state document once. A session created without a state reports + * none until the application or the backend supplies one, so a schema is not + * asked about a document nobody wrote. + */ +function stateReader(declaration: StateDeclaration | undefined) { + // Starting at the default document is what leaves it unread. + let view: StateView = { source: NO_STATE }; + return (source: PlainValue): StateView => { + if (source === view.source) return view; + const reading = readState(declaration, source); + if (!reading.valid) + return (view = { + source, + state: view.state, + issues: Object.freeze([...reading.issues]), + }); + // A schema may hand back the document itself or a value of its own. + if (reading.value === source) return (view = { source, state: source }); + try { + const state = ownState(reading.value); + // `undefined` would read as no state at all. + if (state !== undefined) return (view = { source, state }); + } catch { + /* Reported below. */ + } + return (view = { source, state: view.state, issues: NOT_PLAIN }); + }; +} + /** * The same wording the LangGraph runtime uses when it cannot tell whether a * request completed. A runtime spec fails when the two drift. @@ -129,8 +198,9 @@ function usage(native: SessionSnapshot): AgentUsage | undefined { function project( native: SessionSnapshot, canRetry: boolean, - previous?: AgentSnapshot -): AgentSnapshot { + view: StateView, + previous?: AgUiAgentSnapshot +): AgUiAgentSnapshot { const messages = projectMessages(native, previous?.messages); const toolCalls = projectToolCalls(native, previous?.toolCalls); const error = @@ -145,7 +215,9 @@ function project( previous.toolCalls === toolCalls && previous.error === error && previous.plan === native.plan && - previous.usage === used + previous.usage === used && + previous.state === view.state && + previous.stateIssues === view.issues ) return previous; return Object.freeze({ @@ -155,6 +227,8 @@ function project( ...(error && { error }), ...(native.plan && { plan: native.plan }), ...(used && { usage: used }), + ...(view.state !== undefined && { state: view.state }), + ...(view.issues && { stateIssues: view.issues }), }); } @@ -168,23 +242,35 @@ function project( * `dispose` and, when the native session has it, `retry` go straight to the * native session, so disposing the view disposes the session. `retry` rejects * unless the error is `recovery: 'retry'`. Custom event listeners pass straight - * through to the native session too, when it has them. Application state, - * native resume and client-tool evidence have no core equivalent: keep the - * native session for those. + * through to the native session too, when it has them. Native resume and + * client-tool evidence have no core equivalent: keep the native session for + * those. + * + * `state` is the session's state document, typed by the `stateType` the session + * was created with. With a schema, each document is checked once and `state` + * holds the schema's output; a rejected document leaves `state` at the last + * one that passed and lists the reasons in `stateIssues`, and the run goes on. + * A session created without a state has none until the application submits + * one or the backend reports one. */ -export function createAgentSession(session: NativeSession): AgentSession { +export function createAgentSession( + session: NativeSession +): AgUiAgentSession { let seen: SessionSnapshot | undefined; - let current: AgentSnapshot | undefined; + let current: AgUiAgentSnapshot | undefined; const retry = session.retry; const listen = session.onCustomEvent; - const getSnapshot = (): AgentSnapshot => { + const readView = stateReader(session.stateType); + const read = (): AgUiAgentSnapshot => { const native = session.getSnapshot(); if (native !== seen || !current) { - current = project(native, !!retry, current); + current = project(native, !!retry, readView(native.state), current); seen = native; } return current; }; + // The declaration is the only evidence of TState, as for any typed session. + const getSnapshot = read as () => AgUiAgentSnapshot; return { getSnapshot, subscribe(notify) { @@ -201,7 +287,8 @@ export function createAgentSession(session: NativeSession): AgentSession { onCustomEvent: (listener: (event: AgentSessionCustomEvent) => void) => listen.call(session, listener), }), - submit: (input, options) => session.submit(input, options), + submit: (input, options) => + session.submit(input as SubmitInput, options), stop: () => session.stop(), dispose: () => session.dispose(), ...(retry && { diff --git a/libs/ag-ui/src/runtime/agent-session.type-test.ts b/libs/ag-ui/src/runtime/agent-session.type-test.ts new file mode 100644 index 000000000..965884c12 --- /dev/null +++ b/libs/ag-ui/src/runtime/agent-session.type-test.ts @@ -0,0 +1,80 @@ +import { + type, + type AgentSession, + type StandardSchemaV1, + type ToolContract, +} from '@threadplane/core'; +import { createAgentSession } from './agent-session'; +import { createSession } from './create-session'; + +type Equal = (() => T extends A ? 1 : 2) extends () => T extends B + ? 1 + : 2 + ? true + : false; +type Assert = T; +interface Draft { + title: string; + tags: string[]; + note?: string; +} +declare const schema: StandardSchemaV1; +const options = { threadId: 't', url: 'https://agent.invalid' }; + +// Without a declaration the state is plain data and any record can be sent. +const untyped = createAgentSession(createSession(options)); +const anySession: AgentSession = untyped; +void anySession; +void untyped.submit({ message: 'Go', state: { anything: [1, null] } }); +// @ts-expect-error Plain data has no known keys. +void untyped.getSnapshot().state?.title; + +// type() declares the state for the native session and its core view. +const native = createSession({ ...options, stateType: type() }); +const typed = createAgentSession(native); +export type TypedView = Assert< + Equal< + ReturnType['state'], + | { + readonly title: string; + readonly tags: readonly string[]; + readonly note?: string; + } + | undefined + > +>; +const core: AgentSession, Draft> = typed; +void core; +const issues: readonly string[] | undefined = typed.getSnapshot().stateIssues; +void issues; +void native.submit({ message: 'Go', state: { title: 'New' } }); +void typed.submit({ message: 'Go', state: { title: 'New' } }); +void typed.submit('Go'); +// @ts-expect-error A submitted state holds declared keys only. +void native.submit({ message: 'Go', state: { unknownKey: 1 } }); +// @ts-expect-error A submitted state holds declared keys only. +void typed.submit({ message: 'Go', state: { unknownKey: 1 } }); +// @ts-expect-error A declared key keeps its type. +void typed.submit({ message: 'Go', state: { title: 1 } }); +// @ts-expect-error State is read-only. +typed.getSnapshot().state?.tags.push('x'); + +// A Standard Schema declares the same type from its output. +const checked = createAgentSession( + createSession({ ...options, stateType: schema }) +); +export type CheckedView = Assert< + Equal< + NonNullable['state']>['title'], + string + > +>; + +// The client-tool owner carries the declaration too. +const tools = createSession( + { ...options, stateType: type() }, + {} +); +void tools.submit({ message: 'Go', state: { tags: [] } }); +// @ts-expect-error A submitted state holds declared keys only. +void tools.submit({ message: 'Go', state: { unknownKey: 1 } }); diff --git a/libs/ag-ui/src/runtime/create-session.ts b/libs/ag-ui/src/runtime/create-session.ts index 06e20f36d..310c2a67c 100644 --- a/libs/ag-ui/src/runtime/create-session.ts +++ b/libs/ag-ui/src/runtime/create-session.ts @@ -9,7 +9,9 @@ import { import type { AgentSessionCustomEvent, CompleteOutcome, + InferState, PlainValue, + StateDeclaration, ToolContract, } from '@threadplane/core'; import type { @@ -61,6 +63,13 @@ export interface SessionOptions readonly threadId: string; readonly messages?: readonly Message[] | Transcript; readonly state?: unknown; + /** + * The type of the state document: `type()` to declare it, or a Standard + * Schema to also check each state. `createAgentSession` publishes it as the + * typed `state` of the core snapshot. The native snapshot's `state` stays + * the literal document sent with each request, whatever is declared here. + */ + readonly stateType?: StateDeclaration; /** Child evidence saved with this thread, published as `earlierSubagents`. Their attributed messages belong in `messages`. */ readonly subagents?: Subagents; readonly interruptMode?: InterruptMode; @@ -76,11 +85,13 @@ function nextInvocationSubagents(previous: SessionSnapshot) { ...(earlier && { earlierSubagents: earlier }), }; } -export interface Session { +export interface Session { + /** The state declaration this session was created with, when it has one. */ + readonly stateType?: StateDeclaration; getSnapshot(): SessionSnapshot; subscribe(notify: () => void): () => void; submit( - input: SubmitInput, + input: SubmitInput, options?: { readonly signal?: AbortSignal } ): Promise; resume( @@ -111,10 +122,10 @@ export interface Session { listener: (event: AgentSessionCustomEvent) => void ): () => void; } -export type ClientToolSession> = Omit< - Session, - 'getSnapshot' -> & { +export type ClientToolSession< + C extends Record, + TState = unknown +> = Omit, 'getSnapshot'> & { getSnapshot(): ClientToolSessionSnapshot; }; /** A `CUSTOM` event as an application event, read the way the Angular adapter @@ -154,11 +165,18 @@ interface Attempt { } /** Private protocol owner. This does not yet implement core AgentSession. */ -export function createSession>( - options: SessionOptions, +export function createSession< + T extends Record, + D extends StateDeclaration | undefined = undefined +>( + options: Omit & { readonly stateType?: D }, tools: T & CheckedTools -): ClientToolSession>; -export function createSession(options: SessionOptions): Session; +): ClientToolSession, InferState>; +export function createSession< + D extends StateDeclaration | undefined = undefined +>( + options: Omit & { readonly stateType?: D } +): Session>; export function createSession( options: SessionOptions, tools?: Record @@ -170,6 +188,7 @@ export function createSession( fetch, messages, state, + stateType, subagents, interruptMode = 'native', } = options; @@ -184,6 +203,7 @@ export function createSession( fetch, messages, state, + stateType, subagents, interruptMode, }, @@ -403,6 +423,7 @@ export function createSession( }); }; return { + ...(stateType !== undefined && { stateType }), getSnapshot: publication.getSnapshot, subscribe: (notify) => disposed ? () => undefined : publication.subscribe(notify), @@ -1263,6 +1284,7 @@ function createToolsOwner( ); }; return { + ...(options.stateType !== undefined && { stateType: options.stateType }), getSnapshot: publication.getSnapshot, subscribe: (notify) => disposed ? () => undefined : publication.subscribe(notify), diff --git a/libs/ag-ui/src/runtime/session-observation.ts b/libs/ag-ui/src/runtime/session-observation.ts index cd292c03b..d70ba6b98 100644 --- a/libs/ag-ui/src/runtime/session-observation.ts +++ b/libs/ag-ui/src/runtime/session-observation.ts @@ -13,7 +13,7 @@ import type { } from '@threadplane/core'; import { ownTranscript, type Transcript } from './transcript.js'; import { applySubagent, ownSubagents, type Subagents } from './subagents.js'; -import { ownState, applyState } from './state.js'; +import { NO_STATE, ownState, applyState } from './state.js'; import { reconcileTranscript } from './reconcile-transcript.js'; import { applyTextMessage } from './text-messages.js'; import { applyToolMessage } from './tool-messages.js'; @@ -108,7 +108,7 @@ export function assertTranscriptIdentity(transcript: Transcript): void { } export function initialObservation( messages: readonly Message[] | Transcript = [], - state: unknown = {}, + state?: unknown, subagents?: unknown ): SessionSnapshot { const transcript = ownTranscript(messages); @@ -117,7 +117,7 @@ export function initialObservation( return Object.freeze({ status: 'idle', transcript, - state: ownState(state), + state: state === undefined ? NO_STATE : ownState(state), subagents: Object.freeze([]), ...(earlier && { earlierSubagents: earlier }), }); diff --git a/libs/ag-ui/src/runtime/state.ts b/libs/ag-ui/src/runtime/state.ts index 3dc3cbd5f..0719e6b05 100644 --- a/libs/ag-ui/src/runtime/state.ts +++ b/libs/ag-ui/src/runtime/state.ts @@ -3,6 +3,13 @@ import type { PlainValue } from '@threadplane/core'; import { copyData } from '../lib/internal/copy-data.js'; import { applyPatch, type JsonPatchOp } from '../lib/internal/apply-patch.js'; +/** + * The document of a session created without a state. It is still sent with + * each request, but until the application or the backend replaces it the + * session holds no state to report. + */ +export const NO_STATE: PlainValue = Object.freeze({}); + /** Captures the literal state graph without schema interpretation. */ export function ownState(value: unknown): PlainValue { return copyData(value, true) as PlainValue; diff --git a/libs/ag-ui/src/runtime/submit-input.ts b/libs/ag-ui/src/runtime/submit-input.ts index c253664d9..0a32bd544 100644 --- a/libs/ag-ui/src/runtime/submit-input.ts +++ b/libs/ag-ui/src/runtime/submit-input.ts @@ -2,9 +2,16 @@ import type { PlainValue } from '@threadplane/core'; import { ownState } from './state.js'; export type ApplicationState = Readonly>; -export type SubmitInput = +/** + * The patch a submission merges into the state document. A session with a + * declared state type accepts that type's keys; any other accepts a plain record. + */ +export type SubmitState = unknown extends TState + ? ApplicationState + : Partial; +export type SubmitInput = | string - | { readonly message: string; readonly state?: ApplicationState }; + | { readonly message: string; readonly state?: SubmitState }; export interface CapturedSubmit { readonly message: string; readonly state?: ApplicationState; @@ -17,7 +24,9 @@ function isRecord(value: unknown): value is ApplicationState { } /** Read only the selected input fields and own their data before deferral. */ -export function captureSubmit(input: SubmitInput): CapturedSubmit { +export function captureSubmit( + input: SubmitInput +): CapturedSubmit { if (typeof input === 'string') return Object.freeze({ message: input }); const message = input.message; if (typeof message !== 'string') diff --git a/libs/ag-ui/src/runtime/testing/binding-fixture.ts b/libs/ag-ui/src/runtime/testing/binding-fixture.ts index 232e5e1d2..096183a30 100644 --- a/libs/ag-ui/src/runtime/testing/binding-fixture.ts +++ b/libs/ag-ui/src/runtime/testing/binding-fixture.ts @@ -1,4 +1,5 @@ import type { RunAgentInput } from '@ag-ui/client'; +import type { StateDeclaration } from '@threadplane/core'; import { createSession, type SessionOptions } from '../create-session'; import type { SessionSnapshot } from '../session-observation'; @@ -76,9 +77,12 @@ function controlledFetchResponse( /** Browser-safe test composition. All snapshots and commands belong to the real * private session; the fixture controls only its physical Fetch API response. */ -export function bindingFixture( +export function bindingFixture< + D extends StateDeclaration | undefined = undefined +>( options: Pick & { threadId?: string; + stateType?: D; } = {} ) { const exchanges: ReturnType[] = []; From 3894f08ac8623f66839bd279573b22ad8fef3b3d Mon Sep 17 00:00:00 2001 From: Brian Love Date: Wed, 18 Nov 2026 13:13:18 -0800 Subject: [PATCH 03/18] feat(ag-ui): make the session a core AgentSession The session createSession returns now publishes the core snapshot itself: messages, tool calls, error, usage and typed state beside the protocol evidence. createAgentSession is removed. retry rejects when the failure leaves the backend outcome open, as the core contract requires, and the literal state document a request sends is no longer published. --- .../react-parity/ag-ui-candidate/README.md | 9 +- .../react-parity/ag-ui-candidate/entry.ts | 1 - .../ag-ui-candidate/installed-types.ts | 22 ++- libs/ag-ui/src/runtime/README.md | 88 +++++---- .../src/runtime/agent-session-state.spec.ts | 107 +++++------ libs/ag-ui/src/runtime/agent-session.spec.ts | 134 ++++---------- libs/ag-ui/src/runtime/agent-session.ts | 169 ++++++------------ .../src/runtime/agent-session.type-test.ts | 39 ++-- .../src/runtime/application-input.spec.ts | 2 +- libs/ag-ui/src/runtime/client-tools.ts | 11 +- libs/ag-ui/src/runtime/create-session.ts | 111 +++++++----- libs/ag-ui/src/runtime/custom-events.spec.ts | 29 --- libs/ag-ui/src/runtime/failure-cause.spec.ts | 10 +- .../src/runtime/interrupt-mode.type-test.ts | 4 +- .../src/runtime/message-projection.spec.ts | 12 +- libs/ag-ui/src/runtime/message-projection.ts | 17 +- libs/ag-ui/src/runtime/reasoning-clock.ts | 6 +- libs/ag-ui/src/runtime/retry.spec.ts | 15 +- libs/ag-ui/src/runtime/session-http.spec.ts | 2 +- .../src/runtime/session-observation.spec.ts | 4 +- libs/ag-ui/src/runtime/session-observation.ts | 10 +- libs/ag-ui/src/runtime/session-plan.spec.ts | 19 +- .../src/runtime/session-publication.spec.ts | 7 +- libs/ag-ui/src/runtime/session-publication.ts | 23 ++- .../src/runtime/testing/binding-fixture.ts | 6 +- libs/angular/src/observe-agent.ag-ui.spec.ts | 3 +- libs/angular/src/observe-agent.type-test.ts | 6 +- libs/react/src/chat/ag-ui-messages.spec.tsx | 6 +- libs/react/src/chat/ag-ui-session.spec.tsx | 9 +- libs/react/src/use-agent.ag-ui.spec.tsx | 3 +- libs/react/src/use-agent.type-test.ts | 6 +- .../react-parity/ag-ui-candidate-package.mjs | 4 - .../ag-ui-candidate-package.spec.mjs | 6 +- .../react-parity/verify-ag-ui-candidate.mjs | 9 +- 34 files changed, 379 insertions(+), 530 deletions(-) diff --git a/fixtures/react-parity/ag-ui-candidate/README.md b/fixtures/react-parity/ag-ui-candidate/README.md index 2a6b16bac..e808b5852 100644 --- a/fixtures/react-parity/ag-ui-candidate/README.md +++ b/fixtures/react-parity/ag-ui-candidate/README.md @@ -43,11 +43,10 @@ snapshot type. Core is required by those declarations; its implementation need not occur in the backend's runtime graph. The sole additional bare subpath is a type-only `@threadplane/core/tools` declaration dependency resolved from the actual packed core tools entry. -The candidate has exactly six runtime exports: `createSession`, the text -selector `projectTextTranscript`, the core selectors `projectMessages` and -`projectToolCalls`, which return core `Message` and `ToolCall` values, and -`createAgentSession`, which wraps a native session as a core `AgentSession`, -and `decisionState`, which reads the pending decision and its phase, with its +The candidate has exactly five runtime exports: `createSession`, whose session +is a core `AgentSession`, the text selector `projectTextTranscript`, the core +selectors `projectMessages` and `projectToolCalls`, which return core `Message` +and `ToolCall` values, and `decisionState`, which reads the pending decision and its phase, with its `DecisionState` type. Its client-tool session, snapshot, call and blocker types forward directly from the native runtime modules. Heterogeneous authored handler argument/result contracts are verified under NodeNext and Bundler, diff --git a/fixtures/react-parity/ag-ui-candidate/entry.ts b/fixtures/react-parity/ag-ui-candidate/entry.ts index f2cfea449..82e02f689 100644 --- a/fixtures/react-parity/ag-ui-candidate/entry.ts +++ b/fixtures/react-parity/ag-ui-candidate/entry.ts @@ -13,6 +13,5 @@ export type { export { projectTextTranscript } from '../../../libs/ag-ui/src/runtime/text-transcript.js'; export type { TextTranscriptRow } from '../../../libs/ag-ui/src/runtime/text-transcript.js'; export { projectMessages, projectToolCalls } from '../../../libs/ag-ui/src/runtime/message-projection.js'; -export { createAgentSession } from '../../../libs/ag-ui/src/runtime/agent-session.js'; export { decisionState } from '../../../libs/ag-ui/src/runtime/decision.js'; export type { DecisionState } from '../../../libs/ag-ui/src/runtime/decision.js'; diff --git a/fixtures/react-parity/ag-ui-candidate/installed-types.ts b/fixtures/react-parity/ag-ui-candidate/installed-types.ts index e31eb3000..8b4b51321 100644 --- a/fixtures/react-parity/ag-ui-candidate/installed-types.ts +++ b/fixtures/react-parity/ag-ui-candidate/installed-types.ts @@ -1,5 +1,4 @@ import { - createAgentSession, decisionState, type DecisionState, createSession, @@ -101,20 +100,19 @@ export function checkCandidate(signal: AbortSignal) { } // @ts-expect-error An unsupported pause carries no token to answer. if (pending?.kind === 'unsupported') void pending.id; - const agent: AgentSession = createAgentSession(session); + const agent: AgentSession = session; const core: AgentSnapshot = agent.getSnapshot(); void agent.submit('Hello', { signal }); 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. + // @ts-expect-error A submission takes a message and state only. void agent.submit({ message: 'Hello', messages: [] }); - // @ts-expect-error Native resume stays on the native session. + // @ts-expect-error Resume is not part of the core contract. void agent.resume; - // @ts-expect-error The view wraps a session, not its options. - createAgentSession(options); - const typed = createAgentSession( - createSession({ ...options, stateType: type<{ topic: string }>() }) - ); + const typed = createSession({ + ...options, + stateType: type<{ topic: string }>(), + }); const topic: string | undefined = typed.getSnapshot().state?.topic; void topic; void typed.submit({ message: 'Hello', state: { topic: 'x' } }); @@ -151,7 +149,7 @@ export function checkClientTools(options: SessionOptions) { const blocker: ClientToolBlocker | undefined = snapshot.clientTools.blocker; void outcome; void blocker; - const view: AgentSession = createAgentSession(owner); + const view: AgentSession = owner; void view; for (const call of calls) { const name: 'get_weather' | 'book' = call.name; @@ -185,7 +183,7 @@ export function checkClientTools(options: SessionOptions) { void empty.getSnapshot().clientTools.blocker; // @ts-expect-error No catalog keeps the original exact snapshot. createSession(options).getSnapshot().clientTools; - // @ts-expect-error Native snapshots do not manufacture core aggregates. - snapshot.messages; + // The client-tool session publishes the core fields too. + void [snapshot.messages, snapshot.toolCalls]; return owner; } diff --git a/libs/ag-ui/src/runtime/README.md b/libs/ag-ui/src/runtime/README.md index aff202f3f..635958f3e 100644 --- a/libs/ag-ui/src/runtime/README.md +++ b/libs/ag-ui/src/runtime/README.md @@ -128,43 +128,42 @@ The test-only candidate package entry exports both selectors next to `createSession`. They are still private source: the published package root does not export them. -## Core session view +## Core session -`createAgentSession(session)` wraps a native session, with or without a -client-tool catalog, as a core `AgentSession`, so a component written for core -sessions can observe and drive an AG-UI conversation: +The session `createSession` returns, with or without a client-tool catalog, is a +core `AgentSession`, so a component written for core sessions observes and +drives an AG-UI conversation directly: ```tsx -const native = createSession({ threadId, url }); -const session = createAgentSession(native); +const session = createSession({ threadId, url }); ; ``` -- It is a view, not a second owner. `getSnapshot` derives - `{ status, messages, toolCalls, error?, plan?, usage?, state?, stateIssues? }` - from the native snapshot with the two selectors above and keeps its reference - until one of those fields changes. Subscribers hear about those changes only, - so a native publication that touches only child evidence or a decision is - silent here. -- `submit` takes text, or `{ message, state? }` with a state patch, and goes - straight to the native session, as do `stop` and - `dispose`. Disposing the view disposes the session. `retry` goes to the native - session too, when it has one (see "Retry" below). +- `getSnapshot` returns the core snapshot, + `{ status, messages, toolCalls, error?, plan?, usage?, state?, stateIssues? }`, + together with the protocol evidence behind it: `transcript`, `subagents`, + `earlierSubagents`, `decision`, `reasoningDurations` and `run`. `messages` and + `toolCalls` are what the two selectors above return, and keep their + references until they change. One publication always reads as one snapshot. +- Every publication notifies subscribers, including one that changes only + protocol evidence such as a decision or a child. +- `submit` takes text, or `{ message, state? }` with a state patch. `resume` + and the client-tool evidence are AG-UI additions to the core contract. - A failed run becomes `snapshot.error`. A backend `RUN_ERROR` is a `server` error carrying the backend's message. A stream that ended without a terminal is `interrupted`. A response that was not OK carries its HTTP status: 401 and 403 are an `auth` error, any other status a generic `server` error. The response body is never shown. A request that got no response, such as an unreachable host, is a generic `server` error without a status. -- The native snapshot records that status as `run.failure.status` when a +- The snapshot records that status as `run.failure.status` when a response that was not OK is why the run failed, and clears it with the next run. - A backend `RUN_ERROR` for a submission is `retryable: true` with - `recovery: 'retry'` when the native session has `retry`. Every other error has + `recovery: 'retry'` when the session has `retry`. Every other error has `retryable: false` and `recovery: 'none'`: a stream that ended without a terminal, a response that was not OK and a request that got no response leave open whether the backend did the work. -- The view has no `checkStatus`. AG-UI defines no read-only way to ask a backend +- The session has no `checkStatus`. AG-UI defines no read-only way to ask a backend what became of a run: `HttpAgent` only posts new runs, and it does not implement the client's optional `connect` hook. Reconciling an uncertain run would therefore mean sending a request, which a status check must never do. @@ -172,28 +171,24 @@ const session = createAgentSession(native); reported, one entry per provider and model, with only the provider and model labels and finite counts copied. It is absent while a run is going and after a run that reported none, so it never carries over from an earlier run. The - native snapshot keeps the event's own `usage` on `run.terminal`. -- Native resume and client-tool evidence have no core equivalent. Keep the - native session for those; both can be used together. - While a native decision is waiting, `submit` resolves `error` without sending, - and nothing in the core snapshot says why. Show the decision instead, as - below. + event's own `usage` stays on `run.terminal`. +- While a decision is waiting, `submit` resolves `error` without sending, and + nothing in the core fields says why. Show the decision instead, as below. ### State -The view's `snapshot.state` is the session's state document. Declare its type -with `stateType` when creating the session: +`snapshot.state` is the session's state document. Declare its type with +`stateType` when creating the session: ```ts import { type } from '@threadplane/core'; -const native = createSession({ +const session = createSession({ threadId, url, state: { topic: 'billing', notes: [] }, stateType: type<{ topic: string; notes: string[] }>(), }); -const session = createAgentSession(native); session.getSnapshot().state?.topic; // string | undefined await session.submit({ message: 'Go on', state: { topic: 'refunds' } }); ``` @@ -210,20 +205,20 @@ await session.submit({ message: 'Go on', state: { topic: 'refunds' } }); - A session created without `state` reports none, and its schema is not asked, until the application submits a patch or the backend sends a state. The request still carries `{}` until then. -- The native snapshot's `state` is always the literal document, the one each - request sends, whatever is declared. The schema's output is never sent to the - backend. A typed session's native `submit` accepts the declared keys too. +- Each request sends the literal document, whatever is declared. The schema's + output is never sent to the backend, and the literal document is not + published. ### Retry -The plain native owner has `retry()`. It sends the last submission again after -its run failed with a backend `RUN_ERROR`, rebuilding the request from exactly the -history and state that submission sent. No second user message is added, and the -failed run's output and state changes are dropped. It resolves `aborted` without -sending while a run is active or when the last run was not a failed submission, -and `error` without sending when the failure leaves the backend outcome open. The -view's `retry` resolves `aborted` in the first case, rejects in the second, and -otherwise resolves with the native re-run's outcome. +The session created without a client-tool catalog has `retry()`. It sends the +last submission again after its run failed with a backend `RUN_ERROR`, +rebuilding the request from exactly the history and state that submission sent. +No second user message is added, and the failed run's output and state changes +are dropped. It resolves `aborted` without sending while a run is active, when +nothing failed or when the last run was not a failed submission. It rejects +without sending when the error's `recovery` is not `'retry'`, because the +failure leaves the backend outcome open. - A failed resume is not retried. Its decision stays `uncertain`, as described under "Correlated native resume". @@ -234,12 +229,12 @@ otherwise resolves with the native re-run's outcome. ### Approvals -`decisionState(snapshot)` reads the native snapshot's pending decision and how -far it has got, so an app can show it in `Chat`'s `approval` slot and answer it -on the native session: +`decisionState(snapshot)` reads the snapshot's pending decision and how far it +has got, so an app can show it in `Chat`'s `approval` slot and answer it with +`resume`: ```tsx -const pending = decisionState(useAgent(native)); +const pending = decisionState(useAgent(session)); - void native.resume(pending.id, [ + void session.resume(pending.id, [ { interruptId: pending.interrupts[0].id, status: 'resolved' }, ]), }, @@ -292,8 +287,7 @@ commands a listener issues wait until the current event finishes, so a listener that disposes the session does not stop the rest of that one delivery. The method is optional on the `Session` type so hand-written sessions need not -supply it; the factory always does. `createAgentSession` forwards it when the -native session has one. +supply it; the factory always does. ## Interruption evidence diff --git a/libs/ag-ui/src/runtime/agent-session-state.spec.ts b/libs/ag-ui/src/runtime/agent-session-state.spec.ts index 45a2ccbe1..fa1da1cab 100644 --- a/libs/ag-ui/src/runtime/agent-session-state.spec.ts +++ b/libs/ag-ui/src/runtime/agent-session-state.spec.ts @@ -1,10 +1,11 @@ import { describe, expect, it, vi } from 'vitest'; -import { type, type StandardSchemaV1 } from '@threadplane/core'; -import { createAgentSession, type NativeSession } from './agent-session'; import { - initialObservation, - type SessionSnapshot, -} from './session-observation'; + type, + type StandardSchemaV1, + type StateDeclaration, +} from '@threadplane/core'; +import { createPresenter } from './agent-session'; +import { initialObservation, type Observation } from './session-observation'; import { bindingFixture } from './testing/binding-fixture'; interface Counter { @@ -27,112 +28,86 @@ function doubling(validate = vi.fn()): StandardSchemaV1 { }, }; } -/** A native session whose snapshot the test replaces by hand. */ -function controlled( - first: SessionSnapshot, - stateType?: NativeSession['stateType'] -) { - let snapshot = first; - const listeners = new Set<() => void>(); - const native: NativeSession = { - ...(stateType && { stateType }), - getSnapshot: () => snapshot, - subscribe(notify: () => void) { - listeners.add(notify); - return () => void listeners.delete(notify); - }, - submit: vi.fn(async () => 'success' as const), - stop: vi.fn(async () => undefined), - dispose: vi.fn(async () => undefined), - }; +/** A presenter over an observation the test replaces by hand. */ +function controlled(first: Observation, stateType?: StateDeclaration) { + const present = createPresenter(stateType, false); + let observation = first; return { - native, - publish(extra: Partial) { - snapshot = Object.freeze({ ...snapshot, ...extra }); - for (const notify of [...listeners]) notify(); + observation: () => observation, + getSnapshot: () => present(observation), + publish(extra: Partial) { + observation = Object.freeze({ ...observation, ...extra }); }, }; } -describe('createAgentSession state', () => { +describe('the published state', () => { it('reports no state for a session created without one', () => { - const source = controlled(initialObservation([])); - const session = createAgentSession(source.native); - expect(source.native.getSnapshot().state).toEqual({}); + const session = controlled(initialObservation([])); + expect(session.observation().state).toEqual({}); expect('state' in session.getSnapshot()).toBe(false); expect('stateIssues' in session.getSnapshot()).toBe(false); }); - it('publishes the supplied state document by reference and tells subscribers when it changes', () => { - const source = controlled(initialObservation([], { count: 1 })); - const session = createAgentSession(source.native); + it('publishes the supplied state document by reference', () => { + const session = controlled(initialObservation([], { count: 1 })); const first = session.getSnapshot(); - expect(first.state).toBe(source.native.getSnapshot().state); + expect(first.state).toBe(session.observation().state); expect(Object.isFrozen(first.state)).toBe(true); - const notify = vi.fn(); - session.subscribe(notify); - source.publish({ reasoningDurations: { missing: 5 } }); - expect(notify).not.toHaveBeenCalled(); - expect(session.getSnapshot()).toBe(first); + session.publish({ reasoningDurations: { missing: 5 } }); + expect(session.getSnapshot().state).toBe(first.state); const next = Object.freeze({ count: 2 }); - source.publish({ state: next }); - expect(notify).toHaveBeenCalledTimes(1); + session.publish({ state: next }); expect(session.getSnapshot().state).toBe(next); // An empty document the backend reported is a state, unlike the default. const empty = Object.freeze({}); - source.publish({ state: empty }); + session.publish({ state: empty }); expect(session.getSnapshot().state).toBe(empty); }); it('trusts a type() declaration without checking', () => { - const source = controlled( + const session = controlled( initialObservation([], { count: 'three' }), type() ); - const session = createAgentSession(source.native); expect(session.getSnapshot().state).toEqual({ count: 'three' }); expect('stateIssues' in session.getSnapshot()).toBe(false); }); it('checks each document once and publishes the schema output, frozen', () => { const validate = vi.fn(); - const source = controlled( + const session = controlled( initialObservation([], { count: 2 }), doubling(validate) ); - const session = createAgentSession(source.native); const first = session.getSnapshot(); expect(first.state).toEqual({ count: 4 }); expect(Object.isFrozen(first.state)).toBe(true); - // The native document, which requests send, is not the schema output. - expect(source.native.getSnapshot().state).toEqual({ count: 2 }); - source.publish({ status: 'running' }); + // The document, which requests send, is not the schema output. + expect(session.observation().state).toEqual({ count: 2 }); + session.publish({ status: 'running' }); expect(session.getSnapshot().state).toBe(first.state); session.getSnapshot(); expect(validate).toHaveBeenCalledTimes(1); - source.publish({ state: Object.freeze({ count: 5 }) }); + session.publish({ state: Object.freeze({ count: 5 }) }); expect(session.getSnapshot().state).toEqual({ count: 10 }); expect(validate).toHaveBeenCalledTimes(2); }); it('keeps the last valid state and lists the issues when a document is rejected', () => { - const source = controlled( + const session = controlled( initialObservation([], { count: 1 }), doubling() ); - const session = createAgentSession(source.native); const valid = session.getSnapshot().state; - const notify = vi.fn(); - session.subscribe(notify); - source.publish({ state: Object.freeze({ count: 'many' }) }); - expect(notify).toHaveBeenCalledTimes(1); + session.publish({ state: Object.freeze({ count: 'many' }) }); const rejected = session.getSnapshot(); expect(rejected.state).toBe(valid); expect(rejected.stateIssues).toEqual(['count must be a number']); expect(Object.isFrozen(rejected.stateIssues)).toBe(true); expect(rejected.status).toBe('idle'); expect('error' in rejected).toBe(false); - source.publish({ state: Object.freeze({ count: 3 }) }); + session.publish({ state: Object.freeze({ count: 3 }) }); expect(session.getSnapshot().state).toEqual({ count: 6 }); expect('stateIssues' in session.getSnapshot()).toBe(false); }); @@ -140,12 +115,12 @@ describe('createAgentSession state', () => { it('has no state while the first document is rejected, and asks nothing about the default', () => { const validate = vi.fn(); const untouched = controlled(initialObservation([]), doubling(validate)); - const quiet = createAgentSession(untouched.native).getSnapshot(); + const quiet = untouched.getSnapshot(); expect('state' in quiet).toBe(false); expect('stateIssues' in quiet).toBe(false); expect(validate).not.toHaveBeenCalled(); - const source = controlled(initialObservation([], { count: null }), doubling()); - const snapshot = createAgentSession(source.native).getSnapshot(); + const session = controlled(initialObservation([], { count: null }), doubling()); + const snapshot = session.getSnapshot(); expect('state' in snapshot).toBe(false); expect(snapshot.stateIssues).toEqual(['count must be a number']); }); @@ -158,8 +133,8 @@ describe('createAgentSession state', () => { validate: () => ({ value: { at: new Date(0) } }), }, }; - const source = controlled(initialObservation([], { at: 0 }), schema); - const snapshot = createAgentSession(source.native).getSnapshot(); + const session = controlled(initialObservation([], { at: 0 }), schema); + const snapshot = session.getSnapshot(); expect('state' in snapshot).toBe(false); expect(snapshot.stateIssues).toEqual([ 'The state schema must produce plain data.', @@ -169,7 +144,7 @@ describe('createAgentSession state', () => { it('types and checks the state of a real session across a run', async () => { const fixture = bindingFixture({ stateType: doubling() }); try { - const session = createAgentSession(fixture.session); + const session = fixture.session; expect('state' in session.getSnapshot()).toBe(false); const run = session.submit({ message: 'Go', state: { count: 1 } }); const exchange = await fixture.started(); @@ -177,14 +152,14 @@ describe('createAgentSession state', () => { expect(exchange.body.state).toEqual({ count: 1 }); expect(session.getSnapshot().state).toEqual({ count: 2 }); exchange.emit({ type: 'STATE_SNAPSHOT', snapshot: { count: 4 } }); - await fixture.changed((snapshot) => (snapshot.state as { count: unknown }).count === 4); + await fixture.changed((snapshot) => snapshot.state?.count === 8); const count: number | undefined = session.getSnapshot().state?.count; expect(count).toBe(8); exchange.emit({ type: 'STATE_DELTA', delta: [{ op: 'replace', path: '/count', value: 'lots' }], }); - await fixture.changed((snapshot) => (snapshot.state as { count: unknown }).count === 'lots'); + await fixture.changed((snapshot) => 'stateIssues' in snapshot); expect(session.getSnapshot()).toMatchObject({ status: 'running', state: { count: 8 }, diff --git a/libs/ag-ui/src/runtime/agent-session.spec.ts b/libs/ag-ui/src/runtime/agent-session.spec.ts index 690ca15c1..e712d4f66 100644 --- a/libs/ag-ui/src/runtime/agent-session.spec.ts +++ b/libs/ag-ui/src/runtime/agent-session.spec.ts @@ -1,16 +1,9 @@ -import { describe, expect, it, vi } from 'vitest'; +import { describe, expect, it } from 'vitest'; import type { AgentSession } from '@threadplane/core'; // eslint-disable-next-line @nx/enforce-module-boundaries -- The shared wording is compared with its LangGraph source. import { RECOVERY_COPY } from '../../../langgraph/src/runtime/stream-projection'; -import { - createAgentSession, - INTERRUPTED_COPY, - type NativeSession, -} from './agent-session'; -import { - initialObservation, - type SessionSnapshot, -} from './session-observation'; +import { createPresenter, INTERRUPTED_COPY } from './agent-session'; +import { initialObservation, type Observation } from './session-observation'; import { bindingFixture } from './testing/binding-fixture'; type Records = NonNullable[0]>; @@ -18,34 +11,22 @@ const history: Records = [ { id: 'u', role: 'user', content: 'Ask' }, { id: 'a', role: 'assistant', content: 'Answer' }, ]; -/** A native session whose snapshot the test replaces by hand. */ -function controlled(first: SessionSnapshot) { - let snapshot = first; - const listeners = new Set<() => void>(); - const native = { - getSnapshot: () => snapshot, - subscribe(notify: () => void) { - listeners.add(notify); - return () => void listeners.delete(notify); - }, - submit: vi.fn(async () => 'success' as const), - stop: vi.fn(async () => undefined), - dispose: vi.fn(async () => undefined), - } satisfies NativeSession; +/** A presenter over an observation the test replaces by hand. */ +function controlled(first: Observation, canRetry = false) { + const present = createPresenter(undefined, canRetry); + let observation = first; return { - native, - listeners, - publish(extra: Partial) { - snapshot = Object.freeze({ ...snapshot, ...extra }); - for (const notify of [...listeners]) notify(); + getSnapshot: () => present(observation), + publish(extra: Partial) { + observation = Object.freeze({ ...observation, ...extra }); }, }; } -describe('createAgentSession', () => { - it('publishes the native conversation as a frozen core snapshot', () => { - const { native } = controlled(initialObservation(history)); - const session: AgentSession = createAgentSession(native); +describe('the published snapshot', () => { + it('is the frozen core snapshot with the protocol evidence behind it', () => { + const observation = initialObservation(history); + const session = controlled(observation); const snapshot = session.getSnapshot(); expect(snapshot).toEqual({ status: 'idle', @@ -54,65 +35,44 @@ describe('createAgentSession', () => { expect.objectContaining({ id: 'a', role: 'assistant', content: 'Answer' }), ], toolCalls: [], + transcript: observation.transcript, + subagents: [], }); + expect(snapshot.transcript).toBe(observation.transcript); expect(Object.isFrozen(snapshot)).toBe(true); expect('error' in snapshot).toBe(false); expect('plan' in snapshot).toBe(false); + expect('state' in snapshot).toBe(false); expect(session.getSnapshot()).toBe(snapshot); - expect(session.checkStatus).toBeUndefined(); }); - it('keeps its snapshot and stays silent when only native fields change', () => { - const source = controlled(initialObservation(history)); - const session = createAgentSession(source.native); + it('shares what did not change between observations', () => { + const session = controlled(initialObservation(history)); const before = session.getSnapshot(); - const notify = vi.fn(); - session.subscribe(notify); - source.publish({ reasoningDurations: { missing: 5 } }); - expect(notify).not.toHaveBeenCalled(); - expect(session.getSnapshot()).toBe(before); - source.publish({ status: 'running' }); - expect(notify).toHaveBeenCalledTimes(1); + session.publish({ reasoningDurations: { missing: 5 } }); + const timed = session.getSnapshot(); + expect(timed).not.toBe(before); + expect(timed.messages).toBe(before.messages); + expect(timed.toolCalls).toBe(before.toolCalls); + session.publish({ status: 'running' }); const running = session.getSnapshot(); expect(running.status).toBe('running'); expect(running.messages[0]).toBe(before.messages[0]); }); - it('tells each subscriber once per change and stops after release', () => { - const source = controlled(initialObservation(history)); - const session = createAgentSession(source.native); - const first = vi.fn(); - const second = vi.fn(() => void session.getSnapshot()); - const release = session.subscribe(first); - session.subscribe(second); - source.publish({ status: 'running' }); - expect(first).toHaveBeenCalledTimes(1); - expect(second).toHaveBeenCalledTimes(1); - release(); - release(); - source.publish({ status: 'idle' }); - expect(first).toHaveBeenCalledTimes(1); - expect(second).toHaveBeenCalledTimes(2); - expect(source.listeners.size).toBe(1); - }); - it('carries the declared plan by reference', () => { const plan = Object.freeze([ Object.freeze({ id: '1', label: 'Search', status: 'pending' as const }), ]); - const source = controlled( + const session = controlled( Object.freeze({ ...initialObservation(history), plan }) ); - const session = createAgentSession(source.native); expect(session.getSnapshot().plan).toBe(plan); - source.publish({ plan: undefined }); - expect('plan' in session.getSnapshot()).toBe(false); }); it('reports the backend error text as a server failure with no recovery when the owner cannot retry', () => { - const source = controlled(initialObservation(history)); - const session = createAgentSession(source.native); - source.publish({ + const session = controlled(initialObservation(history)); + session.publish({ status: 'error', run: { id: 'run', @@ -128,14 +88,13 @@ describe('createAgentSession', () => { recovery: 'none', }); expect(Object.isFrozen(error)).toBe(true); - source.publish({ state: { changed: true } }); + session.publish({ state: { changed: true } }); expect(session.getSnapshot().error).toBe(error); }); it('reports a stream that ended without a terminal as interrupted', () => { - const source = controlled(initialObservation(history)); - const session = createAgentSession(source.native); - source.publish({ status: 'error', run: { id: 'run', outcome: 'interrupted' } }); + const session = controlled(initialObservation(history)); + session.publish({ status: 'error', run: { id: 'run', outcome: 'interrupted' } }); expect(session.getSnapshot().error).toEqual({ kind: 'interrupted', message: INTERRUPTED_COPY.message, @@ -150,41 +109,23 @@ describe('createAgentSession', () => { }); it('reports a failure it cannot name generically and clears it on the next run', () => { - const source = controlled(initialObservation(history)); - const session = createAgentSession(source.native); - source.publish({ status: 'error', run: { id: 'run', outcome: 'error' } }); + const session = controlled(initialObservation(history)); + session.publish({ status: 'error', run: { id: 'run', outcome: 'error' } }); expect(session.getSnapshot().error).toEqual({ kind: 'server', message: 'The agent request failed.', retryable: false, recovery: 'none', }); - source.publish({ status: 'running', run: { id: 'next' } }); + session.publish({ status: 'running', run: { id: 'next' } }); expect('error' in session.getSnapshot()).toBe(false); }); - - it('sends commands straight to the native session', async () => { - const { native } = controlled(initialObservation()); - const session = createAgentSession(native); - const signal = new AbortController().signal; - await expect(session.submit('Hello', { signal })).resolves.toBe('success'); - expect(native.submit).toHaveBeenCalledWith('Hello', { signal }); - await session.stop(); - await session.dispose(); - expect(native.stop).toHaveBeenCalledTimes(1); - expect(native.dispose).toHaveBeenCalledTimes(1); - }); }); -describe('createAgentSession over the real owner', () => { +describe('the real session as a core session', () => { it('streams a turn, completes it and reports a backend error on the next', async () => { const fixture = bindingFixture(); - const session = createAgentSession(fixture.session); - const seen: string[] = []; - session.subscribe(() => { - const snapshot = session.getSnapshot(); - seen.push(`${snapshot.status}:${snapshot.messages.length}`); - }); + const session: AgentSession = fixture.session; try { const run = session.submit('Go'); const exchange = await fixture.started(); @@ -213,7 +154,6 @@ describe('createAgentSession over the real owner', () => { phase: 'complete', outcome: 'success', }); - expect(new Set(seen).size).toBe(seen.length); const failed = session.submit('Again'); const next = await fixture.started(1); diff --git a/libs/ag-ui/src/runtime/agent-session.ts b/libs/ag-ui/src/runtime/agent-session.ts index aabea4d3d..cfd13d36c 100644 --- a/libs/ag-ui/src/runtime/agent-session.ts +++ b/libs/ag-ui/src/runtime/agent-session.ts @@ -1,8 +1,6 @@ import { readState, type AgentError, - type AgentSession, - type AgentSessionCustomEvent, type AgentSnapshot, type AgentUsage, type AgentUsageEntry, @@ -10,45 +8,28 @@ import { type StateDeclaration, type ToolContract, } from '@threadplane/core'; -import type { Session } from './create-session.js'; import { NO_STATE, ownState } from './state.js'; -import type { SubmitInput } from './submit-input.js'; import { projectMessages, projectToolCalls } from './message-projection.js'; import { failedWithRunError, - type SessionSnapshot, + type Observation, } from './session-observation.js'; -/** The native owner, with or without a client-tool catalog. */ -export type NativeSession = Pick< - Session, - | 'stateType' - | 'subscribe' - | 'submit' - | 'stop' - | 'dispose' - | 'retry' - | 'onCustomEvent' -> & { getSnapshot(): SessionSnapshot }; - type Tools = Record; -/** The core snapshot of an AG-UI session, with the outcome of its last state check. */ -export type AgUiAgentSnapshot = AgentSnapshot< - Tools, - TState -> & { - /** - * Why the session's state schema rejected the current state document. - * `state` then keeps the last document that passed. Absent while the - * document passes, and always absent without a schema. - */ - readonly stateIssues?: readonly string[]; -}; -/** A core `AgentSession` over an AG-UI session. */ -export type AgUiAgentSession = Omit< - AgentSession, - 'getSnapshot' -> & { getSnapshot(): AgUiAgentSnapshot }; +/** + * What an AG-UI session publishes: the core snapshot, with the protocol + * evidence behind it. `state` is the typed state; the literal document a + * request sends is not published. + */ +export type SessionSnapshot = Omit & + AgentSnapshot & { + /** + * Why the session's state schema rejected the current state document. + * `state` then keeps the last document that passed. Absent while the + * document passes, and always absent without a schema. + */ + readonly stateIssues?: readonly string[]; + }; /** The state to publish for one state document, and why a schema rejected it. */ interface StateView { @@ -109,7 +90,7 @@ export const AUTH_COPY = 'Authentication failed. Check your credentials.'; * reason this view cannot name, such as a host that could not be reached. */ function failure( - native: SessionSnapshot, + native: Observation, canRetry: boolean, previous?: AgentError ): AgentError { @@ -166,7 +147,7 @@ const usageViews = new WeakMap(); * per provider and model. Only labels and finite counts are read. The terminal * is owned and frozen, so one terminal always yields the same projection. */ -function usage(native: SessionSnapshot): AgentUsage | undefined { +function usage(native: Observation): AgentUsage | undefined { if (native.status === 'running') return undefined; const terminal = native.run?.terminal; if (!terminal || terminal.type === 'CUSTOM') return undefined; @@ -196,11 +177,11 @@ function usage(native: SessionSnapshot): AgentUsage | undefined { } function project( - native: SessionSnapshot, + native: Observation, canRetry: boolean, view: StateView, - previous?: AgUiAgentSnapshot -): AgUiAgentSnapshot { + previous?: SessionSnapshot +): SessionSnapshot { const messages = projectMessages(native, previous?.messages); const toolCalls = projectToolCalls(native, previous?.toolCalls); const error = @@ -208,24 +189,12 @@ function project( ? failure(native, canRetry, previous?.error) : undefined; const used = usage(native); - if ( - previous && - previous.status === native.status && - previous.messages === messages && - previous.toolCalls === toolCalls && - previous.error === error && - previous.plan === native.plan && - previous.usage === used && - previous.state === view.state && - previous.stateIssues === view.issues - ) - return previous; + const { state: _document, ...evidence } = native; return Object.freeze({ - status: native.status, + ...evidence, messages, toolCalls, ...(error && { error }), - ...(native.plan && { plan: native.plan }), ...(used && { usage: used }), ...(view.state !== undefined && { state: view.state }), ...(view.issues && { stateIssues: view.issues }), @@ -233,75 +202,37 @@ function project( } /** - * A core `AgentSession` view of a native AG-UI session, so components written - * for core sessions can observe and drive it. - * - * It is a view, not a second owner. The snapshot is derived from the native - * snapshot on read and keeps its reference until something a core observer can - * see changes; subscribers are told about those changes only. `submit`, `stop`, - * `dispose` and, when the native session has it, `retry` go straight to the - * native session, so disposing the view disposes the session. `retry` rejects - * unless the error is `recovery: 'retry'`. Custom event listeners pass straight - * through to the native session too, when it has them. Native resume and - * client-tool evidence have no core equivalent: keep the native session for - * those. + * Builds the snapshot a session publishes from each observation. Messages, + * tool calls, the error, usage and state keep their references until they + * change, and one observation always yields the same snapshot. * - * `state` is the session's state document, typed by the `stateType` the session - * was created with. With a schema, each document is checked once and `state` - * holds the schema's output; a rejected document leaves `state` at the last - * one that passed and lists the reasons in `stateIssues`, and the run goes on. - * A session created without a state has none until the application submits - * one or the backend reports one. + * `state` is the session's state document, typed by its `stateType`. With a + * schema, each document is checked once and `state` holds the schema's output; + * a rejected document leaves `state` at the last one that passed and lists the + * reasons in `stateIssues`, and the run goes on. A session created without a + * state has none until the application submits one or the backend reports one. */ -export function createAgentSession( - session: NativeSession -): AgUiAgentSession { - let seen: SessionSnapshot | undefined; - let current: AgUiAgentSnapshot | undefined; - const retry = session.retry; - const listen = session.onCustomEvent; - const readView = stateReader(session.stateType); - const read = (): AgUiAgentSnapshot => { - const native = session.getSnapshot(); - if (native !== seen || !current) { - current = project(native, !!retry, readView(native.state), current); - seen = native; +export function createPresenter( + declaration: StateDeclaration | undefined, + canRetry: boolean +): (observation: Observation) => SessionSnapshot { + const readView = stateReader(declaration); + let seen: Observation | undefined; + let current: SessionSnapshot | undefined; + return (observation) => { + if (observation !== seen || !current) { + current = project( + observation, + canRetry, + readView(observation.state), + current + ); + seen = observation; } return current; }; - // The declaration is the only evidence of TState, as for any typed session. - const getSnapshot = read as () => AgUiAgentSnapshot; - return { - getSnapshot, - subscribe(notify) { - let last = getSnapshot(); - return session.subscribe(() => { - const next = getSnapshot(); - if (next === last) return; - last = next; - notify(); - }); - }, - // Events are not state, so they pass straight through to the native owner. - ...(listen && { - onCustomEvent: (listener: (event: AgentSessionCustomEvent) => void) => - listen.call(session, listener), - }), - submit: (input, options) => - session.submit(input as SubmitInput, options), - stop: () => session.stop(), - dispose: () => session.dispose(), - ...(retry && { - async retry() { - const snapshot = getSnapshot(); - // Nothing failed or a run is going: nothing runs, as for an ignored submit. - if (snapshot.status !== 'error') return 'aborted' as const; - if (snapshot.error?.recovery !== 'retry') - throw new Error( - 'This failure cannot be retried: the backend may already have done the work.' - ); - return retry.call(session); - }, - }), - }; } + +/** Why `retry` rejects after a failure that leaves the backend outcome open. */ +export const UNSAFE_RETRY = + 'This failure cannot be retried: the backend may already have done the work.'; diff --git a/libs/ag-ui/src/runtime/agent-session.type-test.ts b/libs/ag-ui/src/runtime/agent-session.type-test.ts index 965884c12..119076c8a 100644 --- a/libs/ag-ui/src/runtime/agent-session.type-test.ts +++ b/libs/ag-ui/src/runtime/agent-session.type-test.ts @@ -4,7 +4,6 @@ import { type StandardSchemaV1, type ToolContract, } from '@threadplane/core'; -import { createAgentSession } from './agent-session'; import { createSession } from './create-session'; type Equal = (() => T extends A ? 1 : 2) extends () => T extends B @@ -21,18 +20,25 @@ interface Draft { declare const schema: StandardSchemaV1; const options = { threadId: 't', url: 'https://agent.invalid' }; -// Without a declaration the state is plain data and any record can be sent. -const untyped = createAgentSession(createSession(options)); +// The session is a core session. Without a declaration its state is plain +// data and any record can be sent. +const untyped = createSession(options); const anySession: AgentSession = untyped; void anySession; void untyped.submit({ message: 'Go', state: { anything: [1, null] } }); // @ts-expect-error Plain data has no known keys. void untyped.getSnapshot().state?.title; +// The protocol evidence stays on the snapshot beside the core fields. +const evidence = untyped.getSnapshot(); +void evidence.transcript; +void evidence.messages; +void evidence.decision; +// @ts-expect-error A core observer sees the core snapshot only. +void anySession.getSnapshot().transcript; -// type() declares the state for the native session and its core view. -const native = createSession({ ...options, stateType: type() }); -const typed = createAgentSession(native); -export type TypedView = Assert< +// type() declares the state. +const typed = createSession({ ...options, stateType: type() }); +export type TypedState = Assert< Equal< ReturnType['state'], | { @@ -47,12 +53,9 @@ const core: AgentSession, Draft> = typed; void core; const issues: readonly string[] | undefined = typed.getSnapshot().stateIssues; void issues; -void native.submit({ message: 'Go', state: { title: 'New' } }); void typed.submit({ message: 'Go', state: { title: 'New' } }); void typed.submit('Go'); // @ts-expect-error A submitted state holds declared keys only. -void native.submit({ message: 'Go', state: { unknownKey: 1 } }); -// @ts-expect-error A submitted state holds declared keys only. void typed.submit({ message: 'Go', state: { unknownKey: 1 } }); // @ts-expect-error A declared key keeps its type. void typed.submit({ message: 'Go', state: { title: 1 } }); @@ -60,21 +63,19 @@ void typed.submit({ message: 'Go', state: { title: 1 } }); typed.getSnapshot().state?.tags.push('x'); // A Standard Schema declares the same type from its output. -const checked = createAgentSession( - createSession({ ...options, stateType: schema }) -); -export type CheckedView = Assert< +const checked = createSession({ ...options, stateType: schema }); +export type CheckedState = Assert< Equal< NonNullable['state']>['title'], string > >; -// The client-tool owner carries the declaration too. -const tools = createSession( - { ...options, stateType: type() }, - {} -); +// The client-tool owner is a core session with the declaration too. +const tools = createSession({ ...options, stateType: type() }, {}); +const toolCore: AgentSession, Draft> = tools; +void toolCore; +void tools.getSnapshot().clientTools.calls; void tools.submit({ message: 'Go', state: { tags: [] } }); // @ts-expect-error A submitted state holds declared keys only. void tools.submit({ message: 'Go', state: { unknownKey: 1 } }); diff --git a/libs/ag-ui/src/runtime/application-input.spec.ts b/libs/ag-ui/src/runtime/application-input.spec.ts index 098fc4ca9..84bf108f4 100644 --- a/libs/ag-ui/src/runtime/application-input.spec.ts +++ b/libs/ag-ui/src/runtime/application-input.spec.ts @@ -9,7 +9,7 @@ import { } from '@ag-ui/client'; import { Observable } from 'rxjs'; import { createSession, type Session } from './create-session'; -import type { SessionSnapshot } from './session-observation'; +import type { SessionSnapshot } from './agent-session'; import type { ApplicationState, SubmitInput } from './submit-input'; import { bindingFixture } from './testing/binding-fixture'; diff --git a/libs/ag-ui/src/runtime/client-tools.ts b/libs/ag-ui/src/runtime/client-tools.ts index 0479f3772..e94d4e42c 100644 --- a/libs/ag-ui/src/runtime/client-tools.ts +++ b/libs/ag-ui/src/runtime/client-tools.ts @@ -6,7 +6,7 @@ import type { } from '@threadplane/core'; import type { FunctionToolDefinition } from '@threadplane/core/tools'; import { copyData } from '../lib/internal/copy-data.js'; -import type { SessionSnapshot } from './session-observation.js'; +import type { SessionSnapshot } from './agent-session.js'; export type ClientToolCall> = { [K in keyof C & string]: { @@ -35,15 +35,16 @@ export interface ClientToolBlocker { readonly callIds: readonly string[]; } -export interface ClientToolSessionSnapshot< - C extends Record -> extends SessionSnapshot { +export type ClientToolSessionSnapshot< + C extends Record, + TState = unknown +> = SessionSnapshot & { readonly clientTools: { readonly calls: readonly ClientToolCall[]; readonly blocker?: ClientToolBlocker; readonly commandOutcome?: CompleteOutcome; }; -} +}; interface CapturedClientTool { readonly description: string; diff --git a/libs/ag-ui/src/runtime/create-session.ts b/libs/ag-ui/src/runtime/create-session.ts index 310c2a67c..96d4ec61c 100644 --- a/libs/ag-ui/src/runtime/create-session.ts +++ b/libs/ag-ui/src/runtime/create-session.ts @@ -35,11 +35,16 @@ import { applyObservation, failedWithRunError, initialObservation, - type SessionSnapshot, + type Observation, } from './session-observation.js'; import { earlierSubagents, type Subagents } from './subagents.js'; import { createRun, httpFailure, type RunHandle } from './create-run.js'; import { createPublication } from './session-publication.js'; +import { + createPresenter, + UNSAFE_RETRY, + type SessionSnapshot, +} from './agent-session.js'; import { createReasoningClock } from './reasoning-clock.js'; import type { InterruptMode } from './interrupt-mode.js'; import { @@ -65,9 +70,8 @@ export interface SessionOptions readonly state?: unknown; /** * The type of the state document: `type()` to declare it, or a Standard - * Schema to also check each state. `createAgentSession` publishes it as the - * typed `state` of the core snapshot. The native snapshot's `state` stays - * the literal document sent with each request, whatever is declared here. + * Schema to also check each state. The snapshot's `state` has this type. + * Requests still send the literal document, whatever is declared here. */ readonly stateType?: StateDeclaration; /** Child evidence saved with this thread, published as `earlierSubagents`. Their attributed messages belong in `messages`. */ @@ -75,7 +79,7 @@ export interface SessionOptions readonly interruptMode?: InterruptMode; } /** A new root invocation observes no children yet; settled ones become history. */ -function nextInvocationSubagents(previous: SessionSnapshot) { +function nextInvocationSubagents(previous: Observation) { const earlier = earlierSubagents( previous.earlierSubagents, previous.subagents @@ -88,7 +92,7 @@ function nextInvocationSubagents(previous: SessionSnapshot) { export interface Session { /** The state declaration this session was created with, when it has one. */ readonly stateType?: StateDeclaration; - getSnapshot(): SessionSnapshot; + getSnapshot(): SessionSnapshot; subscribe(notify: () => void): () => void; submit( input: SubmitInput, @@ -105,10 +109,11 @@ export interface Session { * Sends the last submission again after its run failed with a backend * `RUN_ERROR`. The request carries the history and state that submission * sent, so no second user message is added and the failed run's output is - * dropped. Resolves `aborted` without sending while a run is active or when - * the last run was not a failed submission, and `error` without sending when - * the failure leaves the backend outcome open. Absent on the client-tool - * owner, which blocks every dispatched failure as uncertain. + * dropped. Resolves `aborted` without sending while a run is active, when + * nothing failed or when the last run was not a failed submission. Rejects + * without sending when the error's `recovery` is not `'retry'`: the failure + * leaves the backend outcome open. Absent on the client-tool owner, which + * blocks every dispatched failure as uncertain. */ retry?(): Promise; /** @@ -126,7 +131,7 @@ export type ClientToolSession< C extends Record, TState = unknown > = Omit, 'getSnapshot'> & { - getSnapshot(): ClientToolSessionSnapshot; + getSnapshot(): ClientToolSessionSnapshot; }; /** A `CUSTOM` event as an application event, read the way the Angular adapter * reads it: a string value that parses as JSON becomes that data. The legacy @@ -164,7 +169,10 @@ interface Attempt { finished: boolean; } -/** Private protocol owner. This does not yet implement core AgentSession. */ +/** + * Creates the session that owns one AG-UI thread. It is a core `AgentSession`: + * its snapshot is the core snapshot with the protocol evidence behind it. + */ export function createSession< T extends Record, D extends StateDeclaration | undefined = undefined @@ -218,7 +226,8 @@ export function createSession( : Object.freeze({ ...initial, clientTools: Object.freeze({ calls: Object.freeze([]) }), - }) + }), + createPresenter(stateType, true) ); let active: Attempt | undefined; let disposed = false; @@ -247,7 +256,7 @@ export function createSession( attempt.cleanup(); if (active === attempt) { active = undefined; - const previous = publication.getSnapshot(); + const previous = publication.getObservation(); publication.publish( Object.freeze({ ...previous, @@ -281,7 +290,7 @@ export function createSession( if (!current(attempt)) return; let input: RunAgentInput; try { - const value = publication.getSnapshot(); + const value = publication.getObservation(); const decision = value.decision; input = { threadId, @@ -319,7 +328,7 @@ export function createSession( if (!current(attempt)) return; // createRun delivers the SDK's normalized/verified union through its // BaseEvent callback. No second schema parse or sequence verifier. - const previous = publication.getSnapshot(); + const previous = publication.getObservation(); let next = reasoningClock.observe( event as AGUIEvent, applyObservation(previous, event as AGUIEvent, interruptMode), @@ -365,7 +374,7 @@ export function createSession( }; const admit = ( id: string, - next: SessionSnapshot, + next: Observation, signal: AbortSignal | undefined, resolve: (outcome: CompleteOutcome) => void ) => { @@ -446,7 +455,7 @@ export function createSession( const beforeInput = ++revision; let captured: readonly NativeResponse[]; try { - const previous = publication.getSnapshot(); + const previous = publication.getObservation(); if (interruptMode !== 'native' || active) throw new TypeError('Resume requires a settled native owner'); assertResumeEligible( @@ -474,10 +483,10 @@ export function createSession( return; } const beforeAdmission = revision; - let next: SessionSnapshot; + let next: Observation; let id: string; try { - const previous = publication.getSnapshot(); + const previous = publication.getObservation(); if (active || interruptMode !== 'native') throw new TypeError('Resume requires a settled native owner'); const decision = assertResumeEligible( @@ -526,7 +535,7 @@ export function createSession( resolve('aborted'); return; } - if (publication.getSnapshot().decision) { + if (publication.getObservation().decision) { resolve('error'); return; } @@ -551,15 +560,15 @@ export function createSession( resolve('aborted'); return; } - if (publication.getSnapshot().decision) { + if (publication.getObservation().decision) { resolve('error'); return; } const beforeCapture = revision; - let next: SessionSnapshot; + let next: Observation; let id: string; try { - const previous = publication.getSnapshot(); + const previous = publication.getObservation(); // Capture precedes queueing, but admission uses the latest state. // Incompatible patches fail before transferring the active run. const state = mergeSubmitState(previous.state, captured.state); @@ -599,13 +608,23 @@ export function createSession( }); }), retry: () => - new Promise((resolve) => { + new Promise((resolve, reject) => { if (disposed) { resolve('aborted'); return; } + // Nothing failed or a run is going: nothing runs, as for an ignored submit. + const published = publication.getSnapshot(); + if (published.status !== 'error') { + resolve('aborted'); + return; + } + if (published.error?.recovery !== 'retry') { + reject(new Error(UNSAFE_RETRY)); + return; + } publication.command(() => { - const previous = publication.getSnapshot(); + const previous = publication.getObservation(); const last = saved; if ( disposed || @@ -667,7 +686,9 @@ function createToolsOwner( Object.freeze({ ...initial, clientTools: ledger.snapshot(), - }) + }), + // This owner has no retry, so no failure is offered as retryable. + createPresenter(options.stateType, false) ); interface Physical { readonly id: string; @@ -701,9 +722,9 @@ function createToolsOwner( !disposed && !command.controller.signal.aborted && !ledger.snapshot().blocker && - !publication.getSnapshot().decision; + !publication.getObservation().decision; const publishLedger = (outcome?: CompleteOutcome) => { - const previous = publication.getSnapshot(); + const previous = publication.getObservation(); publication.publish( Object.freeze({ ...previous, @@ -727,7 +748,7 @@ function createToolsOwner( }); }; const unresolvedRootIds = () => { - const history = publication.getSnapshot().transcript; + const history = publication.getObservation().transcript; return history.flatMap((message) => message.role === 'assistant' && typeof message.subagentRunId !== 'string' ? (message.toolCalls ?? []) @@ -746,7 +767,7 @@ function createToolsOwner( }; const protectCancellation = (command: Command, physical: Physical) => { ledger.cancelIncomplete(physical.id); - const snapshot = publication.getSnapshot(); + const snapshot = publication.getObservation(); if (snapshot.decision) return; const terminal = snapshot.run?.terminal; const conclusive = @@ -766,7 +787,7 @@ function createToolsOwner( command.cleanup(); // Keep admission busy through final notification; reentrant submit cannot // append a new human while this command's result is being published. - const previous = publication.getSnapshot(); + const previous = publication.getObservation(); publication.publish( Object.freeze({ ...previous, @@ -871,7 +892,7 @@ function createToolsOwner( const completionAuthority = () => revision === completionRevision && eligible(command, physical); try { - const history = publication.getSnapshot().transcript; + const history = publication.getObservation().transcript; if (error !== undefined) ledger.fail( id, @@ -930,7 +951,7 @@ function createToolsOwner( physical.settled = true; physical.fetchInvoked = fetchInvoked; if (!owns(command, physical)) return; - const previous = publication.getSnapshot(); + const previous = publication.getObservation(); const terminal = previous.run?.terminal; if ( previous.decision?.kind === 'native' && @@ -967,7 +988,7 @@ function createToolsOwner( finish(command, 'aborted'); return; } - if (publication.getSnapshot().decision || outcome === 'paused') { + if (publication.getObservation().decision || outcome === 'paused') { finish(command, outcome); return; } @@ -1030,7 +1051,7 @@ function createToolsOwner( let input: RunAgentInput; let capture: ReturnType; try { - const snapshot = publication.getSnapshot(); + const snapshot = publication.getObservation(); const resuming = snapshot.decision?.kind === 'native' && snapshot.decision.attempt?.runId === physical.id; @@ -1092,7 +1113,7 @@ function createToolsOwner( disposed ) return; - const previous = publication.getSnapshot(); + const previous = publication.getObservation(); let next = reasoningClock.observe( event as AGUIEvent, applyObservation(previous, event as AGUIEvent, interruptMode), @@ -1149,7 +1170,7 @@ function createToolsOwner( ledger.snapshot().blocker ) return false; - const decision = publication.getSnapshot().decision; + const decision = publication.getObservation().decision; if ( decision && !( @@ -1195,7 +1216,7 @@ function createToolsOwner( ); }; const startPhysical = (command: Command, id: string) => { - const previous = publication.getSnapshot(); + const previous = publication.getObservation(); const physical: Physical = { id, token: ledger.startPhysical({ @@ -1220,7 +1241,7 @@ function createToolsOwner( queueMicrotask(() => dispatch(command, physical)); }; const admit = ( - next: SessionSnapshot, + next: Observation, id: string, signal: AbortSignal | undefined, resolve: (outcome: CompleteOutcome) => void @@ -1302,7 +1323,7 @@ function createToolsOwner( if ( active || ledger.snapshot().blocker || - publication.getSnapshot().decision + publication.getObservation().decision ) { resolve('error'); return; @@ -1337,13 +1358,13 @@ function createToolsOwner( if ( active || ledger.snapshot().blocker || - publication.getSnapshot().decision + publication.getObservation().decision ) { resolve('error'); return; } try { - const previous = publication.getSnapshot(); + const previous = publication.getObservation(); if (!ledger.historyIntegrity(previous.transcript)) { publishLedger(); resolve('error'); @@ -1396,7 +1417,7 @@ function createToolsOwner( } if (interruptMode !== 'native') throw new TypeError('Native resume required'); - const previous = publication.getSnapshot(); + const previous = publication.getObservation(); assertResumeEligible( previous.decision, previous.run, @@ -1422,7 +1443,7 @@ function createToolsOwner( return; } try { - const previous = publication.getSnapshot(); + const previous = publication.getObservation(); const decision = assertResumeEligible( previous.decision, previous.run, diff --git a/libs/ag-ui/src/runtime/custom-events.spec.ts b/libs/ag-ui/src/runtime/custom-events.spec.ts index 9a89c14cf..a6a0b9c89 100644 --- a/libs/ag-ui/src/runtime/custom-events.spec.ts +++ b/libs/ag-ui/src/runtime/custom-events.spec.ts @@ -2,7 +2,6 @@ import { ok } from 'node:assert/strict'; import { describe, expect, it, vi } from 'vitest'; import type { RunAgentInput } from '@ag-ui/client'; import type { AgentSessionCustomEvent } from '@threadplane/core'; -import { createAgentSession } from './agent-session'; import { createSession, type Session } from './create-session'; /** Each request answers with the next run's events between its lifecycle. */ @@ -127,31 +126,3 @@ describe('plain AG-UI session disposal', () => { expect(second).not.toHaveBeenCalled(); }); }); - -describe('core AG-UI session view custom events', () => { - it('forwards listeners to the native session', async () => { - const native = createSession({ - threadId: 't', - url: 'unused', - fetch: wire([custom('tick', { n: 1 })]), - }); - const session = createAgentSession(native); - const listener = vi.fn(); - listen(session, listener); - expect(await session.submit('hello')).toBe('success'); - expect(listener).toHaveBeenCalledWith({ name: 'tick', data: { n: 1 } }); - }); - - it('has no listener method when the native session has none', () => { - const session = createAgentSession({ - getSnapshot: () => { - throw new Error('unused'); - }, - subscribe: () => () => undefined, - submit: async () => 'success', - stop: async () => undefined, - dispose: async () => undefined, - }); - expect(session.onCustomEvent).toBeUndefined(); - }); -}); diff --git a/libs/ag-ui/src/runtime/failure-cause.spec.ts b/libs/ag-ui/src/runtime/failure-cause.spec.ts index 27f2000b6..281e43776 100644 --- a/libs/ag-ui/src/runtime/failure-cause.spec.ts +++ b/libs/ag-ui/src/runtime/failure-cause.spec.ts @@ -1,7 +1,7 @@ import { describe, expect, it } from 'vitest'; // eslint-disable-next-line @nx/enforce-module-boundaries -- The shared wording is compared with its LangGraph source. import { failureProjection } from '../../../langgraph/src/runtime/stream-projection'; -import { AUTH_COPY, createAgentSession } from './agent-session'; +import { AUTH_COPY } from './agent-session'; import { httpFailure } from './create-run'; import { createSession } from './create-session'; @@ -65,7 +65,7 @@ describe.each([ ])('the failure cause %s', (_label, tools) => { it('keeps the status of a rejected response and clears it on the next run', async () => { const session = scripted([rejected(401), finished], tools); - const view = createAgentSession(session); + const view = session; try { expect(await session.submit('Go')).toBe('error'); expect(session.getSnapshot()).toMatchObject({ @@ -99,7 +99,7 @@ describe.each([ try { expect(await session.submit('Go')).toBe('error'); expect(session.getSnapshot().run?.failure).toEqual({ status: 503 }); - expect(createAgentSession(session).getSnapshot().error).toEqual({ + expect(session.getSnapshot().error).toEqual({ kind: 'server', message: 'The agent request failed.', status: 503, @@ -120,7 +120,7 @@ describe.each([ ], tools ); - const view = createAgentSession(session); + const view = session; try { expect(await session.submit('Go')).toBe('error'); expect(session.getSnapshot().run?.failure).toBeUndefined(); @@ -145,7 +145,7 @@ describe.each([ ], tools ); - const view = createAgentSession(session); + const view = session; try { expect(await session.submit('Go')).toBe('error'); expect(session.getSnapshot().run?.failure).toBeUndefined(); diff --git a/libs/ag-ui/src/runtime/interrupt-mode.type-test.ts b/libs/ag-ui/src/runtime/interrupt-mode.type-test.ts index 71554118f..cdd9b5ac8 100644 --- a/libs/ag-ui/src/runtime/interrupt-mode.type-test.ts +++ b/libs/ag-ui/src/runtime/interrupt-mode.type-test.ts @@ -1,7 +1,7 @@ import { createSession } from './create-session'; import { createRun } from './create-run'; import type { InterruptMode } from './interrupt-mode'; -import type { SessionSnapshot } from './session-observation'; +import type { Observation } from './session-observation'; const mode: InterruptMode = 'native'; createSession({ threadId: 't', url: 'unused', interruptMode: mode }); @@ -16,7 +16,7 @@ createRun({ url: 'unused', interruptMode: 'legacy-observation' }); createRun({ url: 'unused', interruptMode: 'mastra' }); // @ts-expect-error resume interpretation is not supported createSession({ threadId: 't', url: 'unused', interruptMode: 'legacy-resume' }); -declare const snapshot: SessionSnapshot; +declare const snapshot: Observation; if (snapshot.run?.legacyInterrupt) { const name: string = snapshot.run.legacyInterrupt.name; // @ts-expect-error selected notice evidence is readonly diff --git a/libs/ag-ui/src/runtime/message-projection.spec.ts b/libs/ag-ui/src/runtime/message-projection.spec.ts index 6a06e66aa..58923bd50 100644 --- a/libs/ag-ui/src/runtime/message-projection.spec.ts +++ b/libs/ag-ui/src/runtime/message-projection.spec.ts @@ -4,15 +4,15 @@ import { projectMessages, projectToolCalls } from './message-projection'; import { createReasoningClock } from './reasoning-clock'; import { initialObservation, - type SessionSnapshot, + type Observation, } from './session-observation'; import { bindingFixture } from './testing/binding-fixture'; type Records = NonNullable[0]>; const observed = ( messages: Records, - extra: Partial = {} -): SessionSnapshot => + extra: Partial = {} +): Observation => Object.freeze({ ...initialObservation(messages), ...extra }); const turn: Records = [ { id: 'system', role: 'system', content: 'Policy' }, @@ -160,7 +160,7 @@ describe('projectMessages', () => { }); it('streams only the message built from the last root record while running', () => { - const phases = (messages: Records, extra: Partial) => + const phases = (messages: Records, extra: Partial) => projectMessages(observed(messages, extra)).map((message) => message.delivery.phase === 'complete' ? message.delivery.outcome @@ -695,7 +695,9 @@ describe('citations from application state', () => { type: 'STATE_DELTA', delta: [{ op: 'add', path: '/citations', value: { saved: [{ id: 'doc', title: 'Doc' }] } }], }); - await fixture.changed((snapshot) => 'citations' in (snapshot.state as object)); + await fixture.changed( + (snapshot) => 'citations' in ((snapshot.state ?? {}) as object) + ); // The listing is keyed by the saved identifier, which the stream has not used yet. expect('citations' in view().at(-1)!).toBe(false); exchange.emit({ diff --git a/libs/ag-ui/src/runtime/message-projection.ts b/libs/ag-ui/src/runtime/message-projection.ts index c18680e62..11eb614d9 100644 --- a/libs/ag-ui/src/runtime/message-projection.ts +++ b/libs/ag-ui/src/runtime/message-projection.ts @@ -7,7 +7,16 @@ import { type ToolCall, } from '@threadplane/core'; import { copyData } from '../lib/internal/copy-data.js'; -import type { SessionSnapshot } from './session-observation.js'; +import type { Observation } from './session-observation.js'; + +/** + * What the selectors read. Both a session's published snapshot and the + * observation behind it qualify; the published `state` may be absent. + */ +export type Projectable = Pick< + Observation, + 'status' | 'transcript' | 'reasoningDurations' | 'run' +> & { readonly state?: unknown }; import type { Transcript } from './transcript.js'; const empty: readonly Message[] = Object.freeze([]); @@ -46,7 +55,7 @@ const textOf = (content: unknown): string => * object or array (more fragments could not keep it valid). Until then the call * is withheld, so a view never sees half an argument object. */ -function selectCalls(snapshot: SessionSnapshot) { +function selectCalls(snapshot: Projectable) { const { transcript } = snapshot; const running = snapshot.status === 'running'; const results = new Map(); @@ -118,7 +127,7 @@ const sources = new WeakMap< * `previous` is an optional identity hint, as in `projectMessages`. */ export function projectToolCalls( - snapshot: SessionSnapshot, + snapshot: Projectable, previous: readonly ToolCall[] = noCalls ): readonly ToolCall[] { const running = snapshot.status === 'running'; @@ -285,7 +294,7 @@ interface Pending { * list, are returned as the same references. Selection is O(N). */ export function projectMessages( - snapshot: SessionSnapshot, + snapshot: Projectable, previous: readonly Message[] = empty ): readonly Message[] { const durations = snapshot.reasoningDurations; diff --git a/libs/ag-ui/src/runtime/reasoning-clock.ts b/libs/ag-ui/src/runtime/reasoning-clock.ts index 7cddef4e3..308fec525 100644 --- a/libs/ag-ui/src/runtime/reasoning-clock.ts +++ b/libs/ag-ui/src/runtime/reasoning-clock.ts @@ -1,5 +1,5 @@ import type { AGUIEvent } from '@ag-ui/client'; -import type { SessionSnapshot } from './session-observation.js'; +import type { Observation } from './session-observation.js'; import type { Transcript } from './transcript.js'; type Durations = Readonly>; @@ -85,10 +85,10 @@ export function createReasoningClock(now: () => number = () => Date.now()) { * ends. `previous` is the snapshot the event was applied to; with it, a * messages snapshot carries the measured times over to the new records. */ - observe( + observe( event: AGUIEvent, next: T, - previous?: SessionSnapshot + previous?: Observation ): T { if (event.type === 'MESSAGES_SNAPSHOT' && previous) { const carried = carryReasoningDurations( diff --git a/libs/ag-ui/src/runtime/retry.spec.ts b/libs/ag-ui/src/runtime/retry.spec.ts index c41a1f9cc..dc9fd6be9 100644 --- a/libs/ag-ui/src/runtime/retry.spec.ts +++ b/libs/ag-ui/src/runtime/retry.spec.ts @@ -1,5 +1,4 @@ import { describe, expect, it } from 'vitest'; -import { createAgentSession } from './agent-session'; import { createSession } from './create-session'; import { bindingFixture } from './testing/binding-fixture'; @@ -13,10 +12,10 @@ const usage = [ { provider: 'openai', model: 'small', inputTokens: 12, outputTokens: 3 }, ]; -describe('retry over the native owner', () => { +describe('retry', () => { it('sends a submission that ended in RUN_ERROR again without a second user message', async () => { const fixture = bindingFixture(); - const session = createAgentSession(fixture.session); + const session = fixture.session; try { const failed = session.submit('Plan a visit'); const first = await fixture.started(); @@ -81,7 +80,7 @@ describe('retry over the native owner', () => { it('refuses a stream that ended without a terminal and sends nothing', async () => { const fixture = bindingFixture(); - const session = createAgentSession(fixture.session); + const session = fixture.session; try { const failed = session.submit('Go'); const first = await fixture.started(); @@ -93,7 +92,6 @@ describe('retry over the native owner', () => { recovery: 'none', }); await expect(retryOf(session)).rejects.toThrow(/cannot be retried/); - await expect(retryOf(fixture.session)).resolves.toBe('error'); expect(fixture.exchanges).toHaveLength(1); } finally { await fixture.cleanup(); @@ -102,15 +100,13 @@ describe('retry over the native owner', () => { it('is a no-op with nothing saved and while a run is active', async () => { const fixture = bindingFixture(); - const session = createAgentSession(fixture.session); + const session = fixture.session; try { expect(await retryOf(session)).toBe('aborted'); - await expect(retryOf(fixture.session)).resolves.toBe('aborted'); expect(fixture.exchanges).toHaveLength(0); const run = session.submit('Go'); const first = await fixture.started(); expect(await retryOf(session)).toBe('aborted'); - await expect(retryOf(fixture.session)).resolves.toBe('aborted'); first.emit({ type: 'RUN_ERROR', message: 'Failed' }); await run; expect(fixture.exchanges).toHaveLength(1); @@ -121,7 +117,7 @@ describe('retry over the native owner', () => { it('keeps usage per run: a run that reports none clears the previous count', async () => { const fixture = bindingFixture(); - const session = createAgentSession(fixture.session); + const session = fixture.session; try { const first = session.submit('One'); const one = await fixture.started(); @@ -161,6 +157,5 @@ describe('retry over the native owner', () => { } ); expect('retry' in native).toBe(false); - expect(createAgentSession(native).retry).toBeUndefined(); }); }); diff --git a/libs/ag-ui/src/runtime/session-http.spec.ts b/libs/ag-ui/src/runtime/session-http.spec.ts index 64460e8ff..05b8cb4d5 100644 --- a/libs/ag-ui/src/runtime/session-http.spec.ts +++ b/libs/ag-ui/src/runtime/session-http.spec.ts @@ -6,7 +6,7 @@ import type { AddressInfo } from 'node:net'; import { describe, expect, it } from 'vitest'; import type { Message, RunAgentInput } from '@ag-ui/client'; import { createSession, type Session } from './create-session'; -import type { SessionSnapshot } from './session-observation'; +import type { SessionSnapshot } from './agent-session'; function deferred() { let resolve!: (value: T) => void; diff --git a/libs/ag-ui/src/runtime/session-observation.spec.ts b/libs/ag-ui/src/runtime/session-observation.spec.ts index 9be63fa98..a5caf49ec 100644 --- a/libs/ag-ui/src/runtime/session-observation.spec.ts +++ b/libs/ag-ui/src/runtime/session-observation.spec.ts @@ -3,10 +3,10 @@ import { EventType as E, type AGUIEvent, type Message } from '@ag-ui/client'; import { applyObservation, initialObservation, - type SessionSnapshot, + type Observation, } from './session-observation'; -const running = (): SessionSnapshot => +const running = (): Observation => Object.freeze({ ...initialObservation(), status: 'running', diff --git a/libs/ag-ui/src/runtime/session-observation.ts b/libs/ag-ui/src/runtime/session-observation.ts index d70ba6b98..5e6b216cc 100644 --- a/libs/ag-ui/src/runtime/session-observation.ts +++ b/libs/ag-ui/src/runtime/session-observation.ts @@ -49,7 +49,7 @@ export type OwnedRootTerminal = DeepReadonly< > | Pick >; -export interface SessionSnapshot { +export interface Observation { readonly status: 'idle' | 'running' | 'error'; readonly transcript: Transcript; readonly state: PlainValue; @@ -85,7 +85,7 @@ export interface SessionSnapshot { * that ended without a terminal, a response that was not OK and a request that * got no response all leave open whether the backend did the work. */ -export function failedWithRunError(snapshot: SessionSnapshot): boolean { +export function failedWithRunError(snapshot: Observation): boolean { return ( snapshot.status === 'error' && snapshot.run?.terminal?.type === 'RUN_ERROR' && @@ -110,7 +110,7 @@ export function initialObservation( messages: readonly Message[] | Transcript = [], state?: unknown, subagents?: unknown -): SessionSnapshot { +): Observation { const transcript = ownTranscript(messages); assertTranscriptIdentity(transcript); const earlier = ownSubagents(subagents); @@ -127,10 +127,10 @@ export function initialObservation( * RAW, STEP, REASONING_START/END and other CUSTOM events have no retained * projection in this slice. The session owner times reasoning messages itself. Child state still updates the one shared document. */ export function applyObservation( - previous: SessionSnapshot, + previous: Observation, event: AGUIEvent, interruptMode: InterruptMode = 'native' -): SessionSnapshot { +): Observation { assertAttribution(previous.transcript, event); let { transcript, state, subagents, run } = previous; switch (event.type) { diff --git a/libs/ag-ui/src/runtime/session-plan.spec.ts b/libs/ag-ui/src/runtime/session-plan.spec.ts index 320124527..1cc0947b8 100644 --- a/libs/ag-ui/src/runtime/session-plan.spec.ts +++ b/libs/ag-ui/src/runtime/session-plan.spec.ts @@ -1,15 +1,18 @@ import { describe, expect, it } from 'vitest'; import type { RunAgentInput } from '@ag-ui/client'; import { createSession } from './create-session'; -import { initialObservation, type SessionSnapshot } from './session-observation'; +import { initialObservation, type Observation } from './session-observation'; import { createPublication } from './session-publication'; +/** A publication that publishes its observation as it is. */ +const observed = (initial: Parameters[0]) => + createPublication(initial, (observation) => observation); -const withState = (previous: SessionSnapshot, state: unknown): SessionSnapshot => - Object.freeze({ ...previous, state: state as SessionSnapshot['state'] }); +const withState = (previous: Observation, state: unknown): Observation => + Object.freeze({ ...previous, state: state as Observation['state'] }); describe('session plan', () => { it('reads the plan from the todos state key, skipping malformed steps', () => { - const store = createPublication( + const store = observed( initialObservation([], { todos: [ { content: ' Find flights ', status: 'completed' }, @@ -30,14 +33,14 @@ describe('session plan', () => { }); it('leaves plan absent when the state declares no todos', () => { - const store = createPublication(initialObservation([], { count: 1 })); + const store = observed(initialObservation([], { count: 1 })); expect('plan' in store.getSnapshot()).toBe(false); store.publish(withState(store.getSnapshot(), { todos: 'not a list' })); expect('plan' in store.getSnapshot()).toBe(false); }); it('shares unchanged steps and the whole list across state updates', () => { - const store = createPublication( + const store = observed( initialObservation([], { todos: [ { content: 'One', status: 'in_progress' }, @@ -71,7 +74,7 @@ describe('session plan', () => { }); it('keeps the plan reference when the state reference is unchanged', () => { - const store = createPublication( + const store = observed( initialObservation([], { todos: [{ content: 'One', status: 'pending' }] }) ); const plan = store.getSnapshot().plan; @@ -81,7 +84,7 @@ describe('session plan', () => { }); it('drops the plan when the state no longer holds todos', () => { - const store = createPublication( + const store = observed( initialObservation([], { todos: [{ content: 'One', status: 'pending' }] }) ); store.publish(withState(store.getSnapshot(), {})); diff --git a/libs/ag-ui/src/runtime/session-publication.spec.ts b/libs/ag-ui/src/runtime/session-publication.spec.ts index 5fbda7c2f..bd18423db 100644 --- a/libs/ag-ui/src/runtime/session-publication.spec.ts +++ b/libs/ag-ui/src/runtime/session-publication.spec.ts @@ -1,10 +1,13 @@ import { describe, expect, it, vi } from 'vitest'; import { initialObservation } from './session-observation'; import { createPublication } from './session-publication'; +/** A publication that publishes its observation as it is. */ +const observed = (initial: Parameters[0]) => + createPublication(initial, (observation) => observation); describe('private session publication', () => { it('publishes owned references and independent registrations without notifying on reads or same reference', () => { const initial = initialObservation(); - const store = createPublication(initial); + const store = observed(initial); const listener = vi.fn(); const off = store.subscribe(listener); store.subscribe(listener); @@ -27,7 +30,7 @@ describe('private session publication', () => { const initial = initialObservation(); const next = initialObservation([], 1); const last = initialObservation([], 2); - const store = createPublication(initial); + const store = observed(initial); const seen: unknown[] = []; let remove = () => undefined as void; store.subscribe(() => { diff --git a/libs/ag-ui/src/runtime/session-publication.ts b/libs/ag-ui/src/runtime/session-publication.ts index 4e06b435d..7873546a7 100644 --- a/libs/ag-ui/src/runtime/session-publication.ts +++ b/libs/ag-ui/src/runtime/session-publication.ts @@ -3,7 +3,7 @@ import { type AgentPlanStep, type AgentSessionCustomEvent, } from '@threadplane/core'; -import type { SessionSnapshot } from './session-observation.js'; +import type { Observation } from './session-observation.js'; type Plan = readonly AgentPlanStep[]; @@ -27,9 +27,9 @@ const freezeStep = (step: AgentPlanStep) => Object.freeze({ ...step }); * changes state (server snapshots and deltas, submitted patches, restore) also * keeps the plan current. Unchanged state keeps the previous plan reference. */ -function withPlan( +function withPlan( next: T, - previous: SessionSnapshot | undefined + previous: Observation | undefined ): T { const plan = previous && Object.is(next.state, previous.state) @@ -40,7 +40,15 @@ function withPlan( return Object.freeze(plan ? { ...rest, plan } : rest) as T; } -export function createPublication(initial: SessionSnapshot) { +/** + * Owns the session's observation and tells subscribers when it changes. + * `present` turns an observation into the snapshot the session publishes; it + * is asked once per observation, on the first read. + */ +export function createPublication( + initial: Observation, + present: (observation: Observation) => TSnapshot +) { let current = withPlan(initial, undefined); const listeners = new Set<{ notify: () => void }>(); const eventListeners = new Set<{ @@ -62,7 +70,7 @@ export function createPublication(initial: SessionSnapshot) { commands.push(action); drain(); }; - const publish = (next: SessionSnapshot) => { + const publish = (next: Observation) => { if (notifying) { command(() => publish(next)); return; @@ -85,7 +93,10 @@ export function createPublication(initial: SessionSnapshot) { } }; return { - getSnapshot: () => current, + /** The published snapshot. */ + getSnapshot: () => present(current), + /** What the owner reduces events into, including the literal state document. */ + getObservation: () => current, subscribe: (notify: () => void): (() => void) => { const registration = { notify }; listeners.add(registration); diff --git a/libs/ag-ui/src/runtime/testing/binding-fixture.ts b/libs/ag-ui/src/runtime/testing/binding-fixture.ts index 096183a30..747627e8b 100644 --- a/libs/ag-ui/src/runtime/testing/binding-fixture.ts +++ b/libs/ag-ui/src/runtime/testing/binding-fixture.ts @@ -1,7 +1,6 @@ import type { RunAgentInput } from '@ag-ui/client'; import type { StateDeclaration } from '@threadplane/core'; import { createSession, type SessionOptions } from '../create-session'; -import type { SessionSnapshot } from '../session-observation'; // Consumer specs assert the declared protocol version without depending on @ag-ui/* directly. export { PROTOCOL_VERSION } from '@ag-ui/client'; @@ -108,6 +107,7 @@ export function bindingFixture< return exchange.response; }, }); + type Published = ReturnType; return { session, exchanges, @@ -121,10 +121,10 @@ export function bindingFixture< } return start.promise; }, - changed(predicate: (snapshot: SessionSnapshot) => boolean) { + changed(predicate: (snapshot: Published) => boolean) { const snapshot = session.getSnapshot(); if (predicate(snapshot)) return Promise.resolve(snapshot); - return new Promise((resolve) => { + return new Promise((resolve) => { const release = session.subscribe(() => { const next = session.getSnapshot(); if (predicate(next)) { diff --git a/libs/angular/src/observe-agent.ag-ui.spec.ts b/libs/angular/src/observe-agent.ag-ui.spec.ts index 394c3f545..296e93214 100644 --- a/libs/angular/src/observe-agent.ag-ui.spec.ts +++ b/libs/angular/src/observe-agent.ag-ui.spec.ts @@ -142,7 +142,8 @@ describe('observeAgent native AG-UI owner', () => { ]); expect(second.snapshot().status).toBe('running'); expect(second.snapshot().run?.outcome).toBeUndefined(); - expect(second.snapshot()).not.toHaveProperty('toolCalls'); + // The core tool calls withhold a call whose arguments are still arriving. + expect(second.snapshot().toolCalls).toEqual([]); const detached = first.snapshot(); first.destroy(); expect(exchange.aborts).toBe(0); diff --git a/libs/angular/src/observe-agent.type-test.ts b/libs/angular/src/observe-agent.type-test.ts index 8ebf22ef5..6b63f2f88 100644 --- a/libs/angular/src/observe-agent.type-test.ts +++ b/libs/angular/src/observe-agent.type-test.ts @@ -10,7 +10,7 @@ import type { bindingFixture } from '../../langgraph/src/runtime/testing/binding // eslint-disable-next-line @nx/enforce-module-boundaries -- Type-only admission proof for the actual private native owner, not a production dependency. import type { createSession } from '../../ag-ui/src/runtime/create-session'; // eslint-disable-next-line @nx/enforce-module-boundaries -- The private native snapshot is inferred without a core display projection. -import type { SessionSnapshot } from '../../ag-ui/src/runtime/session-observation'; +import type { SessionSnapshot } from '../../ag-ui/src/runtime/agent-session'; export function observeInferredRuntime( session: ReturnType['session'] @@ -182,8 +182,8 @@ export function observeNativeSession( snapshot.transcript.push({ id: 'new', role: 'user', content: 'mutable' }); // @ts-expect-error Child start evidence remains readonly. snapshot.subagents[0].started.name = 'changed'; - // @ts-expect-error The native owner does not fabricate executable core tools. - void snapshot.toolCalls; + // The session publishes the core fields beside its protocol evidence. + void [snapshot.messages, snapshot.toolCalls]; // @ts-expect-error Commands belong to the session, not its snapshot. snapshot.submit('Hello'); // @ts-expect-error The native state field is readonly. diff --git a/libs/react/src/chat/ag-ui-messages.spec.tsx b/libs/react/src/chat/ag-ui-messages.spec.tsx index 8d46d0aaa..28617723c 100644 --- a/libs/react/src/chat/ag-ui-messages.spec.tsx +++ b/libs/react/src/chat/ag-ui-messages.spec.tsx @@ -11,12 +11,12 @@ import { // eslint-disable-next-line @nx/enforce-module-boundaries -- Only integration tests compose the actual private native owner. import { initialObservation, - type SessionSnapshot, + type Observation, } from '../../../ag-ui/src/runtime/session-observation'; afterEach(cleanup); -const native = (extra: Partial = {}): SessionSnapshot => +const native = (extra: Partial = {}): Observation => Object.freeze({ ...initialObservation([ { id: 'u', role: 'user', content: 'Ask' }, @@ -38,7 +38,7 @@ const native = (extra: Partial = {}): SessionSnapshot => ]), ...extra, }); -function rows(snapshot: SessionSnapshot) { +function rows(snapshot: Observation) { const content = createMessageContent(); const core: AgentSnapshot = { status: snapshot.status, diff --git a/libs/react/src/chat/ag-ui-session.spec.tsx b/libs/react/src/chat/ag-ui-session.spec.tsx index 00e80d53f..471185731 100644 --- a/libs/react/src/chat/ag-ui-session.spec.tsx +++ b/libs/react/src/chat/ag-ui-session.spec.tsx @@ -5,7 +5,6 @@ import { useAgent } from '../use-agent'; // eslint-disable-next-line @nx/enforce-module-boundaries -- Only integration tests compose the actual private native owner. import { decisionState } from '../../../ag-ui/src/runtime/decision'; // eslint-disable-next-line @nx/enforce-module-boundaries -- Only integration tests compose the actual private native owner. -import { createAgentSession } from '../../../ag-ui/src/runtime/agent-session'; // eslint-disable-next-line @nx/enforce-module-boundaries -- Only integration tests compose the actual private native owner. import { bindingFixture } from '../../../ag-ui/src/runtime/testing/binding-fixture'; // eslint-disable-next-line @nx/enforce-module-boundaries -- Only integration tests compose the actual private native owner. @@ -16,7 +15,7 @@ afterEach(cleanup); describe('Chat over a native AG-UI session', () => { it('sends from the composer, streams the reply with its tool call, and shows a backend error', async () => { const fixture = bindingFixture(); - const session = createAgentSession(fixture.session); + const session = fixture.session; const view = render( { }, }, }); - const view = render(); + const view = render(); try { const sources = view.container.querySelector('.tp-citations'); expect(sources?.textContent).toContain('1'); @@ -116,7 +115,7 @@ describe('Chat over a native AG-UI session', () => { it('shows a pending approval from the native session and answers it', async () => { const fixture = bindingFixture(); const native = fixture.session; - const session = createAgentSession(native); + const session = native; function App() { const pending = decisionState(useAgent(native)); return ( @@ -216,7 +215,7 @@ describe('Chat over a native AG-UI session', () => { headers: { 'content-type': 'application/json' }, }), }); - const view = render(); + const view = render(); try { const box = view.getByRole('textbox'); fireEvent.change(box, { target: { value: 'Hello' } }); diff --git a/libs/react/src/use-agent.ag-ui.spec.tsx b/libs/react/src/use-agent.ag-ui.spec.tsx index 70b6889ce..d1816cfa4 100644 --- a/libs/react/src/use-agent.ag-ui.spec.tsx +++ b/libs/react/src/use-agent.ag-ui.spec.tsx @@ -132,7 +132,8 @@ describe('useAgent native AG-UI owner', () => { ]); expect(second.result.current.status).toBe('running'); expect(second.result.current.run?.outcome).toBeUndefined(); - expect(second.result.current).not.toHaveProperty('toolCalls'); + // The core tool calls withhold a call whose arguments are still arriving. + expect(second.result.current.toolCalls).toEqual([]); const detached = first.result.current; first.unmount(); expect(exchange.aborts).toBe(0); diff --git a/libs/react/src/use-agent.type-test.ts b/libs/react/src/use-agent.type-test.ts index d914c20e4..c0edab7a3 100644 --- a/libs/react/src/use-agent.type-test.ts +++ b/libs/react/src/use-agent.type-test.ts @@ -10,7 +10,7 @@ import type { bindingFixture } from '../../langgraph/src/runtime/testing/binding // eslint-disable-next-line @nx/enforce-module-boundaries -- Type-only admission proof for the actual private native owner, not a production dependency. import type { createSession } from '../../ag-ui/src/runtime/create-session'; // eslint-disable-next-line @nx/enforce-module-boundaries -- The private native snapshot is inferred without a core display projection. -import type { SessionSnapshot } from '../../ag-ui/src/runtime/session-observation'; +import type { SessionSnapshot } from '../../ag-ui/src/runtime/agent-session'; export function useInferredRuntime( session: ReturnType['session'] @@ -181,8 +181,8 @@ export function useNativeSession(session: ReturnType) { snapshot.transcript.push({ id: 'new', role: 'user', content: 'mutable' }); // @ts-expect-error Child start evidence remains readonly. snapshot.subagents[0].started.name = 'changed'; - // @ts-expect-error The native owner does not fabricate executable core tools. - void snapshot.toolCalls; + // The session publishes the core fields beside its protocol evidence. + void [snapshot.messages, snapshot.toolCalls]; // @ts-expect-error Commands belong to the session, not its snapshot. snapshot.submit('Hello'); // @ts-expect-error The native state field is readonly. diff --git a/scripts/react-parity/ag-ui-candidate-package.mjs b/scripts/react-parity/ag-ui-candidate-package.mjs index 00895d70c..cc87d8c8a 100644 --- a/scripts/react-parity/ag-ui-candidate-package.mjs +++ b/scripts/react-parity/ag-ui-candidate-package.mjs @@ -122,8 +122,6 @@ function forwarding(source, declaration) { ? factory : ['projectMessages', 'projectToolCalls'].includes(name.name.text) ? messages - : name.name.text === 'createAgentSession' - ? agent : ['decisionState', 'DecisionState'].includes(name.name.text) ? decision : projector; @@ -163,12 +161,10 @@ function forwarding(source, declaration) { 'TextTranscriptRow', 'projectMessages', 'projectToolCalls', - 'createAgentSession', 'decisionState', 'DecisionState', ] : [ - 'createAgentSession', 'decisionState', 'createSession', 'projectTextTranscript', diff --git a/scripts/react-parity/ag-ui-candidate-package.spec.mjs b/scripts/react-parity/ag-ui-candidate-package.spec.mjs index b4c99ea43..c4fc402bf 100644 --- a/scripts/react-parity/ag-ui-candidate-package.spec.mjs +++ b/scripts/react-parity/ag-ui-candidate-package.spec.mjs @@ -180,11 +180,11 @@ function fixture(t) { mkdirSync(join(source, 'libs/ag-ui/src/runtime'), { recursive: true }); writeFileSync( join(source, entry + '.ts'), - "export { createSession } from '../../../libs/ag-ui/src/runtime/create-session.js';\nexport type { Session, SessionOptions, ClientToolSession } from '../../../libs/ag-ui/src/runtime/create-session.js';\nexport type { ClientToolSessionSnapshot, ClientToolCall, ClientToolBlocker } from '../../../libs/ag-ui/src/runtime/client-tools.js';\nexport { projectTextTranscript } from '../../../libs/ag-ui/src/runtime/text-transcript.js';\nexport type { TextTranscriptRow } from '../../../libs/ag-ui/src/runtime/text-transcript.js';\nexport { projectMessages, projectToolCalls } from '../../../libs/ag-ui/src/runtime/message-projection.js';\nexport { createAgentSession } from '../../../libs/ag-ui/src/runtime/agent-session.js';\nexport { decisionState } from '../../../libs/ag-ui/src/runtime/decision.js';\nexport type { DecisionState } from '../../../libs/ag-ui/src/runtime/decision.js';\n" + "export { createSession } from '../../../libs/ag-ui/src/runtime/create-session.js';\nexport type { Session, SessionOptions, ClientToolSession } from '../../../libs/ag-ui/src/runtime/create-session.js';\nexport type { ClientToolSessionSnapshot, ClientToolCall, ClientToolBlocker } from '../../../libs/ag-ui/src/runtime/client-tools.js';\nexport { projectTextTranscript } from '../../../libs/ag-ui/src/runtime/text-transcript.js';\nexport type { TextTranscriptRow } from '../../../libs/ag-ui/src/runtime/text-transcript.js';\nexport { projectMessages, projectToolCalls } from '../../../libs/ag-ui/src/runtime/message-projection.js';\nexport { decisionState } from '../../../libs/ag-ui/src/runtime/decision.js';\nexport type { DecisionState } from '../../../libs/ag-ui/src/runtime/decision.js';\n" ); writeFileSync( join(source, 'libs/ag-ui/src/runtime/create-session.ts'), - 'export interface SessionOptions { threadId: string }\nexport interface Session { value: string }\nexport type ClientToolSession = Session;\nexport function createSession(options: SessionOptions): Session { return { value: options.threadId }; }' + "import { createPresenter } from './agent-session.js';\nexport interface SessionOptions { threadId: string }\nexport interface Session { value: string }\nexport type ClientToolSession = Session;\nexport function createSession(options: SessionOptions): Session { return { value: createPresenter()(options.threadId) }; }" ); writeFileSync( join(source, 'libs/ag-ui/src/runtime/client-tools.ts'), @@ -200,7 +200,7 @@ function fixture(t) { ); writeFileSync( join(source, 'libs/ag-ui/src/runtime/agent-session.ts'), - 'export function createAgentSession(session: object) { return session; }' + 'export function createPresenter() { return (value: string) => value; }' ); writeFileSync( join(source, 'libs/ag-ui/src/runtime/decision.ts'), diff --git a/scripts/react-parity/verify-ag-ui-candidate.mjs b/scripts/react-parity/verify-ag-ui-candidate.mjs index 34e8c140f..e37f86a78 100644 --- a/scripts/react-parity/verify-ag-ui-candidate.mjs +++ b/scripts/react-parity/verify-ag-ui-candidate.mjs @@ -123,7 +123,7 @@ const original = globalThis.fetch; let attempts = 0; globalThis.fetch = () => { attempts++; throw new Error('Inert lifecycle must not fetch'); }; try { const backend = await import('@threadplane/ag-ui'); - assert.deepEqual(Object.keys(backend).sort(), ['createAgentSession', 'createSession', 'decisionState', 'projectMessages', 'projectTextTranscript', 'projectToolCalls']); + assert.deepEqual(Object.keys(backend).sort(), ['createSession', 'decisionState', 'projectMessages', 'projectTextTranscript', 'projectToolCalls']); const session = backend.createSession({ threadId: 'inert', url: 'http://127.0.0.1:1' }); const snapshot = session.getSnapshot(); assert.ok(Object.isFrozen(snapshot)); assert.equal(session.getSnapshot(), snapshot); let notifications = 0; @@ -131,9 +131,8 @@ try { const rows = backend.projectTextTranscript(snapshot.transcript); assert.ok(Object.isFrozen(rows)); const messages = backend.projectMessages(snapshot); assert.deepEqual(messages, []); assert.equal(backend.projectMessages(snapshot, messages), messages); const calls = backend.projectToolCalls(snapshot); assert.deepEqual(calls, []); assert.equal(backend.projectToolCalls(snapshot, calls), calls); - const agent = backend.createAgentSession(session); const core = agent.getSnapshot(); assert.ok(Object.isFrozen(core)); - assert.deepEqual(core, { status: 'idle', messages: [], toolCalls: [] }); assert.equal(agent.getSnapshot(), core); - let coreNotifications = 0; agent.subscribe(() => coreNotifications++)(); assert.equal(coreNotifications, 0); + assert.deepEqual(snapshot, { status: 'idle', transcript: [], subagents: [], messages: [], toolCalls: [] }); + assert.equal(snapshot.messages, messages); assert.equal(snapshot.toolCalls, calls); assert.equal(backend.decisionState(snapshot), undefined); await session.dispose(); await session.dispose(); assert.equal(session.getSnapshot(), snapshot); assert.equal(notifications, 0); assert.equal(attempts, 0); @@ -450,7 +449,7 @@ export async function verifyAgUiCandidate({ root = defaultRoot, retain } = {}) { absWorkingDir: node, stdin: { contents: - "export { createAgentSession, createSession, decisionState, projectMessages, projectTextTranscript, projectToolCalls } from '@threadplane/ag-ui';", + "export { createSession, decisionState, projectMessages, projectTextTranscript, projectToolCalls } from '@threadplane/ag-ui';", resolveDir: node, }, bundle: true, From 016a1231306ae6b85d153741519151a2bcd82010 Mon Sep 17 00:00:00 2001 From: Brian Love Date: Wed, 18 Nov 2026 15:08:35 -0800 Subject: [PATCH 04/18] test(ag-ui): expect core fields on the session snapshot in the package verifiers --- scripts/react-parity/native-ag-ui-browser.mjs | 3 ++- scripts/react-parity/verify-ag-ui-candidate.mjs | 4 ++-- 2 files changed, 4 insertions(+), 3 deletions(-) diff --git a/scripts/react-parity/native-ag-ui-browser.mjs b/scripts/react-parity/native-ag-ui-browser.mjs index 38e57dc65..5b88b03d0 100644 --- a/scripts/react-parity/native-ag-ui-browser.mjs +++ b/scripts/react-parity/native-ag-ui-browser.mjs @@ -104,7 +104,8 @@ export async function verifyBrowser(browser, server) { }); assert.equal(partial.a.subagents[0].started.name, 'Worker'); assert.equal(partial.a.subagents[0].terminal, undefined); - assert.equal(partial.a.toolCalls, undefined); + // The core tool calls withhold a call whose arguments are still arriving. + assert.deepEqual(partial.a.toolCalls, []); await text('React A', ['First']); await text('Angular A', ['First']); await toolText('React', '{"city":'); diff --git a/scripts/react-parity/verify-ag-ui-candidate.mjs b/scripts/react-parity/verify-ag-ui-candidate.mjs index e37f86a78..974edf806 100644 --- a/scripts/react-parity/verify-ag-ui-candidate.mjs +++ b/scripts/react-parity/verify-ag-ui-candidate.mjs @@ -77,8 +77,8 @@ export function check() { const react = useAgent(session), angular = observeAgent(session)(); const same: typeof react = angular; react.transcript; angular.subagents; - // @ts-expect-error No core message aggregate is manufactured. - react.messages; + // The session publishes the core fields beside its protocol evidence. + react.messages; angular.toolCalls; // @ts-expect-error Native snapshots remain readonly through Angular. angular.state = {}; return same; From 72675d93a165fc95d5e18e32d52990bdc304484f Mon Sep 17 00:00:00 2001 From: Brian Love Date: Thu, 19 Nov 2026 08:49:57 -0800 Subject: [PATCH 05/18] 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 06/18] 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 07/18] 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' } }, From d31ac514b23d9698abb412986c83e095b8f29618 Mon Sep 17 00:00:00 2001 From: Brian Love Date: Thu, 19 Nov 2026 11:37:58 -0800 Subject: [PATCH 08/18] docs(ag-ui): the candidate emits the core session, not a view Co-Authored-By: Claude Opus 5.5 --- libs/ag-ui/src/runtime/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/libs/ag-ui/src/runtime/README.md b/libs/ag-ui/src/runtime/README.md index 5ec6d1660..f65253785 100644 --- a/libs/ag-ui/src/runtime/README.md +++ b/libs/ag-ui/src/runtime/README.md @@ -2,7 +2,7 @@ The test-only [candidate package proof](../../../../fixtures/react-parity/ag-ui-candidate/README.md) emits this actual owner, its text selector, its core message and tool-call -selectors and its core session view with complete declarations, then runs +selectors and its core session with complete declarations, then runs the existing browser and local-provider oracles against installed tarballs. It does not change this private API's status or the current published Angular root. From 1b4a8f82314ac1814e1e0eda88284c70ee53fd4e Mon Sep 17 00:00:00 2001 From: Brian Love Date: Thu, 19 Nov 2026 11:56:41 -0800 Subject: [PATCH 09/18] feat(ag-ui): answer interrupts through the core resume command and publish core child agents --- .../interrupts/react/src/application.spec.ts | 3 +- .../ag-ui/interrupts/react/src/application.ts | 9 +- .../interrupts/react/src/approval-policy.ts | 8 +- .../aws-strands/react/src/application.spec.ts | 5 +- .../aws-strands/react/src/application.ts | 3 +- .../aws-strands/react/src/approval-policy.ts | 11 +- .../mastra/react/src/application.spec.ts | 15 +- .../runtimes/mastra/react/src/application.ts | 3 +- .../mastra/react/src/approval-policy.ts | 4 +- .../react/src/application.spec.ts | 3 +- .../react/src/application.ts | 3 +- .../react/src/approval-policy.ts | 6 +- .../ag-ui-candidate/installed-types.ts | 31 ++- .../native-ag-ui-a2ui/installed-types.ts | 3 +- fixtures/react-parity/native-ag-ui/README.md | 6 +- .../react-parity/native-ag-ui/browser.tsx | 10 +- libs/ag-ui/src/runtime/README.md | 80 ++++--- libs/ag-ui/src/runtime/agent-session.ts | 45 +++- .../src/runtime/child-projection.spec.ts | 201 ++++++++++++++++++ libs/ag-ui/src/runtime/child-projection.ts | 113 ++++++++++ .../runtime/client-tools-session-http.spec.ts | 12 +- libs/ag-ui/src/runtime/create-session.ts | 89 ++++---- libs/ag-ui/src/runtime/decision-state.spec.ts | 37 ++-- libs/ag-ui/src/runtime/decision.spec.ts | 59 ++--- libs/ag-ui/src/runtime/decision.ts | 28 ++- libs/ag-ui/src/runtime/decision.type-test.ts | 74 +++++-- libs/ag-ui/src/runtime/resume-http.spec.ts | 58 +++-- libs/ag-ui/src/runtime/resume.spec.ts | 159 +++++++------- libs/ag-ui/src/runtime/session-http.spec.ts | 46 ++-- libs/angular/src/observe-agent.ag-ui.spec.ts | 9 +- libs/react/src/chat/ag-ui-session.spec.tsx | 54 ++++- libs/react/src/use-agent.ag-ui.spec.tsx | 9 +- scripts/react-parity/dispositions.json | 12 ++ scripts/react-parity/native-mastra-runner.ts | 38 ++-- 34 files changed, 865 insertions(+), 381 deletions(-) create mode 100644 libs/ag-ui/src/runtime/child-projection.spec.ts create mode 100644 libs/ag-ui/src/runtime/child-projection.ts diff --git a/cockpit/ag-ui/interrupts/react/src/application.spec.ts b/cockpit/ag-ui/interrupts/react/src/application.spec.ts index 1bcfd0e6a..dac3f7ac8 100644 --- a/cockpit/ag-ui/interrupts/react/src/application.spec.ts +++ b/cockpit/ag-ui/interrupts/react/src/application.spec.ts @@ -182,12 +182,11 @@ it.each(['approve', 'edit', 'cancel'] as const)( action === 'edit' ? 20 : undefined ); expect(session.resume).toHaveBeenCalledWith( - approval.pause, [ { interruptId: approval.interruptId, status: 'resolved', - payload: + value: action === 'cancel' ? { approved: false } : action === 'edit' diff --git a/cockpit/ag-ui/interrupts/react/src/application.ts b/cockpit/ag-ui/interrupts/react/src/application.ts index 329040a76..e83f29560 100644 --- a/cockpit/ag-ui/interrupts/react/src/application.ts +++ b/cockpit/ag-ui/interrupts/react/src/application.ts @@ -436,8 +436,13 @@ export function createInterruptsApplication(options: { : { approved: true }; if (selected.unsafe || !ownedValid()) return; const pending = selected.session.resume( - approval.pause, - [{ interruptId: approval.interruptId, status: 'resolved', payload }], + [ + { + interruptId: approval.interruptId, + status: 'resolved', + value: payload, + }, + ], { signal: admitted.signal } ); void pending.catch(() => undefined); diff --git a/cockpit/ag-ui/interrupts/react/src/approval-policy.ts b/cockpit/ag-ui/interrupts/react/src/approval-policy.ts index 4038905be..86ff1059a 100644 --- a/cockpit/ag-ui/interrupts/react/src/approval-policy.ts +++ b/cockpit/ag-ui/interrupts/react/src/approval-policy.ts @@ -1,4 +1,8 @@ -import type { Session, TextTranscriptRow } from '@threadplane/ag-ui'; +import type { + DecisionState, + Session, + TextTranscriptRow, +} from '@threadplane/ag-ui'; export type NativeSnapshot = ReturnType; export interface OwnedTurn { readonly threadId: string; @@ -9,7 +13,7 @@ export interface OwnedTurn { export interface RefundApproval { readonly threadId: string; readonly sourceRunId: string; - readonly pause: Parameters[0]; + readonly pause: Extract['id']; readonly interruptId: string; readonly amount: number; readonly customerId: string; diff --git a/cockpit/runtimes/aws-strands/react/src/application.spec.ts b/cockpit/runtimes/aws-strands/react/src/application.spec.ts index 2b41a301e..19a5a6bcb 100644 --- a/cockpit/runtimes/aws-strands/react/src/application.spec.ts +++ b/cockpit/runtimes/aws-strands/react/src/application.spec.ts @@ -690,12 +690,11 @@ it.each([true, false])( void h.app.decide(a, 'approve', 0); expect(h.session.resume).toHaveBeenCalledTimes(1); expect(h.session.resume).toHaveBeenCalledWith( - a.pause, [ { interruptId: 'opaque-native-interrupt', status: 'resolved', - payload: { approved }, + value: { approved }, }, ], expect.anything() @@ -822,7 +821,7 @@ it('Stop during resume aborts and makes late completion powerless', async () => const h = harness(), a = await h.pause(), pending = h.app.decide(a, 'approve', 0); - const options = vi.mocked(h.session.resume).mock.calls[0][2]; + const options = vi.mocked(h.session.resume).mock.calls[0][1]; const stopped = h.app.stop(); expect(options?.signal?.aborted).toBe(true); expect(h.app.getSnapshot().approval).toBeUndefined(); diff --git a/cockpit/runtimes/aws-strands/react/src/application.ts b/cockpit/runtimes/aws-strands/react/src/application.ts index ed4117105..abeb09e29 100644 --- a/cockpit/runtimes/aws-strands/react/src/application.ts +++ b/cockpit/runtimes/aws-strands/react/src/application.ts @@ -547,12 +547,11 @@ export function createStrandsApplication(options: { p.approved = action === 'approve'; const pending = p.methods.resume.call( p.candidate, - approval.pause, [ { interruptId: approval.interruptId, status: 'resolved', - payload: { approved: p.approved }, + value: { approved: p.approved }, }, ], { signal: controller.signal } diff --git a/cockpit/runtimes/aws-strands/react/src/approval-policy.ts b/cockpit/runtimes/aws-strands/react/src/approval-policy.ts index 2edafe727..cb28d2c43 100644 --- a/cockpit/runtimes/aws-strands/react/src/approval-policy.ts +++ b/cockpit/runtimes/aws-strands/react/src/approval-policy.ts @@ -1,4 +1,4 @@ -import type { Session } from '@threadplane/ag-ui'; +import type { DecisionState, Session } from '@threadplane/ag-ui'; export type NativeSnapshot = ReturnType; type Transcript = NativeSnapshot['transcript']; export interface Meeting { @@ -15,7 +15,7 @@ export interface MeetingApproval { readonly threadId: string; readonly sourceRunId: string; /** Keep the original opaque branded occurrence, never decode an interrupt identifier. */ - readonly pause: Parameters[0]; + readonly pause: Extract['id']; readonly interruptId: string; readonly toolCallId: string; readonly meeting: Meeting; @@ -383,9 +383,10 @@ export function captureApproval( if (!valid()) return; const pause = original && - (Object.getOwnPropertyDescriptor(original, 'id')?.value as Parameters< - Session['resume'] - >[0]); + (Object.getOwnPropertyDescriptor(original, 'id')?.value as Extract< + DecisionState, + { kind: 'native' } + >['id']); if (!valid() || pause !== d.id) return; return Object.freeze({ threadId: turn.threadId, diff --git a/cockpit/runtimes/mastra/react/src/application.spec.ts b/cockpit/runtimes/mastra/react/src/application.spec.ts index ef4b443a3..7dcd88c08 100644 --- a/cockpit/runtimes/mastra/react/src/application.spec.ts +++ b/cockpit/runtimes/mastra/react/src/application.spec.ts @@ -180,15 +180,12 @@ it.each(['approve', 'decline'] as const)( const pending = h.app.decide(approval, action); await h.app.decide(approval, action === 'approve' ? 'decline' : 'approve'); expect(h.session.resume).toHaveBeenCalledTimes(1); - expect(vi.mocked(h.session.resume).mock.calls[0].slice(0, 2)).toEqual([ - 'opaque-pause', - [ - { - interruptId: 'opaque-interrupt', - status: 'resolved', - payload: { approved: action === 'approve' }, - }, - ], + expect(vi.mocked(h.session.resume).mock.calls[0][0]).toEqual([ + { + interruptId: 'opaque-interrupt', + status: 'resolved', + value: { approved: action === 'approve' }, + }, ]); h.finish(completed(action === 'approve'), 'success'); await pending; diff --git a/cockpit/runtimes/mastra/react/src/application.ts b/cockpit/runtimes/mastra/react/src/application.ts index 3aba18f10..31530dfe9 100644 --- a/cockpit/runtimes/mastra/react/src/application.ts +++ b/cockpit/runtimes/mastra/react/src/application.ts @@ -425,12 +425,11 @@ export function createMastraApplication(options: { if (!ownedValid() || p.unsafe) return; const pending = method.call( p.session, - approval.pause, [ { interruptId: approval.interruptId, status: 'resolved', - payload: { approved: p.approved }, + value: { approved: p.approved }, }, ], { signal: controller.signal } diff --git a/cockpit/runtimes/mastra/react/src/approval-policy.ts b/cockpit/runtimes/mastra/react/src/approval-policy.ts index cce0dd5ab..e1bd47d5f 100644 --- a/cockpit/runtimes/mastra/react/src/approval-policy.ts +++ b/cockpit/runtimes/mastra/react/src/approval-policy.ts @@ -1,4 +1,4 @@ -import type { Session } from '@threadplane/ag-ui'; +import type { DecisionState, Session } from '@threadplane/ag-ui'; export type NativeSnapshot = ReturnType; type Transcript = NativeSnapshot['transcript']; export interface OwnedTurn { @@ -10,7 +10,7 @@ export interface OwnedTurn { export interface ReservationApproval { readonly threadId: string; readonly sourceRunId: string; - readonly pause: Parameters[0]; + readonly pause: Extract['id']; readonly interruptId: string; readonly toolCallId: string; readonly site: string; diff --git a/cockpit/runtimes/microsoft-agent-framework/react/src/application.spec.ts b/cockpit/runtimes/microsoft-agent-framework/react/src/application.spec.ts index 864b14e42..5513bcbb1 100644 --- a/cockpit/runtimes/microsoft-agent-framework/react/src/application.spec.ts +++ b/cockpit/runtimes/microsoft-agent-framework/react/src/application.spec.ts @@ -634,8 +634,7 @@ it.each([true, false])( void h.app.decide(a, 'approve', 0); expect(h.session.resume).toHaveBeenCalledTimes(1); expect(h.session.resume).toHaveBeenCalledWith( - a.pause, - [{ interruptId: 'call', status: 'resolved', payload: { approved } }], + [{ interruptId: 'call', status: 'resolved', value: { approved } }], expect.anything() ); h.update(completed(approved)); diff --git a/cockpit/runtimes/microsoft-agent-framework/react/src/application.ts b/cockpit/runtimes/microsoft-agent-framework/react/src/application.ts index 77535a8f5..cc17d7be3 100644 --- a/cockpit/runtimes/microsoft-agent-framework/react/src/application.ts +++ b/cockpit/runtimes/microsoft-agent-framework/react/src/application.ts @@ -548,12 +548,11 @@ export function createMafApplication(options: { p.approved = action === 'approve'; const pending = p.methods.resume.call( p.candidate, - approval.pause, [ { interruptId: approval.interruptId, status: 'resolved', - payload: { approved: p.approved }, + value: { approved: p.approved }, }, ], { signal: controller.signal } diff --git a/cockpit/runtimes/microsoft-agent-framework/react/src/approval-policy.ts b/cockpit/runtimes/microsoft-agent-framework/react/src/approval-policy.ts index 82294173e..9e3924dff 100644 --- a/cockpit/runtimes/microsoft-agent-framework/react/src/approval-policy.ts +++ b/cockpit/runtimes/microsoft-agent-framework/react/src/approval-policy.ts @@ -1,4 +1,4 @@ -import type { Session } from '@threadplane/ag-ui'; +import type { DecisionState, Session } from '@threadplane/ag-ui'; export type NativeSnapshot = ReturnType; type Transcript = NativeSnapshot['transcript']; export interface Expense { @@ -17,7 +17,7 @@ export interface ExpenseApproval { readonly threadId: string; readonly sourceRunId: string; /** Original opaque native occurrence; never reconstruct from observation data. */ - readonly pause: Parameters[0]; + readonly pause: Extract['id']; readonly interruptId: string; readonly toolCallId: string; readonly expense: Expense; @@ -432,7 +432,7 @@ export function captureApproval( const pause = originalDecision && (Object.getOwnPropertyDescriptor(originalDecision, 'id') - ?.value as Parameters[0]); + ?.value as Extract['id']); if (!valid() || pause !== d.id) return; return Object.freeze({ threadId: turn.threadId, diff --git a/fixtures/react-parity/ag-ui-candidate/installed-types.ts b/fixtures/react-parity/ag-ui-candidate/installed-types.ts index 419a9abb9..0cd259fd6 100644 --- a/fixtures/react-parity/ag-ui-candidate/installed-types.ts +++ b/fixtures/react-parity/ag-ui-candidate/installed-types.ts @@ -22,7 +22,7 @@ import type { Message, ToolCall, } from '@threadplane/core'; -export type NativeResponse = Parameters[1][number]; +export type NativeResponse = Parameters[0][number]; export function checkCandidate(signal: AbortSignal) { const options: SessionOptions = { threadId: 'candidate', @@ -51,7 +51,7 @@ export function checkCandidate(signal: AbortSignal) { const resolved: NativeResponse = { interruptId: 'backend-id', status: 'resolved', - payload: null, + value: null, metadata: { reviewed: true }, }; const cancelled: NativeResponse = { @@ -59,13 +59,17 @@ export function checkCandidate(signal: AbortSignal) { status: 'cancelled', }; if (snapshot.decision?.kind === 'native') { - void session.resume(snapshot.decision.id, [resolved], { signal }); - void session.resume(snapshot.decision.id, [cancelled]); - // @ts-expect-error Pause generations are branded, not arbitrary strings. - void session.resume('backend-id', [resolved]); - void session.resume(snapshot.decision.id, [ - // @ts-expect-error Cancelled native responses cannot carry a payload. - { interruptId: 'backend-id', status: 'cancelled', payload: null }, + void session.resume([resolved], { signal }); + void session.resume([cancelled]); + // @ts-expect-error Resume takes the responses alone, with no pause id. + void session.resume(snapshot.decision.id, [resolved]); + void session.resume([ + // @ts-expect-error A cancelled response cannot carry a value. + { interruptId: 'backend-id', status: 'cancelled', value: null }, + ]); + void session.resume([ + // @ts-expect-error The answer is the response's value, not a payload. + { interruptId: 'backend-id', status: 'resolved', payload: null }, ]); // @ts-expect-error Decision evidence is readonly. snapshot.decision.interrupts.push({ id: 'changed' }); @@ -92,7 +96,7 @@ export function checkCandidate(signal: AbortSignal) { void session.addToolResult('id', 'result'); const pending: DecisionState | undefined = decisionState(snapshot); if (pending?.kind === 'native' && pending.phase === 'ready') { - void session.resume(pending.id, [ + void session.resume([ { interruptId: pending.interrupts[0].id, status: 'resolved' }, ]); // @ts-expect-error The pending decision is readonly. @@ -107,6 +111,13 @@ export function checkCandidate(signal: AbortSignal) { void agent.submit({ message: 'Hello', state: { topic: 'x' } }); // @ts-expect-error A submission takes a message and state only. void agent.submit({ message: 'Hello', messages: [] }); + // The session's resume is the core contract's command. + const resumed: Promise | undefined = agent.resume?.([ + { interruptId: 'backend-id', status: 'resolved', value: true }, + ]); + const waiting: string | undefined = core.interrupts?.[0]?.id; + const child: string | undefined = core.subagents?.[0]?.id; + void [resumed, waiting, child]; const regenerated: Promise | undefined = session.regenerate?.('assistant-id', { signal }); void regenerated; diff --git a/fixtures/react-parity/native-ag-ui-a2ui/installed-types.ts b/fixtures/react-parity/native-ag-ui-a2ui/installed-types.ts index dbcb9c5cd..77b3389cd 100644 --- a/fixtures/react-parity/native-ag-ui-a2ui/installed-types.ts +++ b/fixtures/react-parity/native-ag-ui-a2ui/installed-types.ts @@ -31,8 +31,7 @@ export function checkInstalledA2ui(signal: AbortSignal) { } if (snapshot.decision?.kind === 'native') void owner.resume( - snapshot.decision.id, - [{ interruptId: 'i', status: 'resolved', payload: null }], + [{ interruptId: 'i', status: 'resolved', value: null }], { signal } ); void [snapshot.status, snapshot.state, snapshot.subagents]; diff --git a/fixtures/react-parity/native-ag-ui/README.md b/fixtures/react-parity/native-ag-ui/README.md index 73889fccb..5f14ce315 100644 --- a/fixtures/react-parity/native-ag-ui/README.md +++ b/fixtures/react-parity/native-ag-ui/README.md @@ -53,8 +53,8 @@ Use each enabled control in order: retains the earlier custom notice beside that terminal. 3. **Mount React** reconnects observation without a request and displays both the retained notice and native terminal. -4. **Resume** uses the observed native pause token and an explicit resolved - `approval` response with payload `{ approved: true }`. It sends full prior native +4. **Resume** answers the observed native pause with an explicit resolved + `approval` response whose value is `{ approved: true }`. It sends full prior native history and `count: 2`, adds no user row or settings patch, then shows root `Next answer`. The diagnostic decision contains the captured running attempt. 5. **Remove Angular**, then **Complete resume**. React receives successful @@ -85,7 +85,7 @@ ending at EOF would be `interrupted`; local cancellation can be `aborted` even after terminal evidence was observed. Explicit private `legacy-observation` mode retains the older close-at-notice convention but supplies no resume capability. Any decision blocks ordinary submission. Only a settled unclaimed native pause -can be answered once with its current token; legacy notices cannot be resumed. +can be answered once; legacy notices cannot be resumed. If an invoked resume fails, ends at EOF or is stopped without conclusive native evidence, its retained attempt is uncertain and blocks replay and ordinary bypass. Local stop or reconstructing an owner is not recovery. Separate held HTTP tests diff --git a/fixtures/react-parity/native-ag-ui/browser.tsx b/fixtures/react-parity/native-ag-ui/browser.tsx index abac227fe..c566c9b07 100644 --- a/fixtures/react-parity/native-ag-ui/browser.tsx +++ b/fixtures/react-parity/native-ag-ui/browser.tsx @@ -16,7 +16,11 @@ import { TextTranscriptComponent, ToolObservationComponent, } from '@threadplane/angular/chat'; -import { createSession, projectTextTranscript, type Session } from './backend-binding.js'; +import { + createSession, + projectTextTranscript, + type Session, +} from './backend-binding.js'; const sequence = [ 'First', @@ -249,11 +253,11 @@ function start(session: Session, text: string) { const command = text === 'Resume' ? decision?.kind === 'native' - ? session.resume(decision.id, [ + ? session.resume([ { interruptId: 'approval', status: 'resolved', - payload: { approved: true }, + value: { approved: true }, }, ]) : Promise.reject(new Error('A current native pause is required')) diff --git a/libs/ag-ui/src/runtime/README.md b/libs/ag-ui/src/runtime/README.md index 5ec6d1660..aae9797bc 100644 --- a/libs/ag-ui/src/runtime/README.md +++ b/libs/ag-ui/src/runtime/README.md @@ -140,15 +140,31 @@ const session = createSession({ threadId, url }); ``` - `getSnapshot` returns the core snapshot, - `{ status, messages, toolCalls, error?, plan?, usage?, state?, stateIssues? }`, - together with the protocol evidence behind it: `transcript`, `subagents`, + `{ status, messages, toolCalls, error?, plan?, usage?, state?, stateIssues?, interrupts?, subagents }`, + together with the protocol evidence behind it: `transcript`, `earlierSubagents`, `decision`, `reasoningDurations` and `run`. `messages` and `toolCalls` are what the two selectors above return, and keep their references until they change. One publication always reads as one snapshot. +- `interrupts` lists what a paused run waits on, from the pause until an answer + is sent. Each entry is the protocol's interrupt, so it has the core `id`, + `reason`, `message` and `toolCallId` and any other field the backend sent. It + is absent when nothing is waiting, and for a pause this session cannot answer. +- `subagents` lists the current run's children as core child agents: `id`, + `name`, `description`, `toolCallId`, `parentId`, `status`, and the child's own + `messages` and `toolCalls`, which the root lists do not repeat. The protocol + evidence stays on each child as `started` and `terminal`. A child with + finished evidence is `complete`, one with error evidence is `error` and + carries its message, and one with neither is `running` while the root run is + going and `unknown` after it. A child keeps its reference until its evidence, + status or records change. Children of earlier runs are bare evidence in + `earlierSubagents`. Records are matched by run id, so a later child that + reuses an id also lists the earlier child's records. - Every publication notifies subscribers, including one that changes only protocol evidence such as a decision or a child. -- `submit` takes text, or `{ message, state? }` with a state patch. `resume` - and the client-tool evidence are AG-UI additions to the core contract. +- `submit` takes text, or `{ message, state? }` with a state patch. +- `resume` is the core contract's command: it takes one response for each + pending interrupt, named by `id` (see "Correlated native resume"). +- The client-tool evidence is an AG-UI addition to the core contract. - A failed run becomes `snapshot.error`. A backend `RUN_ERROR` is a `server` error carrying the backend's message. A stream that ended without a terminal is `interrupted`. A response that was not OK carries its HTTP status: 401 and @@ -266,7 +282,7 @@ const pending = decisionState(useAgent(session)); id: 'approve', label: 'Issue refund', onSelect: () => - void session.resume(pending.id, [ + void session.resume([ { interruptId: pending.interrupts[0].id, status: 'resolved' }, ]), }, @@ -287,8 +303,8 @@ const pending = decisionState(useAgent(session)); the answer. An uncertain answer cannot be sent again. - The same decision in the same phase returns the same reference. - `ready` does not look at the clock: an interrupt past its `expiresAt` still - reads `ready`, and `resume` then resolves `error`. -- What the buttons mean, and which payload answers which interrupt, stay with + reads `ready`, and `resume` then rejects. +- What the buttons mean, and which value answers which interrupt, stay with the app. Response schemas are not interpreted. The candidate package entry exports it. The published package root does not. @@ -342,36 +358,44 @@ Child notices do not create root decisions. Duplicate interrupt IDs retain an unsupported blocker. The locked SDK rejects empty wire batches before delivery; that error preserves an existing blocker or claim and invents no terminal. -After the native pause has locally settled, explicitly answer its current token: +After the native pause has locally settled, answer its interrupts with the core +contract's `resume`: ```ts const snapshot = session.getSnapshot(); -if ( - snapshot.decision?.kind === 'native' && - !snapshot.decision.attempt && - snapshot.run?.outcome -) { - await session.resume(snapshot.decision.id, [ - { - interruptId: 'approval', +if (snapshot.interrupts?.length && snapshot.run?.outcome) { + await session.resume( + snapshot.interrupts.map((interrupt) => ({ + interruptId: interrupt.id, status: 'resolved', - payload: { approved: true }, - }, - ]); + value: { approved: true }, + })) + ); } ``` -Every observed interrupt needs exactly one response with its exact ID. Resolved -responses may omit payload; a `null` payload is treated as absent (the AG-UI 1.0 -client omits whole-optional nulls on the wire). Cancelled responses use -`{ interruptId, status: 'cancelled' }` and cannot contain a defined payload. -Optional metadata must be a plain record. Responses and the options signal are +`resume` takes the responses alone and answers the pause that is pending; there +is no pause token to pass. Every pending interrupt needs exactly one response +with its exact ID. A resolved response may omit `value`; a `null` value is +treated as absent (the AG-UI 1.0 client omits whole-optional nulls on the wire). +The request carries the value as the protocol's `payload`, and so does +`decision.attempt.responses`. A cancelled response is +`{ interruptId, status: 'cancelled' }` and cannot carry a value. A response may +also carry the protocol's optional `metadata`, which must be a plain record. + +`resume` rejects with a `TypeError`, sending nothing, when no interrupt is +waiting, the pausing run has not settled, an answer was already sent, a run is +active, an interrupt has expired, the responses are not an array, a response +names an interrupt that is not pending or names one twice, or an interrupt is +left unanswered. It resolves `aborted`, sending nothing, after disposal and when +its signal is already aborted. Once the answer is sent it resolves with that +run's outcome. Responses and the options signal are captured once before queueing; nested data is copied and frozen without freezing the caller. Extra runtime getters are ignored. Response schemas are opaque; this owner neither validates business answers nor guesses defaults or aliases. -Eligibility is checked at invocation and admission. The token must identify the -current unclaimed native generation, the current run must be locally settled, +Eligibility is checked at invocation and admission. The pending decision must be +the current unclaimed native generation, the current run must be locally settled, and every supplied expiry must parse to a time strictly in the future. An observing terminal callback cannot enqueue future resume intent before settlement. Two observers can claim only once. Admission publishes the attempt and new run @@ -389,14 +413,14 @@ controls, not backend rejection or recovery. Each private run result reports `fetchInvoked`, recorded immediately before the captured fetch call. A claim cancelled before that boundary is released and can -be retried with the same token. Once fetch was invoked, failure, EOF or abort +be retried. Once fetch was invoked, failure, EOF or abort without conclusive native evidence retains the attempt and forbids replay or ordinary bypass. `RUN_STARTED`, local promise completion and exception properties do not establish server acknowledgement or socket closure. No retry, reset, session reconstruction or persistence/recovery guarantee is provided. Native success clears the decision at local settlement, even if a terminal -listener selected local `aborted`. A new native pause receives a fresh token even +listener selected local `aborted`. A new native pause is a fresh generation even when backend interrupt IDs repeat; old finalizers cannot clear that generation. Legacy observation has no resume support. Captured Strands replay establishes native response wire shape with synthetic completion only. Captured Mastra and diff --git a/libs/ag-ui/src/runtime/agent-session.ts b/libs/ag-ui/src/runtime/agent-session.ts index cfd13d36c..090f8fbbc 100644 --- a/libs/ag-ui/src/runtime/agent-session.ts +++ b/libs/ag-ui/src/runtime/agent-session.ts @@ -1,6 +1,7 @@ import { readState, type AgentError, + type AgentInterrupt, type AgentSnapshot, type AgentUsage, type AgentUsageEntry, @@ -8,12 +9,11 @@ import { type StateDeclaration, type ToolContract, } from '@threadplane/core'; +import { projectSubagents, type SessionSubagent } from './child-projection.js'; +import type { OwnedInterrupt } from './decision.js'; import { NO_STATE, ownState } from './state.js'; import { projectMessages, projectToolCalls } from './message-projection.js'; -import { - failedWithRunError, - type Observation, -} from './session-observation.js'; +import { failedWithRunError, type Observation } from './session-observation.js'; type Tools = Record; /** @@ -21,8 +21,23 @@ type Tools = Record; * evidence behind it. `state` is the typed state; the literal document a * request sends is not published. */ -export type SessionSnapshot = Omit & - AgentSnapshot & { +export type SessionSnapshot = Omit< + Observation, + 'state' | 'subagents' +> & + Omit, 'interrupts' | 'subagents'> & { + /** + * What a paused run waits on, each with the protocol's own fields. Listed + * from the pause until an answer is sent, and absent otherwise; a pause + * this session cannot answer lists nothing. + */ + readonly interrupts?: readonly SessionInterrupt[]; + /** + * The current root run's children, each with its own messages and tool + * calls and the protocol evidence it was read from. Children of earlier + * runs are in `earlierSubagents`. + */ + readonly subagents: readonly SessionSubagent[]; /** * Why the session's state schema rejected the current state document. * `state` then keeps the last document that passed. Absent while the @@ -31,6 +46,9 @@ export type SessionSnapshot = Omit & readonly stateIssues?: readonly string[]; }; +/** A pending interrupt: the core interrupt, with the protocol's own fields. */ +export type SessionInterrupt = AgentInterrupt & OwnedInterrupt; + /** The state to publish for one state document, and why a schema rejected it. */ interface StateView { readonly source: PlainValue; @@ -99,8 +117,10 @@ function failure( terminal?.type === 'RUN_ERROR' && 'message' in terminal ? terminal.message : undefined; - const interrupted = reported === undefined && native.run?.outcome === 'interrupted'; - const status = reported === undefined ? native.run?.failure?.status : undefined; + const interrupted = + reported === undefined && native.run?.outcome === 'interrupted'; + const status = + reported === undefined ? native.run?.failure?.status : undefined; const auth = status === 401 || status === 403; const kind = interrupted ? 'interrupted' : auth ? 'auth' : 'server'; const message = interrupted @@ -189,11 +209,18 @@ function project( ? failure(native, canRetry, previous?.error) : undefined; const used = usage(native); - const { state: _document, ...evidence } = native; + const { state: _document, subagents: _children, ...evidence } = native; + const decision = native.decision; + const interrupts = + decision?.kind === 'native' && !decision.attempt + ? decision.interrupts + : undefined; return Object.freeze({ ...evidence, messages, toolCalls, + subagents: projectSubagents(native, previous?.subagents), + ...(interrupts && { interrupts }), ...(error && { error }), ...(used && { usage: used }), ...(view.state !== undefined && { state: view.state }), diff --git a/libs/ag-ui/src/runtime/child-projection.spec.ts b/libs/ag-ui/src/runtime/child-projection.spec.ts new file mode 100644 index 000000000..7b8d3e9d0 --- /dev/null +++ b/libs/ag-ui/src/runtime/child-projection.spec.ts @@ -0,0 +1,201 @@ +import type { AgentSession } from '@threadplane/core'; +import { describe, expect, it } from 'vitest'; +import { bindingFixture } from './testing/binding-fixture'; + +describe('core interrupts and child agents on the AG-UI snapshot', () => { + it('publishes each child with its own messages and tool calls', async () => { + const fixture = bindingFixture(); + try { + const run = fixture.session.submit('Research it'); + const exchange = await fixture.started(); + const streamed = fixture.changed( + (snapshot) => + snapshot.subagents[0]?.messages[0]?.content === 'Two sources' + ); + exchange.emit({ + type: 'TEXT_MESSAGE_START', + messageId: 'root', + role: 'assistant', + }); + exchange.emit({ + type: 'TOOL_CALL_START', + toolCallId: 'delegate', + toolCallName: 'task', + parentMessageId: 'root', + }); + exchange.emit({ + type: 'SUBAGENT_STARTED', + subagentRunId: 'child', + name: 'researcher', + description: 'Find the sources', + parentToolCallId: 'delegate', + }); + exchange.emit({ + type: 'TEXT_MESSAGE_START', + messageId: 'finding', + role: 'assistant', + subagentRunId: 'child', + }); + exchange.emit({ + type: 'TEXT_MESSAGE_CONTENT', + messageId: 'finding', + delta: 'Two sources', + }); + exchange.emit({ type: 'TEXT_MESSAGE_END', messageId: 'finding' }); + await streamed; + const running = fixture.session.getSnapshot(); + expect(running.subagents).toHaveLength(1); + const child = running.subagents[0]; + expect(child).toMatchObject({ + id: 'child', + name: 'researcher', + description: 'Find the sources', + toolCallId: 'delegate', + status: 'running', + toolCalls: [], + }); + expect(child.messages.map((message) => message.content)).toEqual([ + 'Two sources', + ]); + // The child's messages are its own: the root transcript does not repeat them. + expect(running.messages.map((message) => message.id)).not.toContain( + 'finding' + ); + // The protocol evidence stays alongside the core fields. + expect(child.started.subagentRunId).toBe('child'); + expect(child.terminal).toBeUndefined(); + + // A publication that does not touch the child keeps its reference. + const worked = fixture.changed((snapshot) => + snapshot.messages.some((message) => message.content === 'Working') + ); + exchange.emit({ + type: 'TEXT_MESSAGE_CONTENT', + messageId: 'root', + delta: 'Working', + }); + await worked; + expect(fixture.session.getSnapshot().subagents).toBe(running.subagents); + + const ended = fixture.changed( + (snapshot) => snapshot.subagents[0]?.terminal !== undefined + ); + exchange.emit({ + type: 'SUBAGENT_ERROR', + subagentRunId: 'child', + message: 'The search failed', + }); + await ended; + const failed = fixture.session.getSnapshot().subagents[0]; + expect(failed).not.toBe(child); + expect(failed).toMatchObject({ + id: 'child', + status: 'error', + error: 'The search failed', + }); + // A child that has ended streams nothing further. + expect(child.messages[0].delivery.phase).toBe('streaming'); + expect(failed.messages[0].delivery.phase).toBe('complete'); + + exchange.emit({ type: 'TOOL_CALL_END', toolCallId: 'delegate' }); + exchange.emit({ type: 'TEXT_MESSAGE_END', messageId: 'root' }); + exchange.emit({ + type: 'RUN_FINISHED', + threadId: exchange.body.threadId, + runId: exchange.body.runId, + }); + await expect(run).resolves.toBe('success'); + // A core observer reads the same children. + const observer: AgentSession = fixture.session; + expect(observer.getSnapshot().subagents?.[0]?.id).toBe('child'); + } finally { + await fixture.cleanup(); + } + }); + + it('reports a child with no ending as unknown once the run settles', async () => { + const fixture = bindingFixture(); + try { + const run = fixture.session.submit('Go'); + const exchange = await fixture.started(); + const seen = fixture.changed( + (snapshot) => snapshot.subagents.length === 1 + ); + exchange.emit({ + type: 'SUBAGENT_STARTED', + subagentRunId: 'open', + name: 'worker', + }); + await seen; + expect(fixture.session.getSnapshot().subagents[0].status).toBe('running'); + exchange.emit({ + type: 'RUN_FINISHED', + threadId: exchange.body.threadId, + runId: exchange.body.runId, + }); + // The protocol requires every child to end before its run does. + await expect(run).resolves.toBe('error'); + expect(fixture.session.getSnapshot().subagents[0].status).toBe('unknown'); + } finally { + await fixture.cleanup(); + } + }); + + it('lists pending interrupts until an answer is sent, and answers them by id', async () => { + const fixture = bindingFixture(); + try { + expect('interrupts' in fixture.session.getSnapshot()).toBe(false); + const run = fixture.session.submit('Refund it'); + const exchange = await fixture.started(); + exchange.emit({ + type: 'RUN_FINISHED', + threadId: exchange.body.threadId, + runId: exchange.body.runId, + outcome: { + type: 'interrupt', + interrupts: [ + { id: 'approval', reason: 'approve', message: 'Refund $20?' }, + ], + }, + }); + await expect(run).resolves.toBe('paused'); + const paused = fixture.session.getSnapshot(); + expect(paused.interrupts).toEqual([ + { id: 'approval', reason: 'approve', message: 'Refund $20?' }, + ]); + // A core observer answers through the core command. + const observer: AgentSession = fixture.session; + await expect( + observer.resume?.([{ interruptId: 'other', status: 'resolved' }]) + ).rejects.toThrow(TypeError); + expect(fixture.session.getSnapshot()).toBe(paused); + const pending = observer.getSnapshot().interrupts ?? []; + const resumed = observer.resume?.( + pending.map((interrupt) => ({ + interruptId: interrupt.id, + status: 'resolved' as const, + value: { approved: true }, + })) + ); + const next = await fixture.started(1); + expect(next.body.resume).toEqual([ + { + interruptId: 'approval', + status: 'resolved', + payload: { approved: true }, + }, + ]); + // The answer is on its way: nothing is waiting on a person now. + expect('interrupts' in fixture.session.getSnapshot()).toBe(false); + next.emit({ + type: 'RUN_FINISHED', + threadId: next.body.threadId, + runId: next.body.runId, + }); + await expect(resumed).resolves.toBe('success'); + expect('interrupts' in fixture.session.getSnapshot()).toBe(false); + } finally { + await fixture.cleanup(); + } + }); +}); diff --git a/libs/ag-ui/src/runtime/child-projection.ts b/libs/ag-ui/src/runtime/child-projection.ts new file mode 100644 index 000000000..e29b602e1 --- /dev/null +++ b/libs/ag-ui/src/runtime/child-projection.ts @@ -0,0 +1,113 @@ +import type { AgentSubagent, Message, ToolCall } from '@threadplane/core'; +import { projectMessages, projectToolCalls } from './message-projection.js'; +import type { Observation } from './session-observation.js'; +import type { SubagentObservation } from './subagents.js'; +import type { Transcript } from './transcript.js'; + +type TranscriptRecord = Transcript[number]; + +/** + * One child of the current root run: the core child, with the protocol + * evidence it was read from. `messages` and `toolCalls` are the child's own + * and are not repeated in the root snapshot's. They are every transcript record + * attributed to the child's run id, so a later child that reuses an id also + * lists the earlier child's records. + */ +export type SessionSubagent = AgentSubagent & SubagentObservation; + +/** A child's records read as a root transcript, so the root selectors apply. */ +const unattributed = new WeakMap(); +function asRoot(record: TranscriptRecord): TranscriptRecord { + let known = unattributed.get(record); + if (!known) { + const { subagentRunId: _child, ...rest } = record as TranscriptRecord & { + subagentRunId?: string; + }; + known = Object.freeze(rest) as TranscriptRecord; + unattributed.set(record, known); + } + return known; +} + +function status( + evidence: SubagentObservation, + running: boolean +): AgentSubagent['status'] { + if (evidence.terminal) + return evidence.terminal.type === 'SUBAGENT_ERROR' ? 'error' : 'complete'; + return running ? 'running' : 'unknown'; +} + +const none: readonly SessionSubagent[] = Object.freeze([]); +const noMessages: readonly Message[] = Object.freeze([]); +const noCalls: readonly ToolCall[] = Object.freeze([]); + +/** + * The current run's children as core children. Each keeps its reference, and + * the list keeps its own, until that child's evidence, status or transcript + * changes. `previous` is the list this function returned last. + */ +export function projectSubagents( + native: Observation, + previous: readonly SessionSubagent[] = none +): readonly SessionSubagent[] { + if (!native.subagents.length) return previous.length ? none : previous; + const records = new Map(); + for (const record of native.transcript) { + const child = (record as { subagentRunId?: unknown }).subagentRunId; + if (typeof child !== 'string') continue; + const own = records.get(child); + if (own) own.push(asRoot(record)); + else records.set(child, [asRoot(record)]); + } + const prior = new Map(previous.map((child) => [child.id, child])); + const running = native.status === 'running'; + let changed = previous.length !== native.subagents.length; + const children = native.subagents.map((evidence, index) => { + const { started, terminal } = evidence; + const id = started.subagentRunId; + const before = prior.get(id); + const state = status(evidence, running); + // A child with terminal evidence streams nothing further. + const view = { + status: state === 'running' ? ('running' as const) : ('idle' as const), + transcript: Object.freeze(records.get(id) ?? []) as Transcript, + reasoningDurations: native.reasoningDurations, + }; + const messages = projectMessages(view, before?.messages ?? noMessages); + const toolCalls = projectToolCalls(view, before?.toolCalls ?? noCalls); + if ( + before && + before.started === started && + before.terminal === terminal && + before.status === state && + before.messages === messages && + before.toolCalls === toolCalls + ) { + if (previous[index] !== before) changed = true; + return before; + } + changed = true; + return Object.freeze({ + id, + ...(typeof started.name === 'string' && { name: started.name }), + ...(typeof started.description === 'string' && { + description: started.description, + }), + ...(typeof started.parentToolCallId === 'string' && { + toolCallId: started.parentToolCallId, + }), + ...(typeof started.parentSubagentRunId === 'string' && { + parentId: started.parentSubagentRunId, + }), + status: state, + messages, + toolCalls, + ...(terminal?.type === 'SUBAGENT_ERROR' && + typeof terminal.message === 'string' && { error: terminal.message }), + started, + ...(terminal && { terminal }), + }) as SessionSubagent; + }); + return changed ? Object.freeze(children) : previous; +} diff --git a/libs/ag-ui/src/runtime/client-tools-session-http.spec.ts b/libs/ag-ui/src/runtime/client-tools-session-http.spec.ts index 5aef450cc..f3b4cbc60 100644 --- a/libs/ag-ui/src/runtime/client-tools-session-http.spec.ts +++ b/libs/ag-ui/src/runtime/client-tools-session-http.spec.ts @@ -187,8 +187,8 @@ describe('native client tools over physical HTTP', () => { const paused = owner.getSnapshot(); if (paused.decision?.kind !== 'native') throw new Error('Missing pause'); - const done = owner.resume(paused.decision.id, [ - { interruptId: 'approve', status: 'resolved', payload: true }, + const done = owner.resume([ + { interruptId: 'approve', status: 'resolved', value: true }, ]); const resumed = await server.next(1); resumed.send( @@ -360,8 +360,8 @@ describe('native client tools over physical HTTP', () => { if (paused.decision?.kind !== 'native') throw new Error('Missing native pause'); expect(paused.run?.id).toBe(continuation.body.runId); - const done = owner.resume(paused.decision.id, [ - { interruptId: 'approve', status: 'resolved', payload: true }, + const done = owner.resume([ + { interruptId: 'approve', status: 'resolved', value: true }, ]); const resumed = await server.next(2); expect(resumed.body.resume).toEqual([ @@ -409,8 +409,8 @@ describe('native client tools over physical HTTP', () => { const paused = owner.getSnapshot(); if (paused.decision?.kind !== 'native') throw new Error('Missing native pause'); - const done = owner.resume(paused.decision.id, [ - { interruptId: 'approve', status: 'resolved', payload: true }, + const done = owner.resume([ + { interruptId: 'approve', status: 'resolved', value: true }, ]); const resumed = await server.next(1); resumed.send(lifecycle(resumed), lifecycle(resumed, 'RUN_FINISHED')); diff --git a/libs/ag-ui/src/runtime/create-session.ts b/libs/ag-ui/src/runtime/create-session.ts index 9e3b87c63..5d40a174c 100644 --- a/libs/ag-ui/src/runtime/create-session.ts +++ b/libs/ag-ui/src/runtime/create-session.ts @@ -53,9 +53,13 @@ import { claimDecision, observeDecision, settleDecision, + type InterruptResponse, type NativeResponse, type PauseId, } from './decision.js'; + +/** Why `resume` rejects while a run is active or the session cannot answer. */ +const NOT_SETTLED = 'Resume needs a settled session with a pending interrupt.'; import { copyData } from '../lib/internal/copy-data.js'; import { captureSubmit, @@ -98,9 +102,18 @@ export interface Session { input: SubmitInput, options?: { readonly signal?: AbortSignal } ): Promise; + /** + * Answers the pending interrupts, as the core contract's `resume`: one + * response for each interrupt in the snapshot's `interrupts`, naming it by + * `id`. A response may also carry the protocol's `metadata`. + * + * Rejects without sending when no interrupt is waiting, a run is active, an + * interrupt has expired, a response names an interrupt that is not pending + * or names one twice, or an interrupt is left unanswered. Resolves `aborted` + * without sending after disposal or when the signal is already aborted. + */ resume( - pause: PauseId, - responses: readonly NativeResponse[], + responses: readonly InterruptResponse[], options?: { readonly signal?: AbortSignal } ): Promise; stop(): Promise; @@ -453,8 +466,8 @@ export function createSession( disposed ? () => undefined : publication.subscribe(notify), onCustomEvent: (listener) => disposed ? () => undefined : publication.onCustomEvent(listener), - resume: (pause, responses, options) => - new Promise((resolve) => { + resume: (responses, options) => + new Promise((resolve, reject) => { const beforeSignal = revision; let signal: AbortSignal | undefined; try { @@ -472,20 +485,17 @@ export function createSession( try { const previous = publication.getObservation(); if (interruptMode !== 'native' || active) - throw new TypeError('Resume requires a settled native owner'); - assertResumeEligible( - previous.decision, - previous.run, - pause, - Date.now() - ); + throw new TypeError(NOT_SETTLED); captured = captureResponses(responses); - } catch { - resolve( - disposed || signal?.aborted || revision !== beforeInput - ? 'aborted' - : 'error' + claimDecision( + assertResumeEligible(previous.decision, previous.run, Date.now()), + captured, + '' ); + } catch (error) { + if (disposed || signal?.aborted || revision !== beforeInput) + resolve('aborted'); + else reject(error); return; } if (disposed || signal?.aborted || revision !== beforeInput) { @@ -503,11 +513,10 @@ export function createSession( try { const previous = publication.getObservation(); if (active || interruptMode !== 'native') - throw new TypeError('Resume requires a settled native owner'); + throw new TypeError(NOT_SETTLED); const decision = assertResumeEligible( previous.decision, previous.run, - pause, Date.now() ); id = crypto.randomUUID(); @@ -518,12 +527,10 @@ export function createSession( ...nextInvocationSubagents(previous), run: Object.freeze({ id }), }); - } catch { - resolve( - disposed || signal?.aborted || revision !== beforeAdmission - ? 'aborted' - : 'error' - ); + } catch (error) { + if (disposed || signal?.aborted || revision !== beforeAdmission) + resolve('aborted'); + else reject(error); return; } if (disposed || signal?.aborted || revision !== beforeAdmission) { @@ -1466,14 +1473,14 @@ function createToolsOwner( } }); }), - resume: (pause, responses, options) => - new Promise((resolve) => { + resume: (responses, options) => + new Promise((resolve, reject) => { if (disposed) { resolve('aborted'); return; } if (active || ledger.snapshot().blocker) { - resolve('error'); + reject(new TypeError(NOT_SETTLED)); return; } const before = revision; @@ -1486,21 +1493,18 @@ function createToolsOwner( return; } if (interruptMode !== 'native') - throw new TypeError('Native resume required'); + throw new TypeError(NOT_SETTLED); const previous = publication.getObservation(); - assertResumeEligible( - previous.decision, - previous.run, - pause, - Date.now() - ); captured = captureResponses(responses); - } catch { - resolve( - disposed || signal?.aborted || revision !== before - ? 'aborted' - : 'error' + claimDecision( + assertResumeEligible(previous.decision, previous.run, Date.now()), + captured, + '' ); + } catch (error) { + if (disposed || signal?.aborted || revision !== before) + resolve('aborted'); + else reject(error); return; } publication.command(() => { @@ -1509,7 +1513,7 @@ function createToolsOwner( return; } if (active || ledger.snapshot().blocker) { - resolve('error'); + reject(new TypeError(NOT_SETTLED)); return; } try { @@ -1517,7 +1521,6 @@ function createToolsOwner( const decision = assertResumeEligible( previous.decision, previous.run, - pause, Date.now() ); const id = crypto.randomUUID(); @@ -1533,8 +1536,8 @@ function createToolsOwner( signal, resolve ); - } catch { - resolve('error'); + } catch (error) { + reject(error); } }); }), diff --git a/libs/ag-ui/src/runtime/decision-state.spec.ts b/libs/ag-ui/src/runtime/decision-state.spec.ts index 3ad1d1946..0c796d3ed 100644 --- a/libs/ag-ui/src/runtime/decision-state.spec.ts +++ b/libs/ag-ui/src/runtime/decision-state.spec.ts @@ -1,9 +1,5 @@ import { describe, expect, it } from 'vitest'; -import { - decisionState, - type NativeDecision, - type PauseId, -} from './decision'; +import { decisionState, type NativeDecision, type PauseId } from './decision'; import { bindingFixture } from './testing/binding-fixture'; const id = '00000000-0000-4000-8000-000000000001' as PauseId; @@ -29,7 +25,9 @@ const claimed: NativeDecision = Object.freeze({ describe('decisionState', () => { it('is absent when nothing is waiting', () => { expect(decisionState({})).toBeUndefined(); - expect(decisionState({ run: { id: 'run', outcome: 'success' } })).toBeUndefined(); + expect( + decisionState({ run: { id: 'run', outcome: 'success' } }) + ).toBeUndefined(); }); it('reads a pause this owner cannot answer as unsupported', () => { @@ -82,13 +80,21 @@ describe('decisionState', () => { expect(await fixture.session.submit('Ignored')).toBe('error'); expect(fixture.exchanges).toHaveLength(1); - const answered = fixture.session.resume(ready.id, [ - { interruptId: 'approval', status: 'resolved', payload: { approved: true } }, + const answered = fixture.session.resume([ + { + interruptId: 'approval', + status: 'resolved', + value: { approved: true }, + }, ]); const next = await fixture.started(1); expect(state()).toMatchObject({ phase: 'answering', id: ready.id }); expect((next.body as { resume?: unknown }).resume).toEqual([ - { interruptId: 'approval', status: 'resolved', payload: { approved: true } }, + { + interruptId: 'approval', + status: 'resolved', + payload: { approved: true }, + }, ]); next.emit({ type: 'RUN_FINISHED', @@ -112,23 +118,26 @@ describe('decisionState', () => { type: 'RUN_FINISHED', threadId: exchange.body.threadId, runId: exchange.body.runId, - outcome: { type: 'interrupt', interrupts: [{ id: 'approval', reason: 'Approve' }] }, + outcome: { + type: 'interrupt', + interrupts: [{ id: 'approval', reason: 'Approve' }], + }, }); await paused; const ready = state(); if (ready?.kind !== 'native') throw new Error('Expected a native pause'); - const answered = fixture.session.resume(ready.id, [ + const answered = fixture.session.resume([ { interruptId: 'approval', status: 'cancelled' }, ]); await fixture.started(1); await fixture.session.stop(); expect(await answered).toBe('aborted'); expect(state()).toMatchObject({ phase: 'uncertain', id: ready.id }); - expect( - await fixture.session.resume(ready.id, [ + await expect( + fixture.session.resume([ { interruptId: 'approval', status: 'cancelled' }, ]) - ).toBe('error'); + ).rejects.toThrow('No interrupt is waiting for an answer.'); expect(fixture.exchanges).toHaveLength(2); } finally { await fixture.cleanup(); diff --git a/libs/ag-ui/src/runtime/decision.spec.ts b/libs/ag-ui/src/runtime/decision.spec.ts index 9aae4ccff..2eb9b5f91 100644 --- a/libs/ag-ui/src/runtime/decision.spec.ts +++ b/libs/ag-ui/src/runtime/decision.spec.ts @@ -9,7 +9,7 @@ import { observeDecision, settleDecision, type NativeDecision, - type NativeResponse, + type InterruptResponse, type PauseId, } from './decision'; @@ -39,7 +39,7 @@ const decision = (): NativeDecision => }); const responses = () => captureResponses([ - { interruptId: 'a', status: 'resolved', payload: null }, + { interruptId: 'a', status: 'resolved', value: null }, { interruptId: 'b', status: 'cancelled' }, ]); @@ -49,7 +49,7 @@ describe('captured native response ownership', () => { const reads = { id: vi.fn(() => 'a'), status: vi.fn(() => 'resolved' as const), - payload: vi.fn(() => graph), + value: vi.fn(() => graph), metadata: vi.fn(() => ({ m: graph })), }; const ignored = vi.fn((): never => { @@ -63,8 +63,8 @@ describe('captured native response ownership', () => { get status() { return reads.status(); }, - get payload() { - return reads.payload(); + get value() { + return reads.value(); }, get metadata() { return reads.metadata(); @@ -100,7 +100,7 @@ describe('captured native response ownership', () => { expect(owned[0]).not.toHaveProperty('payload'); expect( captureResponses([ - { interruptId: 'a', status: 'resolved', payload: undefined }, + { interruptId: 'a', status: 'resolved', value: undefined }, ]) ).toEqual([{ interruptId: 'a', status: 'resolved' }]); }); @@ -109,13 +109,13 @@ describe('captured native response ownership', () => { [{ id: 'a', status: 'resolved' }], [{ interruptId: 1, status: 'resolved' }], [{ interruptId: 'a', status: 'future' }], - [{ interruptId: 'a', status: 'cancelled', payload: null }], - [{ interruptId: 'a', status: 'resolved', payload: new Date() }], + [{ interruptId: 'a', status: 'cancelled', value: null }], + [{ interruptId: 'a', status: 'resolved', value: new Date() }], [{ interruptId: 'a', status: 'resolved', metadata: [] }], - [{ interruptId: 'a', status: 'resolved', payload: () => true }], + [{ interruptId: 'a', status: 'resolved', value: () => true }], ])('rejects unsupported selected decision fields %j', (input) => { expect(() => - captureResponses(input as unknown as readonly NativeResponse[]) + captureResponses(input as unknown as readonly InterruptResponse[]) ).toThrow(); }); }); @@ -160,26 +160,23 @@ describe('pure decision correlation and settlement', () => { ).toEqual({ kind: 'unsupported', sourceRunId: 'source' }); } }); - it('requires current generation and local settlement, then exactly one response per observed ID', () => { + it('requires local settlement and no earlier attempt, then exactly one response per observed ID', () => { const current = decision(); + expect(() => assertResumeEligible(current, { id: 'source' }, 1)).toThrow( + 'No interrupt is waiting for an answer.' + ); expect(() => - assertResumeEligible(current, { id: 'source' }, first, 1) - ).toThrow(); + assertResumeEligible(undefined, { id: 'source', outcome: 'paused' }, 1) + ).toThrow('No interrupt is waiting for an answer.'); expect(() => assertResumeEligible( - current, + { kind: 'unsupported', sourceRunId: 'source' }, { id: 'source', outcome: 'paused' }, - second, 1 ) - ).toThrow(); + ).toThrow('No interrupt is waiting for an answer.'); expect( - assertResumeEligible( - current, - { id: 'source', outcome: 'aborted' }, - first, - 1 - ) + assertResumeEligible(current, { id: 'source', outcome: 'aborted' }, 1) ).toBe(current); for (const input of [ [], @@ -202,13 +199,8 @@ describe('pure decision correlation and settlement', () => { expect(claimed.attempt?.responses).toBe(captured); expect(claimed.interrupts).toBe(current.interrupts); expect(() => - assertResumeEligible( - claimed, - { id: 'resume', outcome: 'aborted' }, - first, - 1 - ) - ).toThrow(); + assertResumeEligible(claimed, { id: 'resume', outcome: 'aborted' }, 1) + ).toThrow('No interrupt is waiting for an answer.'); }); it.each(['invalid', '2020-01-01T00:00:00Z', '2019-01-01T00:00:00Z'])( 'fails closed on expired/invalid date %s', @@ -221,7 +213,6 @@ describe('pure decision correlation and settlement', () => { assertResumeEligible( current, { id: 'source', outcome: 'paused' }, - first, Date.parse('2020-01-01T00:00:00Z') ) ).toThrow(); @@ -238,7 +229,6 @@ describe('pure decision correlation and settlement', () => { assertResumeEligible( current, { id: 'source', outcome: 'paused' }, - first, Date.parse('2020-01-01T00:00:00Z') ) ).toBe(current); @@ -251,12 +241,7 @@ describe('pure decision correlation and settlement', () => { ); expect(released).toEqual(original); expect( - assertResumeEligible( - released, - { id: 'resume', outcome: 'aborted' }, - first, - 1 - ) + assertResumeEligible(released, { id: 'resume', outcome: 'aborted' }, 1) ).toBe(released); expect( settleDecision(claimed, { id: 'resume', outcome: 'aborted' }, true) diff --git a/libs/ag-ui/src/runtime/decision.ts b/libs/ag-ui/src/runtime/decision.ts index 210477078..b827439f8 100644 --- a/libs/ag-ui/src/runtime/decision.ts +++ b/libs/ag-ui/src/runtime/decision.ts @@ -1,5 +1,6 @@ import type { Interrupt } from '@ag-ui/client'; import type { + AgentInterruptResponse, CompleteOutcome, DeepReadonly, PlainValue, @@ -9,6 +10,17 @@ import { copyData } from '../lib/internal/copy-data.js'; declare const pauseId: unique symbol; export type PauseId = string & { readonly [pauseId]: true }; +/** + * One answer for `resume`: the core response, which names a pending interrupt + * and resolves it with an optional `value` or cancels it, plus the protocol's + * optional `metadata`. + */ +export type InterruptResponse = AgentInterruptResponse & { + readonly metadata?: Readonly>; + /** The request's name for the answer. `resume` reads `value`. */ + readonly payload?: never; +}; +/** A response as the protocol carries it, with the value as its `payload`. */ export type NativeResponse = | { readonly interruptId: string; @@ -43,14 +55,14 @@ export interface DecisionRun { } export function captureResponses( - responses: readonly NativeResponse[] + responses: readonly InterruptResponse[] ): readonly NativeResponse[] { if (!Array.isArray(responses)) - throw new TypeError('A native response array is required'); + throw new TypeError('Resume takes an array of responses.'); const length = responses.length; const selected: NativeResponse[] = []; for (let index = 0; index < length; index++) { - const { interruptId, status, payload, metadata } = responses[index]; + const { interruptId, status, value: payload, metadata } = responses[index]; if ( typeof interruptId !== 'string' || (status !== 'resolved' && status !== 'cancelled') @@ -59,7 +71,7 @@ export function captureResponses( 'Explicit interruptId and native status are required' ); if (status === 'cancelled' && payload !== undefined) - throw new TypeError('Cancelled decisions cannot have a payload'); + throw new TypeError('A cancelled response cannot carry a value.'); if ( metadata !== undefined && (metadata === null || @@ -115,19 +127,15 @@ export function observeDecision( export function assertResumeEligible( decision: Decision | undefined, run: DecisionRun | undefined, - pause: PauseId, now: number ): NativeDecision { if ( !decision || decision.kind !== 'native' || - decision.id !== pause || decision.attempt || run?.outcome === undefined ) - throw new TypeError( - 'No settled unclaimed native decision matches this pause' - ); + throw new TypeError('No interrupt is waiting for an answer.'); if (!Number.isFinite(now)) throw new TypeError('A finite admission time is required'); for (const interrupt of decision.interrupts) { @@ -195,7 +203,7 @@ export function settleDecision( * What a view can do about the session's pending decision. * * - `observing`: the pausing run has not settled locally yet; do not answer. - * - `ready`: the pause can be answered with `session.resume(id, responses)`. + * - `ready`: the pause can be answered with `session.resume(responses)`. * - `answering`: an answer was sent and its run is still going. * - `uncertain`: the answering run ended without proof that the backend took * the answer. It cannot be sent again; only a new session can continue. diff --git a/libs/ag-ui/src/runtime/decision.type-test.ts b/libs/ag-ui/src/runtime/decision.type-test.ts index 7bdd99ac5..bfb4fdcfc 100644 --- a/libs/ag-ui/src/runtime/decision.type-test.ts +++ b/libs/ag-ui/src/runtime/decision.type-test.ts @@ -1,30 +1,45 @@ +import type { AgentSession } from '@threadplane/core'; import { captureResponses, type Decision, + type InterruptResponse, type NativeResponse, type PauseId, } from './decision'; import type { Session } from './create-session'; -const resolved: NativeResponse = { +const resolved: InterruptResponse = { interruptId: 'i', status: 'resolved', - payload: null, + value: null, metadata: { nested: [1, undefined] }, }; -const cancelled: NativeResponse = { interruptId: 'i', status: 'cancelled' }; -captureResponses([resolved, cancelled] as const); +const cancelled: InterruptResponse = { interruptId: 'i', status: 'cancelled' }; +// A caller answers with `value`; the captured response carries `payload`. +const captured: readonly NativeResponse[] = captureResponses([ + resolved, + cancelled, +] as const); +void captured; +const wire: NativeResponse = { + interruptId: 'i', + status: 'resolved', + payload: { approved: true }, +}; +void wire; // @ts-expect-error status is mandatory captureResponses([{ interruptId: 'i' }]); // @ts-expect-error no aliases for backend interrupt IDs captureResponses([{ id: 'i', status: 'resolved' }]); -// @ts-expect-error cancelled responses cannot have a defined payload -captureResponses([{ interruptId: 'i', status: 'cancelled', payload: null }]); -// @ts-expect-error functions are not portable payloads -captureResponses([{ interruptId: 'i', status: 'resolved', payload: () => 1 }]); +// @ts-expect-error cancelled responses cannot have a value +captureResponses([{ interruptId: 'i', status: 'cancelled', value: null }]); +// @ts-expect-error the wire name is not a response field +captureResponses([{ interruptId: 'i', status: 'resolved', payload: true }]); +// @ts-expect-error functions are not portable values +captureResponses([{ interruptId: 'i', status: 'resolved', value: () => 1 }]); captureResponses([ // @ts-expect-error Date is not a portable value - { interruptId: 'i', status: 'resolved', payload: new Date() }, + { interruptId: 'i', status: 'resolved', value: new Date() }, ]); // @ts-expect-error metadata must be a plain record captureResponses([{ interruptId: 'i', status: 'resolved', metadata: [] }]); @@ -38,22 +53,49 @@ if (decision.kind === 'native') { // @ts-expect-error snapshots own readonly batches decision.interrupts.push({ id: 'i', reason: 'Approve' }); // @ts-expect-error captured attempt responses are readonly - decision.attempt?.responses.push(resolved); + decision.attempt?.responses.push(wire); void token; } void plain; declare const session: Session; declare const pause: PauseId; -session.resume(pause, [resolved, cancelled] as const, { +session.resume([resolved, cancelled] as const, { signal: new AbortController().signal, }); -// @ts-expect-error a backend ID cannot stand in for a native pause generation +void session.resume([ + { + interruptId: 'i', + status: 'resolved', + value: { approved: true, notes: ['ok'] }, + metadata: { origin: 'review' }, + }, +]); +void session.resume([ + // @ts-expect-error an answer is carried as `value`, not the wire `payload` + { interruptId: 'i', status: 'resolved', payload: { approved: true } }, +]); +// @ts-expect-error there is no pause token: the pending decision is answered +session.resume(pause, [resolved]); +// @ts-expect-error a backend ID cannot stand in for the responses session.resume('backend-id', [resolved]); // @ts-expect-error native resume never accepts a new user message -session.resume(pause, [resolved], { message: 'new intent' }); +session.resume([resolved], { message: 'new intent' }); // @ts-expect-error native resume never accepts a state patch -session.resume(pause, [resolved], { state: {} }); +session.resume([resolved], { state: {} }); // @ts-expect-error transport fields cannot override a correlated native resume -session.resume(pause, [resolved], { runId: 'guessed' }); +session.resume([resolved], { runId: 'guessed' }); // @ts-expect-error an explicit response batch is required -session.resume(pause); +session.resume(); + +// The session is a core session, and a core observer answers through it. +const observer: AgentSession = session; +void observer.resume?.([ + { interruptId: 'i', status: 'resolved', value: { approved: true } }, + { interruptId: 'j', status: 'cancelled' }, +]); +void observer.resume?.([ + // @ts-expect-error the core response has no wire `payload` either + { interruptId: 'i', status: 'resolved', payload: true }, +]); +// @ts-expect-error the core contract has no pause token +void observer.resume?.(pause, [resolved]); diff --git a/libs/ag-ui/src/runtime/resume-http.spec.ts b/libs/ag-ui/src/runtime/resume-http.spec.ts index cea21291f..504405b4a 100644 --- a/libs/ag-ui/src/runtime/resume-http.spec.ts +++ b/libs/ag-ui/src/runtime/resume-http.spec.ts @@ -120,11 +120,11 @@ describe('correlated native resume over held HTTP', () => { { interruptId: 'approval', status: 'resolved' as const, - payload: null, + value: null, metadata: { origin: 'review' }, }, ]; - const done = owner.resume(firstToken, responses); + const done = owner.resume(responses); const second = await server.next(1); expect(second.body).toStrictEqual({ threadId: 'thread', @@ -168,9 +168,8 @@ describe('correlated native resume over held HTTP', () => { expect( next.decision?.kind === 'native' && next.decision.attempt ).toBeUndefined(); - expect(await owner.resume(firstToken, responses)).toBe('error'); expect(server.exchanges).toHaveLength(2); - const cancelled = owner.resume(nextToken, [ + const cancelled = owner.resume([ { interruptId: 'approval', status: 'cancelled' }, ]); const third = await server.next(2); @@ -211,9 +210,8 @@ describe('correlated native resume over held HTTP', () => { const owner = createSession({ threadId: 'thread', url: server.url }); try { await paused(owner, server); - const pause = token(owner); - const done = owner.resume(pause, [ - { interruptId: 'approval', status: 'resolved', payload: true }, + const done = owner.resume([ + { interruptId: 'approval', status: 'resolved', value: true }, ]); const exchange = await server.next(1); const claimed = owner.getSnapshot().decision; @@ -243,11 +241,9 @@ describe('correlated native resume over held HTTP', () => { expect(final.run?.terminal?.type).toBe( ending === 'error' ? 'RUN_ERROR' : undefined ); - expect( - await owner.resume(pause, [ - { interruptId: 'approval', status: 'resolved' }, - ]) - ).toBe('error'); + await expect( + owner.resume([{ interruptId: 'approval', status: 'resolved' }]) + ).rejects.toThrow('No interrupt is waiting for an answer.'); expect(await owner.submit('bypass')).toBe('error'); await owner.stop(); expect(owner.getSnapshot()).toBe(final); @@ -265,7 +261,6 @@ describe('correlated native resume over held HTTP', () => { const owner = createSession({ threadId: 'thread', url: server.url }); try { await paused(owner, server); - const pause = token(owner); let stopped = false; owner.subscribe(() => { const snapshot = owner.getSnapshot(); @@ -279,7 +274,7 @@ describe('correlated native resume over held HTTP', () => { void owner.stop(); } }); - const done = owner.resume(pause, [ + const done = owner.resume([ { interruptId: 'approval', status: 'resolved' }, ]); const exchange = await server.next(1); @@ -305,11 +300,11 @@ describe('correlated native resume over held HTTP', () => { { id: 'approval', reason: 'Approve', expiresAt }, ]); const before = owner.getSnapshot(); - expect( - await owner.resume(token(owner), [ - { interruptId: 'approval', status: 'resolved' }, - ]) - ).toBe('error'); + const refused = owner.resume([ + { interruptId: 'approval', status: 'resolved' }, + ]); + await expect(refused).rejects.toThrow(TypeError); + await expect(refused).rejects.toThrow('The interrupt has expired'); expect(owner.getSnapshot()).toBe(before); expect(server.exchanges).toHaveLength(1); } finally { @@ -345,11 +340,13 @@ describe('correlated native resume over held HTTP', () => { kind: 'unsupported', sourceRunId: exchange.body.runId, }); - expect( - await owner.resume('guessed' as PauseId, [ - { interruptId: 'approval', status: 'resolved' }, - ]) - ).toBe('error'); + await expect( + owner.resume([{ interruptId: 'approval', status: 'resolved' }]) + ).rejects.toThrow( + interruptMode === 'native' + ? 'No interrupt is waiting for an answer.' + : 'Resume needs a settled session with a pending interrupt.' + ); expect(await owner.submit('bypass')).toBe('error'); expect(server.exchanges).toHaveLength(1); } finally { @@ -404,16 +401,15 @@ describe('correlated native resume over held HTTP', () => { exchange.response.write(trace.replaceAll('run-1', exchange.body.runId)); expect(await bounded(first)).toBe('paused'); await bounded(exchange.closed); + const interruptId = + 'v1:tool_call:call_A9ckGX1LrvO82OhqZinzDsom:340a4daa-b874-5aad-8309-a63b92d507dd'; + const value = { chosen_label: 'Tuesday 10:00' }; + // The session takes the answer as `value`; the wire carries `payload`. const responses = [ - { - interruptId: - 'v1:tool_call:call_A9ckGX1LrvO82OhqZinzDsom:340a4daa-b874-5aad-8309-a63b92d507dd', - status: 'resolved' as const, - payload: { chosen_label: 'Tuesday 10:00' }, - }, + { interruptId, status: 'resolved' as const, payload: value }, ]; expect(responses).toStrictEqual(captured.resume); - const done = owner.resume(token(owner), responses); + const done = owner.resume([{ interruptId, status: 'resolved', value }]); const resumed = await server.next(1); expect(resumed.body).toStrictEqual({ threadId: 'th-int-555800', diff --git a/libs/ag-ui/src/runtime/resume.spec.ts b/libs/ag-ui/src/runtime/resume.spec.ts index 403ad6b47..9ddf58452 100644 --- a/libs/ag-ui/src/runtime/resume.spec.ts +++ b/libs/ag-ui/src/runtime/resume.spec.ts @@ -1,7 +1,7 @@ import { PROTOCOL_VERSION } from '@ag-ui/client'; import { describe, expect, it, vi } from 'vitest'; import { bindingFixture } from './testing/binding-fixture'; -import type { NativeResponse, PauseId } from './decision'; +import type { InterruptResponse, PauseId } from './decision'; import type { CompleteOutcome } from '@threadplane/core'; import { createSession } from './create-session'; import type { RunAgentInput } from '@ag-ui/client'; @@ -51,30 +51,6 @@ async function pause(fixture: ReturnType) { } describe('native decision owner', () => { - it('rejects a real foreign owner token without changing either owner', async () => { - const first = bindingFixture(), - second = bindingFixture(); - try { - const firstToken = await pause(first), - secondToken = await pause(second); - expect(firstToken).not.toBe(secondToken); - const before = first.session.getSnapshot(), - other = second.session.getSnapshot(); - expect( - await first.session.resume(secondToken, [ - { interruptId: 'approval', status: 'resolved' }, - ]) - ).toBe('error'); - expect(first.session.getSnapshot()).toBe(before); - expect(second.session.getSnapshot()).toBe(other); - expect(first.exchanges).toHaveLength(1); - expect(second.exchanges).toHaveLength(1); - } finally { - await first.cleanup(); - await second.cleanup(); - } - }); - it('rechecks expiry after selected caller reads and before admission', async () => { const fixture = bindingFixture(); const now = vi.spyOn(Date, 'now').mockReturnValue(1000); @@ -99,18 +75,18 @@ describe('native decision owner', () => { expect(await bounded(first)).toBe('paused'); await bounded(exchange.closed); const before = fixture.session.getSnapshot(); - expect( - await fixture.session.resume(currentPause(fixture), [ - { - interruptId: 'approval', - status: 'resolved', - get payload() { - now.mockReturnValue(2000); - return null; - }, + const expired = fixture.session.resume([ + { + interruptId: 'approval', + status: 'resolved', + get value() { + now.mockReturnValue(2000); + return null; }, - ]) - ).toBe('error'); + }, + ]); + await expect(expired).rejects.toThrow(TypeError); + await expect(expired).rejects.toThrow('The interrupt has expired'); expect(fixture.session.getSnapshot()).toBe(before); expect(fixture.exchanges).toHaveLength(1); } finally { @@ -131,7 +107,6 @@ describe('native decision owner', () => { snapshot.decision?.kind === 'native' ) { pending = fixture.session.resume( - snapshot.decision.id, [{ interruptId: 'approval', status: 'resolved' }], { signal: controller.signal } ); @@ -150,32 +125,40 @@ describe('native decision owner', () => { } }); - it('rejects foreign tokens, invalid batches and pre-aborted input without reads, publication or dispatch', async () => { + it('rejects invalid batches, and aborts pre-aborted input without reads, publication or dispatch', async () => { const fixture = bindingFixture(); try { - const token = await pause(fixture); + await pause(fixture); const before = fixture.session.getSnapshot(); const notify = vi.fn(); fixture.session.subscribe(notify); - for (const responses of [ - [], - [{ interruptId: 'other', status: 'resolved' }], + for (const [responses, message] of [ + [[], 'Exactly one response per interrupt is required'], [ - { interruptId: 'approval', status: 'resolved' }, - { interruptId: 'approval', status: 'cancelled' }, + [{ interruptId: 'other', status: 'resolved' }], + 'Unknown or duplicate interrupt response', ], - [{ interruptId: 'approval', status: 'cancelled', payload: null }], - ] as unknown as readonly NativeResponse[][]) - expect(await fixture.session.resume(token, responses)).toBe('error'); - expect( - await fixture.session.resume('foreign' as PauseId, [ - { interruptId: 'approval', status: 'resolved' }, - ]) - ).toBe('error'); + [ + [ + { interruptId: 'approval', status: 'resolved' }, + { interruptId: 'approval', status: 'cancelled' }, + ], + 'Exactly one response per interrupt is required', + ], + [ + [{ interruptId: 'approval', status: 'cancelled', value: null }], + 'A cancelled response cannot carry a value.', + ], + ['approval', 'Resume takes an array of responses.'], + ] as unknown as readonly [readonly InterruptResponse[], string?][]) { + const refused = fixture.session.resume(responses); + await expect(refused).rejects.toThrow(TypeError); + if (message) await expect(refused).rejects.toThrow(message); + } const unread = vi.fn((): never => { throw new Error('unread'); }); - const responses: readonly NativeResponse[] = [ + const responses: readonly InterruptResponse[] = [ { get interruptId() { return unread(); @@ -184,7 +167,7 @@ describe('native decision owner', () => { }, ]; expect( - await fixture.session.resume(token, responses, { + await fixture.session.resume(responses, { signal: AbortSignal.abort(), }) ).toBe('aborted'); @@ -192,7 +175,7 @@ describe('native decision owner', () => { expect(notify).not.toHaveBeenCalled(); expect(fixture.exchanges).toHaveLength(1); await fixture.session.dispose(); - expect(await fixture.session.resume(token, responses)).toBe('aborted'); + expect(await fixture.session.resume(responses)).toBe('aborted'); expect(unread).not.toHaveBeenCalled(); } finally { await fixture.cleanup(); @@ -202,7 +185,7 @@ describe('native decision owner', () => { it('captures selected option/input getters once and ignores extra getters', async () => { const fixture = bindingFixture(); try { - const token = await pause(fixture); + await pause(fixture); const signal = new AbortController().signal; const selected = vi.fn(() => signal); const ignored = vi.fn((): never => { @@ -219,12 +202,12 @@ describe('native decision owner', () => { const response = { interruptId: 'approval', status: 'resolved' as const, - payload: null, + value: null, get forwardedProps() { return ignored(); }, }; - const done = fixture.session.resume(token, [response], options); + const done = fixture.session.resume([response], options); const exchange = await bounded(fixture.started(1)); // 1.0 client rule: a whole-optional `payload: null` is sent as absent. expect(exchange.body.resume).toStrictEqual([ @@ -242,13 +225,12 @@ describe('native decision owner', () => { it('retains cancellation precedence when a selected signal getter disposes then throws', async () => { const fixture = bindingFixture(); try { - const token = await pause(fixture); + await pause(fixture); const unread = vi.fn((): never => { throw new Error('unread'); }); expect( await fixture.session.resume( - token, [ { get interruptId() { @@ -326,8 +308,8 @@ describe('native decision owner', () => { throw new Error('Missing native decision'); expect( await bounded( - owner.resume(decision.id, [ - { interruptId: 'approval', status: 'resolved', payload: null }, + owner.resume([ + { interruptId: 'approval', status: 'resolved', value: null }, ]) ) ).toBe(action === 'stop' ? 'aborted' : 'error'); @@ -336,11 +318,9 @@ describe('native decision owner', () => { id: decision.id, attempt: { runId: owner.getSnapshot().run?.id }, }); - expect( - await owner.resume(decision.id, [ - { interruptId: 'approval', status: 'resolved' }, - ]) - ).toBe('error'); + await expect( + owner.resume([{ interruptId: 'approval', status: 'resolved' }]) + ).rejects.toThrow('No interrupt is waiting for an answer.'); expect(await owner.submit('bypass')).toBe('error'); expect(calls).toBe(2); } finally { @@ -355,8 +335,8 @@ describe('native decision owner', () => { const token = await pause(fixture); const before = fixture.session.getSnapshot(); const payload = { values: [1] }; - const done = fixture.session.resume(token, [ - { interruptId: 'approval', status: 'resolved', payload }, + const done = fixture.session.resume([ + { interruptId: 'approval', status: 'resolved', value: payload }, ]); payload.values.push(99); const admitted = fixture.session.getSnapshot(); @@ -378,11 +358,13 @@ describe('native decision owner', () => { ], }, }); - expect( - await fixture.session.resume(token, [ + await expect( + fixture.session.resume([ { interruptId: 'approval', status: 'cancelled' }, ]) - ).toBe('error'); + ).rejects.toThrow( + 'Resume needs a settled session with a pending interrupt.' + ); const unread = vi.fn((): never => { throw new Error('unread'); }); @@ -436,15 +418,18 @@ describe('native decision owner', () => { !attempted && snapshot.run?.terminal?.type === 'RUN_FINISHED' && snapshot.decision?.kind === 'native' - ) - attempted = fixture.session.resume(snapshot.decision.id, [ + ) { + attempted = fixture.session.resume([ { interruptId: 'approval', status: 'resolved' }, ]); + // Observed below; the refusal lands before the test awaits it. + attempted.catch(() => undefined); + } }); try { await pause(fixture); if (!attempted) throw new Error('Missing terminal callback attempt'); - expect(await bounded(attempted)).toBe('error'); + await expect(bounded(attempted)).rejects.toThrow(TypeError); expect(fixture.exchanges).toHaveLength(1); expect(fixture.session.getSnapshot().decision?.kind).toBe('native'); } finally { @@ -467,16 +452,18 @@ describe('native decision owner', () => { scheduled = true; const payload = { values: [1] }; attempts.push( - fixture.session.resume(snapshot.decision.id, [ - { interruptId: 'approval', status: 'resolved', payload }, + fixture.session.resume([ + { interruptId: 'approval', status: 'resolved', value: payload }, ]) ); payload.values.push(99); attempts.push( - fixture.session.resume(snapshot.decision.id, [ + fixture.session.resume([ { interruptId: 'approval', status: 'cancelled' }, ]) ); + // Observed below; the refusal lands before the test awaits it. + attempts[1].catch(() => undefined); }); try { await pause(fixture); @@ -488,7 +475,7 @@ describe('native decision owner', () => { payload: { values: [1] }, }, ]); - expect(await bounded(attempts[1])).toBe('error'); + await expect(bounded(attempts[1])).rejects.toThrow(TypeError); await fixture.session.stop(); expect(await bounded(attempts[0])).toBe('aborted'); expect(fixture.exchanges).toHaveLength(2); @@ -503,15 +490,15 @@ describe('native decision owner', () => { const fixture = bindingFixture(); let inner: Promise = Promise.resolve(); try { - const token = await pause(fixture); - const responses: readonly NativeResponse[] = [ + await pause(fixture); + const responses: readonly InterruptResponse[] = [ { interruptId: 'approval', status: 'resolved', - get payload(): never { + get value(): never { inner = command === 'resume' - ? fixture.session.resume(token, [ + ? fixture.session.resume([ { interruptId: 'approval', status: 'cancelled' }, ]) : fixture.session[command](); @@ -519,7 +506,7 @@ describe('native decision owner', () => { }, }, ]; - expect(await fixture.session.resume(token, responses)).toBe('aborted'); + expect(await fixture.session.resume(responses)).toBe('aborted'); if (command === 'resume') { const exchange = await bounded(fixture.started(1)); expect(exchange.body.resume).toEqual([ @@ -550,7 +537,7 @@ describe('native decision owner', () => { } }); expect( - await fixture.session.resume(token, [ + await fixture.session.resume([ { interruptId: 'approval', status: 'resolved' }, ]) ).toBe('aborted'); @@ -563,7 +550,7 @@ describe('native decision owner', () => { expect(fixture.session.getSnapshot().run?.id).not.toBe( decision.sourceRunId ); - const retry = fixture.session.resume(token, [ + const retry = fixture.session.resume([ { interruptId: 'approval', status: 'resolved' }, ]); await bounded(fixture.started(1)); diff --git a/libs/ag-ui/src/runtime/session-http.spec.ts b/libs/ag-ui/src/runtime/session-http.spec.ts index 05b8cb4d5..ef29ccec0 100644 --- a/libs/ag-ui/src/runtime/session-http.spec.ts +++ b/libs/ag-ui/src/runtime/session-http.spec.ts @@ -296,8 +296,8 @@ describe('composed private session over held HTTP', () => { expect(settled.state).toEqual({ count: 2 }); if (settled.decision?.kind !== 'native') throw new Error('Missing native pause'); - second = owner.resume(settled.decision.id, [ - { interruptId: 'approval', status: 'resolved', payload: true }, + second = owner.resume([ + { interruptId: 'approval', status: 'resolved', value: true }, ]); const next = await server.next(1); expect(next.body).toStrictEqual({ @@ -323,12 +323,14 @@ describe('composed private session over held HTTP', () => { expect(owner.getSnapshot().subagents).toEqual([]); expect(settled).not.toHaveProperty('earlierSubagents'); expect(settled.subagents[0].terminal?.type).toBe('SUBAGENT_FINISHED'); + // History keeps the child's protocol evidence, by reference, without + // the core child fields the current run's list adds. + const { started, terminal: finished } = settled.subagents[0]; expect(owner.getSnapshot().earlierSubagents).toStrictEqual([ - settled.subagents[0], + { started, terminal: finished }, ]); - expect(owner.getSnapshot().earlierSubagents?.[0]).toBe( - settled.subagents[0] - ); + expect(owner.getSnapshot().earlierSubagents?.[0].started).toBe(started); + expect(owner.getSnapshot().earlierSubagents?.[0].terminal).toBe(finished); expect(owner.getSnapshot().run?.terminal).toBeUndefined(); next.send(lifecycle(next), lifecycle(next, 'RUN_FINISHED')); expect(await bounded(second)).toBe('success'); @@ -351,20 +353,29 @@ describe('composed private session over held HTTP', () => { expect(await bounded(third)).toBe('success'); expect(owner.getSnapshot().earlierSubagents).toBe(history); const latest = owner.getSnapshot().subagents; - expect(latest).toStrictEqual([ - { - started: { - type: 'SUBAGENT_STARTED', - subagentRunId: 'child', - name: 'again', - }, - terminal: { type: 'SUBAGENT_FINISHED', subagentRunId: 'child' }, + const reused = { + started: { + type: 'SUBAGENT_STARTED', + subagentRunId: 'child', + name: 'again', }, + terminal: { type: 'SUBAGENT_FINISHED', subagentRunId: 'child' }, + }; + // This turn asserts the child's identity and evidence, not its own + // messages and tool calls. + expect(latest).toHaveLength(1); + expect(latest).toMatchObject([ + { id: 'child', name: 'again', status: 'complete', ...reused }, ]); + expect(latest[0].started).toStrictEqual(reused.started); + expect(latest[0].terminal).toStrictEqual(reused.terminal); const fourth = owner.submit('once more'); const last = await server.next(3); expect(owner.getSnapshot().subagents).toEqual([]); - expect(owner.getSnapshot().earlierSubagents).toStrictEqual(latest); + expect(owner.getSnapshot().earlierSubagents).toStrictEqual([reused]); + expect(owner.getSnapshot().earlierSubagents?.[0].started).toBe( + latest[0].started + ); last.send(lifecycle(last), lifecycle(last, 'RUN_FINISHED')); expect(await bounded(fourth)).toBe('success'); } finally { @@ -481,6 +492,11 @@ describe('composed private session over held HTTP', () => { if (ending === 'EOF' || ending === 'error') expect(owner.getSnapshot().subagents).toEqual([ { + id: 'open', + name: 'worker', + status: 'unknown', + messages: [], + toolCalls: [], started: { type: 'SUBAGENT_STARTED', subagentRunId: 'open', diff --git a/libs/angular/src/observe-agent.ag-ui.spec.ts b/libs/angular/src/observe-agent.ag-ui.spec.ts index 296e93214..e85b62563 100644 --- a/libs/angular/src/observe-agent.ag-ui.spec.ts +++ b/libs/angular/src/observe-agent.ag-ui.spec.ts @@ -128,6 +128,11 @@ describe('observeAgent native AG-UI owner', () => { }); expect(second.snapshot().subagents).toEqual([ { + id: 'child', + name: 'worker', + status: 'complete', + messages: [], + toolCalls: [], started: { type: 'SUBAGENT_STARTED', subagentRunId: 'child', @@ -178,8 +183,8 @@ describe('observeAgent native AG-UI owner', () => { expect(second.snapshot().run?.outcome).toBe('paused'); const decision = second.snapshot().decision; if (decision?.kind !== 'native') throw new Error('Missing observed pause'); - const nextRun = f.session.resume(decision.id, [ - { interruptId: 'approval', status: 'resolved', payload: 'yes' }, + const nextRun = f.session.resume([ + { interruptId: 'approval', status: 'resolved', value: 'yes' }, ]); const next = await f.started(1); expect(next.body).toEqual({ diff --git a/libs/react/src/chat/ag-ui-session.spec.tsx b/libs/react/src/chat/ag-ui-session.spec.tsx index 471185731..0e1ba5dae 100644 --- a/libs/react/src/chat/ag-ui-session.spec.tsx +++ b/libs/react/src/chat/ag-ui-session.spec.tsx @@ -45,7 +45,11 @@ describe('Chat over a native AG-UI session', () => { toolCallName: 'search', parentMessageId: 'a1', }); - exchange.emit({ type: 'TOOL_CALL_ARGS', toolCallId: 'c1', delta: '{"q":"tea"}' }); + exchange.emit({ + type: 'TOOL_CALL_ARGS', + toolCallId: 'c1', + delta: '{"q":"tea"}', + }); exchange.emit({ type: 'TOOL_CALL_END', toolCallId: 'c1' }); exchange.emit({ type: 'TOOL_CALL_RESULT', @@ -53,8 +57,16 @@ describe('Chat over a native AG-UI session', () => { messageId: 't1', content: '{"hits":2}', }); - exchange.emit({ type: 'TEXT_MESSAGE_START', messageId: 'a2', role: 'assistant' }); - exchange.emit({ type: 'TEXT_MESSAGE_CONTENT', messageId: 'a2', delta: 'Two teas found.' }); + exchange.emit({ + type: 'TEXT_MESSAGE_START', + messageId: 'a2', + role: 'assistant', + }); + exchange.emit({ + type: 'TEXT_MESSAGE_CONTENT', + messageId: 'a2', + delta: 'Two teas found.', + }); exchange.emit({ type: 'TEXT_MESSAGE_END', messageId: 'a2' }); exchange.emit({ type: 'RUN_FINISHED', @@ -97,7 +109,13 @@ describe('Chat over a native AG-UI session', () => { ], state: { citations: { - a: [{ id: 'doc', title: 'Signals guide', url: 'https://example.test/signals' }], + a: [ + { + id: 'doc', + title: 'Signals guide', + url: 'https://example.test/signals', + }, + ], }, }, }); @@ -132,11 +150,10 @@ describe('Chat over a native AG-UI session', () => { label: 'Issue refund', onSelect: () => void native.resume( - pending.id, pending.interrupts.map((interrupt) => ({ interruptId: interrupt.id, status: 'resolved' as const, - payload: { approved: true }, + value: { approved: true }, })) ), }, @@ -178,15 +195,30 @@ describe('Chat over a native AG-UI session', () => { fireEvent.click(approve); const next = await act(() => fixture.started(1)); expect((next.body as { resume?: unknown }).resume).toEqual([ - { interruptId: 'approval', status: 'resolved', payload: { approved: true } }, + { + interruptId: 'approval', + status: 'resolved', + payload: { approved: true }, + }, ]); expect( - (view.getByRole('button', { name: 'Issue refund' }) as HTMLButtonElement) - .disabled + ( + view.getByRole('button', { + name: 'Issue refund', + }) as HTMLButtonElement + ).disabled ).toBe(true); await act(async () => { - next.emit({ type: 'TEXT_MESSAGE_START', messageId: 'a', role: 'assistant' }); - next.emit({ type: 'TEXT_MESSAGE_CONTENT', messageId: 'a', delta: 'Refund issued.' }); + next.emit({ + type: 'TEXT_MESSAGE_START', + messageId: 'a', + role: 'assistant', + }); + next.emit({ + type: 'TEXT_MESSAGE_CONTENT', + messageId: 'a', + delta: 'Refund issued.', + }); next.emit({ type: 'TEXT_MESSAGE_END', messageId: 'a' }); next.emit({ type: 'RUN_FINISHED', diff --git a/libs/react/src/use-agent.ag-ui.spec.tsx b/libs/react/src/use-agent.ag-ui.spec.tsx index d1816cfa4..660f10e0c 100644 --- a/libs/react/src/use-agent.ag-ui.spec.tsx +++ b/libs/react/src/use-agent.ag-ui.spec.tsx @@ -118,6 +118,11 @@ describe('useAgent native AG-UI owner', () => { }); expect(second.result.current.subagents).toEqual([ { + id: 'child', + name: 'worker', + status: 'complete', + messages: [], + toolCalls: [], started: { type: 'SUBAGENT_STARTED', subagentRunId: 'child', @@ -174,8 +179,8 @@ describe('useAgent native AG-UI owner', () => { const decision = second.result.current.decision; if (decision?.kind !== 'native') throw new Error('Missing observed pause'); await act(async () => { - run = f.session.resume(decision.id, [ - { interruptId: 'approval', status: 'resolved', payload: 'yes' }, + run = f.session.resume([ + { interruptId: 'approval', status: 'resolved', value: 'yes' }, ]); await f.started(1); }); diff --git a/scripts/react-parity/dispositions.json b/scripts/react-parity/dispositions.json index 36fcdc566..a4c4fe7d0 100644 --- a/scripts/react-parity/dispositions.json +++ b/scripts/react-parity/dispositions.json @@ -19267,6 +19267,18 @@ "reason": "Private core AgentSession view of the native owner: a snapshot derived from the native one with the message and tool-call selectors, change-only notification, a display error for a failed run, and text submit, stop and dispose forwarded to the owner.", "note": "Covered by runtime specs and a React Chat integration spec over the real owner. Exported from the test-only candidate package entry and checked from installed tarballs; not exported from the published package root. A rejected credential (401 or 403) is an auth error and another HTTP status is carried on a server error. State patches, native resume, client-tool evidence, a status check and a failure without a response are not represented." }, + { + "id": "source:libs/ag-ui/src/runtime/child-projection.ts", + "taskIds": [ + "T12", + "T14", + "T23" + ], + "treatment": "internal", + "status": "in-progress", + "reason": "Private projection of the current run's child evidence into the core contract's child agents: each child's id, name, task, status and its own messages and tool calls, with the protocol evidence kept alongside.", + "note": "Covered by runtime specs over the real owner. Children of earlier runs stay bare evidence in earlierSubagents, and a child that reuses a run id also lists the earlier child's records." + }, { "id": "source:libs/ag-ui/src/runtime/message-projection.ts", "taskIds": [ diff --git a/scripts/react-parity/native-mastra-runner.ts b/scripts/react-parity/native-mastra-runner.ts index a742dae63..02fb56d47 100644 --- a/scripts/react-parity/native-mastra-runner.ts +++ b/scripts/react-parity/native-mastra-runner.ts @@ -9,9 +9,11 @@ import { import { PROTOCOL_VERSION, type RunAgentInput } from '@ag-ui/client'; // eslint-disable-next-line @nx/enforce-module-boundaries -- Explicit fixture binding preserves the source or installed owner. import { createSession } from '../../fixtures/react-parity/native-ag-ui/mastra-backend.js'; -type NativeResponse = Parameters< - ReturnType['resume'] ->[1][number]; +type Answer = Parameters['resume']>[0][number]; +/** An answer as the request carries it. */ +type NativeResponse = + | { interruptId: string; status: 'resolved'; payload?: unknown } + | { interruptId: string; status: 'cancelled' }; // eslint-disable-next-line @nx/enforce-module-boundaries -- Test-only local service composition; no package API is introduced. import { bounded, @@ -293,7 +295,7 @@ async function verifyCase( assert.equal(owner.getSnapshot(), paused); assert.equal(proxy.posts(), pendingPosts); assert.equal(service.stats().length, providerPosts); - const pauseId = paused.decision.id; + // The request carries the answer as `payload`; the command takes `value`. scenario.response = name === 'cancel' ? { interruptId: interrupt.id, status: 'cancelled' } @@ -302,16 +304,21 @@ async function verifyCase( status: 'resolved', payload: { approved: name !== 'decline' }, }; - const done = owner.resume(pauseId, [scenario.response]); + const answer: Answer = + name === 'cancel' + ? { interruptId: interrupt.id, status: 'cancelled' } + : { + interruptId: interrupt.id, + status: 'resolved', + value: { approved: name !== 'decline' }, + }; + const done = owner.resume([answer]); const claimed = owner.getSnapshot(); assert.equal(claimed.transcript, paused.transcript); assert.equal(claimed.state, paused.state); - assert.equal( - await bounded( - owner.resume(pauseId, [scenario.response]), - 'duplicate active claim' - ), - 'error' + await assert.rejects( + bounded(owner.resume([answer]), 'duplicate active claim'), + TypeError ); assert.equal(owner.getSnapshot(), claimed); const outcome = await bounded(done, `${name} resume`); @@ -370,12 +377,9 @@ async function verifyCase( assert.equal(second.suppressed, 0); assert.equal(final.decision, undefined); } - assert.equal( - await bounded( - owner.resume(pauseId, [scenario.response]), - 'stale or uncertain resume' - ), - 'error' + await assert.rejects( + bounded(owner.resume([answer]), 'stale or uncertain resume'), + TypeError ); assert.equal(owner.getSnapshot(), final); assert.equal(proxy.posts(), pendingPosts + 1); From 24df2a7bd85f64d7552a674cd2047155cf5b8f23 Mon Sep 17 00:00:00 2001 From: Brian Love Date: Thu, 19 Nov 2026 12:17:56 -0800 Subject: [PATCH 10/18] feat(langgraph): publish child graphs as core child agents --- libs/langgraph/src/runtime/README.md | 44 +++++++-- .../src/runtime/langgraph-snapshot.ts | 14 ++- libs/langgraph/src/runtime/ownership.ts | 22 ++++- .../langgraph/src/runtime/publication.spec.ts | 28 +++--- libs/langgraph/src/runtime/publication.ts | 6 +- .../src/runtime/session-lifecycle.spec.ts | 1 + .../src/runtime/subagent-projection.ts | 86 ++++++++++++++++++ .../src/runtime/subgraph-projection.ts | 8 +- libs/langgraph/src/runtime/subgraphs.spec.ts | 89 +++++++++++++++++++ .../src/runtime/subgraphs.type-test.ts | 21 ++++- scripts/react-parity/dispositions.json | 13 ++- 11 files changed, 300 insertions(+), 32 deletions(-) create mode 100644 libs/langgraph/src/runtime/subagent-projection.ts diff --git a/libs/langgraph/src/runtime/README.md b/libs/langgraph/src/runtime/README.md index 2ff51505c..4f8c834c6 100644 --- a/libs/langgraph/src/runtime/README.md +++ b/libs/langgraph/src/runtime/README.md @@ -317,15 +317,15 @@ panel or telemetry: `getSnapshot()` returns a frozen `LangGraphLifecycle` and `useSyncExternalStore`. Each value is epoch milliseconds on this clock, null until its milestone happens. -| Value | Stamped | -| --------------------- | -------------------------------------------------------------- | -| `streamStartedAt` | The first event to arrive on any run's stream. | -| `streamErrorAt` | The most recent published failure, as `{ at, kind }`. | -| `interruptReceivedAt` | The first time the session held a pending interrupt. | -| `interruptResolvedAt` | The most recent `resume` the session accepted. | -| `threadPersistedAt` | The first history read that returned saved checkpoints. | -| `toolCallStartedAt` | The first time the session held a tool call. | -| `toolCallCompletedAt` | The first time a tool call was complete or failed. | +| Value | Stamped | +| --------------------- | ------------------------------------------------------- | +| `streamStartedAt` | The first event to arrive on any run's stream. | +| `streamErrorAt` | The most recent published failure, as `{ at, kind }`. | +| `interruptReceivedAt` | The first time the session held a pending interrupt. | +| `interruptResolvedAt` | The most recent `resume` the session accepted. | +| `threadPersistedAt` | The first history read that returned saved checkpoints. | +| `toolCallStartedAt` | The first time the session held a tool call. | +| `toolCallCompletedAt` | The first time a tool call was complete or failed. | A session serves one thread, so nothing is reset: where the Angular adapter clears its `AgentLifecycle` on `switchThread()`, a session for another thread @@ -365,6 +365,32 @@ paused. The preflight detects already-observed consumption, but it is not an ato server claim. Applications must coordinate responders to the same task. Distinct checkpoint branches do not provide independent opposing decisions on one task. +## Child agents + +`snapshot.subgraphs` holds one entry for each child graph the run reported, with +its `namespace`, its own `messages` and `toolCalls`, its `state`, `interrupts` +and `error`. `snapshot.subagents` publishes the same children as the core +contract's child agents, one for each and in the same order, so a component +written for core sessions can show them: + +- `id` is the namespace path as JSON, which stays unique whatever a segment + contains. `parentId` is the `id` of the enclosing child graph, and is absent + for a child of the root graph. `namespace` is kept alongside. +- `name` is the node that started the child: the part of the last namespace + segment before its `:`. +- `messages` and `toolCalls` are the child graph's own, the same references as + in `subgraphs`. The root `messages` and `toolCalls` do not repeat them. +- `status` is `error` for a child that failed, with the display text in + `error`, and `running` while the root run is going. After the run, a child + whose last message succeeded is `complete`, one a pause stopped is still + `running` because a resume continues it, and any other child is `unknown`. +- LangGraph does not relate a child graph to a tool call, so `toolCallId` and + `description` are never set. + +A child agent keeps its reference while its child graph and status are +unchanged. Child agents give no command authority: answering a pause is the +root session's `resume`. + ## Thread directory `createLangGraphThreadDirectory` in `thread-directory.ts` implements the diff --git a/libs/langgraph/src/runtime/langgraph-snapshot.ts b/libs/langgraph/src/runtime/langgraph-snapshot.ts index 1393ead24..04442086d 100644 --- a/libs/langgraph/src/runtime/langgraph-snapshot.ts +++ b/libs/langgraph/src/runtime/langgraph-snapshot.ts @@ -5,8 +5,10 @@ import type { DeepReadonly, PlainValue, Message, + ToolCall, ToolContract, } from '@threadplane/core'; +import type { LangGraphSubagent } from './subagent-projection.js'; import type { Interrupt, ThreadState } from '@langchain/langgraph-sdk'; /** Compact metadata from an explicitly loaded page, without repeated state data. */ @@ -39,12 +41,17 @@ export type LangGraphSnapshotState = unknown extends TState export interface LangGraphSubgraph { readonly namespace: readonly string[]; readonly messages: readonly Message[]; + /** The child graph's own tool calls, referenced by `Message.toolCallIds` in `messages`. */ + readonly toolCalls: readonly ToolCall[]; /** A child graph's state. It is never checked against the session's declaration. */ readonly state: LangGraphState | undefined; readonly interrupts: readonly LangGraphWireInterrupt[]; readonly error?: AgentError; } +/** What a publication supplies: the session derives `subagents` from `subgraphs`. */ +export type LangGraphPublication = Omit; + /** Backend-private extension; the core snapshot remains backend-independent. */ export type LangGraphSnapshot< TTools extends { [K in keyof TTools]: ToolContract } = Record< @@ -52,7 +59,7 @@ export type LangGraphSnapshot< ToolContract >, TState = unknown -> = Omit, 'interrupts'> & { +> = Omit, 'interrupts' | 'subagents'> & { /** Last explicit history page; undefined until loaded. Not a live branch tree. */ readonly history: readonly LangGraphHistoryEntry[] | undefined; /** @@ -68,4 +75,9 @@ export type LangGraphSnapshot< readonly reconnect?: { readonly runId: string }; readonly interrupts: readonly LangGraphInterrupt[]; readonly subgraphs: readonly LangGraphSubgraph[]; + /** + * The child graphs in `subgraphs` as the core contract's child agents, one + * for each and in the same order. + */ + readonly subagents: readonly LangGraphSubagent[]; }; diff --git a/libs/langgraph/src/runtime/ownership.ts b/libs/langgraph/src/runtime/ownership.ts index 6a6dabf7d..f44f750a5 100644 --- a/libs/langgraph/src/runtime/ownership.ts +++ b/libs/langgraph/src/runtime/ownership.ts @@ -10,11 +10,13 @@ import { } from '@threadplane/core'; import type { LangGraphInterrupt, + LangGraphPublication, LangGraphWireInterrupt, LangGraphSnapshot, LangGraphSubgraph, LangGraphState, } from './langgraph-snapshot.js'; +import { projectSubagents } from './subagent-projection.js'; // Only objects projected here are trusted. Object.isFrozen on external input is // insufficient: its children may still be mutable. The weak set retains no data. @@ -324,7 +326,7 @@ export function ownSnapshot( /** One backend aggregate, composing the core fields and owned application data. */ export function ownLangGraphSnapshot( - input: LangGraphSnapshot, + input: LangGraphPublication, previous?: LangGraphSnapshot ): LangGraphSnapshot { const core = ownSnapshot(input, previous); @@ -333,6 +335,12 @@ export function ownLangGraphSnapshot( previous?.history as PlainValue ) as LangGraphSnapshot['history']; const subgraphs = ownSubgraphs(input.subgraphs, previous?.subgraphs); + // Derived here, so the children always agree with the published child graphs. + const subagents = projectSubagents( + subgraphs, + core.status, + previous?.subagents + ); const state = ownValueWithSharing(input.state, previous?.state) as | LangGraphState | undefined; @@ -355,6 +363,7 @@ export function ownLangGraphSnapshot( stateIssues === previous?.stateIssues && interrupts === previous?.interrupts && subgraphs === previous?.subgraphs && + subagents === previous?.subagents && reconnect === previous?.reconnect ) return previous; @@ -371,6 +380,7 @@ export function ownLangGraphSnapshot( ...(stateIssues ? { stateIssues } : {}), interrupts, subgraphs, + subagents, ...(reconnect ? { reconnect } : {}), }); } @@ -390,6 +400,13 @@ export function ownSubgraph( ownMessage, sameMessage ); + // A restored child graph may predate `toolCalls`. + const toolCalls = ownArray( + input.toolCalls ?? [], + previous?.toolCalls, + ownToolCall, + sameToolCall + ); const state = ownValueWithSharing(input.state, previous?.state) as | LangGraphState | undefined; @@ -404,6 +421,7 @@ export function ownSubgraph( previous && namespace === previous.namespace && messages === previous.messages && + toolCalls === previous.toolCalls && state === previous.state && interrupts === previous.interrupts && error === previous.error @@ -412,6 +430,7 @@ export function ownSubgraph( return freeze({ namespace, messages, + toolCalls, state, interrupts, ...(error ? { error } : {}), @@ -430,6 +449,7 @@ export function ownSubgraphs( a === b || (a.namespace === b.namespace && a.messages === b.messages && + a.toolCalls === b.toolCalls && a.state === b.state && a.interrupts === b.interrupts && sameError(a.error, b.error)) diff --git a/libs/langgraph/src/runtime/publication.spec.ts b/libs/langgraph/src/runtime/publication.spec.ts index 7595663ac..eadd9d6e1 100644 --- a/libs/langgraph/src/runtime/publication.spec.ts +++ b/libs/langgraph/src/runtime/publication.spec.ts @@ -2,9 +2,9 @@ import { streamingDelivery } from '@threadplane/core'; import { describe, expect, it } from 'vitest'; import { createPublication } from './publication'; import { deferred } from './testing/deferred'; -import type { LangGraphSnapshot } from './langgraph-snapshot'; +import type { LangGraphPublication } from './langgraph-snapshot'; -function snapshot(content = 'one'): LangGraphSnapshot { +function snapshot(content = 'one'): LangGraphPublication { return { status: 'idle', history: undefined, @@ -36,7 +36,7 @@ describe('private snapshot publication', () => { it('publishes reasoning-only changes, owns queued getter strings and suppresses equal values', () => { const publication = createPublication(snapshot()); let reasoning = 'Captured'; - const input = (): LangGraphSnapshot => ({ + const input = (): LangGraphPublication => ({ ...snapshot(), messages: [ { @@ -47,7 +47,7 @@ describe('private snapshot publication', () => { }, ], }); - const seen: LangGraphSnapshot[] = []; + const seen: LangGraphPublication[] = []; publication.subscribe(() => { seen.push(publication.getSnapshot()); if (seen.length === 1) { @@ -78,11 +78,11 @@ describe('private snapshot publication', () => { const citations = [ { id: 'c', index: 1, title: 'Original', extra: { tags: ['original'] } }, ]; - const input = (): LangGraphSnapshot => ({ + const input = (): LangGraphPublication => ({ ...snapshot('two'), messages: [{ ...snapshot('two').messages[0], citations }], }); - const seen: LangGraphSnapshot[] = []; + const seen: LangGraphPublication[] = []; publication.subscribe(() => { seen.push(publication.getSnapshot()); if (seen.length === 1) { @@ -138,7 +138,7 @@ describe('private snapshot publication', () => { if (populated) array[0] = 1; return array; }; - const input = (length: number): LangGraphSnapshot => ({ + const input = (length: number): LangGraphPublication => ({ ...snapshot(), toolCalls: [ { @@ -230,7 +230,7 @@ describe('private snapshot publication', () => { ...snapshot('Invalid'), state: { count: 9 }, interrupts: [{ value: new Date() }], - } as unknown as LangGraphSnapshot) + } as unknown as LangGraphPublication) ).toThrow(TypeError); expect(publication.getSnapshot()).toBe(before); }); @@ -241,7 +241,7 @@ describe('private snapshot publication', () => { publication.publish({ ...snapshot('candidate'), state: { bad: new Date(0) }, - } as unknown as LangGraphSnapshot) + } as unknown as LangGraphPublication) ).toThrow(TypeError); expect(publication.getSnapshot()).toBe(before); }); @@ -249,12 +249,12 @@ describe('private snapshot publication', () => { it('owns application values and suppresses equal queued aggregate publications', () => { const data = { stable: { x: 1 }, count: 1 }; const publication = createPublication({ ...snapshot(), state: data }); - const first = publication.getSnapshot() as LangGraphSnapshot; + const first = publication.getSnapshot() as LangGraphPublication; expect(first.state).toEqual(data); expect(first.state).not.toBe(data); data.stable.x = 9; expect(first.state?.['stable']).toEqual({ x: 1 }); - const seen: LangGraphSnapshot[] = []; + const seen: LangGraphPublication[] = []; for (let index = 0; index < 2; index++) publication.subscribe(() => { if (publication.getSnapshot().status === 'running') { @@ -268,7 +268,7 @@ describe('private snapshot publication', () => { } }); publication.subscribe(() => - seen.push(publication.getSnapshot() as LangGraphSnapshot) + seen.push(publication.getSnapshot() as LangGraphPublication) ); publication.publish({ ...first, status: 'running' }); expect(seen).toHaveLength(2); @@ -288,7 +288,7 @@ describe('private snapshot publication', () => { toolCalls: [{ ...input.toolCalls[0], args: new Date() }], }; expect(() => - createPublication(invalid as unknown as LangGraphSnapshot) + createPublication(invalid as unknown as LangGraphPublication) ).toThrow(TypeError); const publication = createPublication({ ...input, @@ -300,7 +300,7 @@ describe('private snapshot publication', () => { toolCalls: [ { id: 't', name: 'search', status: 'running', args: new Date() }, ], - } as unknown as LangGraphSnapshot) + } as unknown as LangGraphPublication) ).toThrow(TypeError); }); it('caches repeated reads per session and observes only actual changes', () => { diff --git a/libs/langgraph/src/runtime/publication.ts b/libs/langgraph/src/runtime/publication.ts index a1ad40a82..d40e34936 100644 --- a/libs/langgraph/src/runtime/publication.ts +++ b/libs/langgraph/src/runtime/publication.ts @@ -1,12 +1,12 @@ import type { AgentSessionCustomEvent } from '@threadplane/core'; -import type { LangGraphSnapshot } from './langgraph-snapshot.js'; +import type { LangGraphPublication } from './langgraph-snapshot.js'; import { ownLangGraphSnapshot } from './ownership.js'; /** Backend-private publication. Listener failures are reported once to the * optional callback and otherwise ignored; reporter failures are contained too. * Neither kind of failure changes execution state or rejects a command. */ export function createPublication( - initial: LangGraphSnapshot, + initial: LangGraphPublication, reportListenerError: (error: unknown) => void = () => undefined ) { let current = ownLangGraphSnapshot(initial); @@ -36,7 +36,7 @@ export function createPublication( } } - function publish(input: LangGraphSnapshot): void { + function publish(input: LangGraphPublication): void { // Capture external ingress now, including when a listener queues a publish. const captured = ownLangGraphSnapshot(input, current); schedule(() => { diff --git a/libs/langgraph/src/runtime/session-lifecycle.spec.ts b/libs/langgraph/src/runtime/session-lifecycle.spec.ts index 28ba2fb3f..08045e632 100644 --- a/libs/langgraph/src/runtime/session-lifecycle.spec.ts +++ b/libs/langgraph/src/runtime/session-lifecycle.spec.ts @@ -77,6 +77,7 @@ describe('neutral session ownership', () => { state: undefined, interrupts: [], subgraphs: [], + subagents: [], }); expect(first).not.toHaveBeenCalled(); expect(a.stream).not.toHaveBeenCalled(); diff --git a/libs/langgraph/src/runtime/subagent-projection.ts b/libs/langgraph/src/runtime/subagent-projection.ts new file mode 100644 index 000000000..2eddefe70 --- /dev/null +++ b/libs/langgraph/src/runtime/subagent-projection.ts @@ -0,0 +1,86 @@ +import type { AgentStatus, AgentSubagent } from '@threadplane/core'; +import type { LangGraphSubgraph } from './langgraph-snapshot.js'; + +/** + * A child graph as a core child agent. `id` is the child's namespace path as + * JSON, which stays unique whatever a segment contains, and `name` is the node + * that started it. LangGraph does not + * relate a child graph to a tool call, so `toolCallId` and `description` are + * never set. + */ +export type LangGraphSubagent = AgentSubagent & { + /** The child graph's full namespace path, as in `subgraphs`. */ + readonly namespace: readonly string[]; +}; + +/** A namespace segment is `node:task`; a node name may itself hold no colon. */ +function nodeOf(segment: string): string { + const at = segment.indexOf(':'); + return at < 0 ? segment : segment.slice(0, at); +} + +/** + * - A child that failed is `error`. + * - While the root run is going, a child is `running`. + * - After it, the child's last message decides: a successful one is + * `complete`, and one a pause stopped is still `running`, because a resume + * continues it. Anything else, and a child with no messages, is `unknown`. + */ +function statusOf( + child: LangGraphSubgraph, + running: boolean +): AgentSubagent['status'] { + if (child.error) return 'error'; + if (running) return 'running'; + const last = child.messages.at(-1)?.delivery; + if (last?.phase !== 'complete') return 'unknown'; + if (last.outcome === 'success') return 'complete'; + return last.outcome === 'paused' ? 'running' : 'unknown'; +} + +const projected = new WeakMap< + LangGraphSubgraph, + Partial> +>(); +const none: readonly LangGraphSubagent[] = Object.freeze([]); + +/** + * The session's child graphs as core child agents, in the order they were + * first observed. A child keeps its reference while its child graph and status + * are unchanged, and the list keeps its own while every child does. + */ +export function projectSubagents( + subgraphs: readonly LangGraphSubgraph[], + status: AgentStatus, + previous: readonly LangGraphSubagent[] = none +): readonly LangGraphSubagent[] { + if (!subgraphs.length) return previous.length ? none : previous; + const running = status === 'running'; + let changed = previous.length !== subgraphs.length; + const children = subgraphs.map((child, index) => { + const state = statusOf(child, running); + let known = projected.get(child); + if (!known) projected.set(child, (known = {})); + let subagent = known[state]; + if (!subagent) { + const { namespace } = child; + const message = child.error?.message; + subagent = Object.freeze({ + id: JSON.stringify(namespace), + name: nodeOf(namespace[namespace.length - 1] ?? ''), + ...(namespace.length > 1 && { + parentId: JSON.stringify(namespace.slice(0, -1)), + }), + status: state, + messages: child.messages, + toolCalls: child.toolCalls, + ...(state === 'error' && message && { error: message }), + namespace, + }); + known[state] = subagent; + } + if (previous[index] !== subagent) changed = true; + return subagent; + }); + return changed ? Object.freeze(children) : previous; +} diff --git a/libs/langgraph/src/runtime/subgraph-projection.ts b/libs/langgraph/src/runtime/subgraph-projection.ts index 215b02ce8..2ac8a0fbd 100644 --- a/libs/langgraph/src/runtime/subgraph-projection.ts +++ b/libs/langgraph/src/runtime/subgraph-projection.ts @@ -95,7 +95,7 @@ function replace( previous: SubgraphObservation, namespace: readonly string[], child: ChildProjection, - entry: LangGraphSubgraph + entry: Omit ): SubgraphObservation { const key = JSON.stringify(namespace); const active = new Map(previous.active); @@ -104,7 +104,11 @@ function replace( (value) => JSON.stringify(value.namespace) === key ); const entries = [...previous.subgraphs]; - const projected = ownSubgraph(entry, previous.subgraphs[index]); + // The child's reducer state is the one source of its tool calls. + const projected = ownSubgraph( + { ...entry, toolCalls: child.state.toolCalls }, + previous.subgraphs[index] + ); if (index < 0) entries.push(projected); else entries[index] = projected; return { active, subgraphs: ownSubgraphs(entries, previous.subgraphs) }; diff --git a/libs/langgraph/src/runtime/subgraphs.spec.ts b/libs/langgraph/src/runtime/subgraphs.spec.ts index e8fab8c93..992fbddc7 100644 --- a/libs/langgraph/src/runtime/subgraphs.spec.ts +++ b/libs/langgraph/src/runtime/subgraphs.spec.ts @@ -1,5 +1,6 @@ import { afterEach, describe, expect, it, vi } from 'vitest'; import type { ThreadState } from '@langchain/langgraph-sdk'; +import type { AgentSession } from '@threadplane/core'; import { createSession } from './create-session'; import type { AgentTransport, StreamEvent } from './transport.types'; import { controlledTransport } from './testing/controlled-transport'; @@ -76,6 +77,82 @@ afterEach(async () => { await Promise.all(cleanups.splice(0).map((cleanup) => cleanup())); }); +describe('child graphs as core child agents', () => { + it('publishes one child agent for each child graph, with its own transcript', async () => { + const f = fixture(); + expect(f.session.getSnapshot().subagents).toEqual([]); + const run = f.session.submit('Go'); + await f.started(); + await f.emit(child('Found it', ['research:1'])); + await f.emit(child('Nested', ['research:1', 'tools:2'])); + const running = f.session.getSnapshot(); + expect(running.subagents).toHaveLength(2); + const [research, nested] = running.subagents; + expect(research).toMatchObject({ + id: '["research:1"]', + name: 'research', + status: 'running', + namespace: ['research:1'], + toolCalls: [], + }); + expect('parentId' in research).toBe(false); + expect(nested).toMatchObject({ + id: '["research:1","tools:2"]', + name: 'tools', + parentId: research.id, + status: 'running', + }); + // The child agent and the child graph share one transcript. + expect(research.messages).toBe(running.subgraphs[0].messages); + expect(research.messages[0].content).toBe('Found it'); + // The root transcript does not repeat a child's messages. + expect(running.messages.map((message) => message.content)).toEqual(['Go']); + + // A change to one child leaves the other child agent's reference alone. + await f.emit(child(' again', ['research:1', 'tools:2'])); + const next = f.session.getSnapshot(); + expect(next.subagents[0]).toBe(research); + expect(next.subagents[1]).not.toBe(nested); + // A root-only event keeps the whole list. + await f.emit({ ...child('Root'), namespace: undefined }); + expect(f.session.getSnapshot().subagents).toBe(next.subagents); + + await f.emit(full('Root answer')); + f.streams[0].finish(); + expect(await run).toBe('success'); + const settled = f.session.getSnapshot(); + expect(settled.subagents.map((entry) => entry.status)).toEqual([ + 'complete', + 'complete', + ]); + // A core observer reads the same children. + const observer: AgentSession = f.session; + expect(observer.getSnapshot().subagents?.[0]?.id).toBe('["research:1"]'); + }); + + it('reports a failed child as error and an aborted one as unknown', async () => { + const f = fixture(); + const run = f.session.submit('Go'); + await f.started(); + await f.emit(child('Working', ['ok:1'])); + await f.emit(child('Working', ['bad:2'])); + await f.emit({ + type: 'error', + namespace: ['bad:2'], + data: { error: 'Boom', message: 'The search failed' }, + }); + const failed = f.session.getSnapshot().subagents[1]; + expect(failed.status).toBe('error'); + expect(typeof failed.error).toBe('string'); + expect(f.session.getSnapshot().subagents[0].status).toBe('running'); + await f.session.stop(); + expect(await run).toBe('aborted'); + expect( + f.session.getSnapshot().subagents.map((entry) => entry.status) + ).toEqual(['unknown', 'error']); + }); +}); + describe('private subgraph observations', () => { it('preserves custom root error wrapper fields when capturing event routing', async () => { const session = createSession({ @@ -196,6 +273,18 @@ describe('private subgraph observations', () => { recovery: 'none', }); expect(JSON.stringify(snapshot)).not.toContain('SECRET'); + // The child's call is the child's own: listed with it, not at the root. + expect(snapshot.subgraphs[0].toolCalls.map((call) => call.id)).toEqual([ + 'child-tool', + ]); + expect(snapshot.subagents[0].toolCalls).toBe( + snapshot.subgraphs[0].toolCalls + ); + expect(snapshot.subagents[0].messages[0].toolCallIds).toEqual([ + 'child-tool', + ]); + expect(snapshot.subagents[0]).toMatchObject({ status: 'error' }); + expect(snapshot.subagents[0].error).not.toContain('SECRET'); expect(snapshot.subgraphs[0].messages[0].delivery).toMatchObject({ outcome: 'error', }); diff --git a/libs/langgraph/src/runtime/subgraphs.type-test.ts b/libs/langgraph/src/runtime/subgraphs.type-test.ts index fd962061f..57b6f10e3 100644 --- a/libs/langgraph/src/runtime/subgraphs.type-test.ts +++ b/libs/langgraph/src/runtime/subgraphs.type-test.ts @@ -1,6 +1,13 @@ -import type { AgentSession, Message, PlainValue } from '@threadplane/core'; +import type { + AgentSession, + AgentSubagent, + Message, + PlainValue, + ToolCall, +} from '@threadplane/core'; import { createSession } from './create-session'; import type { LangGraphSubgraph } from './langgraph-snapshot'; +import type { LangGraphSubagent } from './subagent-projection'; const session = createSession({ assistantId: 'a', threadId: 't', @@ -20,6 +27,18 @@ const snapshot = session.getSnapshot(); const children: readonly LangGraphSubgraph[] = snapshot.subgraphs; const messages: readonly Message[] = children[0].messages; const payload: PlainValue = children[0].state?.['any']; +// Child graphs are also published as the core contract's child agents. +const agents: readonly LangGraphSubagent[] = snapshot.subagents; +const coreAgents: readonly AgentSubagent[] | undefined = + observer.getSnapshot().subagents; +const agentCalls: readonly ToolCall[] = agents[0].toolCalls; +const childCalls: readonly ToolCall[] = children[0].toolCalls; +const path: readonly string[] = agents[0].namespace; +// @ts-expect-error The child agents are derived, not assigned. +snapshot.subagents = []; +// @ts-expect-error A child agent exposes no commands. +agents[0].resume([]); +void [coreAgents, agentCalls, childCalls, path]; // @ts-expect-error Observation collection is readonly. snapshot.subgraphs = []; // @ts-expect-error Observation arrays are readonly. diff --git a/scripts/react-parity/dispositions.json b/scripts/react-parity/dispositions.json index ed2e0e46a..96104edda 100644 --- a/scripts/react-parity/dispositions.json +++ b/scripts/react-parity/dispositions.json @@ -12767,6 +12767,17 @@ "reason": "Private staged LangGraph runtime subset; fixture-only and not a neutral public LangGraph root or tarball.", "note": "Resume projection preserves unchanged baseline delivery, attributes current same-ID activity, and limits finalized tool eligibility to the resumed turn across stream batches and follow-ups. Live pause delivery still uses the shared root interrupt batch. Broader T09 migration remains open." }, + { + "id": "source:libs/langgraph/src/runtime/subagent-projection.ts", + "taskIds": [ + "T09", + "T10" + ], + "treatment": "internal", + "status": "in-progress", + "reason": "Private projection of the session's child graphs into the core contract's child agents: an id, the starting node's name, a status and the child's own messages and tool calls.", + "note": "Covered by runtime specs. LangGraph does not relate a child graph to a tool call, so toolCallId and description are never set." + }, { "id": "source:libs/langgraph/src/runtime/subgraph-projection.ts", "taskIds": [ @@ -19227,7 +19238,7 @@ "treatment": "internal", "status": "in-progress", "reason": "Private core AgentSession view of the native owner: a snapshot derived from the native one with the message and tool-call selectors, change-only notification, a display error for a failed run, and text submit, stop and dispose forwarded to the owner.", - "note": "Covered by runtime specs and a React Chat integration spec over the real owner. Exported from the test-only candidate package entry and checked from installed tarballs; not exported from the published package root. A rejected credential (401 or 403) is an auth error and another HTTP status is carried on a server error. State patches, native resume, client-tool evidence, a status check and a failure without a response are not represented." + "note": "Covered by runtime specs and a React Chat integration spec over the real owner. Exported from the test-only candidate package entry and checked from installed tarballs; not exported from the published package root. A rejected credential (401 or 403) is an auth error and another HTTP status is carried on a server error. Client-tool evidence, a status check and a failure without a response are not represented in the core fields." }, { "id": "source:libs/ag-ui/src/runtime/child-projection.ts", From 0b3b7025416bf5438cc949bdf1ed855194b116d0 Mon Sep 17 00:00:00 2001 From: Brian Love Date: Thu, 19 Nov 2026 12:37:09 -0800 Subject: [PATCH 11/18] test(parity): list the AG-UI child projection in the reviewed candidate sources --- scripts/react-parity/ag-ui-candidate-package.mjs | 1 + 1 file changed, 1 insertion(+) diff --git a/scripts/react-parity/ag-ui-candidate-package.mjs b/scripts/react-parity/ag-ui-candidate-package.mjs index cc87d8c8a..5dffbed5e 100644 --- a/scripts/react-parity/ag-ui-candidate-package.mjs +++ b/scripts/react-parity/ag-ui-candidate-package.mjs @@ -36,6 +36,7 @@ export const reviewedSources = [ ...[ 'activity-messages', 'agent-session', + 'child-projection', 'client-tool-ledger', 'client-tools', 'create-http-request', From 6409626d1a0cfdc1bd3813eeff81203382610d99 Mon Sep 17 00:00:00 2001 From: Brian Love Date: Thu, 19 Nov 2026 12:44:57 -0800 Subject: [PATCH 12/18] feat(ag-ui): keep earlier child agents, continue a paused child, and separate reused run ids --- cockpit/ag-ui/subagents/react/src/children.ts | 8 +- cockpit/ag-ui/subagents/react/src/policy.ts | 2 +- libs/ag-ui/src/runtime/README.md | 27 ++-- libs/ag-ui/src/runtime/agent-session.ts | 7 +- .../src/runtime/child-projection.spec.ts | 96 ++++++++++++++ libs/ag-ui/src/runtime/child-projection.ts | 122 +++++++++++++----- libs/ag-ui/src/runtime/create-session.ts | 35 ++--- libs/ag-ui/src/runtime/decision.type-test.ts | 7 + libs/ag-ui/src/runtime/session-http.spec.ts | 42 +++++- libs/ag-ui/src/runtime/session-observation.ts | 8 +- libs/ag-ui/src/runtime/subagents.ts | 95 +++++++++++++- libs/angular/src/observe-agent.ag-ui.spec.ts | 3 +- libs/react/src/use-agent.ag-ui.spec.tsx | 3 +- scripts/react-parity/dispositions.json | 2 +- 14 files changed, 382 insertions(+), 75 deletions(-) diff --git a/cockpit/ag-ui/subagents/react/src/children.ts b/cockpit/ag-ui/subagents/react/src/children.ts index 9a4e77113..e660cd401 100644 --- a/cockpit/ag-ui/subagents/react/src/children.ts +++ b/cockpit/ag-ui/subagents/react/src/children.ts @@ -50,14 +50,16 @@ export function observeChildren( const cards = new Map(previous.map((card) => [card.id, card])); let unsupported = false; try { + // Cards follow the current run; children of earlier runs are history. + const children = snapshot.subagents.filter((child) => !child.earlier); if ( cards.size !== previous.length || previous.length > 100 || - snapshot.subagents.length > 30 + children.length > 30 ) throw new Error(); const attributed = new Set( - snapshot.subagents.map((child) => child.started.subagentRunId) + children.map((child) => child.started.subagentRunId) ); if ( snapshot.transcript.some( @@ -68,7 +70,7 @@ export function observeChildren( ) throw new Error(); const seen = new Set(); - for (const child of snapshot.subagents) { + for (const child of children) { const started = child.started; const id = started.subagentRunId, callId = started.parentToolCallId; diff --git a/cockpit/ag-ui/subagents/react/src/policy.ts b/cockpit/ag-ui/subagents/react/src/policy.ts index 6abf36c79..95467c257 100644 --- a/cockpit/ag-ui/subagents/react/src/policy.ts +++ b/cockpit/ag-ui/subagents/react/src/policy.ts @@ -85,7 +85,7 @@ export function confirmParent( if (!valid()) return; const run = snapshot.run, transcript = snapshot.transcript, - children = snapshot.subagents; + children = snapshot.subagents.filter((child) => !child.earlier); if ( !valid() || snapshot.status !== 'idle' || diff --git a/libs/ag-ui/src/runtime/README.md b/libs/ag-ui/src/runtime/README.md index 96926b977..84ee317bd 100644 --- a/libs/ag-ui/src/runtime/README.md +++ b/libs/ag-ui/src/runtime/README.md @@ -149,16 +149,23 @@ const session = createSession({ threadId, url }); is sent. Each entry is the protocol's interrupt, so it has the core `id`, `reason`, `message` and `toolCallId` and any other field the backend sent. It is absent when nothing is waiting, and for a pause this session cannot answer. -- `subagents` lists the current run's children as core child agents: `id`, - `name`, `description`, `toolCallId`, `parentId`, `status`, and the child's own - `messages` and `toolCalls`, which the root lists do not repeat. The protocol - evidence stays on each child as `started` and `terminal`. A child with - finished evidence is `complete`, one with error evidence is `error` and - carries its message, and one with neither is `running` while the root run is - going and `unknown` after it. A child keeps its reference until its evidence, - status or records change. Children of earlier runs are bare evidence in - `earlierSubagents`. Records are matched by run id, so a later child that - reuses an id also lists the earlier child's records. +- `subagents` lists every child the session knows as a core child agent: + children of earlier root runs first, marked `earlier`, then the current run's, + each in start order. A child has `id`, `name`, `description`, `toolCallId`, + `parentId`, `status`, and its own `messages` and `toolCalls`, which the root + lists do not repeat. The protocol evidence stays on each child as `started` + and `terminal`. `earlierSubagents` still holds the earlier children's bare + evidence. + - Error evidence is `error` and carries its message. Finished evidence is + `complete`, unless the child finished `suspended`: it paused and can + continue, so it is `running` in its own run and while a later run is going, + and `unknown` once a later run ends without continuing it. A child with no + ending is `running` while the root run is going and `unknown` after it. + - A child lists the records attributed to its run id within its own run. A + child that starts again after pausing continues: it is one child, and keeps + the records from before the pause. Any other child that reuses a run id + replaces the earlier one and starts with none of its records. + - A child keeps its reference until its evidence, status or records change. - Every publication notifies subscribers, including one that changes only protocol evidence such as a decision or a child. - `submit` takes text, or `{ message, state? }` with a state patch. diff --git a/libs/ag-ui/src/runtime/agent-session.ts b/libs/ag-ui/src/runtime/agent-session.ts index 090f8fbbc..85280f524 100644 --- a/libs/ag-ui/src/runtime/agent-session.ts +++ b/libs/ag-ui/src/runtime/agent-session.ts @@ -33,9 +33,10 @@ export type SessionSnapshot = Omit< */ readonly interrupts?: readonly SessionInterrupt[]; /** - * The current root run's children, each with its own messages and tool - * calls and the protocol evidence it was read from. Children of earlier - * runs are in `earlierSubagents`. + * Every child agent the session knows, each with its own messages and + * tool calls and the protocol evidence it was read from: children of + * earlier root runs first, marked `earlier`, then the current run's. + * `earlierSubagents` still holds the earlier children's bare evidence. */ readonly subagents: readonly SessionSubagent[]; /** diff --git a/libs/ag-ui/src/runtime/child-projection.spec.ts b/libs/ag-ui/src/runtime/child-projection.spec.ts index 7b8d3e9d0..497e25c74 100644 --- a/libs/ag-ui/src/runtime/child-projection.spec.ts +++ b/libs/ag-ui/src/runtime/child-projection.spec.ts @@ -141,6 +141,102 @@ describe('core interrupts and child agents on the AG-UI snapshot', () => { } }); + it('keeps a paused child running and continues it with its records after resume', async () => { + const fixture = bindingFixture(); + try { + const run = fixture.session.submit('Book it'); + const exchange = await fixture.started(); + const paused = fixture.changed( + (snapshot) => snapshot.subagents[0]?.terminal !== undefined + ); + exchange.emit({ + type: 'SUBAGENT_STARTED', + subagentRunId: 'child', + name: 'booker', + }); + exchange.emit({ + type: 'TEXT_MESSAGE_START', + messageId: 'before', + role: 'assistant', + subagentRunId: 'child', + }); + exchange.emit({ + type: 'TEXT_MESSAGE_CONTENT', + messageId: 'before', + delta: 'Need approval', + }); + exchange.emit({ type: 'TEXT_MESSAGE_END', messageId: 'before' }); + exchange.emit({ + type: 'SUBAGENT_FINISHED', + subagentRunId: 'child', + outcome: { type: 'suspended', interruptIds: ['approval'] }, + }); + await paused; + exchange.emit({ + type: 'RUN_FINISHED', + threadId: exchange.body.threadId, + runId: exchange.body.runId, + outcome: { + type: 'interrupt', + interrupts: [{ id: 'approval', reason: 'approve' }], + }, + }); + await expect(run).resolves.toBe('paused'); + // Paused is not finished: the child can continue. + expect(fixture.session.getSnapshot().subagents[0].status).toBe('running'); + + const resumed = fixture.session.resume([ + { interruptId: 'approval', status: 'resolved' }, + ]); + const next = await fixture.started(1); + // Between the answer and the child's restart it is history, still going. + expect(fixture.session.getSnapshot().subagents).toMatchObject([ + { id: 'child', status: 'running', earlier: true }, + ]); + const continued = fixture.changed( + (snapshot) => + snapshot.subagents.length === 1 && + snapshot.subagents[0].messages.length === 2 + ); + next.emit({ + type: 'SUBAGENT_STARTED', + subagentRunId: 'child', + name: 'booker', + }); + next.emit({ + type: 'TEXT_MESSAGE_START', + messageId: 'after', + role: 'assistant', + subagentRunId: 'child', + }); + next.emit({ + type: 'TEXT_MESSAGE_CONTENT', + messageId: 'after', + delta: 'Booked', + }); + next.emit({ type: 'TEXT_MESSAGE_END', messageId: 'after' }); + // One child, not two, and it keeps what it said before the pause. + const child = (await continued).subagents[0]; + expect(child).not.toHaveProperty('earlier'); + expect(child.messages.map((message) => message.content)).toEqual([ + 'Need approval', + 'Booked', + ]); + next.emit({ type: 'SUBAGENT_FINISHED', subagentRunId: 'child' }); + next.emit({ + type: 'RUN_FINISHED', + threadId: next.body.threadId, + runId: next.body.runId, + }); + await expect(resumed).resolves.toBe('success'); + expect(fixture.session.getSnapshot().subagents[0].status).toBe( + 'complete' + ); + } finally { + await fixture.cleanup(); + } + }); + it('lists pending interrupts until an answer is sent, and answers them by id', async () => { const fixture = bindingFixture(); try { diff --git a/libs/ag-ui/src/runtime/child-projection.ts b/libs/ag-ui/src/runtime/child-projection.ts index e29b602e1..25a92f008 100644 --- a/libs/ag-ui/src/runtime/child-projection.ts +++ b/libs/ag-ui/src/runtime/child-projection.ts @@ -1,19 +1,27 @@ import type { AgentSubagent, Message, ToolCall } from '@threadplane/core'; import { projectMessages, projectToolCalls } from './message-projection.js'; import type { Observation } from './session-observation.js'; -import type { SubagentObservation } from './subagents.js'; +import { + currentFrom, + earlierSpan, + suspended, + type ChildSpan, + type SubagentObservation, +} from './subagents.js'; import type { Transcript } from './transcript.js'; type TranscriptRecord = Transcript[number]; /** - * One child of the current root run: the core child, with the protocol - * evidence it was read from. `messages` and `toolCalls` are the child's own - * and are not repeated in the root snapshot's. They are every transcript record - * attributed to the child's run id, so a later child that reuses an id also - * lists the earlier child's records. + * One child agent: the core child, with the protocol evidence it was read + * from. `messages` and `toolCalls` are the child's own and are not repeated in + * the root snapshot's. */ -export type SessionSubagent = AgentSubagent & SubagentObservation; +export type SessionSubagent = AgentSubagent & + SubagentObservation & { + /** Set on a child that settled in an earlier root run or came with the thread. */ + readonly earlier?: true; + }; /** A child's records read as a root transcript, so the root selectors apply. */ const unattributed = new WeakMap(); @@ -29,12 +37,23 @@ function asRoot(record: TranscriptRecord): TranscriptRecord { return known; } +/** + * - Error evidence is `error`, and finished evidence is `complete`, unless the + * child finished `suspended`: it paused and can continue, so it is `running` + * in its own run and while a later run is going, and `unknown` once a later + * run ends without continuing it. + * - A child with no ending is `running` while the root run is going and + * `unknown` after it. + */ function status( evidence: SubagentObservation, - running: boolean + running: boolean, + earlier: boolean ): AgentSubagent['status'] { - if (evidence.terminal) - return evidence.terminal.type === 'SUBAGENT_ERROR' ? 'error' : 'complete'; + const terminal = evidence.terminal; + if (terminal?.type === 'SUBAGENT_ERROR') return 'error'; + if (terminal && !suspended(evidence)) return 'complete'; + if (terminal) return running || !earlier ? 'running' : 'unknown'; return running ? 'running' : 'unknown'; } @@ -43,35 +62,57 @@ const noMessages: readonly Message[] = Object.freeze([]); const noCalls: readonly ToolCall[] = Object.freeze([]); /** - * The current run's children as core children. Each keeps its reference, and - * the list keeps its own, until that child's evidence, status or transcript - * changes. `previous` is the list this function returned last. + * Every child the session knows as a core child: those of earlier root runs + * first, then the current run's, each list in start order. A current child + * replaces an earlier one with the same run ID. + * + * A child lists the records attributed to its run ID within its own run. A + * child that starts again after pausing continues, and keeps the records from + * before the pause; any other child that reuses an ID starts with none. + * + * Each child keeps its reference, and the list keeps its own, until that + * child's evidence, status or records change. `previous` is the list this + * function returned last. */ export function projectSubagents( native: Observation, previous: readonly SessionSubagent[] = none ): readonly SessionSubagent[] { - if (!native.subagents.length) return previous.length ? none : previous; - const records = new Map(); - for (const record of native.transcript) { - const child = (record as { subagentRunId?: unknown }).subagentRunId; - if (typeof child !== 'string') continue; - const own = records.get(child); - if (own) own.push(asRoot(record)); - else records.set(child, [asRoot(record)]); - } - const prior = new Map(previous.map((child) => [child.id, child])); + const current = native.subagents; + const replaced = new Set(current.map((c) => c.started.subagentRunId)); + const earlier = (native.earlierSubagents ?? []).filter( + (child) => !replaced.has(child.started.subagentRunId) + ); + if (!current.length && !earlier.length) + return previous.length ? none : previous; const running = native.status === 'running'; - let changed = previous.length !== native.subagents.length; - const children = native.subagents.map((evidence, index) => { + const transcript = native.transcript; + const prior = new Map(previous.map((child) => [child.id, child])); + let changed = previous.length !== earlier.length + current.length; + const project = ( + evidence: SubagentObservation, + span: ChildSpan, + isEarlier: boolean, + index: number + ): SessionSubagent => { const { started, terminal } = evidence; const id = started.subagentRunId; + const records: TranscriptRecord[] = []; + const end = Math.min(span.to ?? transcript.length, transcript.length); + for (let position = span.from; position < end; position++) { + const record = transcript[position]; + if ((record as { subagentRunId?: unknown }).subagentRunId === id) + records.push(asRoot(record)); + } const before = prior.get(id); - const state = status(evidence, running); - // A child with terminal evidence streams nothing further. + const state = status(evidence, running, isEarlier); + // Only a child of the run that is going can still be streaming. const view = { - status: state === 'running' ? ('running' as const) : ('idle' as const), - transcript: Object.freeze(records.get(id) ?? []) as Transcript, + status: + state === 'running' && running && !terminal + ? ('running' as const) + : ('idle' as const), + transcript: Object.freeze(records) as Transcript, reasoningDurations: native.reasoningDurations, }; const messages = projectMessages(view, before?.messages ?? noMessages); @@ -81,6 +122,7 @@ export function projectSubagents( before.started === started && before.terminal === terminal && before.status === state && + before.earlier === (isEarlier || undefined) && before.messages === messages && before.toolCalls === toolCalls ) { @@ -107,7 +149,27 @@ export function projectSubagents( typeof terminal.message === 'string' && { error: terminal.message }), started, ...(terminal && { terminal }), + ...(isEarlier && { earlier: true as const }), }) as SessionSubagent; - }); + }; + const children = [ + ...earlier.map((child, index) => + project(child, earlierSpan(child), true, index) + ), + ...current.map((child, index) => + project( + child, + { + from: currentFrom( + child.started.subagentRunId, + current, + native.earlierSubagents + ), + }, + false, + earlier.length + index + ) + ), + ]; return changed ? Object.freeze(children) : previous; } diff --git a/libs/ag-ui/src/runtime/create-session.ts b/libs/ag-ui/src/runtime/create-session.ts index 5d40a174c..502238007 100644 --- a/libs/ag-ui/src/runtime/create-session.ts +++ b/libs/ag-ui/src/runtime/create-session.ts @@ -37,7 +37,7 @@ import { initialObservation, type Observation, } from './session-observation.js'; -import { earlierSubagents, type Subagents } from './subagents.js'; +import { nextInvocation, type Subagents } from './subagents.js'; import { createRun, httpFailure, type RunHandle } from './create-run.js'; import { createPublication } from './session-publication.js'; import { @@ -82,16 +82,20 @@ export interface SessionOptions readonly subagents?: Subagents; readonly interruptMode?: InterruptMode; } -/** A new root invocation observes no children yet; settled ones become history. */ -function nextInvocationSubagents(previous: Observation) { - const earlier = earlierSubagents( - previous.earlierSubagents, - previous.subagents +/** + * A new root invocation observes no children yet; settled ones become history. + * `transcript` is the history the new invocation begins with, when it is not + * the previous one. + */ +function nextInvocationSubagents( + previous: Observation, + transcript: Transcript = previous.transcript +) { + return nextInvocation( + previous, + previous.transcript.length, + transcript.length ); - return { - subagents: Object.freeze([]) as Subagents, - ...(earlier && { earlierSubagents: earlier }), - }; } export interface Session { /** The state declaration this session was created with, when it has one. */ @@ -673,7 +677,7 @@ export function createSession( status: 'running', transcript: last.transcript, state: last.state, - ...nextInvocationSubagents(previous), + ...nextInvocationSubagents(previous, last.transcript), run: Object.freeze({ id }), }), undefined, @@ -703,7 +707,9 @@ export function createSession( root(index) ); if (at < 0) - throw new Error('Regenerate needs the id of an assistant message.'); + throw new Error( + 'Regenerate needs the id of an assistant message.' + ); for (let index = at - 1; index >= 0 && prompt < 0; index--) if (transcript[index].role === 'user' && root(index)) prompt = index; @@ -728,7 +734,7 @@ export function createSession( ...previous, status: 'running', transcript, - ...nextInvocationSubagents(previous), + ...nextInvocationSubagents(previous, transcript), run: Object.freeze({ id }), }), signal, @@ -1492,8 +1498,7 @@ function createToolsOwner( resolve('aborted'); return; } - if (interruptMode !== 'native') - throw new TypeError(NOT_SETTLED); + if (interruptMode !== 'native') throw new TypeError(NOT_SETTLED); const previous = publication.getObservation(); captured = captureResponses(responses); claimDecision( diff --git a/libs/ag-ui/src/runtime/decision.type-test.ts b/libs/ag-ui/src/runtime/decision.type-test.ts index bfb4fdcfc..9845aa13e 100644 --- a/libs/ag-ui/src/runtime/decision.type-test.ts +++ b/libs/ag-ui/src/runtime/decision.type-test.ts @@ -99,3 +99,10 @@ void observer.resume?.([ ]); // @ts-expect-error the core contract has no pause token void observer.resume?.(pause, [resolved]); + +// Child agents of earlier root runs are marked, so a view can tell them apart. +const earlierChild: true | undefined = + session.getSnapshot().subagents[0]?.earlier; +// @ts-expect-error The mark is derived, not assigned. +session.getSnapshot().subagents[0].earlier = true; +void earlierChild; diff --git a/libs/ag-ui/src/runtime/session-http.spec.ts b/libs/ag-ui/src/runtime/session-http.spec.ts index ef29ccec0..f358c4746 100644 --- a/libs/ag-ui/src/runtime/session-http.spec.ts +++ b/libs/ag-ui/src/runtime/session-http.spec.ts @@ -319,8 +319,18 @@ describe('composed private session over held HTTP', () => { [...exchange.body.messages, ...next.body.messages].map((m) => m.id) ).size ).toBe(next.body.messages.length); - // The resumed invocation observes no children yet; the finished one is history. - expect(owner.getSnapshot().subagents).toEqual([]); + // The resumed invocation observes no children yet; the finished one is + // history, and still listed as a child agent with its own records. + const carried = owner.getSnapshot().subagents; + expect(carried).toHaveLength(1); + expect(carried[0]).toMatchObject({ + id: 'child', + status: 'complete', + earlier: true, + }); + expect(carried[0].messages).toEqual(settled.subagents[0].messages); + expect(carried[0].started).toBe(settled.subagents[0].started); + expect(settled.subagents[0]).not.toHaveProperty('earlier'); expect(settled).not.toHaveProperty('earlierSubagents'); expect(settled.subagents[0].terminal?.type).toBe('SUBAGENT_FINISHED'); // History keeps the child's protocol evidence, by reference, without @@ -361,17 +371,35 @@ describe('composed private session over held HTTP', () => { }, terminal: { type: 'SUBAGENT_FINISHED', subagentRunId: 'child' }, }; - // This turn asserts the child's identity and evidence, not its own - // messages and tool calls. + // The new child replaces the earlier one with its ID, and starts with + // none of that child's records. expect(latest).toHaveLength(1); - expect(latest).toMatchObject([ - { id: 'child', name: 'again', status: 'complete', ...reused }, + expect(latest).toStrictEqual([ + { + id: 'child', + name: 'again', + status: 'complete', + messages: [], + toolCalls: [], + ...reused, + }, ]); + expect(carried[0].messages).not.toEqual([]); expect(latest[0].started).toStrictEqual(reused.started); expect(latest[0].terminal).toStrictEqual(reused.terminal); const fourth = owner.submit('once more'); const last = await server.next(3); - expect(owner.getSnapshot().subagents).toEqual([]); + expect(owner.getSnapshot().subagents).toStrictEqual([ + { + id: 'child', + name: 'again', + status: 'complete', + messages: [], + toolCalls: [], + ...reused, + earlier: true, + }, + ]); expect(owner.getSnapshot().earlierSubagents).toStrictEqual([reused]); expect(owner.getSnapshot().earlierSubagents?.[0].started).toBe( latest[0].started diff --git a/libs/ag-ui/src/runtime/session-observation.ts b/libs/ag-ui/src/runtime/session-observation.ts index 5e6b216cc..11601a9e4 100644 --- a/libs/ag-ui/src/runtime/session-observation.ts +++ b/libs/ag-ui/src/runtime/session-observation.ts @@ -12,7 +12,11 @@ import type { PlainValue, } from '@threadplane/core'; import { ownTranscript, type Transcript } from './transcript.js'; -import { applySubagent, ownSubagents, type Subagents } from './subagents.js'; +import { + applySubagent, + restoredSubagents, + type Subagents, +} from './subagents.js'; import { NO_STATE, ownState, applyState } from './state.js'; import { reconcileTranscript } from './reconcile-transcript.js'; import { applyTextMessage } from './text-messages.js'; @@ -113,7 +117,7 @@ export function initialObservation( ): Observation { const transcript = ownTranscript(messages); assertTranscriptIdentity(transcript); - const earlier = ownSubagents(subagents); + const earlier = restoredSubagents(subagents, transcript.length); return Object.freeze({ status: 'idle', transcript, diff --git a/libs/ag-ui/src/runtime/subagents.ts b/libs/ag-ui/src/runtime/subagents.ts index 9993c3f00..9581466e3 100644 --- a/libs/ag-ui/src/runtime/subagents.ts +++ b/libs/ag-ui/src/runtime/subagents.ts @@ -32,6 +32,97 @@ export interface SubagentObservation { } export type Subagents = readonly SubagentObservation[]; +/** Where in the transcript a child's own records lie: from `from`, up to but + * not including `to`. A child of the current invocation has no `to`. */ +export interface ChildSpan { + readonly from: number; + readonly to?: number; +} +/** Bookkeeping beside the evidence, so the published evidence keeps its shape. */ +const invocationStarts = new WeakMap(); +const spans = new WeakMap(); + +/** True for a child whose last evidence says it paused and can continue. */ +export function suspended(child: SubagentObservation): boolean { + const terminal = child.terminal; + return ( + terminal?.type === 'SUBAGENT_FINISHED' && + (terminal.outcome as { type?: unknown } | undefined)?.type === 'suspended' + ); +} + +/** The transcript length when the invocation that owns `current` began. */ +export function invocationStart(current: Subagents): number { + return invocationStarts.get(current) ?? 0; +} + +/** + * The records an earlier child owns. Evidence restored with a thread owns the + * restored records attributed to it. + */ +export function earlierSpan(child: SubagentObservation): ChildSpan { + return spans.get(child) ?? { from: 0 }; +} + +/** + * Where a child of the current invocation begins. A child continues an earlier + * one with the same ID when that one paused, so it keeps those records; any + * other reuse of an ID starts a separate child. + */ +export function currentFrom( + id: string, + current: Subagents, + earlier: Subagents | undefined +): number { + const before = earlier?.find((child) => child.started.subagentRunId === id); + return before && suspended(before) + ? earlierSpan(before).from + : invocationStart(current); +} + +/** Restored evidence owns the restored transcript's records, and no later ones. */ +export function restoredSubagents( + restored: unknown, + transcriptLength: number +): Subagents | undefined { + const owned = ownSubagents(restored); + for (const child of owned ?? []) + spans.set(child, { from: 0, to: transcriptLength }); + return owned; +} + +/** + * Child evidence for the next root invocation. `ending` is the transcript + * length the ending invocation reached, and `start` the length the next one + * begins with; they differ when the next invocation rebuilds its history. + */ +export function nextInvocation( + previous: { + readonly subagents: Subagents; + readonly earlierSubagents?: Subagents; + }, + ending: number, + start: number +): { readonly subagents: Subagents; readonly earlierSubagents?: Subagents } { + for (const child of previous.subagents) + if (child.terminal) + spans.set(child, { + from: currentFrom( + child.started.subagentRunId, + previous.subagents, + previous.earlierSubagents + ), + to: ending, + }); + const earlier = earlierSubagents( + previous.earlierSubagents, + previous.subagents + ); + const subagents: Subagents = Object.freeze([]); + invocationStarts.set(subagents, start); + return { subagents, ...(earlier && { earlierSubagents: earlier }) }; +} + /** History for the next root invocation: earlier children, then this * invocation's children that have terminal evidence. A child with no terminal * evidence is dropped, because nothing later can establish what became of it. @@ -160,5 +251,7 @@ export function applySubagent( started: previous[index].started, terminal: captured, }); - return Object.freeze(next); + const applied: Subagents = Object.freeze(next); + invocationStarts.set(applied, invocationStart(previous)); + return applied; } diff --git a/libs/angular/src/observe-agent.ag-ui.spec.ts b/libs/angular/src/observe-agent.ag-ui.spec.ts index e85b62563..b6c498160 100644 --- a/libs/angular/src/observe-agent.ag-ui.spec.ts +++ b/libs/angular/src/observe-agent.ag-ui.spec.ts @@ -130,7 +130,8 @@ describe('observeAgent native AG-UI owner', () => { { id: 'child', name: 'worker', - status: 'complete', + // The child finished suspended: it paused and can continue. + status: 'running', messages: [], toolCalls: [], started: { diff --git a/libs/react/src/use-agent.ag-ui.spec.tsx b/libs/react/src/use-agent.ag-ui.spec.tsx index 660f10e0c..69591dc4e 100644 --- a/libs/react/src/use-agent.ag-ui.spec.tsx +++ b/libs/react/src/use-agent.ag-ui.spec.tsx @@ -120,7 +120,8 @@ describe('useAgent native AG-UI owner', () => { { id: 'child', name: 'worker', - status: 'complete', + // The child finished suspended: it paused and can continue. + status: 'running', messages: [], toolCalls: [], started: { diff --git a/scripts/react-parity/dispositions.json b/scripts/react-parity/dispositions.json index ed2e0e46a..8c3a82f29 100644 --- a/scripts/react-parity/dispositions.json +++ b/scripts/react-parity/dispositions.json @@ -19239,7 +19239,7 @@ "treatment": "internal", "status": "in-progress", "reason": "Private projection of the current run's child evidence into the core contract's child agents: each child's id, name, task, status and its own messages and tool calls, with the protocol evidence kept alongside.", - "note": "Covered by runtime specs over the real owner. Children of earlier runs stay bare evidence in earlierSubagents, and a child that reuses a run id also lists the earlier child's records." + "note": "Covered by runtime specs over the real owner. Children of earlier runs are listed first and marked earlier. A child that restarts after pausing continues with its records; any other reuse of a run id starts a separate child." }, { "id": "source:libs/ag-ui/src/runtime/message-projection.ts", From fa88cb8ea61d673536960cb9889281a627d17937 Mon Sep 17 00:00:00 2001 From: Brian Love Date: Thu, 19 Nov 2026 12:54:18 -0800 Subject: [PATCH 13/18] feat(react): show the session's child agents as subagent cards in Chat --- .../chat/components/chat-subagent-card.mdx | 6 +- .../react/src/chat/chat-fake-session.spec.tsx | 95 +++++++++++++ libs/react/src/chat/chat.tsx | 29 +++- libs/react/src/chat/index.ts | 4 + libs/react/src/chat/message-list.tsx | 44 +++++- libs/react/src/chat/session-subagents.spec.ts | 125 ++++++++++++++++++ libs/react/src/chat/session-subagents.ts | 114 ++++++++++++++++ scripts/react-parity/dispositions.json | 30 +++++ 8 files changed, 435 insertions(+), 12 deletions(-) create mode 100644 libs/react/src/chat/session-subagents.spec.ts create mode 100644 libs/react/src/chat/session-subagents.ts diff --git a/apps/website/content/docs/react/chat/components/chat-subagent-card.mdx b/apps/website/content/docs/react/chat/components/chat-subagent-card.mdx index b09b4c6a0..3cd16d872 100644 --- a/apps/website/content/docs/react/chat/components/chat-subagent-card.mdx +++ b/apps/website/content/docs/react/chat/components/chat-subagent-card.mdx @@ -57,7 +57,11 @@ The existing shared backend runs c-subagents. Runtime settings can select a deve `SubagentCard` shows one child agent: its name, a status, a message count, and the child's messages and tool activity behind a closed disclosure. It only presents the data you pass it. Your application still owns the run, the session and any saved history. -Pass `subagents` to `MessageList` or `Chat` to place cards for you. A child whose `toolCallId` matches a tool call in a row renders as a card in place of that call's activity. A child with no matching call is not placed; render `SubagentCard` yourself where it belongs. +`Chat` shows a card for each child agent its session reports in `snapshot.subagents`, with no code from you. A child that names the tool call that started it takes that call's place. A child that names no call, such as a LangGraph child graph, follows the tool calls of the first assistant message of the latest turn, so its card keeps its place as the turn goes on. `toolLabel` and `toolOutcome` apply to the children's own tool calls. + +Pass `subagents` to `Chat` to show your own list instead; an empty list shows no cards. Pass `subagents` to `MessageList` to place cards for you there. A child whose `toolCallId` matches a tool call in a row renders as a card in place of that call's activity. A child with no matching call is not placed unless you set `placeUnanchoredSubagents`; otherwise render `SubagentCard` yourself where it belongs. + +`sessionSubagents(snapshot.subagents)` returns the same card data `Chat` builds, for an application that renders `MessageList` itself. It keeps each card's reference while its child is unchanged. ```tsx import { MessageList, subagentsFromEvidence } from '@threadplane/react/chat'; diff --git a/libs/react/src/chat/chat-fake-session.spec.tsx b/libs/react/src/chat/chat-fake-session.spec.tsx index 05e22763d..9408d8095 100644 --- a/libs/react/src/chat/chat-fake-session.spec.tsx +++ b/libs/react/src/chat/chat-fake-session.spec.tsx @@ -73,3 +73,98 @@ it('drives useAgent through the fake session controls', () => { expect(result.current.status).toBe('error'); expect(result.current.error?.message).toBe('Down'); }); + +it('shows the child agents the session reports, with no subagents prop', () => { + const fake = createFakeAgentSession(); + const view = render(); + act(() => { + fake.set({ + messages: [ + { role: 'user', content: 'Research it' }, + { role: 'assistant', content: 'Delegating', toolCallIds: ['task-1'] }, + { role: 'assistant', content: 'Here is the summary' }, + ], + toolCalls: [ + { id: 'task-1', name: 'task', args: {}, status: 'complete', result: 1 }, + ], + subagents: [ + { + // Related to the root call that started it: the card takes its place. + id: 'anchored', + name: 'researcher', + toolCallId: 'task-1', + messages: [ + { + role: 'assistant', + content: 'Found two sources', + toolCallIds: ['search-1'], + }, + ], + toolCalls: [ + { + id: 'search-1', + name: 'search', + args: { q: 'sources' }, + status: 'complete', + result: 'ok', + }, + ], + }, + // Related to no call, as a LangGraph child graph is. + { id: 'loose', name: 'writer', status: 'error', error: 'It failed' }, + ], + }); + }); + const cards = [ + ...view.container.querySelectorAll('[data-subagent-id]'), + ]; + expect(cards.map((card) => card.dataset['subagentId'])).toEqual([ + 'anchored', + 'loose', + ]); + expect(cards[0].textContent).toContain('researcher'); + expect(cards[0].textContent).toContain('Found two sources'); + expect(cards[1].textContent).toContain('writer'); + expect(cards[1].textContent).toContain('It failed'); + // Both belong to the turn's first assistant message, not the last one. + const first = view.getByText('Delegating').closest('.tp-chat-message'); + expect(first?.contains(cards[0])).toBe(true); + expect(first?.contains(cards[1])).toBe(true); + // The delegating call is the card, not also a tool row. + expect(view.queryByText('task')).toBeNull(); +}); + +it('lets the subagents prop replace the session child agents', () => { + const fake = createFakeAgentSession({ + subagents: [{ id: 'reported', name: 'reported-child' }], + messages: [ + { role: 'user', content: 'Go' }, + { role: 'assistant', content: 'Done', toolCallIds: ['task-1'] }, + ], + toolCalls: [ + { id: 'task-1', name: 'task', args: {}, status: 'complete', result: 1 }, + ], + }); + const none = render(); + expect(none.container.querySelector('[data-subagent-id]')).toBeNull(); + none.unmount(); + const own = render( + + ); + expect( + [...own.container.querySelectorAll('[data-subagent-id]')].map( + (card) => card.dataset['subagentId'] + ) + ).toEqual(['mine']); +}); diff --git a/libs/react/src/chat/chat.tsx b/libs/react/src/chat/chat.tsx index fd992db17..c272892bd 100644 --- a/libs/react/src/chat/chat.tsx +++ b/libs/react/src/chat/chat.tsx @@ -33,6 +33,7 @@ import { type MessageListProps, } from './message-list.js'; import { ScrollBubble } from './scroll-bubble.js'; +import { sessionSubagents } from './session-subagents.js'; import { Select, type SelectOption } from './select.js'; import { ThreadList, type ThreadListItem } from './thread-list.js'; @@ -71,7 +72,11 @@ export interface ChatProps * the composer when none is. The app passes `clientTools.tools` to the session; Chat never runs a tool. Off unless set. */ readonly clientTools?: ChatClientTools; - /** Child agents shown as subagent cards in place of the tool calls that started them. Keep stable. */ + /** + * Child agents shown as subagent cards in place of the tool calls that started them. Keep stable. + * Left unset, Chat shows the child agents the session reports in `snapshot.subagents`. Pass a list, + * which may be empty, to show that instead. + */ readonly subagents?: MessageListProps['subagents']; /** Application-owned handler for a retry declared by `toolOutcome`; Chat never re-runs a call. Keep stable. */ readonly onToolRetry?: MessageListProps['onToolRetry']; @@ -281,7 +286,8 @@ export function Chat({ // handles it itself. Built-in actions stay off until `messageActions` is set. const actions = useMemo(() => { if (!messageActions || !session.regenerate) return messageActions; - if (messageActions !== true && messageActions.onRegenerate) return messageActions; + if (messageActions !== true && messageActions.onRegenerate) + return messageActions; return { ...(messageActions === true ? {} : messageActions), onRegenerate: (messageId: string) => { @@ -415,6 +421,15 @@ export function Chat({ suggestionFocus.current = false; composer.current?.focus(); }, [greeted]); + // The session's own child agents, unless the app supplies the cards. + const children = subagents === undefined ? snapshot.subagents : undefined; + const reported = useMemo( + () => + children?.length + ? sessionSubagents(children, { toolLabel, toolOutcome }) + : undefined, + [children, toolLabel, toolOutcome] + ); // The run's messages keep their identity while only later snapshots change. const messages = snapshot.messages; const runMessages = useMemo(() => { @@ -458,7 +473,9 @@ export function Chat({ renderToolCall={renderToolCall} renderToolCallPrompt={renderPrompt} renderToolResult={renderToolResult} - subagents={subagents} + subagents={subagents ?? reported} + // A session child may name no tool call, as a LangGraph child graph does not. + placeUnanchoredSubagents={subagents === undefined} onToolRetry={onToolRetry} plan={snapshot.plan} onStop={snapshot.status === 'running' ? stop : undefined} @@ -485,7 +502,11 @@ export function Chat({ } > {runActivity === null ? null : ( -
+
{runActivity}
)} diff --git a/libs/react/src/chat/index.ts b/libs/react/src/chat/index.ts index 7869e31f6..9af627f18 100644 --- a/libs/react/src/chat/index.ts +++ b/libs/react/src/chat/index.ts @@ -58,6 +58,10 @@ export { type SubagentEvidenceRecord, type SubagentProjection, } from './subagent-evidence.js'; +export { + sessionSubagents, + type SessionSubagentOptions, +} from './session-subagents.js'; export { Suggestions, type SuggestionItem, diff --git a/libs/react/src/chat/message-list.tsx b/libs/react/src/chat/message-list.tsx index be566778f..182abbaaf 100644 --- a/libs/react/src/chat/message-list.tsx +++ b/libs/react/src/chat/message-list.tsx @@ -160,6 +160,11 @@ export interface MessageListProps { * stable between updates; custom renderMessage retains full ownership. */ readonly subagents?: readonly SubagentInfo[]; + /** + * Also places a child that names no tool call: its card follows the tool calls of the first + * assistant message of the latest turn. Off unless set, so such children stay with the application. + */ + readonly placeUnanchoredSubagents?: boolean; /** * Answered approvals, each rendered as a one-line `ApprovalRecord` after the row its `afterId` * names, or after the last row when that row is absent. Records stay where the app put them while @@ -320,15 +325,33 @@ function toolRowsShownElsewhere( } const NO_CITATIONS: readonly never[] = []; const NO_SUBAGENTS: readonly SubagentInfo[] = Object.freeze([]); -/** Each row's children by spawning call. Rows without one share a constant so their memo stays stable. */ +/** + * Each row's children by spawning call. With `unanchored`, a child that names + * no call belongs to the first assistant message of the latest turn, so its + * card keeps its place as the turn goes on. Rows without one share a constant + * so their memo stays stable. + */ function subagentsByRow( rows: readonly MessageRow[], - subagents: readonly SubagentInfo[] + subagents: readonly SubagentInfo[], + unanchored: boolean ): readonly (readonly SubagentInfo[])[] { - return rows.map((row) => { - const own = subagents.filter((subagent) => - row.toolCalls.some((call) => call.id === subagent.toolCallId) + const loose = unanchored + ? subagents.filter((subagent) => subagent.toolCallId === undefined) + : []; + let home = -1; + if (loose.length) + for (let index = rows.length - 1; index >= 0; index--) { + if (rows[index].role === 'user') break; + if (rows[index].role === 'assistant') home = index; + } + return rows.map((row, index) => { + const own = subagents.filter( + (subagent) => + subagent.toolCallId !== undefined && + row.toolCalls.some((call) => call.id === subagent.toolCallId) ); + if (index === home) own.push(...loose); return own.length ? own : NO_SUBAGENTS; }); } @@ -558,6 +581,9 @@ function RowView({ if (last && 'activities' in last) last.activities.push(activity); else runs.push({ activities: [activity] }); }); + // A child that names no call follows the message's own calls. + for (const child of subagents) + if (child.toolCallId === undefined) runs.push({ child }); // The plan and Stop belong to the row's last built-in group, the one the turn is still running. const planGroup = [...runs].reverse().find((run) => 'activities' in run); const actionLabel = @@ -722,6 +748,7 @@ export function MessageList({ onStop, running = false, subagents, + placeUnanchoredSubagents = false, approvalRecords, typingIndicator = true, messageActions, @@ -754,8 +781,11 @@ export function MessageList({ [onToolRetry, rows] ); const rowSubagents = useMemo( - () => (subagents?.length ? subagentsByRow(rows, subagents) : undefined), - [rows, subagents] + () => + subagents?.length + ? subagentsByRow(rows, subagents, placeUnanchoredSubagents) + : undefined, + [rows, subagents, placeUnanchoredSubagents] ); const retrying = useMemo( () => (toolOutcome ? retryingByRow(rows) : undefined), diff --git a/libs/react/src/chat/session-subagents.spec.ts b/libs/react/src/chat/session-subagents.spec.ts new file mode 100644 index 000000000..a0d136c3f --- /dev/null +++ b/libs/react/src/chat/session-subagents.spec.ts @@ -0,0 +1,125 @@ +import { completeDelivery, type AgentSubagent } from '@threadplane/core'; +import { describe, expect, it, vi } from 'vitest'; +import { sessionSubagents } from './session-subagents'; + +const child = (over: Partial = {}): AgentSubagent => ({ + id: 'c', + name: 'researcher', + description: 'Find sources', + toolCallId: 'task-1', + status: 'complete', + messages: [ + { + id: 'u', + role: 'user', + content: 'Find sources', + delivery: completeDelivery('g', 'success'), + }, + { + id: 'a', + role: 'assistant', + content: 'Found two', + reasoning: 'Looking', + toolCallIds: ['search-1', 'missing'], + delivery: completeDelivery('g', 'success'), + }, + { + id: 'empty', + role: 'assistant', + content: '', + delivery: completeDelivery('g', 'success'), + }, + ], + toolCalls: [ + { + id: 'search-1', + name: 'search', + args: { q: 'sources' }, + status: 'complete', + result: { hits: 2 }, + }, + ], + ...over, +}); + +describe('sessionSubagents', () => { + it('builds card data from a core child agent', () => { + const [card] = sessionSubagents([child()], { + toolLabel: (name) => (name === 'search' ? 'Searching' : undefined), + }); + expect(card).toMatchObject({ + id: 'c', + name: 'researcher', + description: 'Find sources', + toolCallId: 'task-1', + status: 'complete', + }); + // Only the child's own answers are shown; an empty one adds nothing. + expect(card.messages).toHaveLength(1); + expect(card.messages[0]).toMatchObject({ + id: 'a', + text: 'Found two', + reasoning: 'Looking', + }); + // A call the child does not list is skipped, not invented. + expect(card.messages[0].activities).toEqual([ + expect.objectContaining({ + id: 'search-1', + name: 'search', + label: 'Searching', + phase: 'complete', + resultText: JSON.stringify({ hits: 2 }, null, 2), + }), + ]); + }); + + it('carries a failure as the card summary and omits absent fields', () => { + const [card] = sessionSubagents([ + { + id: 'x', + status: 'error', + error: 'It failed', + messages: [], + toolCalls: [], + }, + ]); + expect(card).toEqual({ + id: 'x', + status: 'error', + messages: [], + errorSummary: 'It failed', + }); + }); + + it('keeps references while a child and the callbacks are unchanged', () => { + const first = child(); + const second = child({ id: 'd' }); + const toolLabel = vi.fn(() => undefined); + const children = [first, second]; + const cards = sessionSubagents(children, { toolLabel }); + expect(sessionSubagents(children, { toolLabel })).toBe(cards); + // A new list with one changed child keeps the other child's card. + const next = sessionSubagents( + [first, child({ id: 'd', status: 'error' })], + { + toolLabel, + } + ); + expect(next).not.toBe(cards); + expect(next[0]).toBe(cards[0]); + expect(next[1]).not.toBe(cards[1]); + // A different callback rebuilds, so a stale label is never shown. + expect( + sessionSubagents(children, { toolLabel: () => 'Other' })[0] + ).not.toBe(cards[0]); + }); + + it('contains a throwing outcome callback', () => { + const [card] = sessionSubagents([child()], { + toolOutcome: () => { + throw new Error('app bug'); + }, + }); + expect(card.messages[0].activities?.[0].phase).toBe('complete'); + }); +}); diff --git a/libs/react/src/chat/session-subagents.ts b/libs/react/src/chat/session-subagents.ts new file mode 100644 index 000000000..164a0dd46 --- /dev/null +++ b/libs/react/src/chat/session-subagents.ts @@ -0,0 +1,114 @@ +import type { AgentSubagent, ToolCall } from '@threadplane/core'; +import type { SubagentInfo, SubagentMessageInfo } from './subagent-card.js'; +import { toolActivityPhase, type ToolActivityInfo } from './tool-activity.js'; +import { + resolveToolOutcome, + type ToolActivityOutcome, +} from './tool-outcome.js'; + +/** App-authored presentation for the children's own tool calls. */ +export interface SessionSubagentOptions { + readonly toolLabel?: (name: string, args?: unknown) => string | undefined; + readonly toolOutcome?: ( + activity: ToolActivityInfo + ) => ToolActivityOutcome | undefined; +} + +/** Argument and result text, as `MessageList` shows it for root calls. */ +const literal = (value: unknown): string => + typeof value === 'string' ? value : JSON.stringify(value, null, 2) ?? ''; + +function card( + child: AgentSubagent, + { toolLabel, toolOutcome }: SessionSubagentOptions +): SubagentInfo { + const calls = new Map( + child.toolCalls.map((call) => [call.id, call]) + ); + const running = child.status === 'running'; + const messages: SubagentMessageInfo[] = []; + for (const message of child.messages) { + if (message.role !== 'assistant') continue; + const activities: ToolActivityInfo[] = []; + for (const id of message.toolCallIds ?? []) { + const call = calls.get(id); + if (!call) continue; + const activity: ToolActivityInfo = { + id: call.id, + name: call.name, + label: toolLabel?.(call.name, call.args), + phase: toolActivityPhase(call.status, message.delivery, running), + argumentsText: literal(call.args), + resultText: + call.status === 'complete' ? literal(call.result) : undefined, + errorText: call.status === 'error' ? call.error : undefined, + }; + let outcome: ToolActivityOutcome | undefined; + try { + outcome = toolOutcome?.(activity); + } catch { + // A throwing app hook must not break the card; the call keeps its phase. + } + activities.push( + outcome ? resolveToolOutcome(activity, outcome) : activity + ); + } + const text = message.content || undefined; + const reasoning = message.reasoning || undefined; + if (!text && !reasoning && !activities.length) continue; + messages.push({ + id: message.id, + ...(text && { text }), + ...(reasoning && { reasoning }), + ...(activities.length && { activities }), + }); + } + return { + id: child.id, + ...(child.toolCallId !== undefined && { toolCallId: child.toolCallId }), + ...(child.name !== undefined && { name: child.name }), + ...(child.description !== undefined && { + description: child.description, + }), + status: child.status, + messages, + ...(child.error !== undefined && { errorSummary: child.error }), + }; +} + +interface Known { + readonly options: SessionSubagentOptions; + readonly info: SubagentInfo; +} +const cards = new WeakMap(); +const lists = new WeakMap< + readonly AgentSubagent[], + { + readonly options: SessionSubagentOptions; + readonly list: readonly SubagentInfo[]; + } +>(); +const same = (a: SessionSubagentOptions, b: SessionSubagentOptions) => + a.toolLabel === b.toolLabel && a.toolOutcome === b.toolOutcome; + +/** + * Card data for the child agents a session reports in `snapshot.subagents`. + * A child whose reference is unchanged keeps its card's reference, and an + * unchanged list keeps its own, while the two callbacks stay the same. + */ +export function sessionSubagents( + children: readonly AgentSubagent[], + options: SessionSubagentOptions = {} +): readonly SubagentInfo[] { + const known = lists.get(children); + if (known && same(known.options, options)) return known.list; + const list = children.map((child) => { + const before = cards.get(child); + if (before && same(before.options, options)) return before.info; + const info = card(child, options); + cards.set(child, { options, info }); + return info; + }); + lists.set(children, { options, list }); + return list; +} diff --git a/scripts/react-parity/dispositions.json b/scripts/react-parity/dispositions.json index d89540b13..bf78471fc 100644 --- a/scripts/react-parity/dispositions.json +++ b/scripts/react-parity/dispositions.json @@ -19108,6 +19108,36 @@ "target": "libs/react/src/chat/subagent-card.tsx", "reason": "Readonly child-agent presentation matching the Angular subagent card: name, status, message count, and the child's messages and tool activity behind one closed disclosure. MessageList places a card in the tool call that started the child. Status and messages are borrowed; execution, sessions and restored child history remain application-owned. This does not certify whole-framework parity." }, + { + "id": "export:libs/react/src/chat/index.ts#sessionSubagents", + "taskIds": [ + "T28" + ], + "treatment": "react", + "status": "in-progress", + "target": "libs/react/src/chat/session-subagents.ts", + "reason": "React-only projection from the child agents a core session reports into subagent card data. Chat applies it by default when no subagents prop is given; a child keeps its card's reference while it is unchanged. No session ownership." + }, + { + "id": "export:libs/react/src/chat/index.ts#SessionSubagentOptions", + "taskIds": [ + "T28" + ], + "treatment": "react", + "status": "in-progress", + "target": "libs/react/src/chat/session-subagents.ts", + "reason": "React-only projection from the child agents a core session reports into subagent card data. Chat applies it by default when no subagents prop is given; a child keeps its card's reference while it is unchanged. No session ownership." + }, + { + "id": "source:libs/react/src/chat/session-subagents.ts", + "taskIds": [ + "T28" + ], + "treatment": "react", + "status": "in-progress", + "target": "libs/react/src/chat/session-subagents.ts", + "reason": "React-only projection from the child agents a core session reports into subagent card data. Chat applies it by default when no subagents prop is given; a child keeps its card's reference while it is unchanged. No session ownership." + }, { "id": "export:libs/react/src/chat/index.ts#subagentsFromEvidence", "taskIds": [ From fb5fb6c04cb3629da62550b8e66999829acb6b3d Mon Sep 17 00:00:00 2001 From: Brian Love Date: Thu, 19 Nov 2026 12:57:48 -0800 Subject: [PATCH 14/18] feat(react): answer session interrupts from Chat with renderInterrupt --- .../chat/components/chat-interrupt-panel.mdx | 35 +++++ .../react/src/chat/chat-fake-session.spec.tsx | 136 +++++++++++++++++- libs/react/src/chat/chat.tsx | 30 +++- libs/react/src/chat/index.ts | 4 + libs/react/src/chat/session-interrupts.tsx | 114 +++++++++++++++ scripts/react-parity/dispositions.json | 30 ++++ 6 files changed, 347 insertions(+), 2 deletions(-) create mode 100644 libs/react/src/chat/session-interrupts.tsx diff --git a/apps/website/content/docs/react/chat/components/chat-interrupt-panel.mdx b/apps/website/content/docs/react/chat/components/chat-interrupt-panel.mdx index 5f5cb5733..1e6461df3 100644 --- a/apps/website/content/docs/react/chat/components/chat-interrupt-panel.mdx +++ b/apps/website/content/docs/react/chat/components/chat-interrupt-panel.mdx @@ -57,6 +57,41 @@ The shared backend runs c-interrupts by default. Runtime settings can select a d Moving between Code and Run preserves the mounted example and unsent draft. Reloading starts an empty page-local conversation. +## Answer session interrupts from Chat + +A session that can pause lists what it waits on in `snapshot.interrupts`. `Chat` shows nothing for an interrupt by itself, because which value answers an interrupt is the backend's contract. Pass `renderInterrupt` to draw each one, and call `respond.resolve(value)` or `respond.cancel()` from your card: + +```tsx +import { ApprovalCard, Chat } from '@threadplane/react/chat'; + + ( + respond.resolve({ approved: true }), + }, + { + id: 'decline', + label: 'Decline', + onSelect: () => respond.resolve({ approved: false }), + }, + ]} + > + {interrupt.message ?? interrupt.reason} + + )} +/>; +``` + +The cards take the place of the `approval` slot, so the composer reads "Answer the approval to continue" while they are pending and focus returns to it afterwards. `Chat` holds each answer until every pending interrupt has one, then sends them together with one `session.resume`, because a paused run continues once. `respond.answered` is true for an interrupt whose answer waits on the others, and `respond.sending` is true while the answers are on their way. + +If `session.resume` rejects, the answers are dropped so the person can answer again, and the failure goes to `onInterruptError`. `renderInterrupt` is ignored while `approval` is set and on a session that has no `resume`. + ## Build from source From a Threadplane checkout with dependencies installed: diff --git a/libs/react/src/chat/chat-fake-session.spec.tsx b/libs/react/src/chat/chat-fake-session.spec.tsx index 9408d8095..806164545 100644 --- a/libs/react/src/chat/chat-fake-session.spec.tsx +++ b/libs/react/src/chat/chat-fake-session.spec.tsx @@ -10,8 +10,9 @@ import { createFakeAgentSession, type FakeAssistantStream, } from '@threadplane/core/testing'; +import type { AgentSession, CompleteOutcome } from '@threadplane/core'; import { useAgent } from '../use-agent'; -import { Chat } from './index'; +import { Chat, type RenderInterrupt } from './index'; afterEach(cleanup); @@ -168,3 +169,136 @@ it('lets the subagents prop replace the session child agents', () => { ) ).toEqual(['mine']); }); + +const card: RenderInterrupt = (interrupt, respond) => ( +
+

{interrupt.message}

+ + +
+); + +it('shows nothing for a pending interrupt unless renderInterrupt is set', () => { + const fake = createFakeAgentSession({ + interrupts: [{ id: 'i1', message: 'Refund $20?' }], + }); + const view = render(); + expect(view.queryByText('Refund $20?')).toBeNull(); + expect( + view.getByRole('textbox', { name: 'Message' }).getAttribute('placeholder') + ).not.toBe('Answer the approval to continue'); +}); + +it('answers one interrupt through session.resume from renderInterrupt', async () => { + const fake = createFakeAgentSession({ + interrupts: [{ id: 'i1', message: 'Refund $20?' }], + }); + const view = render(); + expect(view.getByText('Refund $20?')).toBeTruthy(); + // The composer waits on the answer, as it does for the approval slot. + expect( + view.getByRole('textbox', { name: 'Message' }).getAttribute('placeholder') + ).toBe('Answer the approval to continue'); + await act(async () => { + fireEvent.click(view.getByRole('button', { name: 'Approve i1' })); + }); + expect(fake.resumes.map((call) => call.responses)).toEqual([ + [{ interruptId: 'i1', status: 'resolved', value: { approved: true } }], + ]); + // The fake removes an answered interrupt; the card goes with it. + expect(view.queryByText('Refund $20?')).toBeNull(); +}); + +it('holds answers until every pending interrupt has one, then sends them together', async () => { + const fake = createFakeAgentSession({ + interrupts: [ + { id: 'i1', message: 'First?' }, + { id: 'i2', message: 'Second?' }, + ], + }); + const view = render(); + await act(async () => { + fireEvent.click(view.getByRole('button', { name: 'Cancel i2' })); + }); + expect(fake.resumes).toHaveLength(0); + expect( + view.container + .querySelector('[data-interrupt="i2"]') + ?.getAttribute('data-answered') + ).toBe('true'); + await act(async () => { + fireEvent.click(view.getByRole('button', { name: 'Approve i1' })); + }); + // One resume, in the order the session lists the interrupts. + expect(fake.resumes.map((call) => call.responses)).toEqual([ + [ + { interruptId: 'i1', status: 'resolved', value: { approved: true } }, + { interruptId: 'i2', status: 'cancelled' }, + ], + ]); +}); + +it('lets the interrupts be answered again after resume rejects', async () => { + let fail = true; + const fake = createFakeAgentSession({ + interrupts: [{ id: 'i1', message: 'Refund $20?' }], + }); + // A session that refuses the first answer and leaves the interrupt pending. + const session: AgentSession = { + ...fake.session, + resume: (responses, options) => + fail + ? Promise.reject(new TypeError('Not accepted')) + : (fake.session.resume?.( + responses, + options + ) as Promise), + }; + const errors: unknown[] = []; + const view = render( + errors.push(error)} + /> + ); + await act(async () => { + fireEvent.click(view.getByRole('button', { name: 'Approve i1' })); + }); + expect(errors).toHaveLength(1); + expect(errors[0]).toBeInstanceOf(TypeError); + expect(fake.resumes).toHaveLength(0); + // Still pending, and its control is usable again. + const again = view.getByRole('button', { name: 'Approve i1' }); + expect((again as HTMLButtonElement).disabled).toBe(false); + fail = false; + await act(async () => { + fireEvent.click(again); + }); + expect(errors).toHaveLength(1); + expect(fake.resumes).toHaveLength(1); + expect(view.queryByText('Refund $20?')).toBeNull(); +}); + +it('leaves the approval slot to the app when approval is set', () => { + const fake = createFakeAgentSession({ + interrupts: [{ id: 'i1', message: 'Refund $20?' }], + }); + const view = render( + App approval

} + /> + ); + expect(view.getByText('App approval')).toBeTruthy(); + expect(view.queryByText('Refund $20?')).toBeNull(); +}); diff --git a/libs/react/src/chat/chat.tsx b/libs/react/src/chat/chat.tsx index c272892bd..0ccb2968c 100644 --- a/libs/react/src/chat/chat.tsx +++ b/libs/react/src/chat/chat.tsx @@ -33,6 +33,10 @@ import { type MessageListProps, } from './message-list.js'; import { ScrollBubble } from './scroll-bubble.js'; +import { + useSessionInterrupts, + type RenderInterrupt, +} from './session-interrupts.js'; import { sessionSubagents } from './session-subagents.js'; import { Select, type SelectOption } from './select.js'; import { ThreadList, type ThreadListItem } from './thread-list.js'; @@ -109,6 +113,20 @@ export interface ChatProps * composer. The app decides when it is pending and what answering does. */ readonly approval?: ReactNode; + /** + * Draws each interrupt the session reports in `snapshot.interrupts`, in the place `approval` + * takes. Chat shows nothing for an interrupt by itself: return the card, and call + * `respond.resolve(value)` or `respond.cancel()` from it. Chat holds each answer until every + * pending interrupt has one, then sends them together with `session.resume`. Which value answers + * an interrupt is the backend's contract, so it stays with the app. Ignored while `approval` is + * set, and on a session with no `resume`. Off unless set. + */ + readonly renderInterrupt?: RenderInterrupt; + /** + * Called when `session.resume` rejects an answer sent from `renderInterrupt`; the interrupts can + * then be answered again. Left unset, the failure is reported as an unhandled error. + */ + readonly onInterruptError?: (error: unknown) => void; /** Answered approvals as one-line records in the transcript; see `MessageListProps.approvalRecords`. */ readonly approvalRecords?: MessageListProps['approvalRecords']; /** Built-in Copy and rating under finished assistant messages; see `MessageListProps.messageActions`. Keep stable. */ @@ -252,7 +270,9 @@ export function Chat({ inputTrailing, inputFooter, modelPicker, - approval, + approval: ownApproval, + renderInterrupt, + onInterruptError, approvalRecords, messageActions, math, @@ -322,6 +342,14 @@ export function Chat({ // composer. An app that disables the composer while the answered run goes on // gets focus there as soon as it is enabled again. const composer = useRef(null); + // The session's own pending interrupts, unless the app supplies the approval. + const asks = useSessionInterrupts( + session, + snapshot.interrupts, + ownApproval === undefined ? renderInterrupt : undefined, + onInterruptError + ); + const approval = ownApproval === undefined ? asks : ownApproval; const pending = approval !== undefined && approval !== null && approval !== false; const disabled = input.disabled ?? false; diff --git a/libs/react/src/chat/index.ts b/libs/react/src/chat/index.ts index 9af627f18..afc292122 100644 --- a/libs/react/src/chat/index.ts +++ b/libs/react/src/chat/index.ts @@ -58,6 +58,10 @@ export { type SubagentEvidenceRecord, type SubagentProjection, } from './subagent-evidence.js'; +export type { + InterruptResponder, + RenderInterrupt, +} from './session-interrupts.js'; export { sessionSubagents, type SessionSubagentOptions, diff --git a/libs/react/src/chat/session-interrupts.tsx b/libs/react/src/chat/session-interrupts.tsx new file mode 100644 index 000000000..cd3a37de5 --- /dev/null +++ b/libs/react/src/chat/session-interrupts.tsx @@ -0,0 +1,114 @@ +import { Fragment, useCallback, useRef, useState, type ReactNode } from 'react'; +import type { + AgentInterrupt, + AgentInterruptResponse, + AgentSession, + PlainValue, +} from '@threadplane/core'; + +/** Answers one pending interrupt from the view `renderInterrupt` returns. */ +export interface InterruptResponder { + /** Resolves this interrupt, with the value the backend expects for it. */ + resolve(value?: PlainValue): void; + /** Cancels this interrupt, where the backend supports cancelling. */ + cancel(): void; + /** True once this interrupt has an answer that waits on the other pending ones. */ + readonly answered: boolean; + /** True while the answers are being sent; disable the controls. */ + readonly sending: boolean; +} + +/** Draws one pending interrupt. Return `null` to show nothing for it. */ +export type RenderInterrupt = ( + interrupt: AgentInterrupt, + respond: InterruptResponder +) => ReactNode; + +interface Collected { + /** The pause these answers belong to: the snapshot's `interrupts` list. */ + readonly pause: readonly AgentInterrupt[]; + readonly answers: ReadonlyMap; + readonly sending: boolean; +} + +function report(error: unknown, onError?: (error: unknown) => void): void { + if (onError) onError(error); + // An unhandled failure must not be silent. + else + (globalThis as { reportError?: (error: unknown) => void }).reportError?.( + error + ); +} + +/** + * The views for a session's pending interrupts, or undefined when there is + * nothing to show. Each answer is held until every pending interrupt has one; + * they are then sent together with one `session.resume`, because a paused run + * continues once. A new pause starts with no answers. If `resume` rejects, the + * answers are dropped so the person can answer again, and the failure goes to + * `onError`. + */ +export function useSessionInterrupts( + session: AgentSession, + interrupts: readonly AgentInterrupt[] | undefined, + render: RenderInterrupt | undefined, + onError?: (error: unknown) => void +): ReactNode | undefined { + const [collected, setCollected] = useState(); + const current = + collected && collected.pause === interrupts ? collected : undefined; + // The latest values for callbacks a view may keep past this render. + const live = useRef({ session, interrupts, current, onError }); + live.current = { session, interrupts, current, onError }; + + const answer = useCallback((response: AgentInterruptResponse) => { + const { session, interrupts, current, onError } = live.current; + if (!interrupts?.length || current?.sending) return; + if (!interrupts.some((entry) => entry.id === response.interruptId)) return; + const answers = new Map(current?.answers); + answers.set(response.interruptId, response); + const complete = interrupts.every((entry) => answers.has(entry.id)); + const next = { pause: interrupts, answers, sending: complete }; + live.current = { ...live.current, current: next }; + setCollected(next); + if (!complete) return; + const responses = interrupts.map( + (entry) => answers.get(entry.id) as AgentInterruptResponse + ); + const failed = (error: unknown) => { + // Answerable again, unless a newer pause has already replaced this one. + setCollected((latest) => (latest === next ? undefined : latest)); + report(error, onError); + }; + try { + const run = session.resume?.(responses); + if (!run) throw new TypeError('This session cannot resume.'); + run.then( + () => setCollected((latest) => (latest === next ? undefined : latest)), + failed + ); + } catch (error) { + failed(error); + } + }, []); + + if (!render || !interrupts?.length || !session.resume) return undefined; + const sending = current?.sending ?? false; + const views = interrupts.map((interrupt) => { + const view = render(interrupt, { + resolve: (value) => + answer({ + interruptId: interrupt.id, + status: 'resolved', + ...(value !== undefined && { value }), + }), + cancel: () => answer({ interruptId: interrupt.id, status: 'cancelled' }), + answered: current?.answers.has(interrupt.id) ?? false, + sending, + }); + return view == null || view === false ? null : ( + {view} + ); + }); + return views.some((view) => view !== null) ? <>{views} : undefined; +} diff --git a/scripts/react-parity/dispositions.json b/scripts/react-parity/dispositions.json index bf78471fc..ce3b65da3 100644 --- a/scripts/react-parity/dispositions.json +++ b/scripts/react-parity/dispositions.json @@ -19108,6 +19108,36 @@ "target": "libs/react/src/chat/subagent-card.tsx", "reason": "Readonly child-agent presentation matching the Angular subagent card: name, status, message count, and the child's messages and tool activity behind one closed disclosure. MessageList places a card in the tool call that started the child. Status and messages are borrowed; execution, sessions and restored child history remain application-owned. This does not certify whole-framework parity." }, + { + "id": "export:libs/react/src/chat/index.ts#InterruptResponder", + "taskIds": [ + "T28" + ], + "treatment": "react", + "status": "in-progress", + "target": "libs/react/src/chat/session-interrupts.tsx", + "reason": "React-only opt-in view of the interrupts a core session reports. Chat draws nothing by itself: the application returns each card from renderInterrupt, and Chat holds the answers until every pending interrupt has one, then sends them with one session.resume. No built-in card and no answer values." + }, + { + "id": "export:libs/react/src/chat/index.ts#RenderInterrupt", + "taskIds": [ + "T28" + ], + "treatment": "react", + "status": "in-progress", + "target": "libs/react/src/chat/session-interrupts.tsx", + "reason": "React-only opt-in view of the interrupts a core session reports. Chat draws nothing by itself: the application returns each card from renderInterrupt, and Chat holds the answers until every pending interrupt has one, then sends them with one session.resume. No built-in card and no answer values." + }, + { + "id": "source:libs/react/src/chat/session-interrupts.tsx", + "taskIds": [ + "T28" + ], + "treatment": "react", + "status": "in-progress", + "target": "libs/react/src/chat/session-interrupts.tsx", + "reason": "React-only opt-in view of the interrupts a core session reports. Chat draws nothing by itself: the application returns each card from renderInterrupt, and Chat holds the answers until every pending interrupt has one, then sends them with one session.resume. No built-in card and no answer values." + }, { "id": "export:libs/react/src/chat/index.ts#sessionSubagents", "taskIds": [ From eb7dec8a7cb74c6529e5df1c1da479470a467f82 Mon Sep 17 00:00:00 2001 From: Brian Love Date: Thu, 19 Nov 2026 17:20:41 -0800 Subject: [PATCH 15/18] test(cockpit): answer the Strands fixture's pauses through the core resume command --- .../react-cockpit/native-strands-fixture.spec.mjs | 12 ++++-------- 1 file changed, 4 insertions(+), 8 deletions(-) diff --git a/scripts/react-cockpit/native-strands-fixture.spec.mjs b/scripts/react-cockpit/native-strands-fixture.spec.mjs index cfb428b90..0844d17c2 100644 --- a/scripts/react-cockpit/native-strands-fixture.spec.mjs +++ b/scripts/react-cockpit/native-strands-fixture.spec.mjs @@ -109,11 +109,10 @@ for (const scenario of ['approval', 'batch']) ); const outcome = await bounded( session.resume( - decision.id, decision.interrupts.map((i) => ({ interruptId: i.id, status: 'resolved', - payload: { approved }, + value: { approved }, })) ) ); @@ -207,11 +206,10 @@ test( assert.equal(d.kind, 'native'); await bounded( session.resume( - d.id, d.interrupts.map((i) => ({ interruptId: i.id, status: 'resolved', - payload: { approved }, + value: { approved }, })) ) ); @@ -254,11 +252,10 @@ test( assert.equal( await bounded( session.resume( - d.id, d.interrupts.map((i) => ({ interruptId: i.id, status: 'resolved', - payload: { approved: approve }, + value: { approved: approve }, })) ) ), @@ -399,11 +396,10 @@ for (const scenario of [ const d = session.getSnapshot().decision; await bounded( session.resume( - d.id, d.interrupts.map((i) => ({ interruptId: i.id, status: 'resolved', - payload: { approved: true }, + value: { approved: true }, })) ) ); From 47b6bb87a7c3e40bde8aaa56f5dc423fc6645c5a Mon Sep 17 00:00:00 2001 From: Brian Love Date: Thu, 19 Nov 2026 17:25:58 -0800 Subject: [PATCH 16/18] test(parity): count the child-agent projection and check child tool calls as readonly observations --- scripts/react-parity/runtime-consumer.mjs | 7 +++++-- scripts/react-parity/verify-langgraph-candidate.mjs | 2 +- 2 files changed, 6 insertions(+), 3 deletions(-) diff --git a/scripts/react-parity/runtime-consumer.mjs b/scripts/react-parity/runtime-consumer.mjs index a8b4f238a..893b09b69 100644 --- a/scripts/react-parity/runtime-consumer.mjs +++ b/scripts/react-parity/runtime-consumer.mjs @@ -308,8 +308,11 @@ export function assertTextTranscript(messages: readonly Message[]) { child.messages[0].content = 'changed'; // @ts-expect-error Child streams have no execution commands. child.submit('Run'); - // @ts-expect-error Child streams have no executable tool list. - void child.toolCalls; + // A child's tool calls are observations of the child graph; nothing here runs them. + // @ts-expect-error Child tool calls are immutable. + child.toolCalls.push(child.toolCalls[0]); + // @ts-expect-error Child streams have no tool execution command. + child.addToolResult('id', 'result'); if (child.state) { // @ts-expect-error Child values are readonly plain data. child.state['stage'] = 'changed'; diff --git a/scripts/react-parity/verify-langgraph-candidate.mjs b/scripts/react-parity/verify-langgraph-candidate.mjs index 3b2586a6e..941653a7b 100644 --- a/scripts/react-parity/verify-langgraph-candidate.mjs +++ b/scripts/react-parity/verify-langgraph-candidate.mjs @@ -391,7 +391,7 @@ export async function verifyLangGraphCandidate({ const emission = emitCandidate(root, candidate); assert.equal( emission.sources.length, - 35, + 36, 'Complete reviewed backend graph' ); const packed = packCandidate(candidate, temporary); From 6e556cf519c7d6b8379b45ac4241ebfa7676be26 Mon Sep 17 00:00:00 2001 From: Brian Love Date: Thu, 19 Nov 2026 17:31:24 -0800 Subject: [PATCH 17/18] test(parity): list sessionSubagents among the supported React chat exports --- scripts/react-parity/verify-packages.mjs | 1 + scripts/react-parity/verify-packages.spec.mjs | 1 + 2 files changed, 2 insertions(+) diff --git a/scripts/react-parity/verify-packages.mjs b/scripts/react-parity/verify-packages.mjs index e4ceb5e37..2580b59e8 100644 --- a/scripts/react-parity/verify-packages.mjs +++ b/scripts/react-parity/verify-packages.mjs @@ -518,6 +518,7 @@ const SUPPORTED_EXPORTS = { 'ToolObservation', 'SubagentCard', 'subagentsFromEvidence', + 'sessionSubagents', 'Welcome', 'WelcomeSuggestion', 'Suggestions', diff --git a/scripts/react-parity/verify-packages.spec.mjs b/scripts/react-parity/verify-packages.spec.mjs index 29d28c5a1..f1f5efb55 100644 --- a/scripts/react-parity/verify-packages.spec.mjs +++ b/scripts/react-parity/verify-packages.spec.mjs @@ -1062,6 +1062,7 @@ test('React chat requires its real supported export', () => { supported.citationsWithToolSources = component; supported.SubagentCard = component; supported.subagentsFromEvidence = component; + supported.sessionSubagents = component; supported.StatusPanel = component; supported.ChatError = component; supported.TypingIndicator = component; From 670c133b6b4248e807bae699566f5936477a12c9 Mon Sep 17 00:00:00 2001 From: Brian Love Date: Thu, 19 Nov 2026 19:44:14 -0800 Subject: [PATCH 18/18] Keep the canonical demo bundle budget from main (#1679) --- examples/chat/angular/project.json | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/examples/chat/angular/project.json b/examples/chat/angular/project.json index 9fa578d77..d06422bcf 100644 --- a/examples/chat/angular/project.json +++ b/examples/chat/angular/project.json @@ -44,7 +44,7 @@ { "type": "initial", "maximumWarning": "1.6mb", - "maximumError": "1.75mb" + "maximumError": "1.85mb" }, { "type": "anyComponentStyle", @@ -68,7 +68,7 @@ { "type": "initial", "maximumWarning": "1.6mb", - "maximumError": "1.75mb" + "maximumError": "1.85mb" }, { "type": "anyComponentStyle",