The Open Framework for Building Agents
feat(eve): agent-handle lifecycle contracts (three-phase handles, turn outcomes) (#1328)
Ruiab86523b3e07
diff --git a/packages/eve/src/channel/session-callback.ts b/packages/eve/src/channel/session-callback.tsindex 27c4430ae..31c60dec6 100644--- a/packages/eve/src/channel/session-callback.ts+++ b/packages/eve/src/channel/session-callback.ts@@ -44,9 +44,9 @@ const sessionCallbackSchema = z});}- // SSRF guard: the framework POSTs to this URL on session completion, so a- // caller-supplied private/link-local host (e.g. cloud metadata) must be- // rejected. The path/token check above does not constrain the host.+ // SSRF guard: the framework POSTs to this URL when delegated work settles,+ // so a caller-supplied private/link-local host (e.g. cloud metadata) must+ // be rejected. The path/token check above does not constrain the host.if (isReservedIpAddress(url.hostname)) {ctx.addIssue({code: "custom",diff --git a/packages/eve/src/channel/types.ts b/packages/eve/src/channel/types.tsindex e93c85b2e..f1165c6a6 100644--- a/packages/eve/src/channel/types.ts+++ b/packages/eve/src/channel/types.ts@@ -127,6 +127,15 @@ export type EventEmitFn = (event: UnstampedMessageStreamEvent) => Promise<void>;// Deliver payload// ---------------------------------------------------------------------------+/** Framework-internal caller waiting for one delegated conversation turn. */+export interface TurnCaller {+ readonly callId: string;+ readonly subagentName: string;+ readonly replyTo:+ | { readonly kind: "hook"; readonly token: string }+ | { readonly kind: "callback"; readonly url: string };+}+/*** Base deliver payload crossing the runtime boundary.*@@ -154,12 +163,13 @@ export interface DeliverPayload {/*** Deliver payload sent through the workflow `resumeHook`.*- * Wraps the raw {@link DeliverPayload} with an optional auth update so- * deliver-time auth crosses the durable hook boundary without a process-local- * side-channel.+ * Wraps the raw {@link DeliverPayload} with optional auth and turn-caller+ * metadata so both cross the durable hook boundary outside adapter-owned data.*/export interface DeliverHookPayload {readonly auth?: SessionAuthContext | null;+ /** Delegated caller waiting for this turn's settled result. */+ readonly caller?: TurnCaller;/** Inbound channel request id used only for workflow attributes. */readonly requestId?: string;readonly kind: "deliver";@@ -240,11 +250,13 @@ export type HookPayload =| SubagentInputRequestHookPayload;/**- * Terminal callback metadata attached to a session at creation.+ * Initial caller callback attached to a delegated session at creation.** `url` is the absolute callback endpoint. `token` is the capability token* embedded in the framework-owned callback route. `callId` and `subagentName`- * correlate the callee's terminal callback to the pending parent tool call.+ * correlate the callee's result to the pending tool call. Task sessions send a+ * terminal session result. Conversation sessions use this as their first turn's+ * caller; each continuation supplies the caller for that turn.*/export interface SessionCallback {readonly callId: string;@@ -321,8 +333,9 @@ export interface RunInput {*/readonly title?: string;/**- * Optional terminal callback. When present, the runtime posts a single- * callback when the session completes or fails.+ * Optional caller callback. Task sessions post when the session completes or+ * fails. Conversation sessions use it for the first turn; continuations carry+ * the caller for their own turn.*/readonly callback?: SessionCallback;/**@@ -369,12 +382,14 @@ export interface RunInput {export interface DeliverInput {/**- * Authenticated caller principal for this follow-up message.+ * Authenticated principal for this follow-up message.* May differ from the session initiator when different users send* messages to the same session. The runtime updates `AuthKey` from* this field before calling the adapter's hooks.*/readonly auth?: SessionAuthContext | null;+ /** Delegated caller waiting for this turn's settled result. */+ readonly caller?: TurnCaller;/** Inbound channel request id used to correlate workflow attributes. */readonly requestId?: string;readonly continuationToken: string;diff --git a/packages/eve/src/compiler/manifest.ts b/packages/eve/src/compiler/manifest.tsindex f25c18da8..69bb90c3c 100644--- a/packages/eve/src/compiler/manifest.ts+++ b/packages/eve/src/compiler/manifest.ts@@ -422,6 +422,7 @@ const compiledAgentConfigSchema: z.ZodType<CompiledAgentDefinition> = zdynamicModel: compiledDynamicModelDefinitionSchema.optional(),experimental: z.object({+ subagentPersistentSessions: z.boolean().optional(),workflow: compiledAgentWorkflowDefinitionSchema.optional(),}).strict()@@ -810,6 +811,7 @@ export function createCompiledAgentNodeManifest(input: {input.config.experimental === undefined? undefined: {+ subagentPersistentSessions: input.config.experimental.subagentPersistentSessions,workflow:input.config.experimental.workflow === undefined? undefineddiff --git a/packages/eve/src/compiler/normalize-agent-config.ts b/packages/eve/src/compiler/normalize-agent-config.tsindex 49be80d49..cde6cef5b 100644--- a/packages/eve/src/compiler/normalize-agent-config.ts+++ b/packages/eve/src/compiler/normalize-agent-config.ts@@ -170,6 +170,10 @@ function normalizeExperimentalDefinition(const compiledExperimental: Mutable<NonNullable<CompiledAgentDefinition["experimental"]>> = {};+ if (experimental.subagentPersistentSessions !== undefined) {+ compiledExperimental.subagentPersistentSessions = experimental.subagentPersistentSessions;+ }+if (experimental.workflow !== undefined) {compiledExperimental.workflow = {world: experimental.workflow.world,diff --git a/packages/eve/src/context/keys.ts b/packages/eve/src/context/keys.tsindex 81e388872..b9075f0ee 100644--- a/packages/eve/src/context/keys.ts+++ b/packages/eve/src/context/keys.ts@@ -80,7 +80,7 @@ export const SubagentDepthKey = new ContextKey<number>("eve.subagentDepth");export const CapabilitiesKey = new ContextKey<SessionCapabilities>("eve.capabilities");/**- * Optional framework-owned terminal callback metadata for this session.+ * Optional framework-owned caller callback captured when the session is created.*/export const SessionCallbackKey = new ContextKey<SessionCallback>("eve.sessionCallback");diff --git a/packages/eve/src/context/run-step.ts b/packages/eve/src/context/run-step.tsindex 999da7ee1..2efa7df72 100644--- a/packages/eve/src/context/run-step.ts+++ b/packages/eve/src/context/run-step.ts@@ -77,9 +77,9 @@ export async function runStep(callback: (session: HarnessSession) => Promise<StepResult>,): Promise<StepResult> {const { result, session } = await withContextScope(ctx, harnessSession, async (enriched) => {- const stepResult = await callback(enriched);- return { result: stepResult.next, session: stepResult.session };+ const result = await callback(enriched);+ return { result, session: result.session };});- return { next: result, session };+ return { ...result, session };}diff --git a/packages/eve/src/execution/session-callback-request.ts b/packages/eve/src/execution/session-callback-request.tsnew file mode 100644index 000000000..f24901809--- /dev/null+++ b/packages/eve/src/execution/session-callback-request.ts@@ -0,0 +1,17 @@+const SESSION_CALLBACK_TIMEOUT_MS = 30_000;++/** Posts one framework callback payload with the shared callback transport policy. */+export async function postSessionCallbackRequest(input: {+ readonly body: unknown;+ readonly url: string;+}): Promise<Response> {+ return await fetch(input.url, {+ body: JSON.stringify(input.body),+ headers: {+ "content-type": "application/json",+ },+ method: "POST",+ redirect: "error",+ signal: AbortSignal.timeout(SESSION_CALLBACK_TIMEOUT_MS),+ });+}diff --git a/packages/eve/src/harness/agent-handles.test.ts b/packages/eve/src/harness/agent-handles.test.tsnew file mode 100644index 000000000..952a6c3b9--- /dev/null+++ b/packages/eve/src/harness/agent-handles.test.ts@@ -0,0 +1,449 @@+import { describe, expect, it } from "vitest";++import {+ AGENT_HANDLES_STATE_KEY,+ confirmAgentStarted,+ deriveAgentId,+ deriveAgentOperationId,+ formatAgentStatus,+ getAgentHandleStore,+ prepareAgentContinuation,+ prepareAgentStart,+ projectParkedAgentHandles,+ rejectAgentEffect,+ renderAgentsSnippet,+ settleAgentTurn,+ type AgentAddress,+ type AgentHandle,+ type AgentIdentity,+ type ContinueOperation,+ type StartOperation,+} from "#harness/agent-handles.js";+import type { HarnessSession } from "#harness/types.js";+import type { TokenUsage } from "#shared/token-usage.js";++const ZERO_USAGE: TokenUsage = {+ cacheReadTokens: 0,+ cacheWriteTokens: 0,+ inputTokens: 0,+ outputTokens: 0,+};++function createSession(state?: HarnessSession["state"]): HarnessSession {+ return {+ agent: {+ modelReference: { id: "model_test" },+ system: "",+ tools: [],+ },+ compaction: { recentWindowSize: 4, threshold: 1_000_000 },+ continuationToken: "continuation_test",+ history: [],+ sessionId: "session_parent",+ state,+ };+}++const startOperation: StartOperation = {+ callId: "call_1",+ id: deriveAgentOperationId({+ callId: "call_1",+ parentSessionId: "session_parent",+ parentTurnId: "turn_1",+ }),+ kind: "start",+ parentTurnId: "turn_1",+};++const identity: AgentIdentity = {+ id: deriveAgentId("research", startOperation.id),+ name: "research",+ nodeId: "node_research",+};++const address: AgentAddress = {+ continuationToken: "continuation_child",+ kind: "agent/local",+ sessionId: "session_child",+};++function preparedSession(): HarnessSession {+ return prepareAgentStart(createSession(), {+ identity,+ operation: startOperation,+ target: { continuationToken: "continuation_child", kind: "agent/local" },+ });+}++function runningSession(): HarnessSession {+ return confirmAgentStarted(preparedSession(), {+ address,+ operationId: startOperation.id,+ });+}++function parkedSession(): HarnessSession {+ const settled = settleAgentTurn(runningSession(), {+ operationId: startOperation.id,+ outcome: {+ kind: "parked",+ result: { kind: "succeeded", output: "initial findings" },+ usageDelta: ZERO_USAGE,+ },+ sessionId: address.sessionId,+ });+ if (settled.kind !== "settled") {+ throw new Error("expected settled");+ }+ return settled.session;+}++function handlesOf(session: HarnessSession): readonly AgentHandle[] {+ return getAgentHandleStore(session.state)?.handles ?? [];+}++describe("deriveAgentOperationId / deriveAgentId", () => {+ it("is deterministic on parent-controlled inputs and independent of the child session", () => {+ const again = deriveAgentOperationId({+ callId: "call_1",+ parentSessionId: "session_parent",+ parentTurnId: "turn_1",+ });+ expect(again).toBe(startOperation.id);+ expect(deriveAgentId("research", again)).toBe(identity.id);+ expect(identity.id.startsWith("ag_research:")).toBe(true);+ });++ it("changes when any input changes", () => {+ const other = deriveAgentOperationId({+ callId: "call_2",+ parentSessionId: "session_parent",+ parentTurnId: "turn_1",+ });+ expect(other).not.toBe(startOperation.id);+ });+});++describe("getAgentHandleStore", () => {+ it("returns undefined only when no store has been written", () => {+ expect(getAgentHandleStore(undefined)).toBeUndefined();+ expect(getAgentHandleStore({})).toBeUndefined();+ });++ it("throws on a present but malformed store instead of treating it as absent", () => {+ for (const malformed of [+ null,+ { handles: "not-an-array" },+ { handles: [{ phase: "starting" }] },+ { extra: true, handles: [] },+ {+ handles: [+ {+ address,+ identity,+ lastStatus: "x".repeat(121),+ phase: "parked",+ },+ ],+ },+ ]) {+ expect(() => getAgentHandleStore({ [AGENT_HANDLES_STATE_KEY]: malformed })).toThrow(+ AGENT_HANDLES_STATE_KEY,+ );+ }+ });++ it("rejects duplicate handle ids", () => {+ const parked = handlesOf(parkedSession());+ expect(() =>+ getAgentHandleStore({ [AGENT_HANDLES_STATE_KEY]: { handles: [...parked, ...parked] } }),+ ).toThrow("unique");+ });+});++describe("prepareAgentStart", () => {+ it("records starting ownership before any side effect", () => {+ const session = preparedSession();+ expect(handlesOf(session)).toEqual([+ {+ identity,+ operation: startOperation,+ phase: "starting",+ target: { continuationToken: "continuation_child", kind: "agent/local" },+ },+ ]);+ });++ it("throws when the identity already exists", () => {+ expect(() =>+ prepareAgentStart(preparedSession(), {+ identity,+ operation: startOperation,+ target: { continuationToken: "continuation_child", kind: "agent/local" },+ }),+ ).toThrow(identity.id);+ });+});++describe("confirmAgentStarted", () => {+ it("moves starting to running with the confirmed address", () => {+ expect(handlesOf(runningSession())).toEqual([+ { address, identity, operation: startOperation, phase: "running" },+ ]);+ });++ it("is a replay no-op when the handle is already running", () => {+ const running = runningSession();+ expect(confirmAgentStarted(running, { address, operationId: startOperation.id })).toBe(running);+ });++ it("throws for an operation that was never prepared", () => {+ expect(() =>+ confirmAgentStarted(createSession(), { address, operationId: "op_unprepared" }),+ ).toThrow("op_unprepared");+ });+});++describe("prepareAgentContinuation", () => {+ const continueOperation: ContinueOperation = {+ callId: "call_2",+ id: deriveAgentOperationId({+ callId: "call_2",+ parentSessionId: "session_parent",+ parentTurnId: "turn_2",+ }),+ kind: "continue",+ parentTurnId: "turn_2",+ previousStatus: "",+ };++ it("moves parked to running and captures the previous status", () => {+ const result = prepareAgentContinuation(parkedSession(), {+ agentId: identity.id,+ invokedName: "research",+ operation: continueOperation,+ });+ expect(result.kind).toBe("ready");+ if (result.kind !== "ready") {+ return;+ }+ expect(result.handle.phase).toBe("running");+ expect(result.handle.operation).toEqual({+ ...continueOperation,+ previousStatus: "initial findings",+ });+ expect(handlesOf(result.session)).toEqual([result.handle]);+ });++ it("reports unknown, mismatch, and busy without changing the session", () => {+ expect(+ prepareAgentContinuation(parkedSession(), {+ agentId: "ag_missing:000000000000",+ invokedName: "research",+ operation: continueOperation,+ }),+ ).toEqual({ kind: "unknown" });++ expect(+ prepareAgentContinuation(parkedSession(), {+ agentId: identity.id,+ invokedName: "writer",+ operation: continueOperation,+ }),+ ).toEqual({ kind: "mismatch" });++ expect(+ prepareAgentContinuation(runningSession(), {+ agentId: identity.id,+ invokedName: "research",+ operation: continueOperation,+ }),+ ).toEqual({ kind: "busy" });+ });++ it("treats the operation already recorded on a running handle as a replay", () => {+ const running = runningSession();+ const replay = prepareAgentContinuation(running, {+ agentId: identity.id,+ invokedName: "research",+ operation: {+ callId: startOperation.callId,+ id: startOperation.id,+ kind: "continue",+ parentTurnId: startOperation.parentTurnId,+ previousStatus: "",+ },+ });+ expect(replay.kind).toBe("ready");+ if (replay.kind === "ready") {+ expect(replay.session).toBe(running);+ }+ });+});++describe("rejectAgentEffect", () => {+ it("deletes a dead start", () => {+ const session = rejectAgentEffect(preparedSession(), {+ disposition: "dead",+ operationId: startOperation.id,+ });+ expect(handlesOf(session)).toEqual([]);+ });++ it("restores parked with the previous status for a retryable continuation", () => {+ const continueOperation: ContinueOperation = {+ callId: "call_2",+ id: "op_continue",+ kind: "continue",+ parentTurnId: "turn_2",+ previousStatus: "",+ };+ const prepared = prepareAgentContinuation(parkedSession(), {+ agentId: identity.id,+ invokedName: "research",+ operation: continueOperation,+ });+ if (prepared.kind !== "ready") {+ throw new Error("expected ready");+ }++ const restored = rejectAgentEffect(prepared.session, {+ disposition: "retryable",+ operationId: "op_continue",+ });+ expect(handlesOf(restored)).toEqual([+ { address, identity, lastStatus: "initial findings", phase: "parked" },+ ]);+ });++ it("deletes a running start even when the failure is retryable", () => {+ // A fresh start has no parked state to restore; the model retries by+ // starting a new agent instead.+ const session = rejectAgentEffect(runningSession(), {+ disposition: "retryable",+ operationId: startOperation.id,+ });+ expect(handlesOf(session)).toEqual([]);+ });++ it("ignores unknown operations", () => {+ const parked = parkedSession();+ expect(rejectAgentEffect(parked, { disposition: "dead", operationId: "op_gone" })).toBe(parked);+ });+});++describe("settleAgentTurn", () => {+ it("parks the handle with a truncated status on a parked outcome", () => {+ const settled = settleAgentTurn(runningSession(), {+ operationId: startOperation.id,+ outcome: {+ kind: "parked",+ result: { kind: "succeeded", output: ` padded\n${"x".repeat(200)} ` },+ usageDelta: ZERO_USAGE,+ },+ sessionId: address.sessionId,+ });+ expect(settled.kind).toBe("settled");+ if (settled.kind !== "settled") {+ return;+ }+ const [handle] = handlesOf(settled.session);+ expect(handle?.phase).toBe("parked");+ if (handle?.phase === "parked") {+ expect(handle.lastStatus.length).toBeLessThanOrEqual(120);+ expect(handle.lastStatus.startsWith("padded x")).toBe(true);+ }+ });++ it("deletes the handle on a terminal outcome, including failures", () => {+ const settled = settleAgentTurn(runningSession(), {+ operationId: startOperation.id,+ outcome: {+ kind: "terminal",+ result: { error: { code: "BOOM" }, kind: "failed" },+ usageDelta: ZERO_USAGE,+ },+ sessionId: address.sessionId,+ });+ expect(settled.kind).toBe("settled");+ if (settled.kind === "settled") {+ expect(handlesOf(settled.session)).toEqual([]);+ }+ });++ it("keeps a failed-but-parked child resumable", () => {+ const settled = settleAgentTurn(runningSession(), {+ operationId: startOperation.id,+ outcome: {+ kind: "parked",+ result: { error: "model overloaded", kind: "failed" },+ usageDelta: ZERO_USAGE,+ },+ sessionId: address.sessionId,+ });+ expect(settled.kind).toBe("settled");+ if (settled.kind === "settled") {+ expect(handlesOf(settled.session)[0]?.phase).toBe("parked");+ }+ });++ it("ignores stale operations and mismatched child sessions", () => {+ expect(+ settleAgentTurn(runningSession(), {+ operationId: "op_stale",+ outcome: {+ kind: "parked",+ result: { kind: "succeeded", output: "" },+ usageDelta: ZERO_USAGE,+ },+ sessionId: address.sessionId,+ }),+ ).toEqual({ kind: "ignored", reason: "unknown-operation" });++ expect(+ settleAgentTurn(runningSession(), {+ operationId: startOperation.id,+ outcome: {+ kind: "parked",+ result: { kind: "succeeded", output: "" },+ usageDelta: ZERO_USAGE,+ },+ sessionId: "session_forged",+ }),+ ).toEqual({ kind: "ignored", reason: "session-mismatch" });+ });+});++describe("projection", () => {+ it("projects and renders only parked handles", () => {+ const running = runningSession();+ const store = getAgentHandleStore(running.state);+ expect(store).toBeDefined();+ if (store === undefined) {+ return;+ }+ expect(projectParkedAgentHandles(store)).toEqual([]);+ expect(renderAgentsSnippet(store)).toBe("[Agents]\n<agents>\n</agents>");++ const parkedStore = getAgentHandleStore(parkedSession().state);+ expect(parkedStore).toBeDefined();+ if (parkedStore === undefined) {+ return;+ }+ const snippet = renderAgentsSnippet(parkedStore);+ expect(snippet.startsWith("[Agents]\n<agents>")).toBe(true);+ expect(snippet).toContain(+ `<agent id="${identity.id}" name="research">initial findings</agent>`,+ );+ expect(snippet).not.toContain(address.sessionId);+ expect(snippet).not.toContain(address.continuationToken);+ });+});++describe("formatAgentStatus", () => {+ it("collapses whitespace, truncates to 120, and stringifies objects", () => {+ expect(formatAgentStatus(" a\n\tb ")).toBe("a b");+ expect(formatAgentStatus({ ok: true })).toBe('{"ok":true}');+ expect(formatAgentStatus("y".repeat(300)).length).toBe(120);+ });+});diff --git a/packages/eve/src/harness/agent-handles.ts b/packages/eve/src/harness/agent-handles.tsnew file mode 100644index 000000000..949658d47--- /dev/null+++ b/packages/eve/src/harness/agent-handles.ts@@ -0,0 +1,573 @@+import { createHash } from "node:crypto";++import { z } from "#compiled/zod/index.js";++import type { HarnessSession, SessionStateMap } from "#harness/types.js";+import type { AgentTurnOutcome } from "#shared/agent-turn-outcome.js";++/** Session-state key for delegated agent handles. */+export const AGENT_HANDLES_STATE_KEY = "eve.agent.handles";+const AGENTS_SNIPPET_LABEL = "[Agents]";+const MAX_STATUS_LENGTH = 120;++/** Error code for a requested agent id that is not registered. */+export const AGENT_UNKNOWN = "AGENT_UNKNOWN";++/** Error code for an agent id invoked through the wrong subagent tool. */+export const AGENT_MISMATCH = "AGENT_MISMATCH";++/** Error code for a registered agent that cannot be reached. */+export const AGENT_UNREACHABLE = "AGENT_UNREACHABLE";++/** Error code for an agent that is starting or already running a turn. */+export const AGENT_BUSY = "AGENT_BUSY";++/**+ * Stable identity of one delegated child, minted before its start side+ * effect runs. The model-visible `id` derives from the first start+ * operation, never from the child session id, so it exists before the+ * child does and cannot collide on externally supplied session suffixes.+ */+export interface AgentIdentity {+ /** Model-visible identifier: `ag_<name>:<operation-hash>`. */+ readonly id: string;+ /** Subagent tool name. */+ readonly name: string;+ /** Agent-graph node used to re-resolve delivery configuration. */+ readonly nodeId: string;+}++/**+ * One dispatch the parent intends to perform or has performed. Repeating+ * the same operation is a replay; a different operation against a+ * starting/running handle is a busy conflict.+ */+export interface StartOperation {+ readonly kind: "start";+ /** Derived via {@link deriveAgentOperationId}; stable across replays. */+ readonly id: string;+ readonly callId: string;+ readonly parentTurnId: string;+}++/** A continuation delivery against a parked handle. */+export interface ContinueOperation {+ readonly kind: "continue";+ /** Derived via {@link deriveAgentOperationId}; stable across replays. */+ readonly id: string;+ readonly callId: string;+ readonly parentTurnId: string;+ /**+ * Status the handle showed before this delivery, restored when the+ * delivery is rejected as retryable so the handle returns to `parked`+ * without optional state.+ */+ readonly previousStatus: string;+}++/** Where a fresh child will be started. No session exists yet. */+export type AgentStartTarget =+ | {+ readonly kind: "agent/local";+ /** Deterministic child continuation token chosen at dispatch. */+ readonly continuationToken: string;+ }+ | {+ readonly kind: "agent/self";+ readonly continuationToken: string;+ }+ | {+ readonly kind: "agent/remote";+ /** Deliver target base URL; never model-visible. */+ readonly url: string;+ /** Callback base URL stub captured at dispatch; never model-visible. */+ readonly callbackBaseUrl: string;+ };++/** Confirmed delivery coordinates of a started child. */+export type AgentAddress =+ | {+ readonly kind: "agent/local";+ readonly sessionId: string;+ readonly continuationToken: string;+ }+ | {+ readonly kind: "agent/self";+ readonly sessionId: string;+ readonly continuationToken: string;+ }+ | {+ readonly kind: "agent/remote";+ readonly sessionId: string;+ readonly continuationToken: string;+ readonly url: string;+ readonly callbackBaseUrl: string;+ };++/**+ * Durable ownership record for one delegated child.+ *+ * The store owns the full nonterminal lifecycle:+ *+ * - `starting` — the parent committed intent to start; the child may or+ * may not exist yet.+ * - `running` — one identified child turn is outstanding.+ * - `parked` — the child is idle and resumable; only this phase is+ * model-visible.+ *+ * A terminal child has no handle: settlement deletes it.+ */+export type AgentHandle =+ | {+ readonly phase: "starting";+ readonly identity: AgentIdentity;+ readonly operation: StartOperation;+ readonly target: AgentStartTarget;+ }+ | {+ readonly phase: "running";+ readonly identity: AgentIdentity;+ readonly operation: StartOperation | ContinueOperation;+ readonly address: AgentAddress;+ }+ | {+ readonly phase: "parked";+ readonly identity: AgentIdentity;+ readonly address: AgentAddress;+ readonly lastStatus: string;+ };++/** Lifecycle phase of a delegated agent handle. */+export type AgentHandlePhase = AgentHandle["phase"];++/** Session-state collection of delegated agent handles. */+export interface AgentHandleStore {+ readonly handles: readonly AgentHandle[];+}++const nonEmptyString = z.string().min(1);++const identitySchema = z.strictObject({+ id: nonEmptyString,+ name: nonEmptyString,+ nodeId: nonEmptyString,+});++const startOperationSchema = z.strictObject({+ callId: nonEmptyString,+ id: nonEmptyString,+ kind: z.literal("start"),+ parentTurnId: nonEmptyString,+});++const continueOperationSchema = z.strictObject({+ callId: nonEmptyString,+ id: nonEmptyString,+ kind: z.literal("continue"),+ parentTurnId: nonEmptyString,+ previousStatus: z.string().max(MAX_STATUS_LENGTH),+});++const startTargetSchema: z.ZodType<AgentStartTarget> = z.discriminatedUnion("kind", [+ z.strictObject({ continuationToken: nonEmptyString, kind: z.literal("agent/local") }),+ z.strictObject({ continuationToken: nonEmptyString, kind: z.literal("agent/self") }),+ z.strictObject({+ callbackBaseUrl: z.url(),+ kind: z.literal("agent/remote"),+ url: z.url(),+ }),+]);++const addressSchema: z.ZodType<AgentAddress> = z.discriminatedUnion("kind", [+ z.strictObject({+ continuationToken: nonEmptyString,+ kind: z.literal("agent/local"),+ sessionId: nonEmptyString,+ }),+ z.strictObject({+ continuationToken: nonEmptyString,+ kind: z.literal("agent/self"),+ sessionId: nonEmptyString,+ }),+ z.strictObject({+ callbackBaseUrl: z.url(),+ continuationToken: nonEmptyString,+ kind: z.literal("agent/remote"),+ sessionId: nonEmptyString,+ url: z.url(),+ }),+]);++const agentHandleSchema: z.ZodType<AgentHandle> = z.discriminatedUnion("phase", [+ z.strictObject({+ identity: identitySchema,+ operation: startOperationSchema,+ phase: z.literal("starting"),+ target: startTargetSchema,+ }),+ z.strictObject({+ address: addressSchema,+ identity: identitySchema,+ operation: z.discriminatedUnion("kind", [startOperationSchema, continueOperationSchema]),+ phase: z.literal("running"),+ }),+ z.strictObject({+ address: addressSchema,+ identity: identitySchema,+ lastStatus: z.string().max(MAX_STATUS_LENGTH),+ phase: z.literal("parked"),+ }),+]);++const agentHandleStoreSchema: z.ZodType<AgentHandleStore> = z+ .strictObject({+ handles: z.array(agentHandleSchema),+ })+ .refine(+ (store) =>+ new Set(store.handles.map((handle) => handle.identity.id)).size === store.handles.length,+ { message: "Agent handle ids must be unique." },+ );++/**+ * Derives the stable operation id for one dispatch. All three inputs are+ * parent-controlled, so the id exists before any child does and replaying+ * the same call produces the same operation.+ */+export function deriveAgentOperationId(input: {+ readonly callId: string;+ readonly parentSessionId: string;+ readonly parentTurnId: string;+}): string {+ return createHash("sha256")+ .update(`${input.parentSessionId}\0${input.parentTurnId}\0${input.callId}`)+ .digest("hex");+}++/** Derives the model-visible agent id from the first start operation. */+export function deriveAgentId(name: string, startOperationId: string): string {+ return `ag_${name}:${startOperationId.slice(0, 12)}`;+}++/** Collapses whitespace and truncates output into a handle status line. */+export function formatAgentStatus(output: unknown): string {+ const text = typeof output === "string" ? output : (JSON.stringify(output) ?? "");+ return text.replaceAll(/\s+/g, " ").trim().slice(0, MAX_STATUS_LENGTH);+}++/**+ * Reads and validates the agent handle store from session state.+ *+ * Returns `undefined` only when no store has been written. A present but+ * invalid store throws: treating corruption as absence would let the next+ * transition silently replace every delegated child's delivery coordinates.+ */+export function getAgentHandleStore(+ state: SessionStateMap | undefined,+): AgentHandleStore | undefined {+ const raw = state?.[AGENT_HANDLES_STATE_KEY];+ if (raw === undefined) {+ return undefined;+ }+ const parsed = agentHandleStoreSchema.safeParse(raw);+ if (!parsed.success) {+ throw new Error(+ `Corrupt agent handle store under session state key "${AGENT_HANDLES_STATE_KEY}": ${parsed.error.message}`,+ );+ }+ return parsed.data;+}++/**+ * Records intent to start a fresh child. Must commit before the start+ * side effect runs so a crashed dispatch never orphans an unowned child.+ *+ * Throws when the identity or operation already exists: fresh starts mint+ * a new identity, so a collision means corrupted derivation, not a replay.+ */+export function prepareAgentStart(+ session: HarnessSession,+ input: {+ readonly identity: AgentIdentity;+ readonly operation: StartOperation;+ readonly target: AgentStartTarget;+ },+): HarnessSession {+ const handles = getAgentHandleStore(session.state)?.handles ?? [];+ if (handles.some((handle) => handle.identity.id === input.identity.id)) {+ throw new Error(`Agent handle "${input.identity.id}" already exists.`);+ }+ return writeHandles(session, [+ ...handles,+ {+ identity: input.identity,+ operation: input.operation,+ phase: "starting",+ target: input.target,+ },+ ]);+}++/** Result of preparing a continuation against an existing handle. */+export type PrepareAgentContinuationResult =+ | {+ readonly kind: "ready";+ readonly session: HarnessSession;+ readonly handle: Extract<AgentHandle, { phase: "running" }>;+ }+ | { readonly kind: "unknown" }+ | { readonly kind: "mismatch" }+ | { readonly kind: "busy" };++/**+ * Records intent to deliver a follow-up turn to a parked child. Must+ * commit before the delivery side effect runs.+ *+ * `unknown`, `mismatch`, and `busy` do not change the session; the caller+ * maps them onto {@link AGENT_UNKNOWN}, {@link AGENT_MISMATCH}, and+ * {@link AGENT_BUSY} results. Replaying the operation already recorded on+ * a running handle returns `ready` with the unchanged session.+ */+export function prepareAgentContinuation(+ session: HarnessSession,+ input: {+ readonly agentId: string;+ readonly invokedName: string;+ readonly operation: ContinueOperation;+ },+): PrepareAgentContinuationResult {+ const handles = getAgentHandleStore(session.state)?.handles ?? [];+ const existing = handles.find((handle) => handle.identity.id === input.agentId);+ if (existing === undefined) {+ return { kind: "unknown" };+ }+ if (existing.identity.name !== input.invokedName) {+ return { kind: "mismatch" };+ }+ if (existing.phase === "running" && existing.operation.id === input.operation.id) {+ return { handle: existing, kind: "ready", session };+ }+ if (existing.phase !== "parked") {+ return { kind: "busy" };+ }++ const running: Extract<AgentHandle, { phase: "running" }> = {+ address: existing.address,+ identity: existing.identity,+ operation: { ...input.operation, previousStatus: existing.lastStatus },+ phase: "running",+ };+ return {+ handle: running,+ kind: "ready",+ session: writeHandles(+ session,+ handles.map((handle) => (handle.identity.id === input.agentId ? running : handle)),+ ),+ };+}++type ActiveAgentHandle = Extract<AgentHandle, { phase: "starting" | "running" }>;++function findActiveHandle(+ handles: readonly AgentHandle[],+ operationId: string,+): ActiveAgentHandle | undefined {+ return handles.find(+ (handle): handle is ActiveAgentHandle =>+ handle.phase !== "parked" && handle.operation.id === operationId,+ );+}++/**+ * Confirms a started child: `starting` becomes `running` with the child's+ * confirmed address. Throws when no starting handle carries the operation,+ * because confirming an unprepared start means ownership was never+ * committed. Re-confirming an already-running handle with the same+ * operation and address is a replay no-op.+ */+export function confirmAgentStarted(+ session: HarnessSession,+ input: {+ readonly operationId: string;+ readonly address: AgentAddress;+ },+): HarnessSession {+ const handles = getAgentHandleStore(session.state)?.handles ?? [];+ const existing = findActiveHandle(handles, input.operationId);+ if (existing === undefined) {+ throw new Error(`No prepared agent handle for operation "${input.operationId}".`);+ }+ if (existing.phase === "running") {+ return session;+ }++ return writeHandles(+ session,+ handles.map((handle) =>+ handle === existing+ ? {+ address: input.address,+ identity: existing.identity,+ operation: existing.operation,+ phase: "running",+ }+ : handle,+ ),+ );+}++/**+ * Resolves a dispatch that definitively failed.+ *+ * - A dead start or dead continuation deletes the handle: there is no+ * child left to own.+ * - A retryable continuation failure restores `parked` with the status the+ * handle showed before the delivery, so the model may retry the same+ * `agentId` later.+ *+ * Unknown operations are a no-op: the failure raced a settlement that+ * already resolved the handle.+ */+export function rejectAgentEffect(+ session: HarnessSession,+ input: {+ readonly operationId: string;+ readonly disposition: "dead" | "retryable";+ },+): HarnessSession {+ const handles = getAgentHandleStore(session.state)?.handles ?? [];+ const existing = findActiveHandle(handles, input.operationId);+ if (existing === undefined) {+ return session;+ }++ if (input.disposition === "retryable" && existing.phase === "running") {+ const { operation } = existing;+ if (operation.kind === "continue") {+ return writeHandles(+ session,+ handles.map((handle) =>+ handle === existing+ ? {+ address: existing.address,+ identity: existing.identity,+ lastStatus: operation.previousStatus,+ phase: "parked",+ }+ : handle,+ ),+ );+ }+ }++ return writeHandles(+ session,+ handles.filter((handle) => handle !== existing),+ );+}++/** Result of applying a settled child turn to the store. */+export type SettleAgentTurnResult =+ | { readonly kind: "settled"; readonly session: HarnessSession }+ | { readonly kind: "ignored"; readonly reason: "unknown-operation" | "session-mismatch" };++/**+ * Applies one settled child turn: `running` becomes `parked` for a parked+ * outcome or is deleted for a terminal outcome.+ *+ * The settlement must carry the operation currently recorded on the+ * running handle and the child session the address confirms; anything else+ * is ignored so a stale or forged delivery can never move a newer turn.+ */+export function settleAgentTurn(+ session: HarnessSession,+ input: {+ readonly operationId: string;+ readonly sessionId: string;+ readonly outcome: AgentTurnOutcome;+ },+): SettleAgentTurnResult {+ const handles = getAgentHandleStore(session.state)?.handles ?? [];+ const existing = handles.find(+ (handle) => handle.phase === "running" && handle.operation.id === input.operationId,+ );+ if (existing === undefined || existing.phase !== "running") {+ return { kind: "ignored", reason: "unknown-operation" };+ }+ if (existing.address.sessionId !== input.sessionId) {+ return { kind: "ignored", reason: "session-mismatch" };+ }++ if (input.outcome.kind === "terminal") {+ return {+ kind: "settled",+ session: writeHandles(+ session,+ handles.filter((handle) => handle !== existing),+ ),+ };+ }++ const { result } = input.outcome;+ const lastStatus =+ result.kind === "succeeded"+ ? formatAgentStatus(result.output)+ : result.kind === "failed"+ ? formatAgentStatus(result.error)+ : "(cancelled)";+ return {+ kind: "settled",+ session: writeHandles(+ session,+ handles.map((handle) =>+ handle === existing+ ? {+ address: existing.address,+ identity: existing.identity,+ lastStatus,+ phase: "parked",+ }+ : handle,+ ),+ ),+ };+}++/** Returns the resumable handles: the only phase the model may continue. */+export function projectParkedAgentHandles(+ store: AgentHandleStore,+): readonly Extract<AgentHandle, { phase: "parked" }>[] {+ return store.handles.filter((handle) => handle.phase === "parked");+}++/**+ * Renders the model-visible agent listing. Only parked handles appear:+ * starting and running children cannot accept a continuation, and private+ * delivery coordinates never render.+ */+export function renderAgentsSnippet(store: AgentHandleStore): string {+ const agents = projectParkedAgentHandles(store).map(+ (handle) =>+ `<agent id="${escapeXml(handle.identity.id)}" name="${escapeXml(handle.identity.name)}">${escapeXml(handle.lastStatus === "" ? "(no status)" : handle.lastStatus)}</agent>`,+ );+ return [AGENTS_SNIPPET_LABEL, "<agents>", ...agents, "</agents>"].join("\n");+}++function writeHandles(session: HarnessSession, handles: readonly AgentHandle[]): HarnessSession {+ return {+ ...session,+ state: {+ ...session.state,+ [AGENT_HANDLES_STATE_KEY]: { handles } satisfies AgentHandleStore,+ },+ };+}++function escapeXml(value: string): string {+ return value+ .replaceAll("&", "&")+ .replaceAll('"', """)+ .replaceAll("<", "<")+ .replaceAll(">", ">");+}diff --git a/packages/eve/src/harness/types.ts b/packages/eve/src/harness/types.tsindex 9ca153088..7e77321fa 100644--- a/packages/eve/src/harness/types.ts+++ b/packages/eve/src/harness/types.ts@@ -9,6 +9,7 @@ import type { RuntimeModelReference } from "#runtime/agent/bootstrap.js";import type { InputResponse } from "#runtime/input/types.js";import type { SandboxState } from "#sandbox/state.js";import type { JsonObject } from "#shared/json.js";+import type { TokenUsage } from "#shared/token-usage.js";import type { InternalToolDefinition } from "#shared/tool-definition.js";import type { AgentReasoningDefinition } from "#shared/agent-definition.js";import type { HarnessToolDefinition } from "#harness/execute-tool.js";@@ -166,12 +167,24 @@ export interface StepDone {*/export type StepNext = StepDone | StepFn | null;+/** User-facing answer produced when a conversation turn settles. */+export interface SettledTurn {+ readonly output: unknown;+ readonly isError?: boolean;+ readonly usage?: TokenUsage;+}+/*** Result returned by one harness step invocation.*/export interface StepResult {readonly next: StepNext;readonly session: HarnessSession;+ /**+ * Present when a conversation turn settled with a user-facing answer; carried+ * across the park boundary so a delegated parent can be notified.+ */+ readonly settledTurn?: SettledTurn;}/**diff --git a/packages/eve/src/internal/authored-definition/core.test.ts b/packages/eve/src/internal/authored-definition/core.test.tsindex 7a6e94e7f..cc22eb334 100644--- a/packages/eve/src/internal/authored-definition/core.test.ts+++ b/packages/eve/src/internal/authored-definition/core.test.ts@@ -238,6 +238,34 @@ describe("normalizeAgentDefinition", () => {),).toThrow('"experimental.workflow.world" must be a non-empty package name');});++ it("accepts a boolean subagentPersistentSessions flag", () => {+ const definition = normalizeAgentDefinition(+ {+ model: "openai/gpt-5.5",+ experimental: {+ subagentPersistentSessions: true,+ },+ },+ FAILURE_MESSAGE,+ );++ expect(definition.experimental?.subagentPersistentSessions).toBe(true);+ });++ it("rejects non-boolean subagentPersistentSessions values", () => {+ expect(() =>+ normalizeAgentDefinition(+ {+ model: "openai/gpt-5.5",+ experimental: {+ subagentPersistentSessions: "yes",+ },+ },+ FAILURE_MESSAGE,+ ),+ ).toThrow('"experimental.subagentPersistentSessions" must be a boolean.');+ });});describe("normalizeScheduleDefinition", () => {diff --git a/packages/eve/src/internal/authored-definition/core.ts b/packages/eve/src/internal/authored-definition/core.tsindex cb762b803..348ed5a2a 100644--- a/packages/eve/src/internal/authored-definition/core.ts+++ b/packages/eve/src/internal/authored-definition/core.ts@@ -257,9 +257,16 @@ function normalizeAgentExperimentalDefinition(message: string,): NonNullable<NormalizedAgentDefinition["experimental"]> {const record = expectObjectRecord(value, message);- expectOnlyKnownKeys(record, ["workflow"], message);+ expectOnlyKnownKeys(record, ["subagentPersistentSessions", "workflow"], message);const normalizedDefinition: Mutable<NonNullable<NormalizedAgentDefinition["experimental"]>> = {};+ if (record.subagentPersistentSessions !== undefined) {+ if (typeof record.subagentPersistentSessions !== "boolean") {+ throw new Error(`${message} "experimental.subagentPersistentSessions" must be a boolean.`);+ }+ normalizedDefinition.subagentPersistentSessions = record.subagentPersistentSessions;+ }+if (record.workflow !== undefined) {normalizedDefinition.workflow = normalizeAgentWorkflowDefinition(record.workflow, message);}diff --git a/packages/eve/src/runtime/resolve-agent.ts b/packages/eve/src/runtime/resolve-agent.tsindex 980068391..22a61940b 100644--- a/packages/eve/src/runtime/resolve-agent.ts+++ b/packages/eve/src/runtime/resolve-agent.ts@@ -226,6 +226,7 @@ function createResolvedAgentConfig(manifest: CompiledAgentNodeManifest): Resolveif (manifest.config.experimental !== undefined) {config.experimental = {+ subagentPersistentSessions: manifest.config.experimental.subagentPersistentSessions,workflow:manifest.config.experimental.workflow === undefined? undefineddiff --git a/packages/eve/src/shared/agent-definition.ts b/packages/eve/src/shared/agent-definition.tsindex 7acc839d6..e79311fb7 100644--- a/packages/eve/src/shared/agent-definition.ts+++ b/packages/eve/src/shared/agent-definition.ts@@ -196,6 +196,13 @@ export interface AgentLimitsDefinition {* These options are unstable and may change or be removed in any release.*/export interface AgentExperimentalDefinition {+ /**+ * Keeps this agent's delegated subagent sessions alive after they answer.+ * The model can pass `agentId` to a subagent tool to continue a previous+ * delegation, and the system prompt documents the `<agents>` listing.+ * When unset, delegated children run as one-shot tasks.+ */+ readonly subagentPersistentSessions?: boolean;/*** Durable Workflow runtime configuration. Root agents may use this to select* the Workflow world backing sessions and runs.diff --git a/packages/eve/src/shared/agent-turn-outcome.ts b/packages/eve/src/shared/agent-turn-outcome.tsnew file mode 100644index 000000000..ff1a5d4cd--- /dev/null+++ b/packages/eve/src/shared/agent-turn-outcome.ts@@ -0,0 +1,84 @@+import { z } from "#compiled/zod/index.js";++import type { JsonValue } from "#shared/json.js";+import { tokenUsageSchema, type TokenUsage } from "#shared/token-usage.js";++/**+ * What one delegated child turn produced, independent of whether the child+ * session survived it.+ */+export type AgentTurnResult =+ | {+ readonly kind: "succeeded";+ readonly output: JsonValue;+ }+ | {+ readonly kind: "failed";+ readonly error: JsonValue;+ }+ | {+ readonly kind: "cancelled";+ };++/**+ * How one delegated child turn settled.+ *+ * `parked` means the child session survived the turn and can accept another+ * delivery; `terminal` means the child session ended with this turn. The+ * lifecycle is carried explicitly: a failed turn can leave the child parked,+ * and a succeeded turn can be terminal (task mode). Consumers must never+ * infer lifecycle from success or error codes.+ *+ * `usageDelta` is the provider-reported usage this turn added to the child's+ * session subtree: the child captures its session totals at turn entry and+ * reports final-minus-entry when the turn settles. The parent folds each+ * delta exactly once, so repeated turns of a persistent child never re-report+ * earlier turns.+ */+export type AgentTurnOutcome =+ | {+ readonly kind: "parked";+ readonly result: AgentTurnResult;+ readonly usageDelta: TokenUsage;+ }+ | {+ readonly kind: "terminal";+ readonly result: AgentTurnResult;+ readonly usageDelta: TokenUsage;+ };++const jsonValueSchema: z.ZodType<JsonValue> = z.lazy(() =>+ z.union([+ z.null(),+ z.boolean(),+ z.number(),+ z.string(),+ z.array(jsonValueSchema),+ z.record(z.string(), jsonValueSchema),+ ]),+);++const agentTurnResultSchema: z.ZodType<AgentTurnResult> = z.discriminatedUnion("kind", [+ z.strictObject({ kind: z.literal("succeeded"), output: jsonValueSchema }),+ z.strictObject({ error: jsonValueSchema, kind: z.literal("failed") }),+ z.strictObject({ kind: z.literal("cancelled") }),+]);++/**+ * Zod schema for {@link AgentTurnOutcome}.+ *+ * Validates outcomes crossing the process boundary (remote session+ * callbacks). Local notification paths construct the type directly.+ */+export const agentTurnOutcomeSchema: z.ZodType<AgentTurnOutcome> = z.discriminatedUnion("kind", [+ z.strictObject({+ kind: z.literal("parked"),+ result: agentTurnResultSchema,+ usageDelta: tokenUsageSchema,+ }),+ z.strictObject({+ kind: z.literal("terminal"),+ result: agentTurnResultSchema,+ usageDelta: tokenUsageSchema,+ }),+]);