The open-source agent harness - the runtime layer that turns an LLM into a working agent.
AGE-2264: Reset in-flight work when a turn starts with a user message. (#875)
debajyoti-truefoundry88024b621b9c
diff --git a/.changeset/fresh-turn-reset.md b/.changeset/fresh-turn-reset.mdnew file mode 100644index 000000000..bd0c30c21--- /dev/null+++ b/.changeset/fresh-turn-reset.md@@ -0,0 +1,6 @@+---+'@truefoundry/trueforge-core': minor+'@truefoundry/trueforge': minor+---++Reset in-flight sub-agents and open tool calls when a turn starts with a user message, without emitting public thread.done for cancelled children.diff --git a/.github/fern/openapi/openapi.json b/.github/fern/openapi/openapi.jsonindex 5c99aad3f..7fbf631d3 100644--- a/.github/fern/openapi/openapi.json+++ b/.github/fern/openapi/openapi.json@@ -474,26 +474,6 @@],"type": "object"},- "BaseThreadDoneEvent": {- "properties": {- "parent": {- "$ref": "#/components/schemas/AgentParent"- },- "thread_id": {- "description": "Thread that finished.",- "type": "string"- },- "title": {- "description": "Human-readable thread title.",- "type": "string"- }- },- "required": [- "thread_id",- "title"- ],- "type": "object"- },"CancelSessionRequest": {"description": "Empty request body. Cancel identifies the session via the path only.","properties": {},@@ -5007,40 +4987,46 @@"type": "object"},"ThreadDoneEvent": {- "allOf": [- {- "$ref": "#/components/schemas/BaseThreadDoneEvent"+ "properties": {+ "created_at": {+ "description": "ISO 8601 event timestamp.",+ "type": "string"},- {- "properties": {- "created_at": {- "description": "ISO 8601 event timestamp.",- "type": "string"- },- "id": {- "description": "Unique identifier for the event (monotonic ULID).",- "type": "string"- },- "state": {- "$ref": "#/components/schemas/ThreadState"- },- "type": {- "description": "A thread reached a terminal state.",- "enum": [- "thread.done"- ],- "type": "string"- }- },- "required": [- "type",- "id",- "created_at",- "state"+ "id": {+ "description": "Unique identifier for the event (monotonic ULID).",+ "type": "string"+ },+ "parent": {+ "$ref": "#/components/schemas/AgentParent"+ },+ "state": {+ "$ref": "#/components/schemas/ThreadState"+ },+ "thread_id": {+ "description": "Thread that finished.",+ "type": "string"+ },+ "title": {+ "description": "Human-readable thread title.",+ "type": "string"+ },+ "type": {+ "description": "A thread reached a terminal state.",+ "enum": [+ "thread.done"],- "type": "object"+ "type": "string"}- ]+ },+ "required": [+ "type",+ "id",+ "created_at",+ "thread_id",+ "title",+ "state"+ ],+ "type": "object"},"ThreadState": {"discriminator": {diff --git a/docs/openapi.json b/docs/openapi.jsonindex 5c99aad3f..7fbf631d3 100644--- a/docs/openapi.json+++ b/docs/openapi.json@@ -474,26 +474,6 @@],"type": "object"},- "BaseThreadDoneEvent": {- "properties": {- "parent": {- "$ref": "#/components/schemas/AgentParent"- },- "thread_id": {- "description": "Thread that finished.",- "type": "string"- },- "title": {- "description": "Human-readable thread title.",- "type": "string"- }- },- "required": [- "thread_id",- "title"- ],- "type": "object"- },"CancelSessionRequest": {"description": "Empty request body. Cancel identifies the session via the path only.","properties": {},@@ -5007,40 +4987,46 @@"type": "object"},"ThreadDoneEvent": {- "allOf": [- {- "$ref": "#/components/schemas/BaseThreadDoneEvent"+ "properties": {+ "created_at": {+ "description": "ISO 8601 event timestamp.",+ "type": "string"},- {- "properties": {- "created_at": {- "description": "ISO 8601 event timestamp.",- "type": "string"- },- "id": {- "description": "Unique identifier for the event (monotonic ULID).",- "type": "string"- },- "state": {- "$ref": "#/components/schemas/ThreadState"- },- "type": {- "description": "A thread reached a terminal state.",- "enum": [- "thread.done"- ],- "type": "string"- }- },- "required": [- "type",- "id",- "created_at",- "state"+ "id": {+ "description": "Unique identifier for the event (monotonic ULID).",+ "type": "string"+ },+ "parent": {+ "$ref": "#/components/schemas/AgentParent"+ },+ "state": {+ "$ref": "#/components/schemas/ThreadState"+ },+ "thread_id": {+ "description": "Thread that finished.",+ "type": "string"+ },+ "title": {+ "description": "Human-readable thread title.",+ "type": "string"+ },+ "type": {+ "description": "A thread reached a terminal state.",+ "enum": [+ "thread.done"],- "type": "object"+ "type": "string"}- ]+ },+ "required": [+ "type",+ "id",+ "created_at",+ "thread_id",+ "title",+ "state"+ ],+ "type": "object"},"ThreadState": {"discriminator": {diff --git a/packages/trueforge-core/src/agent-session/SessionHandle.ts b/packages/trueforge-core/src/agent-session/SessionHandle.tsindex e29e6f388..815dafee7 100644--- a/packages/trueforge-core/src/agent-session/SessionHandle.ts+++ b/packages/trueforge-core/src/agent-session/SessionHandle.ts@@ -79,11 +79,15 @@ function collectContextAppends(if (event.current_context_usage !== undefined) {existing.current_context_usage = event.current_context_usage;}+ if (event.completion !== undefined) {+ existing.completion = event.completion;+ }} else {appendMap.set(event.thread_id, {thread_id: event.thread_id,context: [...event.context],current_context_usage: event.current_context_usage ?? null,+ completion: event.completion ?? null,});}}diff --git a/packages/trueforge-core/src/agent-session/TurnHandle.ts b/packages/trueforge-core/src/agent-session/TurnHandle.tsindex e12798500..560bed739 100644--- a/packages/trueforge-core/src/agent-session/TurnHandle.ts+++ b/packages/trueforge-core/src/agent-session/TurnHandle.ts@@ -13,6 +13,7 @@ import {} from '../core/runtime/AgentThread.types';import type { AgentThreadOrchestrator } from '../core/runtime/AgentThreadOrchestrator';import { getEmptyCurrentContextUsage } from '../core/runtime/contextUsage';+import { isInternalThreadDoneCancelled } from '../core/runtime/contextUtils';import type { AgentThreadMetrics } from '../core/runtime/metrics';import type { ITurnResourceResolver } from './ITurnResourceResolver';import type { TurnRecord } from './models/TurnRecord';@@ -45,6 +46,10 @@ function cancellationReasonFromAbortReason(abortReason: unknown): CancellationRe}function toThreadDoneEvent(event: InternalThreadDoneEvent): ThreadDoneEvent {+ if (isInternalThreadDoneCancelled(event)) {+ // Public thread.done is done|error only. Cancelled children are dropped, not shown.+ throw new Error('unreachable: cancelled AGENT_DONE cannot be converted to thread.done');+ }const state =event.status === 'error'? { status: 'error' as const, error: event.error, ...(event.output && { output: event.output }) }@@ -463,14 +468,20 @@ export class TurnHandle<TTurnCustom extends object = Record<string, never>> {}case InternalEventType.AGENT_DONE: {+ if (event.parent) {+ await this.store.removeThreads({+ ...scope,+ thread_ids: [event.thread_id],+ });+ }+ if (isInternalThreadDoneCancelled(event)) {+ // Do not send thread.done to the user for a cancelled child.+ return null;+ }if (!event.parent) {return null;}const threadDone = toThreadDoneEvent(event);- await this.store.removeThreads({- ...scope,- thread_ids: [event.thread_id],- });await this.store.appendToEvents({...scope,events: [threadDone],diff --git a/packages/trueforge-core/src/agent-session/store/ISessionStore.ts b/packages/trueforge-core/src/agent-session/store/ISessionStore.tsindex 73884366d..bdf8bed50 100644--- a/packages/trueforge-core/src/agent-session/store/ISessionStore.ts+++ b/packages/trueforge-core/src/agent-session/store/ISessionStore.ts@@ -1,10 +1,6 @@import type { JsonValue } from '../../core/capabilities/AgentCapability';import type { MCPServerInitInfo, ThreadOverwriteContextEvent } from '../../core/events/schema';-import type {- AgentThreadSnapshot,- ContextMessage,- SubAgentCompletionMarker,-} from '../../core/runtime/AgentThread.types';+import type { AgentThreadSnapshot, ContextMessage, SubAgentCompletion } from '../../core/runtime/AgentThread.types';import type { CurrentContextUsage } from '../../core/runtime/contextUsage';import type { SandboxInfo } from '../../core/sandbox/Sandbox';import type { SessionRecord } from '../models/SessionRecord';@@ -120,6 +116,7 @@ export interface TurnContextAppend {thread_id: string;context: ContextMessage[];current_context_usage: CurrentContextUsage | null;+ completion: SubAgentCompletion | null;}export interface CreateTurnInput<TTurnCustom extends object = Record<string, never>> {@@ -219,7 +216,7 @@ export interface AppendToThreadContextInput {thread_id: string;context: ContextMessage[];current_context_usage: CurrentContextUsage | null;- completion: SubAgentCompletionMarker | null;+ completion: SubAgentCompletion | null;}export interface OverwriteThreadContextInput {diff --git a/packages/trueforge-core/src/agent-session/store/InMemorySessionStore.ts b/packages/trueforge-core/src/agent-session/store/InMemorySessionStore.tsindex e5dc38fa2..4f11e3e8f 100644--- a/packages/trueforge-core/src/agent-session/store/InMemorySessionStore.ts+++ b/packages/trueforge-core/src/agent-session/store/InMemorySessionStore.ts@@ -117,6 +117,9 @@ function applyContextAppends(threads: Record<string, AgentThreadSnapshot>, appenif (append.current_context_usage !== null) {thread.current_context_usage = deepCopy(append.current_context_usage);}+ if (append.completion !== null) {+ thread.completion = deepCopy(append.completion);+ }}}diff --git a/packages/trueforge-core/src/core/events/schema.ts b/packages/trueforge-core/src/core/events/schema.tsindex 245302cd9..c55bdb402 100644--- a/packages/trueforge-core/src/core/events/schema.ts+++ b/packages/trueforge-core/src/core/events/schema.ts@@ -300,20 +300,17 @@ export const ThreadStateSchema = z.discriminatedUnion('status', [ThreadStateDoneSchema, ThreadStateErrorSchema]).openapi('ThreadState');-export const BaseThreadDoneEventSchema = z+export const ThreadDoneEventSchema = z.object({+ type: z.literal(EventType.THREAD_DONE).describe('A thread reached a terminal state.'),+ id: EventIdSchema,+ created_at: z.string().describe('ISO 8601 event timestamp.'),parent: AgentParentSchema.optional(),thread_id: z.string().describe('Thread that finished.'),title: z.string().describe('Human-readable thread title.'),+ state: ThreadStateSchema,})- .openapi('BaseThreadDoneEvent');--export const ThreadDoneEventSchema = BaseThreadDoneEventSchema.extend({- type: z.literal(EventType.THREAD_DONE).describe('A thread reached a terminal state.'),- id: EventIdSchema,- created_at: z.string().describe('ISO 8601 event timestamp.'),- state: ThreadStateSchema,-}).openapi('ThreadDoneEvent');+ .openapi('ThreadDoneEvent');const ContextMessageSchema = z.union([LLMUserMessageSchema,@@ -471,7 +468,6 @@ export type ToolResponseEvent = z.infer<typeof ToolResponseEventSchema>;export type ThreadCreatedEvent = z.infer<typeof ThreadCreatedEventSchema>;export type ThreadStateError = z.infer<typeof ThreadStateErrorSchema>;export type ThreadState = z.infer<typeof ThreadStateSchema>;-export type BaseThreadDoneEvent = z.infer<typeof BaseThreadDoneEventSchema>;export type ThreadDoneEvent = z.infer<typeof ThreadDoneEventSchema>;export type ThreadOverwriteContextEvent = z.infer<typeof ThreadOverwriteContextEventSchema>;export type BaseMCPAuthRequiredEvent = z.infer<typeof BaseMCPAuthRequiredEventSchema>;diff --git a/packages/trueforge-core/src/core/index.ts b/packages/trueforge-core/src/core/index.tsindex 725aafd77..0386103ed 100644--- a/packages/trueforge-core/src/core/index.ts+++ b/packages/trueforge-core/src/core/index.ts@@ -15,7 +15,7 @@ export type {AgentThreadEvent,AgentThreadExecutionEvent,AgentThreadExecutionResult,- SubAgentCompletionMarker,+ SubAgentCompletion,} from './runtime/AgentThread.types';export { AgentThreadOrchestrator } from './runtime/AgentThreadOrchestrator';export type { CreateDynamicSubAgentThread } from './runtime/CreateDynamicSubAgentThread';diff --git a/packages/trueforge-core/src/core/runtime/AgentThread.ts b/packages/trueforge-core/src/core/runtime/AgentThread.tsindex f01cf0f51..31290b619 100644--- a/packages/trueforge-core/src/core/runtime/AgentThread.ts+++ b/packages/trueforge-core/src/core/runtime/AgentThread.ts@@ -68,9 +68,10 @@ import {type AgentThreadEvent,type ContextMessage,type InternalCapabilityStateEvent,+ type InternalChildThreadDoneEvent,type InternalMCPAuthRequiredEvent,type InternalThreadDoneEvent,- type SubAgentCompletionMarker,+ type SubAgentCompletion,} from './AgentThread.types';import {currentContextUsageFromCompletion,@@ -496,8 +497,8 @@ export class AgentThread {readonly threadId: string;readonly parent?: AgentParent | undefined;readonly definition: AgentDefinition;- readonly title: string;readonly agentInfo?: AgentInfo | undefined;+ private readonly title: string;private context: ContextMessage[];private currentContextUsage: CurrentContextUsage;@@ -523,7 +524,7 @@ export class AgentThread {private contextBusy = false;private preSendRanThisTurn = false;private currentState: AgentThreadState | null = null;- private readonly preComputedCompletion?: SubAgentCompletionMarker | undefined;+ private preComputedCompletion?: SubAgentCompletion | undefined;/** Mirrored capability KV — source for toSnapshot().capability_state. */private capabilityState: CapabilityState = {};private readonly capabilityStateKeys: ReadonlySet<string>;@@ -602,9 +603,13 @@ export class AgentThread {public async *send(messages: AgentThreadRuntimeSendBatch): AsyncGenerator<AgentThreadAppendContext, void, unknown> {// An empty batch is a no-op only when the thread is not awaiting user input.// While awaiting input, fall through so the validator rejects the empty/incomplete batch.+ // Already-complete threads (e.g. cancelled children left in a tip before AGENT_DONE+ // removed them) must also no-op on [] so orchestrator fan-out resume/approval sends+ // do not fail createTurn.if (messages.length === 0 && !this.isAwaitingUserInput()) {return;}+ this.throwIfAlreadyComplete();this.throwIfContextBusy();this.contextBusy = true;@@ -690,7 +695,7 @@ export class AgentThread {output: AgentOutputEvent[];currentContextUsage: CurrentContextUsage | undefined;usage: CompletionUsage | undefined;- completion?: SubAgentCompletionMarker | undefined;+ completion?: SubAgentCompletion | undefined;}): Generator<AgentThreadAppendContext, void, unknown> {const { context, output, currentContextUsage, usage, completion } = opts;@@ -735,37 +740,91 @@ export class AgentThread {}private generateErrorEvent(message: string, output?: ModelMessageEvent): InternalThreadDoneEvent {+ if (this.parent !== undefined) {+ return {+ type: InternalEventType.AGENT_DONE,+ thread_id: this.threadId,+ title: this.title,+ parent: this.parent,+ status: 'error',+ error: message,+ send_to_parent: {+ role: 'tool',+ content: message,+ tool_call_id: this.parent.tool_call_id,+ },+ output,+ };+ }return {type: InternalEventType.AGENT_DONE,- status: 'error',thread_id: this.threadId,title: this.title,+ status: 'error',error: message,- parent: this.parent,- send_to_parent: this.parent- ? {- role: 'tool',- content: message,- tool_call_id: this.parent.tool_call_id,- }- : undefined,- ...(output && { output }),+ output,};}- public hasOpenToolCallId(toolCallId: string): boolean {+ *cancel(reason: string): Generator<AgentThreadAppendContext, void, unknown> {+ if (this.parent === undefined) {+ throw new Error('unreachable: cancel() requires a parent thread');+ }+ const completion: SubAgentCompletion = this.preComputedCompletion ?? {+ type: 'cancelled',+ reason,+ send_to_parent: {+ role: 'tool',+ tool_call_id: this.parent.tool_call_id,+ content: reason,+ },+ };+ yield {+ type: InternalEventType.AGENT_CONTEXT_APPEND,+ thread_id: this.threadId,+ context: [],+ output: [],+ completion,+ };+ this.preComputedCompletion ??= completion;+ }++ *closeAllOpenToolCalls({+ toolIdToClosureMessages,+ defaultToolClosureContent,+ }: {+ toolIdToClosureMessages: ReadonlyMap<string, LLMToolMessage>;+ defaultToolClosureContent: string;+ }): Generator<AgentThreadAppendContext, void, unknown> {+ this.throwIfAlreadyComplete();+ const openToolCallIds = getOpenToolCallIds(this.context);+ const closed: LLMToolMessage[] = [...openToolCallIds].map(+ id => toolIdToClosureMessages.get(id) ?? { role: 'tool', tool_call_id: id, content: defaultToolClosureContent },+ );+ if (closed.length === 0) {+ return;+ }+ yield* this.appendToContext({+ context: closed,+ output: [],+ currentContextUsage: undefined,+ usage: undefined,+ });+ }++ hasOpenToolCallId(toolCallId: string): boolean {return getOpenToolCallIds(this.context).has(toolCallId);}// User-configured MCP tool sets (spec.mcp_servers) for this thread. Excludes// system tool sets (sandbox / deferred / capabilities).- public getUserToolSets(): readonly IToolSet[] {+ getUserToolSets(): readonly IToolSet[] {return this.definition.toolSets ?? [];}// True when this thread is paused waiting on the user to resolve a pending tool// approval or a client-side tool response.- public isAwaitingUserInput(): boolean {+ private isAwaitingUserInput(): boolean {return (getPendingApprovalToolCalls(this.context).length > 0 || getPendingClientSideToolCalls(this.context).length > 0);@@ -773,7 +832,12 @@ export class AgentThread {// Pure validation of an input batch against this thread's current context; throws// on an invalid/incomplete batch without mutating the context.- public validateSendInput(messages: AgentThreadRuntimeSendBatch): void {+ validateSendInput(messages: AgentThreadRuntimeSendBatch): void {+ // Match send(): empty + not awaiting is a no-op, including already-complete threads.+ if (messages.length === 0 && !this.isAwaitingUserInput()) {+ return;+ }+ this.throwIfAlreadyComplete();validateInputMessageTypesGivenContext(this.context, messages);}@@ -790,7 +854,7 @@ export class AgentThread {};}- public getAgentThreadMetrics(): AgentThreadMetrics {+ getAgentThreadMetrics(): AgentThreadMetrics {return { ...this.metrics };}@@ -1108,7 +1172,7 @@ export class AgentThread {id: modelMessageEventId,});- let completion: SubAgentCompletionMarker | undefined;+ let completion: SubAgentCompletion | undefined;if (this.parent) {if (finishReason === 'length') {const errorMessage = assistantMessageContentToStringForSubAgent(@@ -1140,25 +1204,32 @@ export class AgentThread {});if (finishReason === 'length') {- const errorContent = completion?.error_message ?? 'max_tokens breached';+ const errorContent = completion?.type === 'error' ? completion.error_message : 'max_tokens breached';yield this.generateErrorEvent(errorContent, agentAssistantMessage);return { outcome: 'exit', modelMessageEventId };}- if (!hasToolCalls(assistantMessage)) {+ if (hasToolCalls(assistantMessage)) {+ return { outcome: 'continue', modelMessageEventId };+ }++ // No tool calls: this thread is finished. A child must already have send_to_parent+ // from the completion built above; the root only reports the assistant output.+ if (this.parent !== undefined) {+ if (completion === undefined) {+ throw new Error('unreachable: child finished without a completion');+ }+ yield this.buildReplayEvent(completion);+ } else {yield {type: InternalEventType.AGENT_DONE,- status: 'done',thread_id: this.threadId,title: this.title,+ status: 'done',output: agentAssistantMessage,- parent: this.parent,- send_to_parent: completion?.send_to_parent,};- return { outcome: 'exit', modelMessageEventId };}-- return { outcome: 'continue', modelMessageEventId };+ return { outcome: 'exit', modelMessageEventId };}private async *stepToolResponse(@@ -1303,17 +1374,30 @@ export class AgentThread {return 'exit';}- private buildReplayEvent(c: SubAgentCompletionMarker): InternalThreadDoneEvent {+ private buildReplayEvent(c: SubAgentCompletion): InternalChildThreadDoneEvent {+ if (this.parent === undefined) {+ throw new Error('unreachable: completion replay requires a parent thread');+ }const base = {type: InternalEventType.AGENT_DONE,thread_id: this.threadId,title: this.title,parent: this.parent,send_to_parent: c.send_to_parent,- };- return c.type === 'done'- ? { ...base, status: 'done', output: c.output }- : { ...base, status: 'error', error: c.error_message ?? 'Sub-agent errored', output: c.output };+ } satisfies Pick<InternalChildThreadDoneEvent, 'type' | 'thread_id' | 'title' | 'parent' | 'send_to_parent'>;+ if (c.type === 'done') {+ return { ...base, status: 'done', output: c.output };+ }+ if (c.type === 'error') {+ return { ...base, status: 'error', error: c.error_message, output: c.output };+ }+ return { ...base, status: 'cancelled', reason: c.reason };+ }++ private throwIfAlreadyComplete(): void {+ if (this.preComputedCompletion !== undefined) {+ throw new InvalidAgentSendInputError(`thread ${this.threadId} is already complete`);+ }}public async *execute(options?: {diff --git a/packages/trueforge-core/src/core/runtime/AgentThread.types.ts b/packages/trueforge-core/src/core/runtime/AgentThread.types.tsindex e0b7b12e8..99a695f40 100644--- a/packages/trueforge-core/src/core/runtime/AgentThread.types.ts+++ b/packages/trueforge-core/src/core/runtime/AgentThread.types.ts@@ -10,7 +10,6 @@ import type {AgentOutputEvent,AgentParent,BaseMCPAuthRequiredEvent,- BaseThreadDoneEvent,MCPInitializeEvent,MCPServerAuthInfo,ModelMessageDeltaEvent,@@ -74,10 +73,33 @@ export type InternalMCPAuthRequiredEvent = BaseMCPAuthRequiredEvent & {mcp_servers: InternalMCPServerAuthInfo[];};-export type InternalThreadDoneEvent = BaseThreadDoneEvent & {+export type SubAgentCompletion =+ | { type: 'done'; output: ModelMessageEvent; send_to_parent: LLMToolMessage }+ | { type: 'error'; output: ModelMessageEvent; error_message: string; send_to_parent: LLMToolMessage }+ | { type: 'cancelled'; reason: string; send_to_parent: LLMToolMessage };++export type InternalMainThreadDoneEvent = {+ type: typeof InternalEventType.AGENT_DONE;+ thread_id: string;+ title: string;+ parent?: undefined; // TODO (chiragjn): we should drop this field+} & (+ | { status: 'done'; output: ModelMessageEvent }+ | { status: 'error'; error: string; output?: ModelMessageEvent | undefined }+);++export type InternalChildThreadDoneEvent = {type: typeof InternalEventType.AGENT_DONE;- send_to_parent: LLMToolMessage | undefined;-} & ({ status: 'done'; output: ModelMessageEvent } | { status: 'error'; error: string; output?: ModelMessageEvent });+ thread_id: string;+ title: string;+ parent: AgentParent;+} & (+ | { status: 'done'; output: ModelMessageEvent; send_to_parent: LLMToolMessage }+ | { status: 'error'; error: string; output?: ModelMessageEvent | undefined; send_to_parent: LLMToolMessage }+ | { status: 'cancelled'; reason: string; send_to_parent: LLMToolMessage }+);++export type InternalThreadDoneEvent = InternalMainThreadDoneEvent | InternalChildThreadDoneEvent;export type LLMContextMessage = LLMUserMessage | InternalEnrichedAssistantMessage | LLMToolMessage;@@ -90,20 +112,13 @@ export interface AgentThreadCreateSubAgent {agent_info: AgentInfo;}-export interface SubAgentCompletionMarker {- type: 'done' | 'error';- output: ModelMessageEvent;- error_message?: string | undefined;- send_to_parent: LLMToolMessage;-}-export interface AgentThreadAppendContext {type: typeof InternalEventType.AGENT_CONTEXT_APPEND;thread_id: string;context: ContextMessage[];output: AgentOutputEvent[];current_context_usage?: CurrentContextUsage | undefined;- completion?: SubAgentCompletionMarker | undefined;+ completion?: SubAgentCompletion | undefined;}/** Single public send item (no internal LLM tool messages). */@@ -153,7 +168,7 @@ export interface AgentThreadSnapshot {current_context_usage: CurrentContextUsage;parent: AgentParent | null;agent_info: AgentInfo | null;- completion: SubAgentCompletionMarker | null;+ completion: SubAgentCompletion | null;/** Cross-turn capability KV. Keys: capability.state.key; `tfy.` reserved for builtins. */capability_state: CapabilityState | null;}@@ -166,7 +181,7 @@ export interface AgentThreadConstructorInput {agentInfo?: AgentInfo | undefined;context?: ContextMessage[] | undefined;currentContextUsage?: CurrentContextUsage | undefined;- preComputedCompletion?: SubAgentCompletionMarker | undefined;+ preComputedCompletion?: SubAgentCompletion | undefined;sandbox?: HarnessSandbox | undefined;capabilities?: readonly AgentCapability[] | undefined;/**diff --git a/packages/trueforge-core/src/core/runtime/AgentThreadOrchestrator.ts b/packages/trueforge-core/src/core/runtime/AgentThreadOrchestrator.tsindex e2c33ab3e..5947cf67e 100644--- a/packages/trueforge-core/src/core/runtime/AgentThreadOrchestrator.ts+++ b/packages/trueforge-core/src/core/runtime/AgentThreadOrchestrator.ts@@ -10,6 +10,7 @@ import {type UserToolApprovalMessage,type UserToolResponseMessage,} from '../events/schema';+import type { LLMToolMessage } from '../llm/LLMTypes';import type { AgentExecutionTrace, AgentTracing } from '../tracing/AgentTracing';import { onSignalAbort } from '../util/abort';import { mergeAsyncGenerators } from '../util/promiseUtils';@@ -30,12 +31,15 @@ import {getThreadId,isApprovalDecisionMessage,isClientSideToolResponseMessage,+ isInputUserMessage,+ isInternalThreadDoneCancelled,isInternalThreadDoneError,} from './contextUtils';import type { CreateDynamicSubAgentThread } from './CreateDynamicSubAgentThread';import { addAgentThreadMetrics, createEmptyAgentThreadMetrics, type AgentThreadMetrics } from './metrics';const MAX_PARALLEL_SUB_AGENTS = 5;+const CANCELED_BECAUSE_USER_SENT_NEW_MESSAGE = 'Canceled because user sent a new message.';function agentThreadEventToTerminalFields(event: AgentThreadExecutionEvent): {output?: ModelMessageEvent | undefined;@@ -46,7 +50,7 @@ function agentThreadEventToTerminalFields(event: AgentThreadExecutionEvent): {if ('parent' in event && event.parent) {return {};}- if (event.status === 'error') {+ if (event.status !== 'done') {return {};}return { output: event.output };@@ -68,15 +72,6 @@ function isUserToolApprovalOrResponseBatch(return first !== undefined && (isApprovalDecisionMessage(first) || isClientSideToolResponseMessage(first));}-function getMainThreadId(agentThreads: Map<string, AgentThread>): string {- for (const thread of agentThreads.values()) {- if (!thread.parent) {- return thread.threadId;- }- }- throw new Error('Unreachable: no root thread found');-}-function getActiveAgentThreads(agentThreads: Map<string, AgentThread>): AgentThread[] {const nodes = new Set(agentThreads.keys());const parentNodes = new Set(@@ -166,6 +161,8 @@ function createRootAgentSpan(mainThread: AgentThread, tracing: AgentTracing): Roif (isInternalThreadDoneError(chunk)) {rootAgentErrorMessage = chunk.error;trace.setOutput(JSON.stringify({ error: chunk.error }));+ } else if (isInternalThreadDoneCancelled(chunk)) {+ trace.setOutput(JSON.stringify({ cancelled: chunk.reason }));} else {const content = assistantMessageContentToStringForSubAgent(chunk.output.content);trace.setOutput(JSON.stringify({ result: content }));@@ -204,7 +201,11 @@ export async function* wrapWithSubAgentSpan(try {for await (const event of generator) {if (event.type === InternalEventType.AGENT_DONE) {- if (isInternalThreadDoneError(event)) {+ if (isInternalThreadDoneCancelled(event)) {+ subTrace.setOutput(JSON.stringify({ cancelled: event.reason }));+ subTrace.setMetrics(currentThread.getAgentThreadMetrics());+ subTrace.setError(event.reason);+ } else if (isInternalThreadDoneError(event)) {subTrace.setOutput(JSON.stringify({ error: event.error }));subTrace.setMetrics(currentThread.getAgentThreadMetrics());subTrace.setError(event.error);@@ -262,12 +263,25 @@ export class AgentThreadOrchestrator {return total;}+ private getMainThread(): AgentThread {+ for (const thread of this.agentThreads.values()) {+ if (!thread.parent) {+ return thread;+ }+ }+ throw new Error('Unreachable: no root thread found');+ }++ private getChildThreads(): AgentThread[] {+ return [...this.agentThreads.values()].filter(thread => thread.parent !== undefined);+ }+/*** Apply tool approval policies to the tool sets. Validates* every `server_name` against the currently-configured MCP servers first —* fail-closed: if any name is unknown nothing is applied.*/- public applyApprovalPolicies(policies: ToolApprovalPolicyItem[]): { errors: string[] } {+ applyApprovalPolicies(policies: ToolApprovalPolicyItem[]): { errors: string[] } {const knownServerNames = new Set<string>();for (const thread of this.agentThreads.values()) {for (const toolSet of thread.getUserToolSets()) {@@ -298,6 +312,31 @@ export class AgentThreadOrchestrator {}public async *send(messages: AgentThreadSendBatch): AsyncGenerator<AgentThreadAppendContext, void, unknown> {+ // "some" in this case means all messages are user messages because of the type+ // this check and logic becomes invalid if we allow mixed batches+ if (messages.some(isInputUserMessage)) {+ const mainThread = this.getMainThread();+ const toolIdToClosureMessages = new Map<string, LLMToolMessage>();+ for (const thread of this.getChildThreads()) {+ for (const event of thread.cancel(CANCELED_BECAUSE_USER_SENT_NEW_MESSAGE)) {+ yield event;+ if (event.completion) {+ const toolMessage = event.completion.send_to_parent;+ toolIdToClosureMessages.set(toolMessage.tool_call_id, toolMessage);+ }+ }+ }+ yield* mainThread.closeAllOpenToolCalls({+ toolIdToClosureMessages,+ defaultToolClosureContent: CANCELED_BECAUSE_USER_SENT_NEW_MESSAGE,+ });+ // Send only to main and return. Falling through would fan out [] to cancelled+ // children (harmless no-op now) and also mis-route the user batch through the+ // approval/empty grouping path.+ yield* this.sendToThread(mainThread.threadId, messages);+ return;+ }+const byThread = new Map<string, AgentThreadRuntimeSendBatch>();for (const thread of this.agentThreads.values()) {byThread.set(thread.threadId, []);@@ -318,12 +357,8 @@ export class AgentThreadOrchestrator {byThread.set(threadId, batch);}} else if (messages.length > 0) {- if (this.agentThreads.size > 1) {- throw new InvalidAgentSendInputError(- 'Cannot process user messages while sub agents are running, please send empty input for previous conversation to complete',- );- }- byThread.set(getMainThreadId(this.agentThreads), messages);+ // Note this branch is unreachable because we handle user messages at the beginning of the function+ byThread.set(this.getMainThread().threadId, messages);}const validationErrors: string[] = [];@@ -388,9 +423,6 @@ export class AgentThreadOrchestrator {return { shouldStopExecution: true };case InternalEventType.AGENT_DONE: {if (chunk.parent) {- if (!chunk.send_to_parent) {- throw new Error('unreachable');- }const parentThread = this.agentThreads.get(chunk.parent.thread_id);if (!parentThread) {throw new Error('unreachable: parent thread missing');@@ -468,10 +500,7 @@ export class AgentThreadOrchestrator {const requiredActions: ActionRequiredEvent[] = [];let rootAgentError: AgentThreadExecutionResult['root_agent_error'];const pendingAuthEvents: InternalMCPAuthRequiredEvent[] = [];- const mainThread = [...agentThreads.values()].find(e => !e.parent);- if (!mainThread) {- throw new Error('Unreachable: no root thread found');- }+ const mainThread = this.getMainThread();const rootSpan = createRootAgentSpan(mainThread, this.tracing);onSignalAbort(signal, () => {diff --git a/packages/trueforge-core/src/core/runtime/contextUtils.ts b/packages/trueforge-core/src/core/runtime/contextUtils.tsindex d5cdffca4..63f0982c2 100644--- a/packages/trueforge-core/src/core/runtime/contextUtils.ts+++ b/packages/trueforge-core/src/core/runtime/contextUtils.ts@@ -80,6 +80,12 @@ export function isInternalThreadDoneError(return event.status === 'error';}+export function isInternalThreadDoneCancelled(+ event: InternalThreadDoneEvent,+): event is InternalThreadDoneEvent & { status: 'cancelled' } {+ return event.status === 'cancelled';+}+export function scanApprovalDecisions(context: ContextMessage[]): Map<string, ApprovalDecision> {const decisions = new Map<string, ApprovalDecision>();for (const msg of context) {diff --git a/packages/trueforge-core/tests/agent-session/store/storeContractSuite.ts b/packages/trueforge-core/tests/agent-session/store/storeContractSuite.tsindex 27b2ef52f..48532d783 100644--- a/packages/trueforge-core/tests/agent-session/store/storeContractSuite.ts+++ b/packages/trueforge-core/tests/agent-session/store/storeContractSuite.ts@@ -1676,6 +1676,76 @@ export function runStoreContractSuite(createStore: () => ISessionStore) {expect(main?.capability_state).toEqual({ 'tfy.plan': { step: 2 } });});+ it('createTurn overlays completion from a completion-only append onto a copied thread', async () => {+ const store = createStore();+ await seedSession(store);+ await store.createTurn(+ makeCreateTurnInput({+ sessionId,+ turnId: 't1',+ new_threads: [+ { thread_id: MAIN_THREAD_ID, parent: null, agent_info: null },+ {+ thread_id: 'child',+ parent: { thread_id: MAIN_THREAD_ID, tool_call_id: 'tc-child' },+ agent_info: { type: 'dynamic', name: 'worker', input: 'task' },+ },+ ],+ capability_states: [+ { thread_id: MAIN_THREAD_ID, capability_state: null },+ { thread_id: 'child', capability_state: null },+ ],+ new_context_appends: [+ {+ thread_id: 'child',+ context: [userMessage('child-t1')],+ current_context_usage: null,+ },+ ],+ }),+ );+ await finishTurn(store, 't1');+ const t1ChildContext = contextContents(+ (await store.getTurn({ session_id: sessionId, turn_id: 't1' }))?.snapshot.threads['child']?.context,+ );++ const cancelled = {+ type: 'cancelled' as const,+ reason: 'Canceled because user sent a new message.',+ send_to_parent: {+ role: 'tool' as const,+ tool_call_id: 'tc-child',+ content: 'Canceled because user sent a new message.',+ },+ };+ await store.createTurn(+ makeCreateTurnInput({+ sessionId,+ turnId: 't2',+ previousTurnId: 't1',+ firstTurnId: 't1',+ capability_states: [+ { thread_id: MAIN_THREAD_ID, capability_state: null },+ { thread_id: 'child', capability_state: null },+ ],+ new_context_appends: [+ {+ thread_id: 'child',+ context: [],+ current_context_usage: null,+ completion: cancelled,+ },+ ],+ }),+ );++ const t2 = await store.getTurn({ session_id: sessionId, turn_id: 't2' });+ const child = mustGet(t2).snapshot.threads['child'];+ expect(child?.completion).toEqual(cancelled);+ expect(contextContents(child?.context)).toEqual(t1ChildContext);+ expect(mustGet(t2).snapshot.threads[MAIN_THREAD_ID]?.completion).toBeNull();+ });+it('createTurn atomically persists the complete post-send capability map', async () => {const store = createStore();await seedSession(store);diff --git a/packages/trueforge-core/tests/agent-session/testHelpers.ts b/packages/trueforge-core/tests/agent-session/testHelpers.tsindex ee10e586d..281f5cea4 100644--- a/packages/trueforge-core/tests/agent-session/testHelpers.ts+++ b/packages/trueforge-core/tests/agent-session/testHelpers.ts@@ -190,7 +190,9 @@ export function makeCreateTurnInput(input: {previousTurnId?: string | null;firstTurnId?: string;new_threads?: NewThreadInit[];- new_context_appends?: TurnContextAppend[];+ new_context_appends?: (Omit<TurnContextAppend, 'completion'> & {+ completion?: TurnContextAppend['completion'];+ })[];capability_states?: CreateTurnInput['capability_states'];update_session_title_if_not_exist?: string;}): CreateTurnInput {@@ -207,7 +209,10 @@ export function makeCreateTurnInput(input: {return {turn: turnInit,new_threads: isFirstInChain ? (input.new_threads ?? [defaultRootThread]) : (input.new_threads ?? []),- new_context_appends: input.new_context_appends ?? [],+ new_context_appends: (input.new_context_appends ?? []).map(append => ({+ ...append,+ completion: append.completion ?? null,+ })),capability_states: input.capability_states ?? [{ thread_id: MAIN_THREAD_ID, capability_state: null }],update_session_title_if_not_exist: input.update_session_title_if_not_exist ?? null,};diff --git a/packages/trueforge-core/tests/orchestration/helpers/helpers.ts b/packages/trueforge-core/tests/orchestration/helpers/helpers.tsindex 6727e0db6..c293d0c65 100644--- a/packages/trueforge-core/tests/orchestration/helpers/helpers.ts+++ b/packages/trueforge-core/tests/orchestration/helpers/helpers.ts@@ -130,15 +130,11 @@ export async function* writeNoteToolCallStream() {};}-/** Consume send() then execute(); return raw events and the generator result. */-export async function runTurn(input: {+/** Consume execute(); return raw events and the generator result. */+export async function runExecute(input: {orchestrator: AgentThreadOrchestrator;- sendBatch: AgentThreadSendBatch;signal?: AbortSignal | undefined;}): Promise<{ events: AgentThreadExecutionEvent[]; result: AgentThreadExecutionResult }> {- for await (const _event of input.orchestrator.send(input.sendBatch)) {- void _event;- }const events: AgentThreadExecutionEvent[] = [];const iterator = input.orchestrator.execute({signal: input.signal ?? new AbortController().signal,@@ -151,6 +147,18 @@ export async function runTurn(input: {return { events, result: step.value };}+/** Consume send() then execute(); return raw events and the generator result. */+export async function runTurn(input: {+ orchestrator: AgentThreadOrchestrator;+ sendBatch: AgentThreadSendBatch;+ signal?: AbortSignal | undefined;+}): Promise<{ events: AgentThreadExecutionEvent[]; result: AgentThreadExecutionResult }> {+ for await (const _event of input.orchestrator.send(input.sendBatch)) {+ void _event;+ }+ return runExecute({ orchestrator: input.orchestrator, signal: input.signal });+}+export function llmCreateInputs(llm: ILLM): unknown[] {return jest.mocked(llm).create.mock.calls.map(call => call[0]);}diff --git a/packages/trueforge-core/tests/orchestration/orchestrationUserMessageReset.test.ts b/packages/trueforge-core/tests/orchestration/orchestrationUserMessageReset.test.tsnew file mode 100644index 000000000..fbca0cd8c--- /dev/null+++ b/packages/trueforge-core/tests/orchestration/orchestrationUserMessageReset.test.ts@@ -0,0 +1,317 @@+import { InvalidAgentSendInputError } from '../../src/core/errors';+import { EventType } from '../../src/core/events/schema';+import type { InternalEnrichedAssistantMessage, InternalEnrichedToolCall } from '../../src/core/llm/LLMTypes';+import { AgentThread } from '../../src/core/runtime/AgentThread';+import type { AgentThreadConstructorInput, ContextMessage } from '../../src/core/runtime/AgentThread.types';+import { InternalEventType } from '../../src/core/runtime/AgentThread.types';+import { AgentThreadOrchestrator } from '../../src/core/runtime/AgentThreadOrchestrator';+import { NOOP_AGENT_TRACING } from '../../src/core/tracing/NoopAgentTracing';+import { makeSilentLogger } from '../core/harnessMocks';+import { llmCreateInputs, runExecute, textReplyStream } from './helpers/helpers';++const MAIN_ID = 'main';+const CHILD_ID = 'child';+const TOOL_CALL_ID = 'call-sub';+const CANCELED = 'Canceled because user sent a new message.';+const INSTRUCTION = 'You are running in a test setup.';+const ROOT_REPLY = 'ack new message';+const FINISHED_CHILD_ANSWER = 'already finished work';++function threadCreationToolCall(id: string): InternalEnrichedToolCall {+ return {+ id,+ type: 'function',+ function: { name: 'create_sub_agent', arguments: '{}' },+ tool_info: {+ type: 'truefoundry-system',+ mcp_server_id: '',+ mcp_server_name: '',+ original_tool_name: 'create_sub_agent',+ is_thread_creation: true,+ },+ };+}++function approvalToolCall(id: string): InternalEnrichedToolCall {+ return {+ id,+ type: 'function',+ function: { name: 'needs_approval', arguments: '{}' },+ tool_info: {+ type: 'mcp',+ mcp_server_id: 'test-server',+ mcp_server_name: 'test-server',+ original_tool_name: 'needs_approval',+ is_approval_required: true,+ },+ };+}++function assistantWithCalls(toolCalls: InternalEnrichedToolCall[]): InternalEnrichedAssistantMessage {+ return {+ role: 'assistant',+ content: '',+ tool_calls: toolCalls,+ };+}++function baseThreadInput(+ overrides: Partial<AgentThreadConstructorInput> & Pick<AgentThreadConstructorInput, 'threadId' | 'title'>,+): AgentThreadConstructorInput {+ return {+ definition: {+ modelClient: {+ create: jest.fn().mockImplementation(() => textReplyStream(ROOT_REPLY)),+ createNonStream: jest.fn().mockImplementation(() => textReplyStream(ROOT_REPLY)),+ },+ instruction: INSTRUCTION,+ messages: undefined,+ modelParams: undefined,+ responseFormat: undefined,+ iterationLimit: undefined,+ toolSets: undefined,+ },+ parent: undefined,+ agentInfo: undefined,+ context: undefined,+ currentContextUsage: undefined,+ preComputedCompletion: undefined,+ sandbox: undefined,+ capabilities: undefined,+ capabilityState: undefined,+ tracing: NOOP_AGENT_TRACING,+ logger: makeSilentLogger(),+ ...overrides,+ };+}++describe('orchestration: user-message reset', () => {+ it('cancels in-flight children, closes open tools on main, then sends the user message', async () => {+ const mainContext: ContextMessage[] = [+ assistantWithCalls([threadCreationToolCall(TOOL_CALL_ID), approvalToolCall('call-hitl')]),+ ];+ const main = new AgentThread(+ baseThreadInput({+ threadId: MAIN_ID,+ title: 'main',+ context: mainContext,+ }),+ );+ const child = new AgentThread(+ baseThreadInput({+ threadId: CHILD_ID,+ title: 'worker',+ parent: { thread_id: MAIN_ID, tool_call_id: TOOL_CALL_ID },+ agentInfo: { type: 'dynamic', name: 'worker', input: 'task' },+ definition: {+ modelClient: {+ create: jest.fn().mockImplementation(() => {+ throw new Error('cancelled child must not call the model');+ }),+ createNonStream: jest.fn(),+ },+ instruction: undefined,+ messages: undefined,+ modelParams: undefined,+ responseFormat: undefined,+ iterationLimit: undefined,+ toolSets: undefined,+ },+ }),+ );++ const orchestrator = new AgentThreadOrchestrator({+ agentThreads: new Map([+ [main.threadId, main],+ [child.threadId, child],+ ]),+ createDynamicSubAgentThread: () => Promise.reject(new Error('unexpected sub-agent')),+ tracing: NOOP_AGENT_TRACING,+ logger: makeSilentLogger(),+ });++ const sendEvents = [];+ for await (const event of orchestrator.send([{ type: EventType.USER_MESSAGE, content: 'new topic' }])) {+ sendEvents.push(event);+ }++ const { events, result } = await runExecute({ orchestrator });++ expect(child.toSnapshot().completion).toEqual(expect.objectContaining({ type: 'cancelled', reason: CANCELED }));+ expect(sendEvents).toEqual(+ expect.arrayContaining([+ expect.objectContaining({+ type: InternalEventType.AGENT_CONTEXT_APPEND,+ thread_id: CHILD_ID,+ completion: expect.objectContaining({ type: 'cancelled', reason: CANCELED }),+ }),+ expect.objectContaining({+ type: InternalEventType.AGENT_CONTEXT_APPEND,+ thread_id: MAIN_ID,+ context: expect.arrayContaining([+ { role: 'tool', tool_call_id: TOOL_CALL_ID, content: CANCELED },+ { role: 'tool', tool_call_id: 'call-hitl', content: CANCELED },+ ]),+ }),+ expect.objectContaining({+ type: InternalEventType.AGENT_CONTEXT_APPEND,+ thread_id: MAIN_ID,+ context: [{ role: 'user', content: 'new topic' }],+ }),+ ]),+ );+ expect(events.filter(e => e.type === EventType.TOOL_RESPONSE)).toEqual([]);+ expect(events).toEqual(+ expect.arrayContaining([+ expect.objectContaining({+ type: InternalEventType.AGENT_DONE,+ thread_id: CHILD_ID,+ status: 'cancelled',+ reason: CANCELED,+ }),+ ]),+ );+ expect(result.output?.content).toBe(ROOT_REPLY);+ expect(llmCreateInputs(main.definition.modelClient)).toHaveLength(1);+ });++ it('delivers a finished child send_to_parent instead of the cancel string', async () => {+ const main = new AgentThread(+ baseThreadInput({+ threadId: MAIN_ID,+ title: 'main',+ context: [assistantWithCalls([threadCreationToolCall(TOOL_CALL_ID)])],+ }),+ );+ const child = new AgentThread(+ baseThreadInput({+ threadId: CHILD_ID,+ title: 'worker',+ parent: { thread_id: MAIN_ID, tool_call_id: TOOL_CALL_ID },+ agentInfo: { type: 'dynamic', name: 'worker', input: 'task' },+ preComputedCompletion: {+ type: 'done',+ output: {+ type: EventType.MODEL_MESSAGE,+ id: 'child-out',+ created_at: new Date().toISOString(),+ thread_id: CHILD_ID,+ content: FINISHED_CHILD_ANSWER,+ finish_reason: 'stop',+ },+ send_to_parent: {+ role: 'tool',+ tool_call_id: TOOL_CALL_ID,+ content: FINISHED_CHILD_ANSWER,+ },+ },+ }),+ );++ const orchestrator = new AgentThreadOrchestrator({+ agentThreads: new Map([+ [main.threadId, main],+ [child.threadId, child],+ ]),+ createDynamicSubAgentThread: () => Promise.reject(new Error('unexpected sub-agent')),+ tracing: NOOP_AGENT_TRACING,+ logger: makeSilentLogger(),+ });++ const sendEvents: unknown[] = [];+ for await (const event of orchestrator.send([{ type: EventType.USER_MESSAGE, content: 'new topic' }])) {+ sendEvents.push(event);+ }++ expect(sendEvents).toEqual(+ expect.arrayContaining([+ expect.objectContaining({+ type: InternalEventType.AGENT_CONTEXT_APPEND,+ thread_id: MAIN_ID,+ context: [{ role: 'tool', tool_call_id: TOOL_CALL_ID, content: FINISHED_CHILD_ANSWER }],+ }),+ expect.objectContaining({+ type: InternalEventType.AGENT_CONTEXT_APPEND,+ thread_id: MAIN_ID,+ context: [{ role: 'user', content: 'new topic' }],+ }),+ ]),+ );+ expect(JSON.stringify(sendEvents)).not.toContain(CANCELED);++ const { events } = await runExecute({ orchestrator });+ expect(events).toEqual(+ expect.arrayContaining([+ expect.objectContaining({+ type: InternalEventType.AGENT_DONE,+ thread_id: CHILD_ID,+ status: 'done',+ }),+ ]),+ );+ });++ it('ignores empty send/validate on a completed thread; non-empty still throws', async () => {+ const child = new AgentThread(+ baseThreadInput({+ threadId: CHILD_ID,+ title: 'worker',+ parent: { thread_id: MAIN_ID, tool_call_id: TOOL_CALL_ID },+ preComputedCompletion: {+ type: 'cancelled',+ reason: CANCELED,+ send_to_parent: { role: 'tool', tool_call_id: TOOL_CALL_ID, content: CANCELED },+ },+ }),+ );+ await expect(child.send([]).next()).resolves.toEqual({ done: true, value: undefined });+ expect(() => child.validateSendInput([])).not.toThrow();+ expect(() => child.validateSendInput([{ role: 'tool', tool_call_id: TOOL_CALL_ID, content: 'late' }])).toThrow(+ InvalidAgentSendInputError,+ );+ await expect(+ child.send([{ role: 'tool', tool_call_id: TOOL_CALL_ID, content: 'late' }]).next(),+ ).rejects.toBeInstanceOf(InvalidAgentSendInputError);+ });++ it('empty orchestrator send ignores leftover children with preComputedCompletion', async () => {+ const main = new AgentThread(+ baseThreadInput({+ threadId: MAIN_ID,+ title: 'main',+ context: [assistantWithCalls([threadCreationToolCall(TOOL_CALL_ID)])],+ }),+ );+ const child = new AgentThread(+ baseThreadInput({+ threadId: CHILD_ID,+ title: 'worker',+ parent: { thread_id: MAIN_ID, tool_call_id: TOOL_CALL_ID },+ agentInfo: { type: 'dynamic', name: 'worker', input: 'task' },+ preComputedCompletion: {+ type: 'cancelled',+ reason: CANCELED,+ send_to_parent: { role: 'tool', tool_call_id: TOOL_CALL_ID, content: CANCELED },+ },+ }),+ );++ const orchestrator = new AgentThreadOrchestrator({+ agentThreads: new Map([+ [main.threadId, main],+ [child.threadId, child],+ ]),+ createDynamicSubAgentThread: () => Promise.reject(new Error('unexpected sub-agent')),+ tracing: NOOP_AGENT_TRACING,+ logger: makeSilentLogger(),+ });++ await expect(+ (async () => {+ for await (const _event of orchestrator.send([])) {+ void _event;+ }+ })(),+ ).resolves.toBeUndefined();+ });+});diff --git a/packages/trueforge-sdk/src/api/types/BaseThreadDoneEvent.ts b/packages/trueforge-sdk/src/api/types/BaseThreadDoneEvent.tsdeleted file mode 100644index 62a2afd4e..000000000--- a/packages/trueforge-sdk/src/api/types/BaseThreadDoneEvent.ts+++ /dev/null@@ -1,11 +0,0 @@-// This file was auto-generated by Fern from our API Definition.--import type * as TrueForge from "../index.js";--export interface BaseThreadDoneEvent {- parent?: TrueForge.AgentParent;- /** Thread that finished. */- threadId: string;- /** Human-readable thread title. */- title: string;-}diff --git a/packages/trueforge-sdk/src/api/types/ThreadDoneEvent.ts b/packages/trueforge-sdk/src/api/types/ThreadDoneEvent.tsindex 2cd8345b9..3ded2d068 100644--- a/packages/trueforge-sdk/src/api/types/ThreadDoneEvent.ts+++ b/packages/trueforge-sdk/src/api/types/ThreadDoneEvent.ts@@ -2,11 +2,16 @@import type * as TrueForge from "../index.js";-export interface ThreadDoneEvent extends TrueForge.BaseThreadDoneEvent {+export interface ThreadDoneEvent {/** ISO 8601 event timestamp. */createdAt: string;/** Unique identifier for the event (monotonic ULID). */id: string;+ parent?: TrueForge.AgentParent;state: TrueForge.ThreadState;+ /** Thread that finished. */+ threadId: string;+ /** Human-readable thread title. */+ title: string;type: "thread.done";}diff --git a/packages/trueforge-sdk/src/api/types/index.ts b/packages/trueforge-sdk/src/api/types/index.tsindex 5730217c7..8132075c7 100644--- a/packages/trueforge-sdk/src/api/types/index.ts+++ b/packages/trueforge-sdk/src/api/types/index.ts@@ -18,7 +18,6 @@ export * from "./AvailableModel.js";export * from "./AvailableModelProvider.js";export * from "./AvailableSkill.js";export * from "./BaseMcpAuthRequiredEvent.js";-export * from "./BaseThreadDoneEvent.js";export * from "./CancelSessionResponse.js";export * from "./CapabilitiesData.js";export * from "./CatalogCustomModelProvider.js";diff --git a/packages/trueforge-sdk/src/serialization/types/BaseThreadDoneEvent.ts b/packages/trueforge-sdk/src/serialization/types/BaseThreadDoneEvent.tsdeleted file mode 100644index 2aac85ed1..000000000--- a/packages/trueforge-sdk/src/serialization/types/BaseThreadDoneEvent.ts+++ /dev/null@@ -1,23 +0,0 @@-// This file was auto-generated by Fern from our API Definition.--import type * as TrueForge from "../../api/index.js";-import * as core from "../../core/index.js";-import type * as serializers from "../index.js";-import { AgentParent } from "./AgentParent.js";--export const BaseThreadDoneEvent: core.serialization.ObjectSchema<- serializers.BaseThreadDoneEvent.Raw,- TrueForge.BaseThreadDoneEvent-> = core.serialization.object({- parent: AgentParent.optional(),- threadId: core.serialization.property("thread_id", core.serialization.string()),- title: core.serialization.string(),-});--export declare namespace BaseThreadDoneEvent {- export interface Raw {- parent?: AgentParent.Raw | null;- thread_id: string;- title: string;- }-}diff --git a/packages/trueforge-sdk/src/serialization/types/ThreadDoneEvent.ts b/packages/trueforge-sdk/src/serialization/types/ThreadDoneEvent.tsindex ab43a85cb..d718f8142 100644--- a/packages/trueforge-sdk/src/serialization/types/ThreadDoneEvent.ts+++ b/packages/trueforge-sdk/src/serialization/types/ThreadDoneEvent.ts@@ -3,26 +3,30 @@import type * as TrueForge from "../../api/index.js";import * as core from "../../core/index.js";import type * as serializers from "../index.js";-import { BaseThreadDoneEvent } from "./BaseThreadDoneEvent.js";+import { AgentParent } from "./AgentParent.js";import { ThreadState } from "./ThreadState.js";export const ThreadDoneEvent: core.serialization.ObjectSchema<serializers.ThreadDoneEvent.Raw,TrueForge.ThreadDoneEvent-> = core.serialization- .object({- createdAt: core.serialization.property("created_at", core.serialization.string()),- id: core.serialization.string(),- state: ThreadState,- type: core.serialization.stringLiteral("thread.done"),- })- .extend(BaseThreadDoneEvent);+> = core.serialization.object({+ createdAt: core.serialization.property("created_at", core.serialization.string()),+ id: core.serialization.string(),+ parent: AgentParent.optional(),+ state: ThreadState,+ threadId: core.serialization.property("thread_id", core.serialization.string()),+ title: core.serialization.string(),+ type: core.serialization.stringLiteral("thread.done"),+});export declare namespace ThreadDoneEvent {- export interface Raw extends BaseThreadDoneEvent.Raw {+ export interface Raw {created_at: string;id: string;+ parent?: AgentParent.Raw | null;state: ThreadState.Raw;+ thread_id: string;+ title: string;type: "thread.done";}}diff --git a/packages/trueforge-sdk/src/serialization/types/index.ts b/packages/trueforge-sdk/src/serialization/types/index.tsindex 5730217c7..8132075c7 100644--- a/packages/trueforge-sdk/src/serialization/types/index.ts+++ b/packages/trueforge-sdk/src/serialization/types/index.ts@@ -18,7 +18,6 @@ export * from "./AvailableModel.js";export * from "./AvailableModelProvider.js";export * from "./AvailableSkill.js";export * from "./BaseMcpAuthRequiredEvent.js";-export * from "./BaseThreadDoneEvent.js";export * from "./CancelSessionResponse.js";export * from "./CapabilitiesData.js";export * from "./CatalogCustomModelProvider.js";diff --git a/packages/trueforge/src/db/postgres/session-store/queries/threads.ts b/packages/trueforge/src/db/postgres/session-store/queries/threads.tsindex 1b247a400..932d2120e 100644--- a/packages/trueforge/src/db/postgres/session-store/queries/threads.ts+++ b/packages/trueforge/src/db/postgres/session-store/queries/threads.ts@@ -8,10 +8,7 @@ import type {} from '@truefoundry/trueforge-core/agent-session/store/ISessionStore';import type { JsonValue } from '@truefoundry/trueforge-core/core/capabilities/AgentCapability';import type { AgentInfo } from '@truefoundry/trueforge-core/core/events/schema';-import type {- ContextMessage,- SubAgentCompletionMarker,-} from '@truefoundry/trueforge-core/core/runtime/AgentThread.types';+import type { ContextMessage, SubAgentCompletion } from '@truefoundry/trueforge-core/core/runtime/AgentThread.types';import type { CurrentContextUsage } from '@truefoundry/trueforge-core/core/runtime/contextUsage';import { sql, type Kysely, type RawBuilder, type Transaction } from 'kysely';import { json, jsonbSet } from '../../sqlExpressions';@@ -186,7 +183,7 @@ export async function removeThreads(db: Kysely<Database>, input: RemoveThreadsIn}}-function completionPatchExpr(completion: SubAgentCompletionMarker | null): RawBuilder<TurnThreadCheckpoint> {+function completionPatchExpr(completion: SubAgentCompletion | null): RawBuilder<TurnThreadCheckpoint> {if (completion === null) {return sql<TurnThreadCheckpoint>`checkpoint`;}@@ -209,7 +206,7 @@ async function fencedTurnThreadContextUpdate(context: ContextMessage[];replace_array: boolean;current_context_usage: CurrentContextUsage | null;- completion: SubAgentCompletionMarker | null;+ completion: SubAgentCompletion | null;/** When replace_array, usage is set unconditionally (overwrite contract). */usage_unconditional: CurrentContextUsage | null;},diff --git a/packages/trueforge/src/db/postgres/session-store/queries/turns.ts b/packages/trueforge/src/db/postgres/session-store/queries/turns.tsindex 497ef404b..977a49d8c 100644--- a/packages/trueforge/src/db/postgres/session-store/queries/turns.ts+++ b/packages/trueforge/src/db/postgres/session-store/queries/turns.ts@@ -25,7 +25,11 @@ import {} from '@truefoundry/trueforge-core/agent-session/store/SessionStoreErrors';import type { CapabilityState, JsonValue } from '@truefoundry/trueforge-core/core/capabilities/AgentCapability';import type { AgentInfo, AgentParent, MCPServerInitInfo } from '@truefoundry/trueforge-core/core/events/schema';-import type { AgentThreadSnapshot, ContextMessage } from '@truefoundry/trueforge-core/core/runtime/AgentThread.types';+import type {+ AgentThreadSnapshot,+ ContextMessage,+ SubAgentCompletion,+} from '@truefoundry/trueforge-core/core/runtime/AgentThread.types';import type { CurrentContextUsage } from '@truefoundry/trueforge-core/core/runtime/contextUsage';import { getEmptyCurrentContextUsage } from '@truefoundry/trueforge-core/core/runtime/contextUsage';import type { SandboxInfo } from '@truefoundry/trueforge-core/core/sandbox/Sandbox';@@ -67,6 +71,7 @@ export interface NewContextAppend {thread_id: string;context: ContextMessage[];current_context_usage: CurrentContextUsage | null;+ completion: SubAgentCompletion | null;}export interface CreateTurnTurnFields {@@ -563,10 +568,14 @@ export async function createTurn(db: Kysely<Database>, input: CreateTurnInput):}const appendUsageByThread = new Map<string, CurrentContextUsage>();+ const appendCompletionByThread = new Map<string, SubAgentCompletion>();for (const append of input.new_context_appends) {if (append.current_context_usage !== null) {appendUsageByThread.set(append.thread_id, append.current_context_usage);}+ if (append.completion !== null) {+ appendCompletionByThread.set(append.thread_id, append.completion);+ }}// step5: child turn_thread rows — carried = parent || new ids; new = fresh row.@@ -575,11 +584,13 @@ export async function createTurn(db: Kysely<Database>, input: CreateTurnInput):for (const parent of prevThreadRows) {const newIds = newIdsByThread.get(parent.thread_id) ?? [];const usage = appendUsageByThread.get(parent.thread_id) ?? parent.current_context_usage;+ const completion = appendCompletionByThread.get(parent.thread_id);+ const checkpoint = completion !== undefined ? { ...parent.checkpoint, completion } : parent.checkpoint;turnThreadRows.push({session_id: input.session_id,turn_id: input.turn.turn_id,thread_id: parent.thread_id,- checkpoint: parent.checkpoint,+ checkpoint,agent_info: parent.agent_info !== null ? json(parent.agent_info) : null,current_context_usage: usage,context_ids: parent.context_ids.concat(newIds),diff --git a/packages/trueforge/src/db/postgres/types.ts b/packages/trueforge/src/db/postgres/types.tsindex 121565b6a..20169e9af 100644--- a/packages/trueforge/src/db/postgres/types.ts+++ b/packages/trueforge/src/db/postgres/types.ts@@ -20,7 +20,7 @@ import type {JsonValue,MCPServerInitInfo,SandboxInfo,- SubAgentCompletionMarker,+ SubAgentCompletion,} from '@truefoundry/trueforge-core/core';import type { CurrentContextUsage } from '@truefoundry/trueforge-core/core/runtime/contextUsage';import type { ColumnType, Generated, JSONColumnType } from 'kysely';@@ -44,7 +44,7 @@ import type { OAuthClient, OAuthPendingAuthorizationData, OAuthServer, OAuthToke*/export interface TurnThreadCheckpoint {parent: AgentParent | null;- completion: SubAgentCompletionMarker | null;+ completion: SubAgentCompletion | null;}/** Turn-level checkpoint — threads live in `turn_thread`; only owned top-level keys remain. */diff --git a/packages/trueforge/src/db/sqlite/session-store/queries/threads.ts b/packages/trueforge/src/db/sqlite/session-store/queries/threads.tsindex 811af4b1d..7fcd0029b 100644--- a/packages/trueforge/src/db/sqlite/session-store/queries/threads.ts+++ b/packages/trueforge/src/db/sqlite/session-store/queries/threads.ts@@ -6,10 +6,7 @@ import type {PatchSandboxInfoInput,RemoveThreadsInput,} from '@truefoundry/trueforge-core/agent-session/store/ISessionStore';-import type {- ContextMessage,- SubAgentCompletionMarker,-} from '@truefoundry/trueforge-core/core/runtime/AgentThread.types';+import type { ContextMessage, SubAgentCompletion } from '@truefoundry/trueforge-core/core/runtime/AgentThread.types';import type { CurrentContextUsage } from '@truefoundry/trueforge-core/core/runtime/contextUsage';import { sql, type Kysely, type RawBuilder, type Transaction } from 'kysely';import { jsonbBind, jsonbSet, nowIso } from '../../sqlExpressions';@@ -217,7 +214,7 @@ async function getNextPos(db: DbOrTrx, keys: TurnKeys, thread_id: string): Promireturn (maxRow?.max_pos ?? 0) + 1;}-function completionPatchExpr(completion: SubAgentCompletionMarker | null): RawBuilder<string> {+function completionPatchExpr(completion: SubAgentCompletion | null): RawBuilder<string> {if (completion === null) {return sql`checkpoint`;}@@ -239,7 +236,7 @@ async function fencedTurnThreadContextUpdate(context: ContextMessage[];replace_array: boolean;current_context_usage: CurrentContextUsage | null;- completion: SubAgentCompletionMarker | null;+ completion: SubAgentCompletion | null;/** When replace_array, usage is set unconditionally (overwrite contract). */usage_unconditional: CurrentContextUsage | null;},diff --git a/packages/trueforge/src/db/sqlite/session-store/queries/turns.ts b/packages/trueforge/src/db/sqlite/session-store/queries/turns.tsindex 2bf01faf4..5d4ad9115 100644--- a/packages/trueforge/src/db/sqlite/session-store/queries/turns.ts+++ b/packages/trueforge/src/db/sqlite/session-store/queries/turns.ts@@ -25,7 +25,11 @@ import {} from '@truefoundry/trueforge-core/agent-session/store/SessionStoreErrors';import type { CapabilityState, JsonValue } from '@truefoundry/trueforge-core/core/capabilities/AgentCapability';import type { AgentInfo, AgentParent, MCPServerInitInfo } from '@truefoundry/trueforge-core/core/events/schema';-import type { AgentThreadSnapshot, ContextMessage } from '@truefoundry/trueforge-core/core/runtime/AgentThread.types';+import type {+ AgentThreadSnapshot,+ ContextMessage,+ SubAgentCompletion,+} from '@truefoundry/trueforge-core/core/runtime/AgentThread.types';import type { CurrentContextUsage } from '@truefoundry/trueforge-core/core/runtime/contextUsage';import { getEmptyCurrentContextUsage } from '@truefoundry/trueforge-core/core/runtime/contextUsage';import type { SandboxInfo } from '@truefoundry/trueforge-core/core/sandbox/Sandbox';@@ -67,6 +71,7 @@ export interface NewContextAppend {thread_id: string;context: ContextMessage[];current_context_usage: CurrentContextUsage | null;+ completion: SubAgentCompletion | null;}export interface CreateTurnTurnFields {@@ -524,10 +529,14 @@ export async function createTurn(db: Kysely<Database>, input: CreateTurnInput):}const appendUsageByThread = new Map<string, CurrentContextUsage>();+ const appendCompletionByThread = new Map<string, SubAgentCompletion>();for (const append of input.new_context_appends) {if (append.current_context_usage !== null) {appendUsageByThread.set(append.thread_id, append.current_context_usage);}+ if (append.completion !== null) {+ appendCompletionByThread.set(append.thread_id, append.completion);+ }}// Step 5: insert turn_thread rows for carried-forward and new threads.@@ -551,11 +560,13 @@ export async function createTurn(db: Kysely<Database>, input: CreateTurnInput):for (const parent of prevThreadRows) {const usage = appendUsageByThread.get(parent.thread_id) ?? parent.current_context_usage;+ const completion = appendCompletionByThread.get(parent.thread_id);+ const checkpoint = completion !== undefined ? { ...parent.checkpoint, completion } : parent.checkpoint;turnThreadRows.push({session_id: input.session_id,turn_id: input.turn.turn_id,thread_id: parent.thread_id,- checkpoint: jsonbBind(parent.checkpoint),+ checkpoint: jsonbBind(checkpoint),agent_info: parent.agent_info !== null ? jsonbBind(parent.agent_info) : null,current_context_usage: jsonbBind(usage),updated_at: now,diff --git a/packages/trueforge/src/db/sqlite/types.ts b/packages/trueforge/src/db/sqlite/types.tsindex 60dac6bf0..cea7f3851 100644--- a/packages/trueforge/src/db/sqlite/types.ts+++ b/packages/trueforge/src/db/sqlite/types.ts@@ -23,7 +23,7 @@ import type {JsonValue,MCPServerInitInfo,SandboxInfo,- SubAgentCompletionMarker,+ SubAgentCompletion,} from '@truefoundry/trueforge-core/core';import type { CurrentContextUsage } from '@truefoundry/trueforge-core/core/runtime/contextUsage';import type { ColumnType, Generated, JSONColumnType } from 'kysely';@@ -47,7 +47,7 @@ import type { OAuthClient, OAuthPendingAuthorizationData, OAuthServer, OAuthToke*/export interface TurnThreadCheckpoint {parent: AgentParent | null;- completion: SubAgentCompletionMarker | null;+ completion: SubAgentCompletion | null;}/** Turn-level checkpoint — threads live in `turn_thread`; only owned top-level keys remain. */diff --git a/python/trueforge_sdk/src/trueforge_sdk/__init__.py b/python/trueforge_sdk/src/trueforge_sdk/__init__.pyindex 8768c2d49..bfc2c7f25 100644--- a/python/trueforge_sdk/src/trueforge_sdk/__init__.py+++ b/python/trueforge_sdk/src/trueforge_sdk/__init__.py@@ -27,7 +27,6 @@ if typing.TYPE_CHECKING:AvailableModelProvider,AvailableSkill,BaseMcpAuthRequiredEvent,- BaseThreadDoneEvent,CancelSessionResponse,CapabilitiesData,CatalogCustomModelProvider,@@ -330,7 +329,6 @@ _dynamic_imports: typing.Dict[str, str] = {"BadGatewayError": ".errors","BadRequestError": ".errors","BaseMcpAuthRequiredEvent": ".types",- "BaseThreadDoneEvent": ".types","CancelSessionResponse": ".types","CapabilitiesData": ".types","CatalogCustomModelProvider": ".types",@@ -651,7 +649,6 @@ __all__ = ["BadGatewayError","BadRequestError","BaseMcpAuthRequiredEvent",- "BaseThreadDoneEvent","CancelSessionResponse","CapabilitiesData","CatalogCustomModelProvider",diff --git a/python/trueforge_sdk/src/trueforge_sdk/types/__init__.py b/python/trueforge_sdk/src/trueforge_sdk/types/__init__.pyindex 9d45891a0..3a36bafeb 100644--- a/python/trueforge_sdk/src/trueforge_sdk/types/__init__.py+++ b/python/trueforge_sdk/src/trueforge_sdk/types/__init__.py@@ -26,7 +26,6 @@ if typing.TYPE_CHECKING:from .available_model_provider import AvailableModelProviderfrom .available_skill import AvailableSkillfrom .base_mcp_auth_required_event import BaseMcpAuthRequiredEvent- from .base_thread_done_event import BaseThreadDoneEventfrom .cancel_session_response import CancelSessionResponsefrom .capabilities_data import CapabilitiesDatafrom .catalog_custom_model_provider import CatalogCustomModelProvider@@ -294,7 +293,6 @@ _dynamic_imports: typing.Dict[str, str] = {"AvailableModelProvider": ".available_model_provider","AvailableSkill": ".available_skill","BaseMcpAuthRequiredEvent": ".base_mcp_auth_required_event",- "BaseThreadDoneEvent": ".base_thread_done_event","CancelSessionResponse": ".cancel_session_response","CapabilitiesData": ".capabilities_data","CatalogCustomModelProvider": ".catalog_custom_model_provider",@@ -586,7 +584,6 @@ __all__ = ["AvailableModelProvider","AvailableSkill","BaseMcpAuthRequiredEvent",- "BaseThreadDoneEvent","CancelSessionResponse","CapabilitiesData","CatalogCustomModelProvider",diff --git a/python/trueforge_sdk/src/trueforge_sdk/types/base_thread_done_event.py b/python/trueforge_sdk/src/trueforge_sdk/types/base_thread_done_event.pydeleted file mode 100644index 2b604a655..000000000--- a/python/trueforge_sdk/src/trueforge_sdk/types/base_thread_done_event.py+++ /dev/null@@ -1,29 +0,0 @@-# This file was auto-generated by Fern from our API Definition.--import typing--import pydantic-from ..core.pydantic_utilities import IS_PYDANTIC_V2-from ..core.unchecked_base_model import UncheckedBaseModel-from .agent_parent import AgentParent---class BaseThreadDoneEvent(UncheckedBaseModel):- parent: typing.Optional[AgentParent] = None- thread_id: str = pydantic.Field()- """- Thread that finished.- """-- title: str = pydantic.Field()- """- Human-readable thread title.- """-- if IS_PYDANTIC_V2:- model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow") # type: ignore # Pydantic v2- else:-- class Config:- smart_union = True- extra = pydantic.Extra.allowdiff --git a/python/trueforge_sdk/src/trueforge_sdk/types/thread_done_event.py b/python/trueforge_sdk/src/trueforge_sdk/types/thread_done_event.pyindex c1857c1c9..8c125e95a 100644--- a/python/trueforge_sdk/src/trueforge_sdk/types/thread_done_event.py+++ b/python/trueforge_sdk/src/trueforge_sdk/types/thread_done_event.py@@ -4,11 +4,12 @@ import typingimport pydanticfrom ..core.pydantic_utilities import IS_PYDANTIC_V2-from .base_thread_done_event import BaseThreadDoneEvent+from ..core.unchecked_base_model import UncheckedBaseModel+from .agent_parent import AgentParentfrom .thread_state import ThreadState-class ThreadDoneEvent(BaseThreadDoneEvent):+class ThreadDoneEvent(UncheckedBaseModel):created_at: str = pydantic.Field()"""ISO 8601 event timestamp.@@ -19,7 +20,18 @@ class ThreadDoneEvent(BaseThreadDoneEvent):Unique identifier for the event (monotonic ULID)."""+ parent: typing.Optional[AgentParent] = Nonestate: ThreadState+ thread_id: str = pydantic.Field()+ """+ Thread that finished.+ """++ title: str = pydantic.Field()+ """+ Human-readable thread title.+ """+type: typing.Literal["thread.done"] = "thread.done"if IS_PYDANTIC_V2: