Durable coding-agent harnesses (Claude Code, Codex, OpenCode, Pi, fx) on a Workflow SDK World
durable-harness/fx: Agent Runs for libfx's own durable agents, from its semantic hooks (#11)
Chad Hietala31c87e841442
diff --git a/.changeset/fx-agent-runs-hooks.md b/.changeset/fx-agent-runs-hooks.mdnew file mode 100644index 0000000..77b3ae1--- /dev/null+++ b/.changeset/fx-agent-runs-hooks.md@@ -0,0 +1,7 @@+---+"durable-harness": patch+---++libfx's own durable agents show up in Vercel Agent Runs: `createFxAgent({ hooks: agentRunsHooks() })` with `agentRunsHooks` from `durable-harness/fx` records each libfx turn, its steps with their model calls, and its tool calls and the approvals they wait on, from libfx's semantic hooks (libfx 0.0.14 and later). A turn libfx yields, pauses or hands to another worker stays one turn, continued by the execution that resumes it in any process.++Handed-off and fenced turns stay open for recovery; actual user interruption and cancellation finish the turn. Interrupted tool and approval identities are checkpointed so final cleanup also settles recovered calls the engine does not rerun. Execution IDs isolate overlapping deliveries, and ended session bookkeeping is released. Capture follows policy, hook failures use the tracing error handler, and provider/reasoning metadata and turn ordering are preserved. Unawaited hooks and checkpoint flushing remain best-effort.diff --git a/apps/demo/app/api/libfx/route.ts b/apps/demo/app/api/libfx/route.tsindex ae9f0b5..958c922 100644--- a/apps/demo/app/api/libfx/route.ts+++ b/apps/demo/app/api/libfx/route.ts@@ -1,4 +1,4 @@-import { fxAgent, withFxTraces, log, refuseDisabled } from '@/lib/fx-durable';+import { fxAgent, log, refuseDisabled } from '@/lib/fx-durable';// Interim, as the libfx durability doc says: Vercel Queues delivers libfx's// session messages here until world-vercel can deliver to the function@@ -13,7 +13,7 @@ export async function POST(request: Request): Promise<Response> {if (disabled) return disabled;const started = Date.now();wake ??= fxAgent().then((agent) => agent.wakeHandler());- const response = await withFxTraces(async () => (await wake!)(request));+ const response = await (await wake)(request);const body = await response.clone().text().catch(() => '');log('wake', { ms: Date.now() - started, status: response.status, body: body.slice(0, 120) });return response;diff --git a/apps/demo/lib/fx-durable.test.ts b/apps/demo/lib/fx-durable.test.tsindex c5752c7..91d1255 100644--- a/apps/demo/lib/fx-durable.test.ts+++ b/apps/demo/lib/fx-durable.test.ts@@ -1,19 +1,14 @@import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';-import { fxAgent, withFxTraces } from './fx-durable';+import { fxAgent } from './fx-durable';-const traced = vi.hoisted(() => ({ complete: vi.fn(async () => {}), fail: vi.fn(async () => {}), fetch: undefined as typeof fetch | undefined }));+const captured = vi.hoisted(() => ({ fetch: undefined as typeof fetch | undefined }));vi.mock('libfx', () => ({ createFxAgent: async (options: { fetch: typeof fetch }) => {- traced.fetch = options.fetch;+ captured.fetch = options.fetch;return {};} }));vi.mock('./model', () => ({ MODEL: 'test', INSTRUCTIONS: '' }));vi.mock('./fx-durable-world', () => ({ fxDurability: async () => undefined, fxDurableDisabledReason: () => undefined, refuseDisabled: vi.fn() }));vi.mock('./world', () => ({ getWorld: async () => ({ events: { list: async () => ({ data: [] }) }, streams: { write: async () => {} } }) }));-vi.mock('harness-world/agent-runs', () => {- const step = { modelCall: async () => ({ complete: traced.complete, fail: traced.fail }), attributes() {}, complete: async () => {}, tool: async () => undefined };- const turn = { findTool: () => undefined, complete: async () => {} };- return { agentRunsHook: () => ({ session: () => ({ turn: async () => turn, step: async () => step, flush: async () => {} }) }) };-});beforeEach(() => { vi.stubEnv('HARNESS_CHAOS', '0'); });afterEach(() => {@@ -21,51 +16,40 @@ afterEach(() => {vi.unstubAllGlobals();vi.clearAllMocks();delete (globalThis as { __fxDurableAgent?: unknown }).__fxDurableAgent;- traced.fetch = undefined;+ captured.fetch = undefined;});async function modelRequest() {await fxAgent();- return withFxTraces(() => traced.fetch!('https://gateway.example.test/v3/ai/language-model', {+ return captured.fetch!('https://gateway.example.test/v3/ai/language-model', {method: 'POST', headers: { 'x-session-id': 'test-session' }, body: JSON.stringify({ prompt: [] }),- }));+ });}-describe('native libfx model response tracing', () => {+describe("the libfx lane's model fetch", () => {it.each([{ status: 200, body: 'data: {"type":"text-delta","delta":"hi"}\n\n' },{ status: 204, body: null },{ status: 429, body: '{"error":"rate limited"}' },{ status: 500, body: null },{ status: 302, body: null },- ])('preserves HTTP $status and marks non-success responses as failures', async ({ status, body }) => {+ ])('passes HTTP $status and its body through', async ({ status, body }) => {vi.stubGlobal('fetch', vi.fn().mockResolvedValue(new Response(body, { status })));const response = await modelRequest();expect(response.status).toBe(status);expect(await response.text()).toBe(body ?? '');- if (status >= 200 && status < 300) {- expect(traced.complete).toHaveBeenCalledTimes(1);- expect(traced.fail).not.toHaveBeenCalled();- } else {- expect(traced.complete).not.toHaveBeenCalled();- expect(traced.fail).toHaveBeenCalledWith(new Error(`Model request failed (${status})`));- }});- it('preserves a fetch rejection as the trace error', async () => {+ it('rejects with the fetch rejection', async () => {const error = new Error('network down');vi.stubGlobal('fetch', vi.fn().mockRejectedValue(error));await expect(modelRequest()).rejects.toBe(error);- expect(traced.fail).toHaveBeenCalledTimes(1);- expect(traced.fail).toHaveBeenCalledWith(error);});- it('preserves a response stream failure instead of masking it with the HTTP error', async () => {+ it("fails the response's stream with the stream's own error", async () => {const error = new Error('stream interrupted');vi.stubGlobal('fetch', vi.fn().mockResolvedValue(new Response(new ReadableStream({pull(controller) { controller.error(error); },}), { status: 500 })));const response = await modelRequest();await expect(response.text()).rejects.toBe(error);- expect(traced.fail).toHaveBeenCalledTimes(1);- expect(traced.fail).toHaveBeenCalledWith(error);});});diff --git a/apps/demo/lib/fx-durable.ts b/apps/demo/lib/fx-durable.tsindex eda0d1d..3d543fe 100644--- a/apps/demo/lib/fx-durable.ts+++ b/apps/demo/lib/fx-durable.ts@@ -1,10 +1,6 @@-import { AsyncLocalStorage } from 'node:async_hooks';-import { fxPromptTraceIdentity, fxTraceIdentity, fxTraceRequestBody } from './fx-trace';-import { agentRunsHook, type SessionTracing } from 'harness-world/agent-runs';-import { gatewayModelOptions, gatewayModelResult, ResponseCapture } from 'harness-world-process';import type { World } from '@workflow/world';import type { ChaosSpec } from 'harness-world-demo-ui';-import { fxTools } from 'durable-harness/fx';+import { agentRunsHooks, fxTools } from 'durable-harness/fx';import { virtual } from 'durable-harness/tools';import { type FxChaosLine, type FxWorkspace, LIBFX_WORKFLOW } from 'harness-world-demo-ui/fx-view';import { readFxWorkspace } from 'harness-world-hands/fx';@@ -58,57 +54,6 @@ export const log = (event: string, detail: Record<string, unknown>) => console.lconst LOGGED = new Set(['journal.open', 'checkpoint.save', 'checkpoint.error', 'checkpoint.mismatch', 'session.deadline', 'session.fenced', 'session.error']);type FxAgent = ReturnType<typeof createFxAgent>;-type Turn = NonNullable<Awaited<ReturnType<SessionTracing['turn']>>>;-type Step = Awaited<ReturnType<SessionTracing['step']>>;-/** A libfx turn in Agent Runs: its operation, and the step of its latest model request (the tool calls it asks for go under it). */-type FxTraceState = { session: SessionTracing; turn: Turn; turnId: string; step?: Step; outcome?: 'running' | 'failed' };-type FxTraceInvocation = { traces: Map<string, FxTraceState>; turns: Map<string, { turnId: string; prompt?: string }> };-const fxTraceInvocations = new AsyncLocalStorage<FxTraceInvocation>();--/**- * Agent Runs for libfx's own durable sessions: a turn per libfx turn, a step- * per model request, the tool calls under it. A turn that goes on in a later- * wake delivery continues from its checkpoint; one delivery ends only the- * turns it worked on.- */-export async function withFxTraces<T>(run: () => Promise<T>): Promise<T> {- return fxTraceInvocations.run({ traces: new Map(), turns: new Map() }, async () => {- let error: unknown;- try { return await run(); } catch (caught) { error = caught; throw caught; }- finally {- for (const state of fxTraceInvocations.getStore()!.traces.values()) await endFxTrace(state, error).catch(() => {});- }- });-}-async function endFxTrace(state: FxTraceState, error?: unknown): Promise<void> {- const outcome = state.outcome ?? (error === undefined ? 'completed' : 'failed');- await state.step?.complete();- if (outcome === 'failed') await state.turn.complete({ outcome, failed: true, error: error ?? new Error('the libfx session failed') });- else if (outcome === 'completed') await state.turn.complete({ outcome });- await state.session.flush();-}-async function fxTrace(id: string, key: string, refreshTurn = false): Promise<FxTraceState | undefined> {- const invocation = fxTraceInvocations.getStore();- const hook = agentRunsHook();- if (!invocation || !hook) return undefined;- const { traces, turns } = invocation;- const existing = traces.get(id);- if (existing && !refreshTurn) return existing;- // libfx's accepted journal marks preserve the same turn id across resumes.- const current = turns.get(id);- const identity = current ?? fxTraceIdentity((await (await getWorld()).events.list({- runId: id, pagination: { sortOrder: 'desc', limit: 100 }, resolveData: 'all',- })).data, existing?.turnId ?? key);- const { turnId, prompt } = identity;- if (existing?.turnId === turnId) return existing;- if (existing) await endFxTrace(existing);- const session = hook.session({ world: await getWorld(), runId: id, agentName: 'fx-durable' });- const turn = await session.turn({ turnId, sequence: 0, ...(typeof prompt === 'string' ? { title: prompt } : {}) });- if (!turn) return undefined;- const state: FxTraceState = { session, turn, turnId };- traces.set(id, state);- return state;-}const g = globalThis as { __fxDurableAgent?: Promise<FxAgent> };/** The process's agent. Every process creates the same one, so any of them can run any session. */@@ -123,16 +68,9 @@ export function fxAgent(): Promise<FxAgent> {instructions: INSTRUCTIONS,tools: await workspaceTools(),fetch: timedFetch,+ // Agent Runs, from libfx's semantic hooks: its turns, steps, model and tool calls.+ hooks: agentRunsHooks({ world: await getWorld(), name: 'fx-durable' }),onEvent(event: FxAgentEvent) {- if (event.type === 'acp.send') {- const identity = fxPromptTraceIdentity(event.message);- if (identity) fxTraceInvocations.getStore()?.turns.set(identity.sessionId, identity);- }- if ('sessionId' in event && event.sessionId) {- const state = fxTraceInvocations.getStore()?.traces.get(event.sessionId);- if (state && (event.type === 'session.deadline' || event.type === 'session.fenced')) state.outcome = 'running';- if (state && event.type === 'session.error') state.outcome = 'failed';- }if (!LOGGED.has(event.type)) return;const { type, timestamp: _timestamp, ...detail } = event;log(type, detail);@@ -256,41 +194,21 @@ async function timedFetch(input: RequestInfo | URL, init?: RequestInit): Promiseconst method = (init?.method ?? (input instanceof Request ? input.method : 'GET')).toUpperCase();if (!id || method === 'GET') return fetch(input, init);const key = `model:${crypto.randomUUID().slice(0, 12)}`;- let requestBody: unknown;- try { requestBody = fxTraceRequestBody(init?.body ?? (input instanceof Request ? await input.clone().text() : undefined)); } catch {}- const path = new URL(input instanceof Request ? input.url : String(input)).pathname;- const modelTrace = await (async () => {- const state = await fxTrace(id, key, true);- if (!state) return undefined;- await state.step?.complete();- const step = (state.step = await state.session.step(state.turn, state.turnId));- return { step, model: await step.modelCall(gatewayModelOptions({ path, model: headers.get('ai-language-model-id') ?? MODEL, body: requestBody })) };- })().catch(() => undefined);- const traceBody = new ResponseCapture();- const traceDecoder = new TextDecoder();mark(id, 'model.request', { key, effect: 'model' });// Checked beside the request, so it adds nothing to the model's time.const armed = crashDuring(id, key, 'model', 'model');let ended = false;let response: Response | undefined;- const end = (error?: unknown) => {+ const end = () => {if (ended) return;ended = true;- const status = response?.status;- const failed = error ?? (response && !response.ok ? new Error(`Model request failed (${status})`) : undefined);- if (modelTrace && failed !== undefined) void modelTrace.model.fail(failed).catch(() => {});- else if (modelTrace) {- const { result, attributes } = gatewayModelResult(path, traceBody.text());- modelTrace.step.attributes(attributes);- void modelTrace.model.complete({ outcome: 'completed', result }).catch(() => {});- }void armed.then((disarm) => disarm());mark(id, 'model.done', { key, effect: 'model' });};try {response = await fetch(input, init);} catch (error) {- end(error);+ end();throw error;}if (!response.body) {@@ -306,7 +224,6 @@ async function timedFetch(input: RequestInfo | URL, init?: RequestInit): Promisetry {const { value, done } = await reader.read();if (done) {- traceBody.push(traceDecoder.decode());end();controller.close();return;@@ -318,10 +235,9 @@ async function timedFetch(input: RequestInfo | URL, init?: RequestInit): Promisemark(id, 'model.first_token', { key, effect: 'model' });}}- traceBody.push(traceDecoder.decode(value, { stream: true }));controller.enqueue(value);} catch (error) {- end(error);+ end();controller.error(error);}},@@ -357,22 +273,14 @@ async function crashDuring(id: string, effectKey: string, effectName: string, st}/** Run one tool call with its timing marks and an armed crash. */-async function toolStep<T>(id: string, ctx: FxToolContext, name: string, input: unknown, run: () => Promise<T>): Promise<T> {+async function toolStep<T>(id: string, ctx: FxToolContext, name: string, run: () => Promise<T>): Promise<T> {const key = `tool:${ctx.executionId}`;const effect = `tool.${name}`;- const toolTrace = await (async () => {- const state = await fxTrace(id, key);- if (!state) return undefined;- // `executionId` is the model's id for the call: Agent Runs joins it with the call in the model's reply.- return state.turn.findTool(ctx.executionId) ?? (await (state.step ??= await state.session.step(state.turn, state.turnId)).tool({ callId: ctx.executionId, name, arguments: input }));- })().catch(() => undefined);mark(id, 'tool.start', { key, effect });const disarm = await crashDuring(id, key, effect, 'tool');try {- const result = await run();- await toolTrace?.complete({ outcome: 'completed', output: result }).catch(() => {});- return result;- } catch (error) { await toolTrace?.fail(error).catch(() => {}); throw error; } finally {+ return await run();+ } finally {disarm();mark(id, 'tool.end', { key, effect });}@@ -383,21 +291,21 @@ const descriptor = (name: Spec) => ({ name, description: TOOL_SPECS[name].descri/*** libfx's own tools (durable-harness/fx), each call with this lane's timing- * marks, Agent Runs span and armed crash, and the two unsafe example tools+ * marks and armed crash, and the two unsafe example tools* (not idempotent: never run twice).*/export async function workspaceTools() {const world = await getWorld();const traced = fxTools(virtual(), { world }).map((tool) => ({...tool,- execute: (input: unknown, ctx: FxToolContext) => toolStep(ctx.sessionId, ctx, tool.name, input, async () => tool.execute(input, ctx)),+ execute: (input: unknown, ctx: FxToolContext) => toolStep(ctx.sessionId, ctx, tool.name, async () => tool.execute(input, ctx)),}));const unsafe = (name: UnsafeToolName) => ({...descriptor(name),idempotent: false,writes: true,async execute(input: Record<string, unknown>, ctx: FxToolContext) {- return toolStep(ctx.sessionId, ctx, name, input, async () => {+ return toolStep(ctx.sessionId, ctx, name, async () => {const ref = `${name === 'unsafe_send_email' ? 'msg' : 'pay'}_${ctx.executionId.slice(-10)}`;await new Promise<void>((resolve) => {const timer = setTimeout(resolve, UNSAFE_CONFIRM_MS);diff --git a/apps/demo/lib/fx-trace.test.ts b/apps/demo/lib/fx-trace.test.tsdeleted file mode 100644index ce523de..0000000--- a/apps/demo/lib/fx-trace.test.ts+++ /dev/null@@ -1,47 +0,0 @@-import { describe, expect, it } from 'vitest';-import { fxPromptTraceIdentity, fxTraceIdentity, fxTraceRequestBody } from './fx-trace';--const journal = (entry: unknown) => ({ eventType: 'step_created', eventData: { stepName: 'fx.log', input: new TextEncoder().encode(JSON.stringify(entry)) } });-describe('native libfx trace identity', () => {- it('uses the fresh engine turn before the journal is visible', () => {- expect(fxPromptTraceIdentity({ method: 'session/prompt', params: { sessionId: 'session', prompt: [{ type: 'text', text: 'Hello 世界' }], _meta: { fx: { turnId: 'accepted' } } } })).toEqual({ sessionId: 'session', turnId: 'accepted', prompt: 'Hello 世界' });- expect(fxPromptTraceIdentity({ method: 'session/prompt', params: { sessionId: 'session', prompt: [], _meta: { fx: { continueRecovery: true } } } })).toBeUndefined();- expect(fxPromptTraceIdentity({ method: 'session/cancel', params: { sessionId: 'session' } })).toBeUndefined();- });- it('uses the accepted JSON prompt for the first invocation and across resumed model calls', () => {- const input = journal({ k: 'input', type: 'prompt', messageId: 'turn_1', input: 'Hello 世界' });- expect(fxTraceIdentity([input], 'request_1')).toEqual({ turnId: 'turn_1', prompt: 'Hello 世界' });- expect(fxTraceIdentity([journal({ k: 'record', marks: [{ start: 'turn_1' }] }), input], 'request_2')).toEqual({ turnId: 'turn_1', prompt: 'Hello 世界' });- });- it('selects a fresh prompt ahead of older turn marks and does not use a queued future prompt as an active turn title', () => {- const previous = journal({ k: 'input', type: 'prompt', messageId: 'old', input: 'Previous' });- const next = journal({ k: 'input', type: 'prompt', messageId: 'new', input: 'Next' });- expect(fxTraceIdentity([next, journal({ k: 'record', marks: [{ start: 'old' }, { end: true }] }), previous], 'request')).toEqual({ turnId: 'new', prompt: 'Next' });- expect(fxTraceIdentity([journal({ k: 'record', marks: [{ start: 'old' }] }), next, previous], 'request')).toEqual({ turnId: 'old', prompt: 'Previous' });- });- it('ignores unrelated or malformed payloads and preserves checkpointed turn identity', () => {- const unrelated = { eventType: 'step_created', eventData: { stepName: 'kernel', input: new TextEncoder().encode('devl[]') } };- const broken = { eventType: 'step_created', eventData: { stepName: 'fx.log', input: new TextEncoder().encode('{') } };- expect(fxTraceIdentity([unrelated, broken, journal({ k: 'checkpoint', openTurn: { id: 'resumed' } })], 'request')).toEqual({ turnId: 'resumed' });- });-});--describe('native libfx request capture', () => {- it('decodes transport bytes and offset views without losing Unicode model inputs', () => {- const request = { model: 'test', messages: [{ role: 'user', content: 'Hello 世界' }] };- const json = JSON.stringify(request);- const bytes = new TextEncoder().encode(json);- expect(fxTraceRequestBody(bytes)).toEqual(request);- expect(fxTraceRequestBody(bytes.buffer)).toEqual(request);- const padded = new Uint8Array(bytes.length + 4);- padded.set(bytes, 2);- expect(fxTraceRequestBody(new DataView(padded.buffer, 2, bytes.length))).toEqual(request);- expect(fxTraceRequestBody(json)).toEqual(request);- });- it('omits malformed, unsupported and oversized request bodies', () => {- expect(fxTraceRequestBody('{')).toBeUndefined();- expect(fxTraceRequestBody(undefined)).toBeUndefined();- expect(fxTraceRequestBody(new Uint8Array(256_001))).toBeUndefined();- expect(fxTraceRequestBody(' '.repeat(256_001))).toBeUndefined();- });-});diff --git a/apps/demo/lib/fx-trace.ts b/apps/demo/lib/fx-trace.tsdeleted file mode 100644index 75ecd0b..0000000--- a/apps/demo/lib/fx-trace.ts+++ /dev/null@@ -1,51 +0,0 @@-type JournalEvent = { eventType: string; eventData?: unknown };-const object = (value: unknown): Record<string, unknown> => value !== null && typeof value === 'object' ? value as Record<string, unknown> : {};--/** The engine starts a fresh turn before its optimistic journal writes land. */-export function fxPromptTraceIdentity(message: unknown): { sessionId: string; turnId: string; prompt?: string } | undefined {- const frame = object(message);- if (frame.method !== 'session/prompt') return;- const params = object(frame.params);- const turnId = object(object(params._meta).fx).turnId;- if (typeof params.sessionId !== 'string' || typeof turnId !== 'string') return;- const blocks = Array.isArray(params.prompt) ? params.prompt.map(object) : [];- const text = blocks.filter(block => block.type === 'text' && typeof block.text === 'string').map(block => block.text).join('\n');- return { sessionId: params.sessionId, turnId, ...(text ? { prompt: text } : {}) };-}--/** libfx's WASM transport supplies request bodies as bytes. Never capture headers. */-export function fxTraceRequestBody(body: unknown): unknown {- let text: string;- if (typeof body === 'string') text = body;- else {- const bytes = body instanceof ArrayBuffer ? new Uint8Array(body)- : ArrayBuffer.isView(body) ? new Uint8Array(body.buffer, body.byteOffset, body.byteLength) : undefined;- if (!bytes || bytes.byteLength > 256_000) return;- text = new TextDecoder().decode(bytes);- }- if (text.length > 256_000) return;- try { return JSON.parse(text); } catch { return; }-}--/** Newest-first native libfx journal events: JSON bytes, not the kernel's devalue codec. */-export function fxTraceIdentity(events: readonly JournalEvent[], fallback: string): { turnId: string; prompt?: unknown } {- let turnId = fallback;- let foundTurn = false;- for (const event of events) {- const data = object(event.eventData);- if (event.eventType !== 'step_created' || data.stepName !== 'fx.log') continue;- try {- const raw = data.input instanceof Uint8Array ? new TextDecoder().decode(data.input) : data.input;- if (typeof raw !== 'string') continue;- const entry = object(JSON.parse(raw));- const marks = Array.isArray(entry.marks) ? entry.marks.map(object) : [];- const start = marks.findLast(mark => typeof mark.start === 'string')?.start ?? object(entry.openTurn).id;- if (typeof start === 'string' && !foundTurn) { turnId = start; foundTurn = true; }- if (entry.k === 'input' && entry.type === 'prompt' && typeof entry.messageId === 'string') {- if (foundTurn && entry.messageId !== turnId) continue;- return { turnId: foundTurn ? turnId : entry.messageId, prompt: entry.input };- }- } catch { /* A malformed or unrelated event cannot change trace identity. */ }- }- return { turnId };-}diff --git a/packages/durable-harness/package.json b/packages/durable-harness/package.jsonindex 7c5ff9d..39b21df 100644--- a/packages/durable-harness/package.json+++ b/packages/durable-harness/package.json@@ -150,7 +150,7 @@"@workflow/world-postgres": "^5.0.4","effect": "4.0.0-rc.112","just-bash": "^3.4.2",- "libfx": ">=0.0.13-dev.1432 <0.0.13 || >=0.0.14-0 <0.1.0",+ "libfx": ">=0.0.14 <0.1.0","next": ">=15.1","zod": "^4.0.0"},diff --git a/packages/durable-harness/src/fx-agent-runs.ts b/packages/durable-harness/src/fx-agent-runs.tsnew file mode 100644index 0000000..741b308--- /dev/null+++ b/packages/durable-harness/src/fx-agent-runs.ts@@ -0,0 +1,335 @@+import type { World } from '@workflow/world';+import type { ApprovalOperation, AttemptOperation, ModelOperation, ToolOperation, TurnOperation } from '@vercel/agent-runs';+import { type AgentRunsHook, agentRunsHook, type ContentPart, type ModelOptions, type SessionTracing, type TraceAudience } from 'harness-world/agent-runs';+import type { FxHookEvent, FxHooks } from 'libfx';++type FxHookMessage = NonNullable<Extract<FxHookEvent, { type: 'model.start' }>['data']['messages']>[number];+type FxWaitOutcome = Extract<FxHookEvent, { type: 'wait.end' }>['data']['outcome'];++export interface FxAgentRunsOptions {+ /** The World the agent's sessions live on (`createFxAgent({ durability })`'s). Default: the environment's (`getWorld()`). */+ readonly world?: World;+ /** Names the agent in Agent Runs (`invoke_agent <name>`). Default `fx`. */+ readonly name?: string;+ /** Who may read its sessions' content. Default: `agentRuns({ audience })`'s. */+ readonly audience?: TraceAudience;+}++/** libfx's `FxHooks`, for `createFxAgent({ hooks })`. */+export interface FxAgentRunsHooks extends FxHooks {+ readonly captureContent: boolean;+ /** Wait for already queued events and bounded, best-effort checkpoint writes. */+ flush(): Promise<void>;+}++/** One turn of a session as its events arrive: its operation and what is open in it. */+interface TurnTrace {+ readonly id: string;+ readonly executionId: string;+ op?: TurnOperation;+ fenced: boolean;+ readonly steps: Map<string, AttemptOperation>;+ readonly models: Map<string, { op: ModelOperation; step: AttemptOperation; own?: AttemptOperation }>;+ readonly tools: Map<string, ToolOperation>;+ readonly waits: Map<string, ApprovalOperation>;+}++interface SessionTrace {+ readonly tracing: Promise<SessionTracing | undefined>;+ turn?: TurnTrace;+ /** Its events, recorded one at a time in order. */+ queue: Promise<void>;+ ended: boolean;+}++const parse = (json: string | null | undefined): unknown => {+ if (json === undefined || json === null) return undefined;+ try {+ return JSON.parse(json);+ } catch {+ return json;+ }+};++/** A model request's messages in AI SDK form, which `@vercel/agent-runs` reads; system messages are its instructions. */+function modelMessages(messages: readonly FxHookMessage[]): { role: string; content: Record<string, unknown>[] }[] {+ return messages.flatMap((m): { role: string; content: Record<string, unknown>[] }[] => {+ if (m.role === 'system') return [];+ if (m.role === 'tool') {+ return [{ role: 'tool', content: [{ type: 'tool-result', toolCallId: m.toolCallId, toolName: m.toolName, output: { type: m.toolResultStatus === 'failure' ? 'error-text' : 'text', value: m.content ?? '' } }] }];+ }+ const calls = m.toolCalls.map((c) => ({ type: 'tool-call', toolCallId: c.callId, toolName: c.name, input: parse(c.argumentsJson) }));+ const text = m.content ? [{ type: 'text', text: m.content }] : [];+ return [{ role: m.role, content: [...text, ...calls] }];+ });+}++function modelOptions(data: Extract<FxHookEvent, { type: 'model.start' }>['data']): ModelOptions {+ const instructions = [...(data.instructions ?? []), ...(data.messages ?? []).filter((m) => m.role === 'system')]+ .map((m) => m.content)+ .filter((c): c is string => !!c);+ return {+ // libfx calls AI Gateway: the model id stays whole, as Agent Runs links it.+ provider: 'gateway',+ modelId: data.model,+ ...(data.messages ? { messages: modelMessages(data.messages) } : {}),+ ...(instructions.length ? { instructions: instructions.join('\n\n') } : {}),+ ...(data.tools.length ? { tools: data.tools.map((t) => ({ type: 'function', name: t.name, description: t.description ?? undefined, inputSchema: parse(t.inputSchemaJson) })) } : {}),+ };+}++function modelContent(data: Extract<FxHookEvent, { type: 'model.end' }>['data']): ContentPart[] {+ return [+ ...(data.output ? [{ type: 'text' as const, text: data.output }] : []),+ ...(data.toolCalls ?? []).map((c) => ({ type: 'tool-call' as const, callId: c.callId, toolName: c.name, input: parse(c.argumentsJson) })),+ ];+}++const APPROVAL: Record<FxWaitOutcome, string> = { accepted: 'approved', denied: 'denied', cancelled: 'cancelled', failed: 'failed', timed_out: 'timed_out' };++/** Settles `work` past the response on Vercel (the request context's `waitUntil`). */+function keepAlive(work: Promise<unknown>): void {+ const settled = work.then(() => {}, () => {});+ (globalThis as { [k: symbol]: { get?: () => { waitUntil?: (p: Promise<unknown>) => void } | undefined } | undefined })[Symbol.for('@vercel/request-context')]?.get?.()?.waitUntil?.(settled);+}++/**+ * Agent Runs for libfx's own durable agents, from libfx's semantic hooks:+ *+ * ```ts+ * import { createFxAgent } from 'libfx'+ * import { agentRunsHooks } from 'durable-harness/fx'+ * export const agent = createFxAgent({ durability, model, hooks: agentRunsHooks() })+ * ```+ *+ * Each libfx turn is a turn, each step of it a step with its model call, and+ * the tool calls (and the approvals they wait on) are under the step. A turn+ * that libfx yields, pauses or hands to another worker stays open: the+ * execution that resumes it (in any process) continues the same turn from+ * its checkpoint, its steps numbered by that execution. Nothing is recorded+ * until `agentRuns()` is registered.+ * Requires libfx 0.0.14 or later.+ * Register tracing before creating the agent when content capture is needed.+ * libfx does not await hooks: checkpoints and waitUntil are best effort. A+ * new delivery can see an older checkpoint if it starts before this queue+ * flushes; await flush() when the host controls the handoff.+ */+export function agentRunsHooks(options: FxAgentRunsOptions = {}): FxAgentRunsHooks {+ const sessions = new Map<string, SessionTrace>();+ let world: Promise<World> | undefined;+ const pending = new Set<Promise<void>>();+ const report = (error: unknown) => { try { agentRunsHook()?.onError(error, { phase: 'complete' }); } catch {} };++ /** The session's trace, found or made at once, so its events queue in the order they came. */+ function sessionFor(event: FxHookEvent, hook: AgentRunsHook): SessionTrace | undefined {+ let session = sessions.get(event.sessionId);+ if (!session) {+ if (event.type !== 'turn.start' || !event.turnId || !event.executionId) return undefined;+ world ??= options.world ? Promise.resolve(options.world) : import('./world.ts').then((m) => m.getWorld());+ const tracing = world.then((w) => hook.session({ world: w, runId: event.sessionId, agentName: options.name ?? 'fx', ...(options.audience ? { audience: options.audience } : {}) }));+ session = { tracing: tracing.catch((error: unknown) => (report(error), undefined)), queue: Promise.resolve(), ended: false };+ sessions.set(event.sessionId, session);+ }+ return session;+ }++ function parkTools(tracing: SessionTracing, turn: TurnTrace): Promise<void> {+ return tracing.parkTools(turn.id, [...turn.tools].map(([callId, tool]) => ({+ callId,+ approvals: [...turn.waits].filter(([, wait]) => wait.parent?.spanId === tool.reference.spanId).map(([id]) => id),+ })));+ }++ async function record(session: SessionTrace, tracing: SessionTracing, event: FxHookEvent): Promise<void> {+ if (event.type === 'journal.error' && event.data.fenced) {+ // libfx's journal receipts have no turn/execution id. Preserve the active turn conservatively.+ if (session.turn && !session.ended) session.turn.fenced = true;+ return;+ }+ if (event.type === 'turn.start' && event.turnId && event.executionId) {+ const e = event;+ if (session.turn?.id === e.turnId && session.turn.executionId === e.executionId && !session.ended) return;+ const turn: TurnTrace = { id: e.turnId!, executionId: e.executionId!, fenced: false, steps: new Map(), models: new Map(), tools: new Map(), waits: new Map() };+ session.turn = turn;+ session.ended = false;+ await tracing.flush();+ // Each execution asks again: the library continues the turn from its checkpoint, which another process may have moved on.+ turn.op = await tracing.turn({ turnId: e.turnId!, ...(e.data.input ? { title: e.data.input } : {}) });+ if (turn.op) for (const pending of await tracing.parkedTools(turn.id)) {+ const tool = turn.op.findTool(pending.callId);+ if (!tool) continue;+ turn.tools.set(pending.callId, tool);+ for (const id of pending.approvals) {+ const wait = tool.findApproval(id);+ if (wait) turn.waits.set(id, wait);+ }+ }+ return;+ }+ const turn = session.turn;+ if (!turn || turn.id !== event.turnId || turn.executionId !== event.executionId) return;+ if (event.type === 'turn.end') {+ session.ended = true;+ const outcome = event.data.outcome;+ const continuing = event.data.handoff === true || turn.fenced || outcome === 'yielded' || outcome === 'paused' || outcome === 'fenced';+ const final = outcome === 'interrupted' ? 'cancelled' : outcome;+ if (!continuing) {+ for (const wait of turn.waits.values()) await wait.complete({ outcome: final === 'cancelled' ? 'cancelled' : 'abandoned' });+ turn.waits.clear();+ for (const tool of turn.tools.values()) {+ if (final === 'failed') await tool.fail(new Error(event.data.error ?? 'the turn failed'));+ else await tool.complete({ outcome: final === 'cancelled' ? 'cancelled' : 'abandoned' });+ }+ turn.tools.clear();+ }+ for (const model of turn.models.values()) {+ if (continuing) await model.op.complete({ outcome: 'cancelled' });+ else if (final === 'failed') await model.op.fail(new Error(event.data.error ?? 'the turn failed'));+ else await model.op.complete({ outcome: final === 'cancelled' ? 'cancelled' : 'abandoned' });+ await model.own?.complete();+ }+ turn.models.clear();+ for (const step of turn.steps.values()) await step.complete();+ turn.steps.clear();+ if (!continuing && turn.op && !turn.op.finished) {+ if (final === 'failed') await turn.op.complete({ outcome: final, failed: true, error: new Error(event.data.error ?? 'the turn failed') });+ else await turn.op.complete({ outcome: final });+ }+ if (continuing && turn.op && !turn.op.finished) await parkTools(tracing, turn);+ await tracing.flush();+ return;+ }+ if (!turn.op || turn.op.finished || session.ended) return;+ const op = turn.op;+ const stepKey = `${event.executionId}:${event.stepIndex}`;+ switch (event.type) {+ case 'step.start': {+ if (!event.executionId || event.stepIndex < 1) return;+ turn.steps.set(stepKey, await tracing.step(op, turn.id, { execution: event.executionId, stepIndex: event.stepIndex - 1 }));+ return;+ }+ case 'step.end': {+ await turn.steps.get(stepKey)?.complete();+ turn.steps.delete(stepKey);+ return;+ }+ case 'model.start': {+ const e = event;+ // A call outside a step (a title, a compaction) is a step of its own.+ const step = turn.steps.get(stepKey);+ const own = step ? undefined : await tracing.step(op, turn.id);+ const model = await (step ?? own)!.modelCall(modelOptions(e.data));+ turn.models.set(`${event.executionId}:${e.data.modelCallId}`, { op: model, step: (step ?? own)!, ...(own ? { own } : {}) });+ return;+ }+ case 'model.end': {+ const e = event;+ const key = `${event.executionId}:${e.data.modelCallId}`;+ const model = turn.models.get(key);+ turn.models.delete(key);+ if (!model) return;+ if (e.data.provider) model.op.attributes({ 'gen_ai.provider.name': e.data.provider });+ if (typeof e.data.usage?.reasoningTokens === 'number' && Number.isFinite(e.data.usage.reasoningTokens)) model.step.attributes({ 'agent.usage.reasoning_tokens': e.data.usage.reasoningTokens });+ if (e.data.cancelled) await model.op.complete({ outcome: 'cancelled' });+ else if (e.data.error !== null) await model.op.fail(new Error(e.data.error ?? 'the model call failed'));+ else {+ const u = e.data.usage;+ await model.op.complete({+ outcome: 'completed',+ result: {+ finishReason: e.data.finishReason ?? 'unknown',+ usage: {+ inputTokens: u?.inputTokens ?? undefined,+ outputTokens: u?.outputTokens ?? undefined,+ inputTokenDetails: { cacheReadTokens: u?.cacheReadTokens ?? undefined, cacheWriteTokens: u?.cacheWriteTokens ?? undefined },+ },+ ...(e.data.generationId ? { responseId: e.data.generationId } : {}),+ content: modelContent(e.data),+ },+ });+ }+ await model.own?.complete();+ return;+ }+ case 'tool.start': {+ const e = event;+ const { callId, name } = e.data.call;+ // A call an earlier execution started (a rerun after a crash) is the same call.+ const tool = op.findTool(callId) ?? (await (turn.steps.get(stepKey) ?? [...turn.steps.values()].at(-1))?.tool({ callId, name, arguments: parse(e.data.call.argumentsJson) }));+ if (tool) turn.tools.set(callId, tool);+ await parkTools(tracing, turn);+ return;+ }+ case 'tool.end': {+ const e = event;+ const tool = turn.tools.get(e.data.call.callId) ?? op.findTool(e.data.call.callId);+ if (!tool) return;+ if (e.data.status === 'cancelled') {+ // Only turn.end knows whether cancellation was a user action or a handoff.+ turn.tools.set(e.data.call.callId, tool);+ return;+ }+ turn.tools.delete(e.data.call.callId);+ if (e.data.status === 'success') await tool.complete({ outcome: 'completed', output: parse(e.data.output) });+ else await tool.fail(new Error(e.data.error ?? 'the tool call failed'));+ await parkTools(tracing, turn);+ return;+ }+ case 'wait.start': {+ const e = event;+ const tool = e.data.callId ? (turn.tools.get(e.data.callId) ?? op.findTool(e.data.callId)) : undefined;+ const approval = await tool?.approval({ requestId: String(e.data.requestId), ...(e.data.prompt ? { request: e.data.prompt } : {}) });+ if (approval) turn.waits.set(String(e.data.requestId), approval);+ await parkTools(tracing, turn);+ return;+ }+ case 'wait.end': {+ const e = event;+ const approval = turn.waits.get(String(e.data.requestId));+ if (e.data.outcome === 'cancelled') return;+ turn.waits.delete(String(e.data.requestId));+ await approval?.complete({ outcome: APPROVAL[e.data.outcome] ?? e.data.outcome });+ await parkTools(tracing, turn);+ return;+ }+ }+ }++ return {+ get captureContent() {+ const decision = agentRunsHook()?.capture(options.audience);+ return decision?.recordInputs === true || decision?.recordOutputs === true;+ },+ onEvent(event) {+ const hook = agentRunsHook();+ if (!hook) return;+ if (event.turnId === null && !(event.type === 'journal.error' && event.data.fenced)) return;+ const session = sessionFor(event, hook);+ if (!session) return;+ // libfx does not wait for a hook: each session's events are recorded one at a time, in order.+ const next: Promise<void> = session.queue+ .then(async () => {+ try {+ if (event.type === 'turn.end' && (!session.turn || (session.turn.id === event.turnId && session.turn.executionId === event.executionId))) session.ended = true;+ const tracing = await session.tracing;+ if (tracing) await record(session, tracing, event);+ else if (event.type === 'turn.start') session.ended = false;+ } finally {+ // A handed-off turn is checkpointed too: a later execution reacquires it.+ if (session.queue === next && session.ended && sessions.get(event.sessionId) === session) sessions.delete(event.sessionId);+ }+ })+ .catch(report);+ session.queue = next;+ pending.add(next);+ void next.then(() => pending.delete(next));+ keepAlive(next);+ },+ onError: report,+ async flush() {+ const current = [...sessions.values()];+ await Promise.all([...pending]);+ await Promise.all(current.map(async (s) => (await s.tracing)?.flush()));+ },+ };+}diff --git a/packages/durable-harness/src/fx.ts b/packages/durable-harness/src/fx.tsindex 76f9e31..c15ff12 100644--- a/packages/durable-harness/src/fx.ts+++ b/packages/durable-harness/src/fx.ts@@ -52,6 +52,8 @@ import type { World } from '@workflow/world';import { fxAgentTools } from 'harness-world-hands/fx';import type { FxHostTool } from 'libfx';import { resolveEnvironment } from './environments.ts';++export { agentRunsHooks, type FxAgentRunsHooks, type FxAgentRunsOptions } from './fx-agent-runs.ts';import type { Workspace } from './workspace.ts';import { getWorld } from './world.ts';diff --git a/packages/durable-harness/src/instrumentation/checkpoints.ts b/packages/durable-harness/src/instrumentation/checkpoints.tsindex 973316f..dbdc9d1 100644--- a/packages/durable-harness/src/instrumentation/checkpoints.ts+++ b/packages/durable-harness/src/instrumentation/checkpoints.ts@@ -1,17 +1,18 @@import { createHash } from 'node:crypto';import type { World } from '@workflow/world';import type { TraceCheckpointer, TraceSnapshot } from '@vercel/agent-runs';+import type { ParkedTraceTool } from 'harness-world/agent-runs';import { decodeLine, encodeLine, WRITE_DEADLINE_MS } from 'harness-world/streams';/** Each new line is self-contained, so recovery reads one chunk instead of the turn's history. */-interface Line { version: 1; v?: TraceSnapshot | null; drive: number }-interface State { value?: TraceSnapshot; drives: number; finished: boolean }+interface Line { version: 1; v?: TraceSnapshot | null; drive: number; parked?: readonly ParkedTraceTool[] }+interface State { value?: TraceSnapshot; drives: number; finished: boolean; parked?: readonly ParkedTraceTool[] }interface Turn extends State {runId: string;stream: string;loaded?: Promise<void>;writing: Promise<void>;- pending?: { value: TraceSnapshot | null };+ pending?: { value: TraceSnapshot | null | undefined };scheduled: boolean;/** Queued writes stay counted until the actual World writes settle, even after a caller times out. */storing: number;@@ -101,6 +102,20 @@ export class TraceStreams {return turn.finished;}+ async parkedTools(runId: string, turnId: string): Promise<readonly ParkedTraceTool[]> {+ const turn = this.turn(`turn:${encodeURIComponent(runId)}:${encodeURIComponent(turnId)}`)!;+ await this.load(turn);+ return turn.parked ?? [];+ }++ async parkTools(runId: string, turnId: string, tools: readonly ParkedTraceTool[]): Promise<void> {+ const turn = this.turn(`turn:${encodeURIComponent(runId)}:${encodeURIComponent(turnId)}`)!;+ await this.load(turn, true);+ if (turn.finished) return;+ turn.parked = tools;+ this.enqueue(turn, turn.value);+ }+/** Only writes already queued for this run, not future writes or another session's traffic. */async flush(runId?: string): Promise<void> {const turns = [...this.turns.values()].filter((turn) => runId === undefined || turn.runId === runId);@@ -175,6 +190,7 @@ export class TraceStreams {turn.finished = state.finished;}turn.drives = Math.max(turn.drives, state.drives);+ turn.parked ??= state.parked;});return turn.loaded;}@@ -211,7 +227,7 @@ export class TraceStreams {} finally { signal.removeEventListener('abort', cancel); cancel(); }signal.throwIfAborted();const line = decodeLine(text.split('\n')[0]!) as Partial<Line>;- if (line?.version === 1 && typeof line.drive === 'number') return { value: line.v ?? undefined, drives: line.drive, finished: line.v === null };+ if (line?.version === 1 && typeof line.drive === 'number') return { value: line.v ?? undefined, drives: line.drive, finished: line.v === null, parked: line.parked };// Earlier previews wrote separate snapshot and drive lines. Read that history once, strictly.let value: TraceSnapshot | undefined;@@ -241,7 +257,7 @@ export class TraceStreams {}private async put(turn: Turn, value: TraceSnapshot | undefined, finished: boolean): Promise<void> {- const line: Line = { version: 1, drive: turn.drives, ...(finished ? { v: null } : value === undefined ? {} : { v: value }) };+ const line: Line = { version: 1, drive: turn.drives, ...(finished ? { v: null } : value === undefined ? {} : { v: value }), ...(turn.parked?.length ? { parked: turn.parked } : {}) };// Bound waiting on the queue, not the write itself: no later checkpoint may overtake it.try { await this.world.streams.write(turn.runId, turn.stream, new TextEncoder().encode(`${encodeLine(line)}\n`)); }catch (error) { turn.unavailable = error; this.report(error); throw error; }@@ -250,9 +266,14 @@ export class TraceStreams {private write(key: string, value: TraceSnapshot | null): void {const turn = this.turn(key);if (!turn || turn.unavailable) return;+ this.enqueue(turn, value);+ }++ private enqueue(turn: Turn, value: TraceSnapshot | null | undefined): void {turn.pending = { value };turn.value = value ?? undefined;turn.finished = value === null;+ if (turn.finished) turn.parked = undefined;if (turn.scheduled) return;turn.scheduled = true;turn.storing++;diff --git a/packages/durable-harness/src/instrumentation/otel.ts b/packages/durable-harness/src/instrumentation/otel.tsindex 789e1b2..0f8dede 100644--- a/packages/durable-harness/src/instrumentation/otel.ts+++ b/packages/durable-harness/src/instrumentation/otel.ts@@ -167,7 +167,7 @@ export function agentRuns(options: AgentRunsOptions = {}): AgentRuns {const identity = (turnId: string) => ({ conversationId: runId, runId, turnId });// Another process may have moved the session's turns on since this one last had it.streams.forget(runId);- /** Steps of its turns: this session's number for the turn, and its next step. */+ /** Steps of its turns, per execution (or this session): its number for the turn, and its next step. */const steps = new Map<string, { drive: Promise<number>; next: number }>();return {async turn({ turnId, sequence, title }) {@@ -192,16 +192,20 @@ export function agentRuns(options: AgentRunsOptions = {}): AgentRuns {turn.attributes({ 'agent.channel.audience': given ?? audience });return turn;},- async step(turn, turnId) {- let numbered = steps.get(turnId);+ async step(turn, turnId, at) {+ const key = `${turnId}:${at?.execution ?? ''}`;+ let numbered = steps.get(key);if (!numbered) {const entry = (numbered = { drive: streams.nextDrive(runId, turnId), next: 0 });- steps.set(turnId, entry);- entry.drive.catch(() => steps.get(turnId) === entry && steps.delete(turnId));+ steps.set(key, entry);+ entry.drive.catch(() => steps.get(key) === entry && steps.delete(key));+ if (steps.size > 10_000) steps.delete(steps.keys().next().value!);}- const stepIndex = numbered.next++;+ const stepIndex = at?.stepIndex ?? numbered.next++;return turn.attempt({ stepIndex, attempt: await numbered.drive });},+ parkedTools: turnId => streams.parkedTools(runId, turnId),+ parkTools: (turnId, tools) => streams.parkTools(runId, turnId, tools),flush: () => streams.flush(runId),};},diff --git a/packages/durable-harness/test/canary.test.ts b/packages/durable-harness/test/canary.test.tsindex c97f1c4..443e008 100644--- a/packages/durable-harness/test/canary.test.ts+++ b/packages/durable-harness/test/canary.test.ts@@ -83,7 +83,7 @@ import { sandboxEnvBuilder } from 'pi-world/sandbox';import { afterAll, beforeAll, describe, expect, it } from 'vitest';import { scriptedGateway, text as gatewayText, toolCall as gatewayToolCall, toolResults as gatewayResults } from '../../harness-opencode/test/scripted-gateway.ts';import { agentRuns } from '../src/instrumentation/otel.ts';-import { fxTools } from '../src/fx.ts';+import { agentRunsHooks, fxTools } from '../src/fx.ts';import { opencode } from '../src/opencode.ts';import { CodingTools, openWorldStorage, virtualEnv } from '../src/pi-durable.ts';import { createCodingTools, pi } from '../src/pi.ts';@@ -539,12 +539,14 @@ async function fxRig(on: VirtualWorkspace | Platform): Promise<Rig> {// Both only read: `hold` waits for the drill, `vm_env` lists the VM's environments.const appTool = (name: 'hold' | 'vm_env') => ({ name, description: `The app's ${name}.`, inputSchema: { type: 'object', properties: {} }, idempotent: true, execute: async (_: unknown, c: { sessionId: string }) => (name === 'hold' ? app!.hold() : app!.vmEnv(c.sessionId)) });const host = hostname();+ const hooks = agentRunsHooks({ world, name: 'fx' });const agent = createFxAgent({durability: fxWorld(world, { name: 'canary', livenessKnown: true, alive: () => true, holderInfo: () => ({ pid: process.pid, host }), pollMs: 50 }),apiKey: process.env.AI_GATEWAY_API_KEY!,model: 'test/model',fetch,modelCatalog: [],+ hooks,tools: [...(isPlatform(on) ? (fxAgentTools({ kind: 'sandbox' }, { world: () => world, acquire: atWorkspace(on.acquire()) }) as unknown as ReturnType<typeof fxTools>) : fxTools(on, { world })),appTool('hold'),@@ -554,8 +556,8 @@ async function fxRig(on: VirtualWorkspace | Platform): Promise<Rig> {return {world,dataDir,- // libfx's own agent: its turns are libfx's, so durable-harness's instrumentation emits no Agent Run for them.- traces: false,+ // libfx's own agent, traced from its semantic hooks (agentRunsHooks()).+ traces: true,// Session A's files: on a virtual workspace its log, on the host the World's data directory; on a sandbox, its Drive....sandboxed(on, dataDir),run(who, steps, tools) {@@ -567,6 +569,8 @@ async function fxRig(on: VirtualWorkspace | Platform): Promise<Rig> {await started;for await (const _ of turn);await turn.result;+ // Its spans, before the search reads them.+ await hooks.flush();return ran;})();return { started, done };diff --git a/packages/durable-harness/test/environments.test.ts b/packages/durable-harness/test/environments.test.tsindex af3f834..343253c 100644--- a/packages/durable-harness/test/environments.test.ts+++ b/packages/durable-harness/test/environments.test.ts@@ -181,7 +181,7 @@ describe('the /fx and /sandbox entries', () => {// The builds with durable sessions: a 0.0.13 dev build at or after 1432, or// 0.0.14 (its dev builds too) and up. libfx 0.0.13 itself has no// durable-world exports.- expect(pkg.peerDependencies.libfx).toBe('>=0.0.13-dev.1432 <0.0.13 || >=0.0.14-0 <0.1.0');+ expect(pkg.peerDependencies.libfx).toBe('>=0.0.14 <0.1.0');const catalog = /^\s+libfx:\s*(\S+)\s*$/m.exec(readFileSync(join(import.meta.dirname, '../../../pnpm-workspace.yaml'), 'utf8'))?.[1];const m = /^0\.0\.(\d+)(?:-dev\.(\d+)(?:\.\S+)?)?$/.exec(catalog ?? '');expect(m, `catalog libfx ${catalog}`).not.toBeNull();diff --git a/packages/durable-harness/test/fx-agent-runs-lifecycle.test.ts b/packages/durable-harness/test/fx-agent-runs-lifecycle.test.tsnew file mode 100644index 0000000..23970fb--- /dev/null+++ b/packages/durable-harness/test/fx-agent-runs-lifecycle.test.ts@@ -0,0 +1,250 @@+import { mkdtemp } from 'node:fs/promises';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { InMemorySpanExporter, SimpleSpanProcessor } from '@opentelemetry/sdk-trace-base';+import { createWorld, type LocalWorld } from '@workflow/world-local';+import { AGENT_RUNS, agentRunsHook } from 'harness-world/agent-runs';+import { readJsonLines } from 'harness-world/streams';+import type { FxHookEvent } from 'libfx';+import { afterAll, afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import { agentRunsHooks } from '../src/fx.ts';+import { agentRuns } from '../src/instrumentation/otel.ts';++const exporter = new InMemorySpanExporter();+const errors: unknown[] = [];+const runs = agentRuns({ audience: 'public', spanProcessors: [new SimpleSpanProcessor(exporter)], onError: error => { errors.push(error); } });+runs.register();+const worlds: LocalWorld[] = [];+beforeEach(() => { errors.length = 0; });+afterEach(() => vi.restoreAllMocks());+afterAll(async () => { await runs.forceFlush(); for (const world of worlds) await world.close?.(); });+let number = 0;+const call = { callId: 'call_1', name: 'lookup', provenance: 'fx_local', argumentsJson: '{"query":"hello"}' };++async function fixture(audience: 'public' | 'private' | 'unknown' = 'public') {+ const world = createWorld({ dataDir: await mkdtemp(join(tmpdir(), 'fx-trace-lifecycle-')), recoverActiveRuns: false });+ worlds.push(world);+ const runId = `wrun_fx_lifecycle_${++number}`;+ const hooks = agentRunsHooks({ world, name: 'fx-lifecycle', audience });+ const event = (executionId: string | null, type: string, data: unknown, stepIndex = 0, turnId: string | null = 'turn') => ({+ version: 1, sessionId: runId, rootSessionId: runId, parentSessionId: null, sourceSessionId: null, workId: null,+ turnId, executionId, stepIndex, timestamp: Date.now(), contentCaptured: true, contentTruncated: false, type, data,+ }) as unknown as FxHookEvent;+ const send = (executionId: string | null, type: string, data: unknown, stepIndex = 0, turnId: string | null = 'turn') => hooks.onEvent(event(executionId, type, data, stepIndex, turnId));+ const model = (executionId: string, output: string, stepIndex = 1, turnId = 'turn') => {+ send(executionId, 'step.start', {}, stepIndex, turnId);+ send(executionId, 'model.start', { modelCallId: 1, purpose: 'agent', model: 'test/model', messages: [{ role: 'user', content: output, toolCalls: [] }], tools: [] }, stepIndex, turnId);+ send(executionId, 'model.end', { modelCallId: 1, error: null, cancelled: false, finishReason: 'stop', output, provider: 'test-provider', usage: { inputTokens: 4, outputTokens: 2, cacheReadTokens: 0, cacheWriteTokens: 0, reasoningTokens: 1 } }, stepIndex, turnId);+ };+ const spans = () => exporter.getFinishedSpans().filter(span => span.attributes['agent.run.id'] === runId);+ return { world, runId, hooks, event, send, model, spans };+}++describe('fx handoff and terminal outcomes', () => {+ it.each(['completed', 'cancelled', 'interrupted', 'failed'])('settles a recovered tool that is not rerun when its turn ends %s', async outcome => {+ const f = await fixture();+ f.send('one', 'turn.start', { resumed: false, input: 'Look up the record' });+ f.model('one', 'Looking up the record');+ f.send('one', 'tool.start', { call, rerun: false }, 1);+ f.send('one', 'wait.start', { requestId: 'approval', kind: 'approval', callId: call.callId, prompt: 'Continue?' }, 1);+ f.send('one', 'wait.end', { requestId: 'approval', outcome: 'cancelled', error: null }, 1);+ f.send('one', 'tool.end', { call, status: 'cancelled', error: null }, 1);+ f.send('one', 'step.end', {}, 1);+ f.send('one', 'turn.end', { outcome: 'interrupted', handoff: true, error: null });+ await f.hooks.flush();+ expect(f.spans().filter(span => span.name === 'execute_tool lookup')).toHaveLength(0);++ // A fresh worker can hand off again without ever receiving another event for the ambiguous call.+ for (const execution of ['two', 'three']) {+ const hooks = agentRunsHooks({ world: new Proxy(f.world, {}), name: 'fx-lifecycle', audience: 'public' });+ hooks.onEvent(f.event(execution, 'turn.start', { resumed: true }));+ hooks.onEvent(f.event(execution, 'turn.end', execution === 'two'+ ? { outcome: 'interrupted', handoff: true, error: null }+ : { outcome, error: outcome === 'failed' ? 'turn failed' : null }));+ await hooks.flush();+ }+ await runs.forceFlush();+ const spans = f.spans();+ expect(spans.filter(span => span.name === 'invoke_agent fx-lifecycle')).toHaveLength(1);+ const tools = spans.filter(span => span.name === 'execute_tool lookup');+ expect(tools).toHaveLength(1);+ expect(spans.filter(span => span.name === 'agent.approval')).toHaveLength(1);+ const names = (await f.world.streams.list(f.runId)).filter(name => name.includes('_agent-runs_') && !name.endsWith('_sequence'));+ expect(names).toHaveLength(1);+ expect((await readJsonLines(f.world, f.runId, names[0]!)).at(-1)).toMatchObject({ v: null });+ expect(await agentRunsHook()!.session({ world: new Proxy(f.world, {}), runId: f.runId, agentName: 'fx-lifecycle' }).resume('turn')).toBeUndefined();+ expect(new Set(spans.map(span => span.spanContext().spanId)).size).toBe(spans.length);+ });++ it.each([+ { outcome: 'cancelled', handoff: true, fenced: false },+ { outcome: 'interrupted', handoff: true, fenced: false },+ { outcome: 'yielded', handoff: false, fenced: false },+ { outcome: 'paused', handoff: false, fenced: false },+ { outcome: 'fenced', handoff: false, fenced: false },+ { outcome: 'failed', handoff: false, fenced: true },+ ])('continues $outcome (handoff=$handoff, journal fenced=$fenced) without settling its cancelled tool', async ({ outcome, handoff, fenced }) => {+ const f = await fixture();+ f.send('one', 'turn.start', { resumed: false, input: 'Look up the record' });+ f.model('one', 'Looking up the record');+ f.send('one', 'tool.start', { call, rerun: false }, 1);+ f.send('one', 'wait.start', { requestId: 'approval', kind: 'approval', callId: call.callId, prompt: 'Continue?' }, 1);+ if (fenced) f.send(null, 'journal.error', { fenced: true, error: 'FX_FENCED' }, 0, null);+ f.send('one', 'wait.end', { requestId: 'approval', outcome: 'cancelled', error: null }, 1);+ f.send('one', 'tool.end', { call, status: 'cancelled', error: 'execution stopped' }, 1);+ f.send('one', 'step.end', {}, 1);+ f.send('one', 'turn.end', { outcome, handoff, error: fenced ? 'fenced' : null });+ await f.hooks.flush();+ expect(f.spans().filter(span => span.name === 'invoke_agent fx-lifecycle')).toHaveLength(0);+ expect(f.spans().filter(span => span.name === 'execute_tool lookup')).toHaveLength(0);++ f.send('two', 'turn.start', { resumed: true });+ f.send('two', 'step.start', {}, 1);+ f.send('two', 'tool.start', { call, rerun: true }, 1);+ f.send('two', 'wait.start', { requestId: 'approval', kind: 'approval', callId: call.callId, prompt: 'Continue?' }, 1);+ f.send('two', 'wait.end', { requestId: 'approval', outcome: 'accepted', error: null }, 1);+ f.send('two', 'tool.end', { call, status: 'success', output: '"found"', error: null }, 1);+ f.send('two', 'step.end', {}, 1);+ f.model('two', 'The record was found', 2);+ f.send('two', 'step.end', {}, 2);+ f.send('two', 'turn.end', { outcome: 'completed', error: null });+ await f.hooks.flush();+ await runs.forceFlush();+ const spans = f.spans();+ const roots = spans.filter(span => span.name === 'invoke_agent fx-lifecycle');+ expect(roots).toHaveLength(1);+ expect(roots[0]!.attributes['agent.turn.outcome']).toBe('completed');+ const tools = spans.filter(span => span.name === 'execute_tool lookup');+ expect(tools).toHaveLength(1);+ expect(tools[0]!.attributes['gen_ai.tool.call.result']).toContain('found');+ const approvals = spans.filter(span => span.name === 'agent.approval');+ expect(approvals).toHaveLength(1);+ expect(approvals[0]!.attributes['agent.approval.outcome']).toBe('approved');+ expect(spans.filter(span => span.status.code === 2)).toEqual([]);+ });++ it.each([+ { outcome: 'interrupted', expected: 'cancelled' },+ { outcome: 'cancelled', expected: 'cancelled' },+ { outcome: 'failed', expected: 'failed' },+ { outcome: 'completed', expected: 'completed' },+ ])('finishes a non-handoff $outcome turn and its pending children', async ({ outcome, expected }) => {+ const f = await fixture();+ f.send('one', 'turn.start', { resumed: false, input: 'Look up the record' });+ f.model('one', 'Looking up the record');+ f.send('one', 'tool.start', { call, rerun: false }, 1);+ f.send('one', 'wait.start', { requestId: 'approval', kind: 'approval', callId: call.callId, prompt: 'Continue?' }, 1);+ f.send('one', 'tool.end', { call, status: 'cancelled', error: null }, 1);+ f.send('one', 'step.end', {}, 1);+ f.send('one', 'turn.end', { outcome, handoff: false, error: outcome === 'failed' ? 'turn failed' : null });+ await f.hooks.flush();+ await runs.forceFlush();+ const roots = f.spans().filter(span => span.name === 'invoke_agent fx-lifecycle');+ expect(roots).toHaveLength(1);+ expect(roots[0]!.attributes['agent.turn.outcome']).toBe(expected);+ expect(f.spans().filter(span => span.name === 'execute_tool lookup')).toHaveLength(1);+ expect(f.spans().filter(span => span.name === 'agent.approval')).toHaveLength(1);+ expect(await agentRunsHook()!.session({ world: f.world, runId: f.runId, agentName: 'fx-lifecycle' }).resume('turn')).toBeUndefined();+ });+});++describe('fx execution isolation and bookkeeping', () => {+ it('ignores old execution completions without closing the current execution or losing metadata', async () => {+ const f = await fixture();+ f.send('old', 'turn.start', { resumed: false, input: 'first' });+ f.send('old', 'step.start', {}, 1);+ f.send('old', 'model.start', { modelCallId: 1, purpose: 'agent', model: 'test/model', messages: [], tools: [] }, 1);+ f.send('new', 'turn.start', { resumed: true });+ f.send('new', 'step.start', {}, 1);+ f.send('new', 'model.start', { modelCallId: 1, purpose: 'agent', model: 'test/model', messages: [], tools: [] }, 1);+ f.send('old', 'model.end', { modelCallId: 1, error: null, cancelled: false, output: 'stale answer', usage: {} }, 1);+ f.send('old', 'step.end', {}, 1);+ f.send('old', 'turn.end', { outcome: 'cancelled', error: null });+ await f.hooks.flush();+ expect(f.spans().filter(span => span.name.startsWith('invoke_agent'))).toHaveLength(0);+ f.send('new', 'model.end', { modelCallId: 1, error: null, cancelled: false, finishReason: 'stop', output: 'current answer', provider: 'actual-provider', usage: { inputTokens: 20, outputTokens: 5, reasoningTokens: 7 } }, 1);+ f.send('new', 'step.end', {}, 1);+ f.send('new', 'turn.end', { outcome: 'completed', error: null });+ await f.hooks.flush();+ await runs.forceFlush();+ const spans = f.spans();+ expect(spans.filter(span => span.name.startsWith('invoke_agent'))).toHaveLength(1);+ const model = spans.find(span => String(span.attributes['gen_ai.output.messages']).includes('current answer'))!;+ expect(model.attributes['gen_ai.provider.name']).toBe('actual-provider');+ expect(spans.find(span => span.spanContext().spanId === model.parentSpanContext?.spanId)!.attributes['agent.usage.reasoning_tokens']).toBe(7);+ expect(JSON.stringify(spans.map(span => span.attributes))).not.toContain('stale answer');+ const steps = spans.filter(span => span.name === 'agent.step');+ expect(new Set(steps.map(span => span.spanContext().spanId)).size).toBe(2);+ });++ it.each(['completed', 'yielded'])('evicts a drained %s acquisition and ignores late receipts and title calls', async outcome => {+ const f = await fixture();+ const acquire = vi.spyOn(agentRunsHook()!, 'session');+ f.send('one', 'turn.start', { resumed: false, input: 'first' });+ f.send('one', 'turn.end', { outcome, error: null });+ await f.hooks.flush();+ expect(acquire).toHaveBeenCalledTimes(1);+ f.send(null, 'journal.commit', { cursor: '1', firstSeq: 1, lastSeq: 1, eventCount: 1 }, 0, null);+ f.send(null, 'journal.restore', { cursor: '1', lastSeq: 1, resumable: true, openTurnId: null, lastTurnId: 'turn' }, 0, null);+ f.send(null, 'model.start', { modelCallId: 9, purpose: 'title', model: 'test/model', tools: [] }, 0, null);+ f.send('one', 'model.start', { modelCallId: 10, purpose: 'title', model: 'test/model', tools: [] });+ await f.hooks.flush();+ expect(acquire).toHaveBeenCalledTimes(1);+ const nextTurn = outcome === 'completed' ? 'second' : 'turn';+ f.send('two', 'turn.start', { resumed: outcome !== 'completed', input: 'second' }, 0, nextTurn);+ f.send('two', 'turn.end', { outcome: 'completed', error: null }, 0, nextTurn);+ await f.hooks.flush();+ expect(acquire).toHaveBeenCalledTimes(2);+ await runs.forceFlush();+ const turns = f.spans().filter(span => span.name.startsWith('invoke_agent'));+ expect(turns.map(span => span.attributes['agent.turn.sequence']).sort()).toEqual(outcome === 'completed' ? [0, 1] : [0]);+ });++ it('forwards hook failures to agentRuns onError', async () => {+ const f = await fixture();+ const error = new Error('hook unavailable');+ f.hooks.onError?.(error);+ expect(errors).toEqual([error]);+ });++ it('does nothing until tracing is registered', async () => {+ const current = (globalThis as Record<symbol, unknown>)[AGENT_RUNS];+ delete (globalThis as Record<symbol, unknown>)[AGENT_RUNS];+ try {+ const f = await fixture();+ expect(f.hooks.captureContent).toBe(false);+ f.send('one', 'turn.start', { resumed: false, input: 'ignored' });+ f.send('one', 'turn.end', { outcome: 'completed', error: null });+ await f.hooks.flush();+ expect(f.spans()).toEqual([]);+ } finally { (globalThis as Record<symbol, unknown>)[AGENT_RUNS] = current; }+ });+});++describe('fx default private capture', () => {+ it.each(['private', 'unknown'] as const)('does not transport or record content for %s sessions', async audience => {+ const f = await fixture(audience);+ const marker = 'restricted fx content';+ expect(f.hooks.captureContent).toBe(false);+ f.send('one', 'turn.start', { resumed: false, input: marker });+ f.model('one', marker);+ const privateCall = { ...call, argumentsJson: JSON.stringify({ query: marker }) };+ f.send('one', 'tool.start', { call: privateCall, rerun: false }, 1);+ f.send('one', 'tool.end', { call: privateCall, status: 'success', output: JSON.stringify(marker), error: null }, 1);+ f.send('one', 'step.end', {}, 1);+ f.send('one', 'turn.end', { outcome: 'completed', error: null });+ await f.hooks.flush();+ await runs.forceFlush();+ const spans = f.spans();+ expect(spans.filter(span => span.name.startsWith('invoke_agent'))).toHaveLength(1);+ expect(spans.filter(span => span.name === 'execute_tool lookup')).toHaveLength(1);+ expect(JSON.stringify(spans.map(span => ({ attributes: span.attributes, events: span.events, status: span.status })))).not.toContain(marker);+ const names = (await f.world.streams.list(f.runId)).filter(name => name.includes('_agent-runs_'));+ expect(names.length).toBeGreaterThan(0);+ for (const name of names) {+ const lines = await readJsonLines(f.world, f.runId, name);+ expect(lines.length).toBeGreaterThan(0);+ expect(JSON.stringify(lines)).not.toContain(marker);+ }+ });+});diff --git a/packages/durable-harness/test/fx-agent-runs.test.ts b/packages/durable-harness/test/fx-agent-runs.test.tsnew file mode 100644index 0000000..db49333--- /dev/null+++ b/packages/durable-harness/test/fx-agent-runs.test.ts@@ -0,0 +1,184 @@+import { mkdtemp } from 'node:fs/promises';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { InMemorySpanExporter, type ReadableSpan, SimpleSpanProcessor } from '@opentelemetry/sdk-trace-base';+import { createWorld, type LocalWorld } from '@workflow/world-local';+import { afterAll, beforeAll, describe, expect, it } from 'vitest';+import type { FxHookEvent } from 'libfx';+import { agentRunsHooks } from '../src/fx.ts';+import { agentRuns } from '../src/instrumentation/otel.ts';++const exporter = new InMemorySpanExporter();+const runs = agentRuns({ audience: 'public', spanProcessors: [new SimpleSpanProcessor(exporter)] });+runs.register();++const SESSION = 'wrun_01JZFXHOOKS0000000000000000';+const TURN = 'turn_1';+const worlds: LocalWorld[] = [];+afterAll(async () => {+ for (const w of worlds) await w.close?.();+});++/** An event as libfx sends it: the envelope, then the event's own fields. */+const at = (executionId: string, stepIndex: number) => (type: string, data: unknown): FxHookEvent =>+ ({ version: 1, sessionId: SESSION, rootSessionId: SESSION, turnId: TURN, executionId, stepIndex, timestamp: Date.now(), contentCaptured: true, contentTruncated: false, type, data }) as unknown as FxHookEvent;++const call = { callId: 'call_1', name: 'shout', provenance: 'fx_local', argumentsJson: '{"text":"hi"}' };+const user = { role: 'user', content: 'shout hi', toolCallId: null, toolName: null, toolResultStatus: null, imageCount: 0, toolCalls: [] };++describe('Agent Runs from libfx hooks', () => {+ let spans: ReadableSpan[];+ beforeAll(async () => {+ const dataDir = await mkdtemp(join(tmpdir(), 'dh-fx-hooks-'));+ // The first execution: a model call asks for `shout`, which starts, waits on an approval, and the turn yields.+ const first = createWorld({ dataDir, recoverActiveRuns: false });+ worlds.push(first);+ const one = agentRunsHooks({ world: first, name: 'fx-agent' });+ const e1 = at('exec_1', 1);+ one.onEvent(at('exec_1', 0)('turn.start', { resumed: false, input: 'shout hi' }));+ one.onEvent(e1('step.start', {}));+ one.onEvent(e1('model.start', { modelCallId: 1, purpose: 'agent', model: 'anthropic/claude-haiku-4.5', messages: [user], tools: [{ name: 'shout', description: 'Uppercase.', inputSchemaJson: '{"type":"object"}' }] }));+ one.onEvent(e1('model.end', { modelCallId: 1, error: null, cancelled: false, finishReason: 'tool-calls', usage: { inputTokens: 10, outputTokens: 3, cacheReadTokens: 4, cacheWriteTokens: 0 }, toolCalls: [call] }));+ one.onEvent(e1('tool.start', { call, rerun: false }));+ one.onEvent(e1('wait.start', { requestId: 7, kind: 'approval', callId: 'call_1', prompt: 'Shout?' }));+ one.onEvent(e1('wait.end', { requestId: 7, outcome: 'accepted', error: null }));+ one.onEvent(e1('step.end', {}));+ one.onEvent(at('exec_1', 0)('turn.end', { outcome: 'yielded', error: null }));+ await one.flush();++ // Another process resumes the turn: the call runs again (a rerun), and a second model call answers.+ const second = createWorld({ dataDir, recoverActiveRuns: false });+ worlds.push(second);+ const two = agentRunsHooks({ world: second, name: 'fx-agent' });+ const e2 = (step: number) => at('exec_2', step);+ two.onEvent(e2(0)('turn.start', { resumed: true }));+ two.onEvent(e2(1)('step.start', {}));+ two.onEvent(e2(1)('tool.start', { call, rerun: true }));+ two.onEvent(e2(1)('tool.end', { call, status: 'success', output: '"HI"', error: null }));+ two.onEvent(e2(1)('step.end', {}));+ two.onEvent(e2(2)('step.start', {}));+ two.onEvent(e2(2)('model.start', { modelCallId: 1, purpose: 'agent', model: 'anthropic/claude-haiku-4.5', messages: [user], tools: [] }));+ two.onEvent(e2(2)('model.end', { modelCallId: 1, error: null, cancelled: false, finishReason: 'stop', output: 'Shouted HI.', usage: { inputTokens: 20, outputTokens: 4, cacheReadTokens: 0, cacheWriteTokens: 0 } }));+ two.onEvent(e2(2)('step.end', {}));+ two.onEvent(e2(0)('turn.end', { outcome: 'completed', error: null }));+ await two.flush();+ await runs.forceFlush();+ spans = exporter.getFinishedSpans().filter((s) => s.attributes['agent.run.id'] === SESSION);+ }, 30_000);++ it('records one turn across the two executions, in the eve.agent scope', () => {+ const turns = spans.filter((s) => s.name === 'invoke_agent fx-agent');+ expect(turns).toHaveLength(1);+ expect(turns[0]!.attributes).toMatchObject({ 'agent.turn.id': TURN, 'agent.turn.outcome': 'completed', 'agent.session.title': 'shout hi' });+ expect(new Set(spans.map((s) => s.spanContext().traceId)).size).toBe(1);+ for (const span of spans) expect(span.instrumentationScope.name).toBe('eve.agent');+ });++ it('records a step per model call, numbered by the execution that ran it', () => {+ const steps = spans.filter((s) => s.name === 'agent.step');+ // The first execution's step, and the second's two (the rerun's and the answer's).+ expect(steps).toHaveLength(3);+ expect(new Set(steps.map((s) => s.spanContext().spanId)).size).toBe(3);+ const models = spans.filter((s) => s.name === 'chat anthropic/claude-haiku-4.5');+ expect(models).toHaveLength(2);+ expect(models.map((m) => m.attributes['gen_ai.usage.input_tokens']).sort()).toEqual([10, 20]);+ expect(String(models.find((m) => m.attributes['gen_ai.usage.input_tokens'] === 10)!.attributes['gen_ai.input.messages'])).toContain('shout hi');+ });++ it("keeps the tool call the first execution started, ended by the second, under the step that asked for it", () => {+ const tools = spans.filter((s) => s.name === 'execute_tool shout');+ expect(tools).toHaveLength(1);+ const tool = tools[0]!;+ expect(tool.attributes).toMatchObject({ 'gen_ai.tool.call.id': 'call_1', 'agent.action.outcome': 'completed' });+ expect(String(tool.attributes['gen_ai.tool.call.result'])).toContain('HI');+ const asker = spans.find((s) => s.name === 'chat anthropic/claude-haiku-4.5' && s.attributes['gen_ai.usage.input_tokens'] === 10)!;+ expect(tool.parentSpanContext?.spanId).toBe(asker.parentSpanContext?.spanId);+ const approval = spans.find((s) => s.name === 'agent.approval')!;+ expect(approval.parentSpanContext?.spanId).toBe(tool.spanContext().spanId);+ expect(approval.attributes['agent.approval.outcome']).toBe('approved');+ });+});++describe('Agent Runs from libfx hooks, turn after turn', () => {+ it("records a turn that starts while the previous one's events are still being recorded", async () => {+ const world = createWorld({ dataDir: await mkdtemp(join(tmpdir(), 'dh-fx-next-')), recoverActiveRuns: false });+ worlds.push(world);+ const hooks = agentRunsHooks({ world, name: 'fx-next' });+ const session = 'wrun_01JZFXHOOKSNEXT00000000000';+ const ev = (turnId: string, stepIndex: number) => (type: string, data: unknown): FxHookEvent =>+ ({ version: 1, sessionId: session, rootSessionId: session, turnId, executionId: `exec_${turnId}`, stepIndex, timestamp: Date.now(), contentCaptured: true, contentTruncated: false, type, data }) as unknown as FxHookEvent;+ const model = (turnId: string) => {+ hooks.onEvent(ev(turnId, 1)('step.start', {}));+ hooks.onEvent(ev(turnId, 1)('model.start', { modelCallId: 1, purpose: 'agent', model: 'test/model', messages: [user], tools: [] }));+ hooks.onEvent(ev(turnId, 1)('model.end', { modelCallId: 1, error: null, cancelled: false, finishReason: 'stop', output: 'ok', usage: { inputTokens: 1, outputTokens: 1, cacheReadTokens: 0, cacheWriteTokens: 0 } }));+ hooks.onEvent(ev(turnId, 1)('step.end', {}));+ };+ hooks.onEvent(ev('turn_a', 0)('turn.start', { resumed: false, input: 'first' }));+ model('turn_a');+ hooks.onEvent(ev('turn_a', 0)('turn.end', { outcome: 'completed', error: null }));+ // The next turn starts before the first turn's end is recorded; its other events come after.+ hooks.onEvent(ev('turn_b', 0)('turn.start', { resumed: false, input: 'second' }));+ await hooks.flush();+ model('turn_b');+ hooks.onEvent(ev('turn_b', 0)('turn.end', { outcome: 'completed', error: null }));+ await hooks.flush();+ await runs.forceFlush();++ const own = exporter.getFinishedSpans().filter((s) => s.attributes['agent.run.id'] === session);+ const turns = own.filter((s) => s.name === 'invoke_agent fx-next');+ expect(turns.map((t) => [t.attributes['agent.turn.id'], t.attributes['agent.turn.outcome']]).sort()).toEqual([['turn_a', 'completed'], ['turn_b', 'completed']]);+ const b = turns.find((t) => t.attributes['agent.turn.id'] === 'turn_b')!;+ expect(own.filter((s) => s.name === 'agent.step' && s.parentSpanContext?.spanId === b.spanContext().spanId)).toHaveLength(1);+ }, 30_000);+});++describe('Agent Runs from a real libfx durable agent', () => {+ it('records its turn, its model calls and the tool call their reply asked for', async () => {+ const { createFxAgent } = await import('libfx');+ const { world: fxWorld } = await import('libfx/durable-world');+ const world = createWorld({ dataDir: await mkdtemp(join(tmpdir(), 'dh-fx-real-')), recoverActiveRuns: false });+ worlds.push(world);+ const usage = { inputTokens: { total: 12, cacheRead: 2 }, outputTokens: { total: 3 } };+ const sse = (parts: Record<string, unknown>[]) =>+ new Response([...parts.map((p) => `data: ${JSON.stringify(p)}`), 'data: [DONE]', ''].join('\n\n'), { headers: { 'content-type': 'text/event-stream' } });+ let requests = 0;+ const fetch = async (_url: string | URL | Request, init?: RequestInit) => {+ if ((init?.method ?? 'GET') === 'GET') return Response.json({ object: 'list', data: [] });+ return requests++ === 0+ ? sse([{ type: 'tool-call', toolCallId: 'call_shout', toolName: 'shout', input: '{"text":"hi"}' }, { type: 'finish', finishReason: { unified: 'tool-calls', raw: 'tool-calls' }, usage }])+ : sse([{ type: 'text-delta', id: 't', delta: 'Shouted HI.' }, { type: 'finish', finishReason: { unified: 'stop', raw: 'stop' }, usage }]);+ };+ const hooks = agentRunsHooks({ world, name: 'fx-real' });+ const agent = createFxAgent({+ durability: fxWorld(world, { name: 'fx-real', livenessKnown: true, alive: () => true, holderInfo: () => ({ pid: process.pid, host: 'test' }), pollMs: 50 }),+ apiKey: 'test',+ model: 'test/model',+ fetch: fetch as typeof globalThis.fetch,+ modelCatalog: [],+ hooks,+ tools: [{ name: 'shout', description: 'Uppercase some text.', inputSchema: { type: 'object', properties: { text: { type: 'string' } } }, idempotent: true, execute: async (input: { text: string }) => input.text.toUpperCase() }],+ });+ try {+ const turn = agent.session().prompt('shout hi');+ const { sessionId } = await turn.accepted;+ for await (const _ of turn);+ await turn.result;+ await hooks.flush();+ await runs.forceFlush();+ const own = exporter.getFinishedSpans().filter((s) => s.attributes['agent.run.id'] === sessionId);+ expect(own.filter((s) => s.name === 'invoke_agent fx-real')).toHaveLength(1);+ expect(own.find((s) => s.name === 'invoke_agent fx-real')!.attributes['agent.turn.outcome']).toBe('completed');+ const models = own.filter((s) => s.name === 'chat test/model');+ expect(models.length).toBeGreaterThanOrEqual(2);+ const tool = own.find((s) => s.name === 'execute_tool shout')!;+ expect(tool.attributes['gen_ai.tool.call.id']).toBe('call_shout');+ expect(String(tool.attributes['gen_ai.tool.call.result'])).toContain('HI');+ // The tool span is under the step whose model call asked for it.+ const asker = models.find((m) => String(m.attributes['gen_ai.output.messages']).includes('call_shout'))!;+ expect(tool.parentSpanContext?.spanId).toBe(asker.parentSpanContext?.spanId);+ expect(new Set(own.map((s) => s.spanContext().traceId)).size).toBe(1);+ } finally {+ await agent.close();+ }+ }, 60_000);+});diff --git a/packages/harness-world/src/agent-runs.ts b/packages/harness-world/src/agent-runs.tsindex fdd4aae..b4c06a2 100644--- a/packages/harness-world/src/agent-runs.ts+++ b/packages/harness-world/src/agent-runs.ts@@ -75,6 +75,12 @@ export interface SessionTracingInput {readonly audience?: TraceAudience;}+/** An interrupted tool and approvals that a native engine may not mention again after recovery. */+export interface ParkedTraceTool {+ readonly callId: string;+ readonly approvals: readonly string[];+}+/*** Agent Runs turns for a session that is not driven by the kernel (pi-durable,* libfx's own durable agent), checkpointed with the session.@@ -85,11 +91,17 @@ export interface SessionTracing {/** A saved turn under the current capture policy, without starting one. */resume(turnId: string): Promise<TurnOperation | undefined>;/**- * A new step of `turn`, for a model call: numbered in this process, its- * attempt this process's number for the turn (recorded before it is- * used), so no step of another process, before or after, is the same one.+ * A new step of `turn`, for a model call. Its attempt is a number for the+ * turn recorded before it is used, so no step of another process, before+ * or after, is the same one: this process's number, the step numbered in+ * this process; or, with `at`, the number of the execution that runs it+ * (an engine's run or resume of the turn), the step numbered in it.*/- step(turn: TurnOperation, turnId: string): Promise<AttemptOperation>;+ step(turn: TurnOperation, turnId: string, at?: { readonly execution: string; readonly stepIndex: number }): Promise<AttemptOperation>;+ /** Tool identities retained with the turn's checkpoint, without their content. */+ parkedTools(turnId: string): Promise<readonly ParkedTraceTool[]>;+ /** Replace the tool identities a resumed engine may silently skip. */+ parkTools(turnId: string, tools: readonly ParkedTraceTool[]): Promise<void>;/** Wait for this session's queued checkpoint writes, within the tracing I/O budget. */flush(): Promise<void>;}