Skip to content

Durable coding-agent harnesses (Claude Code, Codex, OpenCode, Pi, fx) on a Workflow SDK World

durable-harness: Agent Runs tracing on @vercel/agent-runs (#10)

Chad Hietala9b1ed08c9ecf
diff --git a/.changeset/agent-runs-library.md b/.changeset/agent-runs-library.md
new file mode 100644
index 0000000..7cf209c
--- /dev/null
+++ b/.changeset/agent-runs-library.md
@@ -0,0 +1,9 @@
+---
+"durable-harness": patch
+---
+
+Agent Runs tracing (`agentRuns()` from `/instrumentation/otel`) records sessions with `@vercel/[email protected]`, the library eve uses: a turn per prompt, a step per model call with the tool calls it asks for under it, in the schema Agent Runs reads. A turn that goes on in a later invocation (out of time, a crash, a wake, a lane handoff) stays one turn, its checkpoint kept with the session. A session's `traceAudience` decides what its spans record (`public`: inputs and outputs; anything else: metadata only), and `agentRuns({ capture })` changes that per audience; `exportPolicy` and `filteringProcessor` are removed. Claude Code, Codex and OpenCode record each model request through the Gateway with its prompt, reply and usage.
+
+Recovery applies the current capture policy to restored operations, keeping newly private content out of checkpoints and exports. Recorded tool definitions exclude provider credentials, untraced proxy requests stream without buffering, and tracing failures cannot change agent results. Checkpoint waits are bounded without discarding final updates after a soft budget expires or a write slows down; queued follow-ups retain their own turn identity.
+
+Agent Runs is an optional peer with inlined declaration types. Tracing requires Node.js 24 and optional tracing peers; other entrypoints retain Node.js 22 support.
diff --git a/apps/demo/agent-runs.ts b/apps/demo/agent-runs.ts
index 89d8fcb..cf9cfe8 100644
--- a/apps/demo/agent-runs.ts
+++ b/apps/demo/agent-runs.ts
@@ -1,13 +1,6 @@
import { agentRuns } from 'durable-harness/instrumentation/otel';
-export default agentRuns({
- // The demo's sessions are public in Agent Runs, their prompts, answers and
- // tool content included: the demo is SSO-protected and its prompts are demo
- // prompts. (A session that records its own audience keeps it.)
- audience: 'public',
- exportPolicy: {
- span: ({ audience }) => audience === 'public'
- ? { emit: true }
- : { redact: true, inputs: true, outputs: true },
- },
-});
+// The demo's sessions are public in Agent Runs, their prompts, answers and
+// tool content included: the demo is SSO-protected and its prompts are demo
+// prompts. (A session that records its own audience keeps it.)
+export default agentRuns({ audience: 'public' });
diff --git a/apps/demo/lib/fx-durable.test.ts b/apps/demo/lib/fx-durable.test.ts
index b1b53c7..c5752c7 100644
--- a/apps/demo/lib/fx-durable.test.ts
+++ b/apps/demo/lib/fx-durable.test.ts
@@ -1,7 +1,7 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { fxAgent, withFxTraces } from './fx-durable';
-const traced = vi.hoisted(() => ({ end: vi.fn(), fetch: undefined as typeof fetch | undefined }));
+const traced = vi.hoisted(() => ({ complete: vi.fn(async () => {}), fail: vi.fn(async () => {}), fetch: undefined as typeof fetch | undefined }));
vi.mock('libfx', () => ({ createFxAgent: async (options: { fetch: typeof fetch }) => {
traced.fetch = options.fetch;
return {};
@@ -9,9 +9,11 @@ vi.mock('libfx', () => ({ createFxAgent: async (options: { fetch: typeof fetch }
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/instrumentation', () => ({ instrumentation: () => ({ session: () => ({
- start: () => ({ end: traced.end }), end() {},
-}) }) }));
+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(() => {
@@ -41,18 +43,20 @@ describe('native libfx model response tracing', () => {
const response = await modelRequest();
expect(response.status).toBe(status);
expect(await response.text()).toBe(body ?? '');
- expect(traced.end).toHaveBeenCalledTimes(1);
- const [output, error] = traced.end.mock.calls[0];
- expect(output).toMatchObject({ status, requestBody: { prompt: [] }, responseBody: body ?? '' });
- if (status >= 200 && status < 300) expect(error).toBeUndefined();
- else expect(error).toEqual(new Error(`Model request failed (${status})`));
+ 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 () => {
const error = new Error('network down');
vi.stubGlobal('fetch', vi.fn().mockRejectedValue(error));
await expect(modelRequest()).rejects.toBe(error);
- expect(traced.end).toHaveBeenCalledTimes(1);
- expect(traced.end.mock.calls[0][1]).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 () => {
const error = new Error('stream interrupted');
@@ -61,8 +65,7 @@ describe('native libfx model response tracing', () => {
}), { status: 500 })));
const response = await modelRequest();
await expect(response.text()).rejects.toBe(error);
- expect(traced.end).toHaveBeenCalledTimes(1);
- expect(traced.end.mock.calls[0][0].status).toBe(500);
- expect(traced.end.mock.calls[0][1]).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.ts
index 1be26c6..eda0d1d 100644
--- a/apps/demo/lib/fx-durable.ts
+++ b/apps/demo/lib/fx-durable.ts
@@ -1,6 +1,7 @@
import { AsyncLocalStorage } from 'node:async_hooks';
import { fxPromptTraceIdentity, fxTraceIdentity, fxTraceRequestBody } from './fx-trace';
-import { instrumentation, type TraceScope } from 'harness-world/instrumentation';
+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';
@@ -57,41 +58,56 @@ export const log = (event: string, detail: Record<string, unknown>) => console.l
const LOGGED = new Set(['journal.open', 'checkpoint.save', 'checkpoint.error', 'checkpoint.mismatch', 'session.deadline', 'session.fenced', 'session.error']);
type FxAgent = ReturnType<typeof createFxAgent>;
-type FxTraceState = { scope: TraceScope; turnId: string; outcome?: 'running' | 'failed' };
+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>();
-/** Queue deliveries close only scopes created by their own async invocation. */
+/**
+ * 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 { scope, outcome } of fxTraceInvocations.getStore()!.traces.values()) {
- scope.end(error, outcome ?? (error === undefined ? 'completed' : 'failed'));
- await scope.flush?.();
- }
+ for (const state of fxTraceInvocations.getStore()!.traces.values()) await endFxTrace(state, error).catch(() => {});
}
});
}
-async function fxTrace(id: string, key: string, refreshTurn = false): Promise<TraceScope | undefined> {
+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();
- if (!invocation || !instrumentation()) return undefined;
+ const hook = agentRunsHook();
+ if (!invocation || !hook) return undefined;
const { traces, turns } = invocation;
const existing = traces.get(id);
- if (existing && !refreshTurn) return existing.scope;
+ 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.scope;
- existing?.scope.end();
- await existing?.scope.flush?.();
- const scope = instrumentation()!.session(id, 'fx-durable', turnId, prompt, undefined, await getWorld());
- traces.set(id, { scope, turnId });
- return scope;
+ 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> };
@@ -242,8 +258,15 @@ async function timedFetch(input: RequestInfo | URL, init?: RequestInit): Promise
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 modelTrace = (await fxTrace(id, key, true).catch(() => undefined))?.start('model', { model: MODEL, requestBody }, key);
- let traceBody = '';
+ 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.
@@ -254,8 +277,13 @@ async function timedFetch(input: RequestInfo | URL, init?: RequestInit): Promise
if (ended) return;
ended = true;
const status = response?.status;
- modelTrace?.end({ requestBody, responseBody: traceBody, status },
- error ?? (response && !response.ok ? new Error(`Model request failed (${status})`) : undefined));
+ 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' });
};
@@ -278,7 +306,7 @@ async function timedFetch(input: RequestInfo | URL, init?: RequestInit): Promise
try {
const { value, done } = await reader.read();
if (done) {
- traceBody += traceDecoder.decode().slice(0, Math.max(0, 256_000 - traceBody.length));
+ traceBody.push(traceDecoder.decode());
end();
controller.close();
return;
@@ -290,7 +318,7 @@ async function timedFetch(input: RequestInfo | URL, init?: RequestInit): Promise
mark(id, 'model.first_token', { key, effect: 'model' });
}
}
- if (traceBody.length < 256_000) traceBody += traceDecoder.decode(value, { stream: true }).slice(0, 256_000 - traceBody.length);
+ traceBody.push(traceDecoder.decode(value, { stream: true }));
controller.enqueue(value);
} catch (error) {
end(error);
@@ -332,14 +360,19 @@ async function crashDuring(id: string, effectKey: string, effectName: string, st
async function toolStep<T>(id: string, ctx: FxToolContext, name: string, input: unknown, run: () => Promise<T>): Promise<T> {
const key = `tool:${ctx.executionId}`;
const effect = `tool.${name}`;
- const toolTrace = (await fxTrace(id, key).catch(() => undefined))?.start(effect, input, key);
+ 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();
- toolTrace?.end(result);
+ await toolTrace?.complete({ outcome: 'completed', output: result }).catch(() => {});
return result;
- } catch (error) { toolTrace?.end(undefined, error); throw error; } finally {
+ } catch (error) { await toolTrace?.fail(error).catch(() => {}); throw error; } finally {
disarm();
mark(id, 'tool.end', { key, effect });
}
diff --git a/apps/durable-ai-sdk/package.json b/apps/durable-ai-sdk/package.json
index 9fb95b6..8d7b4f9 100644
--- a/apps/durable-ai-sdk/package.json
+++ b/apps/durable-ai-sdk/package.json
@@ -22,6 +22,7 @@
"durable-harness": "workspace:*",
"harness-world": "workspace:*",
"harness-world-hands": "workspace:*",
- "zod": "4.5.4"
+ "zod": "4.5.4",
+ "@vercel/agent-runs": "0.0.1"
}
}
diff --git a/apps/durable-ai-sdk/src/harness.ts b/apps/durable-ai-sdk/src/harness.ts
index d7cfe13..a5edca5 100644
--- a/apps/durable-ai-sdk/src/harness.ts
+++ b/apps/durable-ai-sdk/src/harness.ts
@@ -20,6 +20,8 @@ import {
type ToolSet,
wrapLanguageModel,
} from 'ai';
+import { modelContent } from '@vercel/agent-runs/ai-sdk';
+import { modelMessages, modelTools } from 'harness-world/agent-runs';
import { type DriveContext, EffectFailure, Fatal, type Harness, type HostToolIO, type PromptDocs, promptDocsText, type ReplayPolicy, type SessionState, Yield } from 'durable-harness';
/**
@@ -111,20 +113,17 @@ export function aiSdkHarness({ model, tools = {}, promptDocs, ...settings }: AiS
const key = `model:${n}:${step++}`;
sameConversation(ctx, key, params);
const input = { model: model.modelId, messages: params.prompt.length };
- const output = await ctx.effect(key, { name: 'model', replay: 'safe', input: { ...input, ...(ctx.instrumentation ? { instrumentation: 'adapter' } : {}) } }, async (io) => {
+ const output = await ctx.effect(key, { name: 'model', replay: 'safe', input }, async (io) => {
// The prompt hook: the documents as this call pinned them at the
// start of the latest prompt, and what earlier calls showed on
// the earlier ones (so the prompt extends the previous one).
- const shown = promptDocs ? docsShown(ctx.state()) : new Map<number, string>();
+ if (!promptDocs) return tracedGenerate(ctx, model, { ...params, abortSignal: io.signal }, attempts, key);
+ const shown = docsShown(ctx.state());
const at = params.prompt.findLastIndex((m) => m.role === 'user');
const docs = promptDocsText(promptDocs, io.docs) ?? '';
- const prompt = promptDocs ? withDocuments(params.prompt, shown, at, docs) : params.prompt;
- const operation = ctx.instrumentation?.start('model', { model: model.modelId, messages: prompt }, key);
- try {
- const result = await generate(ctx, model, { ...params, prompt, abortSignal: io.signal }, attempts, key);
- operation?.end({ ...result, role: 'assistant' });
- return promptDocs && at >= 0 && docs !== (shown.get(at) ?? '') ? { ...result, promptDocs: { at, text: docs } satisfies ShownDocs } : result;
- } catch (error) { operation?.end(undefined, io.signal.aborted ? undefined : error); throw error; }
+ const prompt = withDocuments(params.prompt, shown, at, docs);
+ const result = await tracedGenerate(ctx, model, { ...params, prompt, abortSignal: io.signal }, attempts, key);
+ return at >= 0 && docs !== (shown.get(at) ?? '') ? { ...result, promptDocs: { at, text: docs } satisfies ShownDocs } : result;
});
const { promptDocs: _, ...result } = output as typeof output & { promptDocs?: ShownDocs };
return result;
@@ -167,6 +166,7 @@ export function aiSdkHarness({ model, tools = {}, promptDocs, ...settings }: AiS
return {
name: 'ai-sdk',
+ modelCalls: 'self',
async drive(ctx) {
for (let n = 0; ; n++) {
const recorded = ctx.state().effects.get(`turn:${n}`)?.input as TurnInput | undefined;
@@ -220,6 +220,54 @@ function sameConversation(ctx: DriveContext, key: string, params: LanguageModelV
* has streamed yet; the raw HTTP request and response bodies are left out
* of the log.
*/
+/** `generate`, recorded as the model call of its step in Agent Runs (when `agentRuns()` is registered). */
+async function tracedGenerate(ctx: DriveContext, model: LanguageModelV4, params: LanguageModelV4CallOptions, attempts: number, key: string) {
+ const system = params.prompt.flatMap((m) => (m.role === 'system' ? [m.content] : []));
+ const traced = await ctx.tracing?.modelCall({
+ provider: model.provider,
+ modelId: model.modelId,
+ messages: modelMessages(params.prompt.filter((m) => m.role !== 'system')),
+ ...(system.length ? { instructions: system.join('\n\n') } : {}),
+ ...(params.tools ? { tools: modelTools(params.tools) } : {}),
+ }).catch(() => undefined);
+ let result: Awaited<ReturnType<typeof generate>>;
+ try {
+ result = await generate(ctx, model, params, attempts, key);
+ } catch (error) {
+ await traced?.model.fail(error).catch(() => {});
+ throw error;
+ }
+ try {
+ const usage = result.usage;
+ await traced?.model.complete({
+ outcome: 'completed',
+ result: {
+ finishReason: result.finishReason.unified,
+ usage: {
+ inputTokens: usage.inputTokens.total,
+ outputTokens: usage.outputTokens.total,
+ inputTokenDetails: { cacheReadTokens: usage.inputTokens.cacheRead, cacheWriteTokens: usage.inputTokens.cacheWrite },
+ },
+ ...(result.response.id ? { responseId: result.response.id } : {}),
+ ...(result.response.modelId ? { responseModelId: result.response.modelId } : {}),
+ content: modelContent(result.content.map((p) => (p.type === 'tool-call' ? { ...p, input: parseJson(p.input) } : p))),
+ },
+ });
+ const gatewayMeta = (result.providerMetadata?.gateway ?? {}) as Record<string, unknown>;
+ const usd = (v: unknown) => (v === undefined || v === null || v === '' || !Number.isFinite(Number(v)) ? undefined : Number(v));
+ traced?.attempt.attributes({ 'gen_ai.usage.cost': usd(gatewayMeta.cost), 'gen_ai.usage.gateway_cost': usd(gatewayMeta.gatewayCost) });
+ } catch { /* Recording a result must not change the model call's outcome. */ }
+ return result;
+}
+
+function parseJson(text: string): unknown {
+ try {
+ return JSON.parse(text);
+ } catch {
+ return text;
+ }
+}
+
async function generate(ctx: DriveContext, model: LanguageModelV4, params: LanguageModelV4CallOptions, attempts: number, key: string) {
for (let attempt = 1; ; attempt++) {
const progress = { streamed: false };
diff --git a/packages/cli-check/README.md b/packages/cli-check/README.md
index 16d8bc2..b99ebc6 100644
--- a/packages/cli-check/README.md
+++ b/packages/cli-check/README.md
@@ -74,14 +74,15 @@ in `test/cli-quirks.test.ts`.
`test/agent-runs.test.ts` runs one tool turn of every server harness (Pi, Pi
with pi-durable, fx, the AI SDK, Claude Code, Codex, OpenCode) with scripted
-models on world-local, through durable-harness's OpenTelemetry integration
-(`durable-harness/instrumentation/otel`) with an in-memory span processor. It
-checks each turn's spans as Vercel Agent Runs reads them: the `invoke_agent`
-root, an `agent.step` per model and tool call with its `chat` or
-`execute_tool` span under it, all in one trace, a tool span carrying the id
-of the call the model's reply names (Agent Runs joins the two by it), and that
-the default export policy leaves no prompt, answer or tool content on a
-non-public session's spans (`src/agent-runs.ts`).
+models on world-local, through durable-harness's `agentRuns()`
+(`durable-harness/instrumentation/otel`, on `@vercel/agent-runs`) with an
+in-memory span processor. It checks each turn's spans as Vercel Agent Runs
+reads them: the `invoke_agent` root in the `eve.agent` scope at schema 4, an
+`agent.step` per model call with its `chat` span and the tool calls it asked
+for under it, all in the turn's trace, and a tool span carrying the id of the
+call the model's reply names (Agent Runs joins the two by it)
+(`src/agent-runs.ts`). That a session that is not public records only
+metadata is durable-harness's own `test/agent-runs.test.ts`.
`test/agent-runs-live.test.ts` does the same with the real CLIs and AI Gateway
models, and also checks model ids, the prompt in the model's input and token
diff --git a/packages/cli-check/src/agent-runs.ts b/packages/cli-check/src/agent-runs.ts
index ee4552f..168906d 100644
--- a/packages/cli-check/src/agent-runs.ts
+++ b/packages/cli-check/src/agent-runs.ts
@@ -1,26 +1,24 @@
import { appendFileSync } from 'node:fs';
import { InMemorySpanExporter, type ReadableSpan, SimpleSpanProcessor } from '@opentelemetry/sdk-trace-base';
-import { type AgentRunsIntegration, agentRuns, filteringProcessor } from 'durable-harness/instrumentation/otel';
+import { type AgentRuns, agentRuns } from 'durable-harness/instrumentation/otel';
import { durableSessions, type Harness, QUEUE_PREFIX, type SessionState } from 'harness-world';
+import type { World } from '@workflow/world';
import { expect } from 'vitest';
import { settled, until } from './scenario.ts';
import { type OpenWorld, storageFor } from './worlds.ts';
/**
- * Vercel Agent Runs checks: durable-harness's OpenTelemetry integration
- * (`agentRuns()`) with an in-memory span processor, and what one tool turn
- * of a harness must give it.
+ * Vercel Agent Runs checks: durable-harness's `agentRuns()` (on
+ * `@vercel/agent-runs`) with an in-memory span processor, and what one tool
+ * turn of a harness must give it.
*
- * Sessions are started with `traceAudience: 'unknown'` (what an
- * authenticated chat route records) and exported with a policy that emits
- * everything, so the content is there to check; the same spans are then
- * replayed through the default policy (`filteringProcessor`, no policy) to
- * check that a non-public session's spans reach a destination with no
- * prompt, tool or model content.
+ * Sessions use an unknown audience. Each scripted harness runs once with
+ * content enabled and once with the default metadata-only policy.
*/
export interface Tracing {
- integration: AgentRunsIntegration;
+ readonly content: boolean;
+ integration: AgentRuns;
exporter: InMemorySpanExporter;
/** The finished spans of one session (every span carries `agent.run.id`). */
spansOf(sessionId: string): ReadableSpan[];
@@ -30,52 +28,55 @@ export interface Tracing {
close(): Promise<void>;
}
-export function tracing(): Tracing {
+export function tracing(content = true): Tracing {
const exporter = new InMemorySpanExporter();
- const integration = agentRuns({ audience: 'public', exportPolicy: { span: () => ({ emit: true }) }, spanProcessors: [new SimpleSpanProcessor(exporter)] });
+ const integration = agentRuns({ ...(content ? { capture: () => ({ emit: true, recordInputs: true, recordOutputs: true }) } : {}), spanProcessors: [new SimpleSpanProcessor(exporter)] });
integration.register();
const spansOf = (sessionId: string) => exporter.getFinishedSpans().filter((s) => s.attributes['agent.run.id'] === sessionId);
return {
+ content,
integration,
exporter,
spansOf,
async finishedTurn(sessionId, harness, timeoutMs = 60_000) {
await until(() => Promise.resolve(spansOf(sessionId).some((s) => s.name === `invoke_agent ${harness}`)), timeoutMs, `the ${harness} turn's root span`);
await integration.forceFlush();
- return spansOf(sessionId);
+ const spans = spansOf(sessionId);
+ for (const root of spans.filter(span => span.name.startsWith('invoke_agent'))) {
+ expect(root.attributes['agent.trace.content.input']).toBe(content);
+ expect(root.attributes['agent.trace.content.output']).toBe(content);
+ }
+ return spans;
},
async close() {
await integration.forceFlush();
- delete (globalThis as Record<symbol, unknown>)[Symbol.for('durable-harness.instrumentation')];
+ delete (globalThis as Record<symbol, unknown>)[Symbol.for('durable-harness.agent-runs')];
},
};
}
-/** Attributes that carry prompt, model or tool content (durable-harness's redaction list). */
-export const CONTENT_KEYS = [
- 'agent.session.title',
- 'agent.channel.delivery.input',
- 'gen_ai.input.messages',
- 'gen_ai.output.messages',
- 'gen_ai.system_instructions',
- 'gen_ai.tool.definitions',
- 'gen_ai.tool.call.arguments',
- 'gen_ai.tool.call.result',
-];
-
-/** The spans as the default export policy hands them to a destination (no policy: non-public audiences redacted). */
-export function redacted(spans: ReadableSpan[]): ReadableSpan[] {
- const out: ReadableSpan[] = [];
- const processor = filteringProcessor({ onStart() {}, onEnd: (s) => void out.push(s), forceFlush: async () => {}, shutdown: async () => {} });
- for (const span of spans) processor.onEnd(span);
- return out;
+export async function expectNoCheckpointContent(world: World, runId: string, marker: string): Promise<void> {
+ const names = (await world.streams.list(runId)).filter(name => name.includes('_agent-runs_'));
+ expect(names.length, 'durable trace checkpoints exist').toBeGreaterThan(0);
+ for (const name of names) {
+ let cursor: string | undefined;
+ let text = '';
+ const decoder = new TextDecoder();
+ for (;;) {
+ const page = await world.streams.getChunks(runId, name, { ...(cursor ? { cursor } : {}) });
+ for (const chunk of page.data) text += decoder.decode(chunk.data, { stream: true });
+ if (!page.hasMore || !page.cursor) break;
+ cursor = page.cursor;
+ }
+ expect(text).not.toContain(marker);
+ }
}
export interface TurnExpect {
sessionId: string;
/** The root's agent name: the harness's name (`invoke_agent <harness>`). */
harness: string;
- /** A string in the prompt and in the tool call's arguments, never in a redacted span. */
+ /** A string in the prompt and in the tool call's arguments. */
marker: string;
/** The tool the turn calls. Undefined: any tool, as long as its arguments carry the marker. */
tool?: string;
@@ -89,7 +90,7 @@ export interface TurnExpect {
usage?: boolean;
}
-/** What one tool turn must give Agent Runs: the span tree, its content, and its redaction. */
+/** What one tool turn must give Agent Runs: the span tree and its content. */
export function expectToolTurn(spans: ReadableSpan[], o: TurnExpect): void {
// `AGENT_RUNS_DUMP=<file>`: append the span tree (names and ids, no content) for a look by eye.
if (process.env.AGENT_RUNS_DUMP) appendFileSync(process.env.AGENT_RUNS_DUMP, `${o.harness} ${o.sessionId}\n${outline(spans)}\n`);
@@ -104,14 +105,18 @@ export function expectToolTurn(spans: ReadableSpan[], o: TurnExpect): void {
'agent.framework.name': 'durable-harness',
'agent.name': o.harness,
'agent.run.id': o.sessionId,
- 'vercel.session_id': o.sessionId,
'gen_ai.operation.name': 'invoke_agent',
'agent.trace.schema.version': 4,
'agent.channel.audience': o.audience ?? 'unknown',
'agent.turn.outcome': 'completed',
});
- expect(String(root.attributes['agent.session.title'] ?? root.attributes['agent.channel.delivery.input'])).toContain(o.marker);
- expect(new Set(spans.map((s) => s.spanContext().traceId)), 'one trace per session').toEqual(new Set([root.spanContext().traceId]));
+ const content = root.attributes['agent.trace.content.input'] === true;
+ if (content) expect(String(root.attributes['agent.session.title'])).toContain(o.marker);
+ else {
+ expect(root.attributes['agent.session.title']).toBeUndefined();
+ expect(JSON.stringify(spans.map(span => ({ attributes: span.attributes, events: span.events, status: span.status })))).not.toContain(o.marker);
+ }
+ expect(new Set(spans.map((s) => s.spanContext().traceId)), 'one trace per turn').toEqual(new Set([root.spanContext().traceId]));
// Steps hang off a root; model and tool spans off a step.
const steps = spans.filter((s) => s.name === 'agent.step');
@@ -122,22 +127,22 @@ export function expectToolTurn(spans: ReadableSpan[], o: TurnExpect): void {
expect(models.length, 'a model span').toBeGreaterThanOrEqual(1);
for (const m of models) expect(parentOf(m)?.name).toBe('agent.step');
expect(models.some(ofRoot), "a model span in the tool turn's trace").toBe(true);
- expect(models[0]!.attributes['gen_ai.output.messages']).toBeDefined();
- if (o.modelContent) expect(models.map((m) => String(m.attributes['gen_ai.input.messages'])).join(''), "the prompt in a model span's input").toContain(o.marker);
+ if (content) expect(models[0]!.attributes['gen_ai.output.messages']).toBeDefined();
+ if (o.modelContent && content) expect(models.map((m) => String(m.attributes['gen_ai.input.messages'])).join(''), "the prompt in a model span's input").toContain(o.marker);
if (o.model) for (const m of models) expect(m.name).toMatch(typeof o.model === 'string' ? new RegExp(`^chat ${o.model.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}$`) : o.model);
if (o.usage) {
const used = models.map((m) => parentOf(m)!).filter((step) => typeof step.attributes['agent.usage.input_tokens'] === 'number');
expect(used.length, 'token usage on a model step').toBeGreaterThanOrEqual(1);
}
const tools = spans.filter((s) => s.attributes['gen_ai.operation.name'] === 'execute_tool' && (o.tool === undefined || s.name === `execute_tool ${o.tool}`));
- const calls = tools.filter((s) => String(s.attributes['gen_ai.tool.call.arguments']).includes(o.marker));
+ const calls = content ? tools.filter((s) => String(s.attributes['gen_ai.tool.call.arguments']).includes(o.marker)) : tools;
expect(calls.length, `an execute_tool ${o.tool ?? '*'} span with the marker in its arguments (tools: ${tools.map((s) => s.name).join(', ') || 'none'})`).toBeGreaterThanOrEqual(1);
if (o.tool) expect(tools).toHaveLength(1);
const call = calls[0]!;
expect(parentOf(call)?.name).toBe('agent.step');
expect(ofRoot(call)).toBe(true);
expect(call.attributes['gen_ai.tool.name']).toBe(call.name.slice('execute_tool '.length));
- expect(call.attributes['gen_ai.tool.call.result']).toBeDefined();
+ if (content) expect(call.attributes['gen_ai.tool.call.result']).toBeDefined();
// Where the model's reply names its tool calls, the tool span carries that
// call's id: Agent Runs joins the two into one tool call by it.
const asked = models.flatMap((m) => {
@@ -154,20 +159,6 @@ export function expectToolTurn(spans: ReadableSpan[], o: TurnExpect): void {
spans.filter((s) => s.status.code === 2).map((s) => `${s.name}: ${s.status.message}`),
'no span failed'
).toEqual([]);
-
- // The default policy: a non-public session's spans carry no content.
- const out = redacted(spans);
- if ((o.audience ?? 'unknown') === 'public') {
- expect(out).toHaveLength(spans.length);
- return;
- }
- expect(out.map((s) => s.name).sort()).toEqual(spans.map((s) => s.name).sort());
- for (const s of out) {
- for (const key of CONTENT_KEYS) expect(s.attributes[key], `${s.name}: ${key}`).toBeUndefined();
- expect(s.attributes['agent.trace.content.input']).toBe(false);
- expect(s.attributes['agent.trace.content.output']).toBe(false);
- expect(JSON.stringify({ name: s.name, attributes: s.attributes, status: s.status, events: s.events })).not.toContain(o.marker);
- }
}
/**
@@ -183,14 +174,15 @@ export async function kernelTurn(
prompt: string,
done: (s: SessionState) => boolean,
timeoutMs = 90_000
-): Promise<{ sessionId: string; state: SessionState; spans: ReadableSpan[] }> {
+): Promise<{ sessionId: string; state: SessionState; spans: ReadableSpan[]; world: World }> {
const open: OpenWorld = await storageFor('local', `agent-runs-${name}`).open();
disposers.push(() => open.close());
const sessions = durableSessions({ world: open.world, harness });
await open.serve(QUEUE_PREFIX, sessions.handler);
const { sessionId } = await sessions.start({ prompt, config: { traceAudience: 'unknown' } });
const state = await settled(open.world, sessions, sessionId, done, { what: `the ${name} tool turn`, timeoutMs });
- return { sessionId, state, spans: await t.finishedTurn(sessionId, harness.name) };
+ const spans = await t.finishedTurn(sessionId, harness.name);
+ return { sessionId, state, spans, world: open.world };
}
/** The span tree, one line per span, indented under its parent: names and step ids, no content. */
diff --git a/packages/cli-check/test/agent-runs.test.ts b/packages/cli-check/test/agent-runs.test.ts
index a8a3173..d86acf8 100644
--- a/packages/cli-check/test/agent-runs.test.ts
+++ b/packages/cli-check/test/agent-runs.test.ts
@@ -27,7 +27,7 @@ import { z } from 'zod';
import { codexStandIn } from '../scenarios/codex.ts';
import { admit, ready, ScriptedHost } from '../scenarios/opencode.ts';
import { newHost, type TrackedHost, turnsEnded } from '../scenarios/process.ts';
-import { expectToolTurn, kernelTurn, type Tracing, tracing } from '../src/agent-runs.ts';
+import { expectNoCheckpointContent, expectToolTurn, kernelTurn, type Tracing, tracing } from '../src/agent-runs.ts';
import { storageFor } from '../src/worlds.ts';
/**
@@ -46,23 +46,25 @@ import { storageFor } from '../src/worlds.ts';
const MARKER = 'zebra-7f3a';
let t: Tracing;
-beforeAll(() => {
- t = tracing();
-});
-afterAll(() => t.close());
const disposers: (() => Promise<void> | void)[] = [];
afterEach(async () => {
for (const d of disposers.splice(0).reverse()) await Promise.resolve(d()).catch(() => {});
});
-const turn = (name: string, harness: Harness, prompt: string, done: (s: SessionState) => boolean) => kernelTurn(t, disposers, name, harness, prompt, done);
+const turn = async (name: string, harness: Harness, prompt: string, done: (s: SessionState) => boolean) => {
+ const result = await kernelTurn(t, disposers, name, harness, prompt, done);
+ if (!t.content) await expectNoCheckpointContent(result.world, result.sessionId, MARKER);
+ return result;
+};
const SHOUT_PROMPT = `shout ${MARKER}`;
const modelDone = (n: number) => (s: SessionState) => s.effectOrder.filter((e) => e.name === 'model' && e.status === 'completed').length >= n;
const checkpointed = (s: SessionState) => s.effects.get('checkpoint:0')?.status === 'completed';
-describe('Agent Runs: one tool turn per server harness', () => {
+describe.each([true, false])('Agent Runs: one tool turn per server harness (capture content: %s)', content => {
+ beforeAll(() => { t = tracing(content); });
+ afterAll(() => t.close());
it('Pi (harness-world-pi)', async () => {
const faux = fauxProvider();
faux.setResponses([fauxAssistantMessage(fauxToolCall('shout', { text: MARKER }), { stopReason: 'toolUse' }), fauxAssistantMessage(fauxText('Shouted.'))]);
@@ -79,7 +81,7 @@ describe('Agent Runs: one tool turn per server harness', () => {
};
const harness = piHarness({ model: faux.getModel(), streamFn: models.streamSimple.bind(models), systemPrompt: 'Be loud.', tools: [shout] });
const { sessionId, spans } = await turn('pi', harness, SHOUT_PROMPT, modelDone(2));
- expectToolTurn(spans, { sessionId, marker: MARKER, harness: 'pi', tool: 'shout', modelContent: true, model: faux.getModel().provider + '/' + faux.getModel().id, usage: true });
+ expectToolTurn(spans, { sessionId, marker: MARKER, harness: 'pi', tool: 'shout', modelContent: true, model: faux.getModel().id, usage: true });
});
const libfxAddon = join(dirname(createRequire(import.meta.url).resolve('libfx')), `libfx.${process.platform}-${process.arch}.node`);
@@ -137,7 +139,8 @@ describe('Agent Runs: one tool turn per server harness', () => {
expect((await (await root.submit({ type: 'input', content: SHOUT_PROMPT }, BACKGROUND_CONTEXT)).wait(BACKGROUND_CONTEXT)).status).toBe('done');
await harness.close(BACKGROUND_CONTEXT);
const spans = await t.finishedTurn(storage.sessionId, 'pi-durable');
- expectToolTurn(spans, { sessionId: storage.sessionId, marker: MARKER, harness: 'pi-durable', tool: 'shout', modelContent: true, model: `${faux.getModel().provider}/${faux.getModel().id}`, usage: true });
+ if (!t.content) await expectNoCheckpointContent(open.world, storage.sessionId, MARKER);
+ expectToolTurn(spans, { sessionId: storage.sessionId, marker: MARKER, harness: 'pi-durable', tool: 'shout', modelContent: true, model: faux.getModel().id, usage: true });
});
/** The scripted process CLIs: `call <tool> <json>` makes one bridged tool call; what they say goes through the proxy to the model. */
diff --git a/packages/durable-harness/package.json b/packages/durable-harness/package.json
index 5e7856f..7c5ff9d 100644
--- a/packages/durable-harness/package.json
+++ b/packages/durable-harness/package.json
@@ -114,8 +114,8 @@
"LICENSE"
],
"scripts": {
- "build": "tsup",
- "prepack": "tsup",
+ "build": "tsup && node scripts/inline-tracing-types.mjs",
+ "prepack": "pnpm run build",
"test": "vitest run",
"typecheck": "tsc --noEmit",
"check-dist": "node scripts/check-dist.mjs"
@@ -145,6 +145,7 @@
"@opentelemetry/otlp-transformer": ">=0.208.0 <1",
"@opentelemetry/resources": "^2.2.0",
"@opentelemetry/sdk-trace-base": "^2.2.0",
+ "@vercel/agent-runs": "0.0.1",
"@vercel/sandbox": "^3.7.0",
"@workflow/world-postgres": "^5.0.4",
"effect": "4.0.0-rc.112",
@@ -154,6 +155,9 @@
"zod": "^4.0.0"
},
"peerDependenciesMeta": {
+ "@vercel/agent-runs": {
+ "optional": true
+ },
"@anthropic-ai/claude-agent-sdk": {
"optional": true
},
@@ -225,6 +229,7 @@
"@opentelemetry/otlp-transformer": "0.208.0",
"@opentelemetry/resources": "2.2.0",
"@opentelemetry/sdk-trace-base": "2.2.0",
+ "@vercel/agent-runs": "0.0.1",
"effect": "4.0.0-rc.112",
"harness-world": "workspace:*",
"harness-world-claude-code": "workspace:*",
@@ -238,6 +243,8 @@
"libfx": "catalog:",
"next": "16.3.8",
"pi-world": "workspace:*",
+ "rollup": "4.63.5",
+ "rollup-plugin-dts": "6.2.3",
"tsup": "8.5.1",
"zod": "4.5.4"
}
diff --git a/packages/durable-harness/scripts/check-dist.mjs b/packages/durable-harness/scripts/check-dist.mjs
index f4d1f92..a5c897b 100644
--- a/packages/durable-harness/scripts/check-dist.mjs
+++ b/packages/durable-harness/scripts/check-dist.mjs
@@ -33,6 +33,10 @@ for (const file of readdirSync(join(root, 'dist'), { recursive: true }).filter((
.split('\n')
.filter((line) => !/^\s*\*(?:\s|\/|$)/.test(line))
.join('\n');
+ if (file.endsWith('.d.ts') && /(?:from\s*|import\(\s*)['"]@vercel\/agent-runs(?:\/[^'"]*)?['"]/.test(text)) {
+ console.error(`${file} references optional agent-runs types instead of inlining them`);
+ bad++;
+ }
for (const [, fromSpec, dynamicSpec] of text.matchAll(/(?:^|[\s;])(?:import|export)\b[^'"]*?from\s*['"]([^'"./][^'"]*)['"]|import\(\s*['"]([^'"./][^'"]*)['"]\s*\)/gm)) {
const spec = fromSpec ?? dynamicSpec;
if (!spec) continue;
diff --git a/packages/durable-harness/scripts/inline-tracing-types.mjs b/packages/durable-harness/scripts/inline-tracing-types.mjs
new file mode 100644
index 0000000..ebd90c3
--- /dev/null
+++ b/packages/durable-harness/scripts/inline-tracing-types.mjs
@@ -0,0 +1,35 @@
+import { mkdirSync, readFileSync, readdirSync, unlinkSync, writeFileSync } from 'node:fs';
+import { dirname, isAbsolute, resolve } from 'node:path';
+import { createRequire } from 'node:module';
+import { fileURLToPath } from 'node:url';
+import { rollup } from 'rollup';
+import { dts } from 'rollup-plugin-dts';
+
+const root = fileURLToPath(new URL('..', import.meta.url));
+const dist = resolve(root, 'dist');
+const pkg = JSON.parse(readFileSync(resolve(root, 'package.json'), 'utf8'));
+const libraryManifest = createRequire(import.meta.url).resolve('@vercel/agent-runs/package.json');
+const library = JSON.parse(readFileSync(libraryManifest, 'utf8'));
+const libraryTypes = resolve(dirname(libraryManifest), library.exports['.'].types);
+const input = Object.fromEntries(Object.values(pkg.publishConfig.exports).flatMap(entry =>
+ typeof entry === 'object' && entry.types
+ ? [[entry.types.replace(/^\.\/dist\//, '').replace(/\.d\.ts$/, ''), resolve(root, entry.types)]]
+ : []));
+
+// tsup treats declared peers as external even with dts.resolve. Only this peer's types must be inlined.
+const bundle = await rollup({
+ input,
+ external: id => !/^@vercel\/agent-runs(?:\/|$)/.test(id) && !id.startsWith('.') && !isAbsolute(id),
+ plugins: [{ name: 'agent-runs-types', resolveId: id => id === '@vercel/agent-runs' ? libraryTypes : null }, dts({ respectExternal: true })],
+ onwarn(warning, warn) { if (warning.code === 'UNRESOLVED_IMPORT') throw new Error(warning.message); warn(warning); },
+});
+try {
+ const { output } = await bundle.generate({ format: 'es', entryFileNames: '[name].js', chunkFileNames: 'types-[hash].js' });
+ const previous = readdirSync(dist, { recursive: true }).filter(file => file.endsWith('.d.ts'));
+ for (const file of previous) unlinkSync(resolve(dist, file));
+ for (const file of output) {
+ const path = resolve(dist, file.fileName.replace(/\.js$/, '.d.ts'));
+ mkdirSync(dirname(path), { recursive: true });
+ writeFileSync(path, file.type === 'chunk' ? file.code : file.source);
+ }
+} finally { await bundle.close(); }
diff --git a/packages/durable-harness/src/instrumentation/checkpoints.ts b/packages/durable-harness/src/instrumentation/checkpoints.ts
new file mode 100644
index 0000000..973316f
--- /dev/null
+++ b/packages/durable-harness/src/instrumentation/checkpoints.ts
@@ -0,0 +1,269 @@
+import { createHash } from 'node:crypto';
+import type { World } from '@workflow/world';
+import type { TraceCheckpointer, TraceSnapshot } from '@vercel/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 Turn extends State {
+ runId: string;
+ stream: string;
+ loaded?: Promise<void>;
+ writing: Promise<void>;
+ pending?: { value: TraceSnapshot | null };
+ scheduled: boolean;
+ /** Queued writes stay counted until the actual World writes settle, even after a caller times out. */
+ storing: number;
+ /** Readers cannot reacquire this writer while a timed-out queue can still change its stream. */
+ delayed?: unknown;
+ unavailable?: unknown;
+}
+const CACHE_LIMIT = 128;
+const READ_LIMIT = 16 * 1024 * 1024;
+
+function parseKey(key: string): { runId: string; turnId: string } | undefined {
+ const [kind, runId, turnId] = key.split(':');
+ if (kind !== 'turn' || runId === undefined || turnId === undefined) return undefined;
+ try { return { runId: decodeURIComponent(runId), turnId: decodeURIComponent(turnId) }; }
+ catch { return undefined; }
+}
+
+export function checkpointStreamName(runId: string, turnId: string): string {
+ return `${runId}_agent-runs_${createHash('sha256').update(turnId).digest('hex').slice(0, 24)}`;
+}
+
+/** Best-effort checkpoints: bounded I/O, ordered per turn, and no shared writer that can stall other sessions. */
+export class TraceStreams {
+ private readonly turns = new Map<string, Turn>();
+ private readonly deadlines = new Map<string, number>();
+
+ constructor(
+ private readonly world: World,
+ private readonly onError: (error: unknown) => void,
+ private readonly timeoutMs = WRITE_DEADLINE_MS
+ ) {}
+
+ setDeadline(runId: string, deadline: number | undefined): void {
+ if (deadline === undefined) this.deadlines.delete(runId);
+ else this.deadlines.set(runId, deadline);
+ }
+
+ readonly checkpointer: TraceCheckpointer = {
+ get: async (key) => {
+ const turn = this.turn(key);
+ if (!turn) return undefined;
+ await this.load(turn);
+ return turn.value;
+ },
+ set: (key, value) => this.write(key, value),
+ delete: (key) => this.write(key, null),
+ };
+
+ forget(runId: string, turnId?: string): void {
+ const only = turnId === undefined ? undefined : `turn:${encodeURIComponent(runId)}:${encodeURIComponent(turnId)}`;
+ for (const [key, turn] of this.turns) {
+ if (turn.runId === runId && (only === undefined || key === only) && !turn.pending && turn.storing === 0) this.turns.delete(key);
+ }
+ }
+
+ async nextDrive(runId: string, turnId: string): Promise<number> {
+ const turn = this.turn(`turn:${encodeURIComponent(runId)}:${encodeURIComponent(turnId)}`)!;
+ return this.increment(turn);
+ }
+
+ async nextSequence(runId: string): Promise<number> {
+ const key = `sequence:${encodeURIComponent(runId)}`;
+ let turn = this.turns.get(key);
+ if (turn && !turn.pending && turn.storing === 0) { this.turns.delete(key); turn = undefined; }
+ turn ??= this.cache(key, runId, `${runId}_agent-runs_sequence`);
+ return (await this.increment(turn)) - 1;
+ }
+
+ private increment(turn: Turn): Promise<number> {
+ if (turn.delayed && turn.storing > 0) return Promise.reject(turn.delayed);
+ const next = turn.writing.then(async () => {
+ await this.load(turn, true);
+ if (turn.unavailable) throw turn.unavailable;
+ const drive = ++turn.drives;
+ await this.put(turn, turn.value, turn.finished);
+ return drive;
+ });
+ turn.storing++;
+ turn.writing = next.then(() => {}, () => {}).finally(() => { if (--turn.storing === 0) turn.delayed = undefined; });
+ this.keepAlive(turn.writing);
+ return this.bounded(turn, () => next, 'write');
+ }
+
+ async finished(runId: string, turnId: string): Promise<boolean> {
+ const turn = this.turn(`turn:${encodeURIComponent(runId)}:${encodeURIComponent(turnId)}`)!;
+ await this.load(turn);
+ return turn.finished;
+ }
+
+ /** 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);
+ await Promise.all(turns.map(async (turn) => {
+ if (turn.storing === 0 && !turn.pending) return;
+ const writing = turn.writing;
+ try { await this.bounded(turn, () => writing, 'write'); }
+ catch { /* Checkpoints never keep a drive alive past its budget. */ }
+ }));
+ for (const [key, turn] of this.turns) if (turn.finished && !turn.pending && turn.storing === 0) this.turns.delete(key);
+ }
+
+ private report(error: unknown): void {
+ try { this.onError(error); } catch {}
+ }
+
+ /** A bounded caller may leave; the ordered queue still needs to store its latest pending state. */
+ private keepAlive(work: Promise<void>): void {
+ try {
+ (globalThis as { [key: symbol]: { get?: () => { waitUntil?: (work: Promise<void>) => void } | undefined } | undefined })[Symbol.for('@vercel/request-context')]?.get?.()?.waitUntil?.(work);
+ } catch (error) { this.report(error); }
+ }
+
+ /** Failed reads disable capture; a timed-out write wait only quarantines readers until its queue drains. */
+ private async bounded<T>(turn: Turn, work: (signal: AbortSignal) => Promise<T>, operation: 'read' | 'write' = 'read'): Promise<T> {
+ const remaining = Math.min(this.timeoutMs, (this.deadlines.get(turn.runId) ?? Infinity) - Date.now());
+ const abort = new AbortController();
+ let timer: ReturnType<typeof setTimeout> | undefined;
+ try {
+ if (remaining <= 0) throw new Error('Agent Runs checkpoint deadline reached');
+ return await Promise.race([
+ Promise.resolve().then(() => work(abort.signal)),
+ new Promise<never>((_, reject) => { timer = setTimeout(() => {
+ const error = new Error('Agent Runs checkpoint I/O timed out');
+ abort.abort(error);
+ reject(error);
+ }, remaining); }),
+ ]);
+ } catch (error) {
+ if (operation === 'read') turn.unavailable = error;
+ else if (turn.storing > 0) turn.delayed = error;
+ this.report(error);
+ throw error;
+ } finally { clearTimeout(timer); }
+ }
+
+ private turn(key: string): Turn | undefined {
+ const turn = this.turns.get(key);
+ if (turn) return turn;
+ const parsed = parseKey(key);
+ if (!parsed) return undefined;
+ return this.cache(key, parsed.runId, checkpointStreamName(parsed.runId, parsed.turnId));
+ }
+
+ private cache(key: string, runId: string, stream: string): Turn {
+ const turn: Turn = { runId, stream, drives: 0, finished: false, writing: Promise.resolve(), scheduled: false, storing: 0 };
+ this.turns.set(key, turn);
+ for (const [oldKey, old] of this.turns) {
+ if (this.turns.size <= CACHE_LIMIT) break;
+ if (old !== turn && old.storing === 0 && !old.pending) this.turns.delete(oldKey);
+ }
+ return turn;
+ }
+
+ private async load(turn: Turn, writing = false): Promise<void> {
+ if (turn.unavailable) throw turn.unavailable;
+ if (!writing && turn.delayed && turn.storing > 0) throw turn.delayed;
+ turn.loaded ??= this.bounded(turn, async (signal) => {
+ const state = await this.read(turn, signal);
+ if (!turn.pending && turn.value === undefined && !turn.finished) {
+ turn.value = state.value;
+ turn.finished = state.finished;
+ }
+ turn.drives = Math.max(turn.drives, state.drives);
+ });
+ return turn.loaded;
+ }
+
+ private async read(turn: Turn, signal: AbortSignal): Promise<State> {
+ const missing = (error: unknown) => {
+ for (let value = error, depth = 0; value && typeof value === 'object' && depth < 5; value = (value as { cause?: unknown }).cause, depth++) {
+ const entry = value as { code?: unknown; status?: unknown; statusCode?: unknown; name?: unknown };
+ if (entry.code === 'ENOENT' || entry.status === 404 || entry.statusCode === 404 || entry.name === 'StreamNotFoundError') return true;
+ }
+ return false;
+ };
+ let tail: number;
+ try { tail = (await this.world.streams.getInfo(turn.runId, turn.stream)).tailIndex; }
+ catch (error) { if (missing(error)) return { drives: 0, finished: false }; throw error; }
+ signal.throwIfAborted();
+ if (tail < 0) return { drives: 0, finished: false };
+ const stream = await this.world.streams.get(turn.runId, turn.stream, tail);
+ const reader = stream.getReader();
+ const cancel = () => { void reader.cancel().catch(() => {}); };
+ signal.addEventListener('abort', cancel, { once: true });
+ let text = '';
+ let bytes = 0;
+ const decoder = new TextDecoder();
+ try {
+ while (!text.includes('\n')) {
+ signal.throwIfAborted();
+ const next = await reader.read();
+ if (next.done) break;
+ bytes += next.value.byteLength;
+ if (bytes > READ_LIMIT) throw new Error('Agent Runs checkpoint exceeds read limit');
+ text += decoder.decode(next.value, { stream: true });
+ }
+ } 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 };
+
+ // Earlier previews wrote separate snapshot and drive lines. Read that history once, strictly.
+ let value: TraceSnapshot | undefined;
+ let drives = 0;
+ let finished = false;
+ let cursor: string | undefined;
+ let buffer = '';
+ bytes = 0;
+ const legacyDecoder = new TextDecoder();
+ for (;;) {
+ signal.throwIfAborted();
+ const page = await this.world.streams.getChunks(turn.runId, turn.stream, { ...(cursor ? { cursor } : {}) });
+ for (const chunk of page.data) {
+ bytes += chunk.data.byteLength;
+ if (bytes > READ_LIMIT) throw new Error('Agent Runs checkpoint history exceeds read limit');
+ buffer += legacyDecoder.decode(chunk.data, { stream: true });
+ }
+ if (!page.hasMore || !page.cursor) break;
+ cursor = page.cursor;
+ }
+ for (const text of buffer.split('\n').filter(Boolean)) {
+ const entry = decodeLine(text) as { v?: TraceSnapshot | null; drive?: number };
+ if (typeof entry.drive === 'number') drives = Math.max(drives, entry.drive);
+ if ('v' in entry) { value = entry.v ?? undefined; finished = entry.v === null; }
+ }
+ return { value, drives, finished };
+ }
+
+ 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 }) };
+ // 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; }
+ }
+
+ private write(key: string, value: TraceSnapshot | null): void {
+ const turn = this.turn(key);
+ if (!turn || turn.unavailable) return;
+ turn.pending = { value };
+ turn.value = value ?? undefined;
+ turn.finished = value === null;
+ if (turn.scheduled) return;
+ turn.scheduled = true;
+ turn.storing++;
+ turn.writing = turn.writing.then(async () => {
+ turn.scheduled = false;
+ const pending = turn.pending;
+ turn.pending = undefined;
+ if (!pending || turn.unavailable) return;
+ await this.load(turn, true);
+ await this.put(turn, pending.value ?? undefined, pending.value === null);
+ }).catch(() => {}).finally(() => { if (--turn.storing === 0) turn.delayed = undefined; });
+ this.keepAlive(turn.writing);
+ }
+}
diff --git a/packages/durable-harness/src/instrumentation/drive.ts b/packages/durable-harness/src/instrumentation/drive.ts
new file mode 100644
index 0000000..073bce6
--- /dev/null
+++ b/packages/durable-harness/src/instrumentation/drive.ts
@@ -0,0 +1,389 @@
+import { AsyncLocalStorage } from 'node:async_hooks';
+import type {
+ AgentRun,
+ AttemptOperation,
+ CaptureDecision,
+ ModelOperation,
+ ToolOperation,
+ TurnInput,
+ TurnOperation,
+} from '@vercel/agent-runs';
+import type { DriveContext, EffectOptions, Harness, SessionState, Submission } from 'harness-world';
+import { type DriveTracing, type ModelOptions, type ModelResult, type TraceAudience, type TracedModelCall, traceAudienceOf } from 'harness-world/agent-runs';
+import { Fatal, Parked } from 'harness-world/errors';
+import type { TraceStreams } from './checkpoints.ts';
+
+export interface DriveTracerOptions {
+ readonly run: AgentRun;
+ readonly streams: TraceStreams;
+ /** For a session whose config records no `traceAudience`. */
+ readonly audience: TraceAudience;
+ readonly capture: (audience: TraceAudience) => CaptureDecision;
+ readonly version: string;
+}
+
+/** A `model` effect running in this drive: the step it is, created when its model call is recorded. */
+interface Slot {
+ readonly drive: object;
+ readonly turn: TurnTrace;
+ readonly stepIndex: number;
+ readonly attempt: number;
+ step?: Promise<Step | undefined>;
+}
+
+/** One step (attempt) of a turn: a model call, and the tool calls its response asks for. */
+interface Step {
+ readonly op: AttemptOperation;
+ /** The tool calls the step's model responses asked for, not yet matched to a tool effect. */
+ readonly asked: { id: string; name: string; args: string }[];
+ /** Model calls still running: a step another one starts beside is not ended under them. */
+ running: number;
+ /** Its tool calls not settled, a parked one among them: ending the step would close them. */
+ open: number;
+}
+
+interface TurnTrace {
+ readonly submission: Submission;
+ op?: Promise<TurnOperation | undefined>;
+ steps: Step[];
+ /** Steps of model calls recorded outside a `model` effect, numbered in this drive. */
+ requests: number;
+ /** This drive's number for the turn, for those steps' attempt numbers. */
+ drive?: Promise<number>;
+}
+
+const slots = new AsyncLocalStorage<Slot>();
+const record = (v: unknown): Record<string, unknown> => (v !== null && typeof v === 'object' ? (v as Record<string, unknown>) : {});
+const isPrompt = (s: Submission | undefined): s is Submission & { text: string } => s?.text !== undefined && s.kind !== 'steer';
+
+/**
+ * Drive `harness` with each turn of the session traced: a turn per prompt
+ * (steers join the open one), a step per model call with the tool calls it
+ * asks for under it. A turn that goes on in a later drive (out of time, a
+ * crash, a handoff) is continued there from its checkpoint, so it stays one
+ * `invoke_agent` span; work already in the log is never traced again.
+ */
+export async function traceDrive(options: DriveTracerOptions, harness: Harness, ctx: DriveContext): Promise<void> {
+ const { run, streams } = options;
+ streams.forget(ctx.runId);
+ streams.setDeadline(ctx.runId, ctx.deadline);
+ const audience = traceAudienceOf(record(ctx.config).traceAudience) ?? options.audience;
+ const capture = options.capture(audience);
+ const self = harness.modelCalls === 'self';
+ const drive = {};
+ const turns = new Map<string, TurnTrace>();
+ const prompts = () => ctx.state().submissions.filter(isPrompt);
+
+ let current: TurnTrace | undefined;
+ const turnOf = (submission: Submission) => {
+ let turn = turns.get(submission.id);
+ if (!turn) turns.set(submission.id, (turn = { submission, steps: [], requests: 0 }));
+ return turn;
+ };
+ const initial = prompts().filter((s) => ctx.state().placed.has(s.id)).at(-1) ?? ctx.pending().find(isPrompt);
+ if (initial) current = turnOf(initial);
+
+ function input(submission: Submission): TurnInput {
+ const first = prompts()[0];
+ const title = capture.recordInputs && first?.text ? first.text.slice(0, 160) : undefined;
+ return {
+ identity: { conversationId: ctx.runId, runId: ctx.runId, turnId: submission.id },
+ agentName: harness.name,
+ sequence: Math.max(0, prompts().findIndex((s) => s.id === submission.id)),
+ framework: { name: 'durable-harness', version: options.version },
+ capture,
+ channel: { kind: 'http', origin: 'channel' },
+ attributes: { 'agent.channel.audience': audience, ...(title ? { 'agent.session.title': title } : {}) },
+ };
+ }
+
+ /** The turn's operation, started if it never was. A turn that already finished is not started again. */
+ function started(turn: TurnTrace): Promise<TurnOperation | undefined> {
+ turn.op ??= (async () => {
+ if (await streams.finished(ctx.runId, turn.submission.id)) return undefined;
+ return run.turn(input(turn.submission));
+ })();
+ return turn.op;
+ }
+
+ /** The turn's operation if this or an earlier drive started it and it is still open. */
+ async function saved(turn: TurnTrace): Promise<TurnOperation | undefined> {
+ if (turn.op) return turn.op;
+ const data = input(turn.submission);
+ if (!(await run.resume({ identity: data.identity }))) return undefined;
+ // Re-enter before exposing restored children so recovery cannot retain an older, wider capture policy.
+ const resumed = await run.turn(data);
+ resumed.attributes({ 'agent.channel.audience': audience });
+ turn.op = Promise.resolve(resumed);
+ return resumed;
+ }
+
+ async function endSteps(turn: TurnTrace, error?: unknown, which: (step: Step) => boolean = () => true): Promise<void> {
+ const ending = turn.steps.filter(which);
+ turn.steps = turn.steps.filter((s) => !ending.includes(s));
+ for (const step of ending) await (error === undefined ? step.op.complete() : step.op.fail(error));
+ }
+
+ async function endTurn(turn: TurnTrace, outcome: 'completed' | 'failed' | 'cancelled' | 'running', error?: unknown): Promise<void> {
+ const op = await saved(turn);
+ // A turn that goes on keeps the steps of its open tool calls: the drive that settles one finds it in them.
+ await endSteps(turn, outcome === 'failed' || outcome === 'running' ? error : undefined, outcome === 'running' ? (s) => s.open === 0 : undefined);
+ if (!op || outcome === 'running') return;
+ if (outcome === 'failed') await op.complete({ outcome, failed: true, error, ...(error instanceof Error ? { errorType: error.name } : {}) });
+ else await op.complete({ outcome });
+ }
+
+ /** A newly placed prompt starts its turn; the one before it is over. */
+ async function place(placed: readonly string[] | undefined): Promise<void> {
+ const submission = ctx.state().submissions.find((s) => placed?.includes(s.id) && isPrompt(s));
+ if (!submission || submission.id === current?.submission.id) return;
+ const previous = current;
+ current = turnOf(submission);
+ if (previous) await endTurn(previous, 'completed');
+ }
+
+ async function newStep(turn: TurnTrace, at: { stepIndex: number; attempt: number }): Promise<Step | undefined> {
+ const op = await started(turn);
+ if (!op || op.finished) return undefined;
+ await endSteps(turn, undefined, (s) => s.running === 0 && s.open === 0);
+ const step: Step = { op: await op.attempt(at), asked: [], running: 0, open: 0 };
+ turn.steps.push(step);
+ return step;
+ }
+
+ /** A step for a model call made outside a `model` effect (a CLI's request through the Gateway proxy). */
+ async function requestStep(turn: TurnTrace): Promise<Step | undefined> {
+ if (!turn.drive) {
+ const drive = (turn.drive = streams.nextDrive(ctx.runId, turn.submission.id));
+ // Not recorded: a later step asks again.
+ drive.catch(() => turn.drive === drive && (turn.drive = undefined));
+ }
+ return newStep(turn, { stepIndex: turn.requests++, attempt: await turn.drive });
+ }
+
+ /** Watches a recorded model call: the step's tool calls are the ones its response asks for. */
+ function watch(model: ModelOperation, step: Step): ModelOperation {
+ step.running++;
+ let settled = false;
+ const settle = (result?: ModelResult) => {
+ if (settled) return;
+ settled = true;
+ step.running--;
+ for (const part of result?.content ?? []) {
+ if (part.type === 'tool-call') step.asked.push({ id: part.callId, name: part.toolName, args: canonical(part.input) });
+ }
+ };
+ return new Proxy(model, {
+ get(target, key, receiver) {
+ if (key === 'complete') return (result?: Parameters<ModelOperation['complete']>[0]) => (settle(result?.result ?? result?.model), target.complete(result));
+ if (key === 'fail') return (error: unknown) => (settle(), target.fail(error));
+ const value = Reflect.get(target, key, receiver);
+ return typeof value === 'function' ? value.bind(target) : value;
+ },
+ });
+ }
+
+ async function modelCall(options: ModelOptions): Promise<TracedModelCall | undefined> {
+ const slot = slots.getStore();
+ const inEffect = slot?.drive === drive;
+ const turn = inEffect ? slot.turn : current;
+ if (!turn) return undefined;
+ const step = inEffect ? await (slot.step ??= newStep(turn, slot)) : await requestStep(turn);
+ if (!step) return undefined;
+ return { model: watch(await step.op.modelCall(options), step), attempt: step.op };
+ }
+
+ /** The tool call's id as the model gave it, so Agent Runs joins the call in the reply with its execution. */
+ function callIdOf(turn: TurnTrace, key: string, name: string, input: unknown): string {
+ const fromKey = key.startsWith('tool:') && !key.slice(5).includes(':') ? key.slice(5).split('@')[0]! : undefined;
+ const args = canonical(input);
+ for (const step of [...turn.steps].reverse()) {
+ const index = [
+ (c: Step['asked'][number]) => c.id === fromKey,
+ (c: Step['asked'][number]) => fromKey === undefined && c.name === name && c.args === args,
+ (c: Step['asked'][number]) => fromKey === undefined && c.name === name,
+ ].reduce((found, test) => (found >= 0 ? found : step.asked.findIndex(test)), -1);
+ if (index >= 0) return step.asked.splice(index, 1)[0]!.id;
+ }
+ return fromKey ?? key;
+ }
+
+ /** The tool call's operation: one an earlier drive started, else a new one under the step that asked for it. */
+ async function openTool(key: string, effect: EffectOptions): Promise<{ tool: ToolOperation; step?: Step } | undefined> {
+ const turn = current;
+ const op = turn && (await started(turn));
+ if (!turn || !op || op.finished) return undefined;
+ const name = effect.name.slice('tool.'.length);
+ const callId = callIdOf(turn, key, name, effect.input);
+ const found = op.findTool(callId);
+ if (found) return { tool: found };
+ const step = turn.steps.at(-1) ?? (await requestStep(turn));
+ const tool = await step?.op.tool({ callId, name, arguments: effect.input });
+ return tool && { tool, step };
+ }
+
+ async function traceTool<T>(key: string, effect: EffectOptions, execute: () => Promise<T>): Promise<T> {
+ // Tracing never fails a tool call: one it cannot record runs untraced.
+ const traced = await openTool(key, effect).catch(() => undefined);
+ if (!traced) return execute();
+ const { tool, step } = traced;
+ if (step) step.open++;
+ let value: T;
+ let entered = false;
+ try {
+ value = await tool.run(() => { entered = true; return execute(); });
+ } catch (error) {
+ if (!entered) {
+ if (step) step.open--;
+ await tool.complete({ outcome: 'abandoned' }).catch(() => {});
+ return execute();
+ }
+ // A call the drive stopped under, or handed off, goes on in a later drive: its span stays open for it.
+ if (!(error instanceof Parked) && !ctx.signal.aborted) {
+ if (step) step.open--;
+ await tool.fail(error).catch(() => {});
+ }
+ throw error;
+ }
+ if (step) step.open--;
+ await tool.complete({ outcome: 'completed', output: value }).catch(() => {});
+ return value;
+ }
+
+ /** A tool call an earlier drive started, which the kernel settled without running it again (interrupted, or parked work collected). */
+ async function settleOpenTool(key: string, effect: EffectOptions, outcome: { value?: unknown; error?: unknown }): Promise<void> {
+ const turn = current;
+ const op = turn && (await saved(turn));
+ if (!turn || !op) return;
+ const tool = op.findTool(callIdOf(turn, key, effect.name.slice('tool.'.length), effect.input));
+ if (!tool) return;
+ if (outcome.error !== undefined) await tool.fail(outcome.error);
+ else await tool.complete({ outcome: 'completed', output: outcome.value });
+ }
+
+ /** A `model` effect of a harness whose model calls are its effects: one call, from what the effect records. */
+ async function effectModelCall<T>(step: Step | undefined, effect: EffectOptions, execute: () => Promise<T>): Promise<T> {
+ if (!step) return execute();
+ const id = String(record(effect.input).model ?? 'unknown');
+ const slash = id.indexOf('/');
+ let model: ModelOperation;
+ try {
+ model = watch(await step.op.modelCall({ provider: slash > 0 ? id.slice(0, slash) : 'unknown', modelId: slash > 0 ? id.slice(slash + 1) : id }), step);
+ } catch { return execute(); }
+ let value: T;
+ let entered = false;
+ try {
+ value = await model.run(() => { entered = true; return execute(); });
+ } catch (error) {
+ if (!entered) {
+ await model.complete({ outcome: 'abandoned' }).catch(() => {});
+ return execute();
+ }
+ await model.fail(error).catch(() => {});
+ throw error;
+ }
+ try {
+ const output = record(value);
+ await model.complete({
+ outcome: 'completed',
+ result: {
+ finishReason: typeof output.finishReason === 'string' ? output.finishReason : 'unknown',
+ usage: {},
+ content: typeof value === 'string' ? [{ type: 'text', text: value }] : undefined,
+ },
+ });
+ } catch { /* Recording a result must not change the model effect's outcome. */ }
+ return value;
+ }
+
+ const tracing: DriveTracing = { modelCall: (o) => modelCall(o).catch(() => undefined) };
+ const traced: DriveContext = {
+ ...ctx,
+ tracing,
+ async effect(key, effect, fn) {
+ await place(effect.placed).catch(() => {});
+ const model = effect.name === 'model';
+ const tool = effect.name.startsWith('tool.');
+ if ((!model && !tool) || !current) return ctx.effect(key, effect, fn);
+ const turn = current;
+ let ran = false;
+ const body = async (io: Parameters<typeof fn>[0]) => {
+ ran = true;
+ if (tool) return traceTool(key, effect, () => fn(io));
+ const slot: Slot = { drive, turn, ...stepOf(ctx.state(), turn.submission.id, key) };
+ if (!self) slot.step = newStep(turn, slot).catch(() => undefined);
+ return slots.run(slot, async () => (self ? fn(io) : effectModelCall(await slot.step, effect, () => fn(io))));
+ };
+ const result = ctx.effect(key, effect, body);
+ if (tool) {
+ void result.then(
+ (value) => (ran ? undefined : settleOpenTool(key, effect, { value })),
+ (error: unknown) => (ran ? undefined : settleOpenTool(key, effect, { error }))
+ ).catch(() => {});
+ }
+ return result;
+ },
+ };
+
+ let outcome: 'completed' | 'failed' | 'cancelled' | 'running' = 'completed';
+ let reason: unknown;
+ try {
+ await harness.drive(traced);
+ } catch (error) {
+ reason = error;
+ throw error;
+ } finally {
+ // ctx.deadline ends agent work, not cleanup: reserve a fixed, bounded flush window after a budget yield.
+ streams.setDeadline(ctx.runId, undefined);
+ const state = ctx.state();
+ const stop = reason instanceof Fatal ? reason : ctx.signal.aborted ? ctx.signal.reason : reason;
+ outcome =
+ state.status === 'cancelled' ? 'cancelled'
+ : stop instanceof Fatal || state.status === 'failed' ? 'failed'
+ : stop !== undefined ? 'running'
+ : 'completed';
+ try {
+ if (current) await endTurn(current, outcome, outcome === 'cancelled' ? undefined : (stop ?? (state.failure ? Object.assign(new Error(state.failure.message), { name: 'RunFailed' }) : undefined)));
+ } catch {
+ // Tracing never fails a drive.
+ }
+ await streams.flush(ctx.runId);
+ streams.forget(ctx.runId);
+ }
+}
+
+/**
+ * A `model` effect's place among its turn's model calls, and its attempt
+ * (a retry after a crash is the same step again): the same in every drive,
+ * so a step an earlier drive started is the same step.
+ */
+function stepOf(state: SessionState, turnId: string, key: string): { stepIndex: number; attempt: number } {
+ const prompts = new Set(state.submissions.filter(isPrompt).map((s) => s.id));
+ const seen = new Set<string>();
+ let turn: string | undefined;
+ for (const effect of state.effectOrder) {
+ const placed = effect.placed.find((id) => prompts.has(id));
+ if (placed) turn = placed;
+ if (effect.name !== 'model' || turn !== turnId || seen.has(effect.key)) continue;
+ if (effect.key === key) break;
+ seen.add(effect.key);
+ }
+ return { stepIndex: seen.size, attempt: Math.max(0, (state.effects.get(key)?.attempt ?? 1) - 1) };
+}
+
+/** Arguments as comparable text: a model may send them as a JSON string or an object. */
+function canonical(args: unknown): string {
+ let value = args;
+ if (typeof args === 'string') {
+ try {
+ value = JSON.parse(args);
+ } catch {
+ return args;
+ }
+ }
+ const sort = (v: unknown): unknown =>
+ Array.isArray(v) ? v.map(sort)
+ : v !== null && typeof v === 'object' ? Object.fromEntries(Object.entries(v).sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0)).map(([k, x]) => [k, sort(x)]))
+ : v;
+ return JSON.stringify(sort(value)) ?? '';
+}
diff --git a/packages/durable-harness/src/instrumentation/otel.ts b/packages/durable-harness/src/instrumentation/otel.ts
index a9ddc8a..789e1b2 100644
--- a/packages/durable-harness/src/instrumentation/otel.ts
+++ b/packages/durable-harness/src/instrumentation/otel.ts
@@ -1,76 +1,71 @@
-import { createHash, randomBytes } from 'node:crypto';
-import { ROOT_CONTEXT, createContextKey, SpanKind, SpanStatusCode, trace, type Attributes, type Span } from '@opentelemetry/api';
-import type { BasicTracerProvider, ReadableSpan, SpanProcessor } from '@opentelemetry/sdk-trace-base';
-import { INSTRUMENTATION, type InstrumentationRuntime, type TraceOperation, type TraceScope } from 'harness-world/instrumentation';
-// Fatal from its own module: from the kernel's index it would load the driver.
-import { Fatal } from 'harness-world/errors';
-import type { DriveContext, Harness } from 'harness-world';
+import { AsyncLocalStorage } from 'node:async_hooks';
+import { ROOT_CONTEXT, context, type Context, type ContextManager } from '@opentelemetry/api';
+import type { BasicTracerProvider, SpanProcessor } from '@opentelemetry/sdk-trace-base';
+import type { AgentRun, CaptureDecision, TraceErrorHandler } from '@vercel/agent-runs';
import type { World } from '@workflow/world';
+import { AGENT_RUNS, type AgentRunsHook, type SessionTracing, type TraceAudience } from 'harness-world/agent-runs';
+import { VERSION } from 'harness-world/names';
+import { TraceStreams } from './checkpoints.ts';
+import { traceDrive } from './drive.ts';
+import { vercelSpanProcessor } from './vercel.ts';
+
+export type { TraceAudience } from 'harness-world/agent-runs';
+export type { CaptureDecision } from '@vercel/agent-runs';
-export type Audience = 'public' | 'private' | 'unknown';
-export interface SpanExportContext {
- readonly audience: Audience;
- readonly name: string;
- readonly traceId: string;
- readonly spanId: string;
- readonly attributes: Readonly<Attributes>;
-}
-export type SpanExportDecision = { readonly emit: boolean } | { readonly redact: true; readonly inputs?: boolean; readonly outputs?: boolean };
-export interface SpanExportPolicy {
- readonly span?: (span: SpanExportContext) => SpanExportDecision;
- readonly attribute?: (input: { key: string; value: unknown; span: SpanExportContext }) =>
- { readonly emit: boolean } | { readonly replace: true; readonly value: NonNullable<Attributes[string]> };
-}
export interface AgentRunsOptions {
- readonly exportPolicy?: SpanExportPolicy;
- /** Default for sessions without an explicit audience. Defaults to unknown (content hidden). */
- readonly audience?: Audience;
+ /** The audience of a session that records none (`traceAudience`). Default `unknown`. */
+ readonly audience?: TraceAudience;
+ /**
+ * What a session's spans record, by its audience. Default: model and tool
+ * inputs and outputs for `public`, metadata only (models, tools, timing,
+ * usage) for `private` and `unknown`. Content a decision declines is never
+ * recorded, checkpointed or exported.
+ */
+ readonly capture?: (audience: TraceAudience) => CaptureDecision;
+ /** `service.name`. Default `durable-harness`. */
readonly serviceName?: string;
- /** Additional destinations, with the same content policy applied. */
+ /** More destinations beside Agent Runs, with the same spans. */
readonly spanProcessors?: readonly SpanProcessor[];
+ /** Every tracing failure, which never fails agent work. Default: a warning. */
+ readonly onError?: TraceErrorHandler;
}
-export interface AgentRunsIntegration {
- /** Call from the host's instrumentation register hook, once per process. */
+
+export interface AgentRuns {
+ /** Start tracing this process's sessions. Call once per process, from the host's instrumentation hook. */
register(): void;
+ /** Export ended spans and settle bounded, best-effort checkpoint writes. */
forceFlush(): Promise<void>;
+ shutdown(): Promise<void>;
}
-/**
- * OpenTelemetry's SDK, which records and serializes the spans, at the versions
- * this module is tested with. Optional peer dependencies, which nothing but
- * `agentRuns()` loads: the harnesses emit through `@opentelemetry/api` alone
- * (a dependency), whose spans are no-ops until a provider is registered. A
- * test keeps these equal to package.json's.
- */
+const CONTENT: CaptureDecision = { emit: true, recordInputs: true, recordOutputs: true };
+const METADATA: CaptureDecision = { emit: true, recordInputs: false, recordOutputs: false };
+const defaultCapture = (audience: TraceAudience) => (audience === 'public' ? CONTENT : METADATA);
+
+/** Optional tracing peers, loaded only by this entrypoint. */
const OTEL_SDK_PINS = {
'@opentelemetry/sdk-trace-base': '2.2.0',
'@opentelemetry/resources': '2.2.0',
'@opentelemetry/otlp-transformer': '0.208.0',
+ '@vercel/agent-runs': '0.0.1',
} as const;
-/** The install line for OpenTelemetry's SDK. */
const OTEL_SDK_INSTALL = `pnpm add ${Object.entries(OTEL_SDK_PINS).map(([name, version]) => `${name}@${version}`).join(' ')}`;
-/**
- * The SDK, loaded when this module is, or why it isn't there. Any other
- * failure to load it fails the import, as a static import would.
- */
-const sdk = await Promise.all([
- import('@opentelemetry/sdk-trace-base'),
- import('@opentelemetry/resources'),
- import('@opentelemetry/otlp-transformer'),
-]).then(
- ([traceBase, resources, transformer]) => ({
+const sdk = await Promise.all([import('@opentelemetry/sdk-trace-base'), import('@opentelemetry/resources'), import('@opentelemetry/otlp-transformer'), import('@vercel/agent-runs')]).then(
+ ([traceBase, resources, transformer, agentRuns]) => ({
BasicTracerProvider: traceBase.BasicTracerProvider,
resourceFromAttributes: resources.resourceFromAttributes,
JsonTraceSerializer: transformer.JsonTraceSerializer,
+ AgentSpanIdGenerator: agentRuns.AgentSpanIdGenerator,
+ createAgentRun: agentRuns.createAgentRun,
+ otelTelemetry: agentRuns.otelTelemetry,
}),
(error: unknown) => {
const missing = missingPackage(error);
if (!missing) throw error;
- return { missing: new Error(`durable-harness/instrumentation/otel: agentRuns() exports spans with OpenTelemetry's SDK, optional peer dependencies of durable-harness, and ${missing} is not installed. Install them: ${OTEL_SDK_INSTALL}`, { cause: error }) };
+ return { missing: new Error(`durable-harness/instrumentation/otel: agentRuns() needs its optional tracing peers, and ${missing} is not installed. Install them: ${OTEL_SDK_INSTALL}`, { cause: error }) };
}
);
-/** Which of the SDK's packages `error` says could not be found, if it says so (on it or its causes). */
function missingPackage(error: unknown): string | undefined {
for (let e = error, depth = 0; e && typeof e === 'object' && depth < 5; e = (e as { cause?: unknown }).cause, depth++) {
const { code, message } = e as { code?: unknown; message?: unknown };
@@ -80,414 +75,150 @@ function missingPackage(error: unknown): string | undefined {
}
return undefined;
}
-function requireSdk() {
- if ('missing' in sdk) throw sdk.missing;
- return sdk;
-}
-const REPORTER = createContextKey('durable-harness.report-spans');
-type Reporter = (payload: unknown) => void;
-interface ReportedSpan { __durableReporter?: Reporter; __durableMetadata?: (span: ReadableSpan) => void }
-function requestReporter(): Reporter | undefined {
- const reader = (globalThis as Record<symbol, { get?: () => { telemetry?: { reportSpans?: Reporter } } } | undefined>)[Symbol.for('@vercel/request-context')];
- try {
- const telemetry = reader?.get?.()?.telemetry;
- return telemetry?.reportSpans?.bind(telemetry);
- } catch { return undefined; }
+/** The async context the library's spans nest by, for a process whose app registered no OpenTelemetry. */
+class AsyncContextManager implements ContextManager {
+ private readonly storage = new AsyncLocalStorage<Context>();
+ active(): Context {
+ return this.storage.getStore() ?? ROOT_CONTEXT;
+ }
+ with<A extends unknown[], F extends (...args: A) => ReturnType<F>>(ctx: Context, fn: F, thisArg?: ThisParameterType<F>, ...args: A): ReturnType<F> {
+ return this.storage.run(ctx, () => fn.apply(thisArg, args));
+ }
+ bind<T>(ctx: Context, target: T): T {
+ if (typeof target !== 'function') return target;
+ const manager = this;
+ return function (this: unknown, ...args: unknown[]) {
+ return manager.with(ctx, () => (target as (...a: unknown[]) => unknown).apply(this, args));
+ } as T;
+ }
+ enable(): this {
+ return this;
+ }
+ disable(): this {
+ this.storage.disable();
+ return this;
+ }
}
-const INPUTS = new Set(['agent.session.title', 'agent.channel.delivery.input', 'gen_ai.input.messages', 'gen_ai.system_instructions', 'gen_ai.tool.definitions', 'gen_ai.tool.call.arguments', 'ai.prompt', 'ai.prompt.tools', 'ai.prompt.toolChoice']);
-const OUTPUTS = new Set(['gen_ai.output.messages', 'gen_ai.tool.call.result', 'ai.response.text', 'ai.response.reasoning', 'ai.response.toolCalls', 'ai.response.tool_calls', 'ai.toolCall.args', 'ai.toolCall.result']);
-const hash = (value: string) => createHash('sha256').update(value).digest('hex');
-const json = (value: unknown): string | undefined => {
- try { const s = JSON.stringify(value); return s && s.length <= 64_000 ? s : undefined; } catch { return undefined; }
-};
-const record = (v: unknown): Record<string, unknown> => v !== null && typeof v === 'object' ? v as Record<string, unknown> : {};
-const audienceOf = (v: unknown): Audience => v === 'public' || v === 'private' ? v : 'unknown';
/**
- * Vercel's Agent Runs destination. Importing or declaring it performs no I/O.
- * Without OpenTelemetry's SDK installed (optional peer dependencies) it
- * throws, naming the install line.
+ * Vercel Agent Runs for this process's sessions, with `@vercel/agent-runs`:
+ * every turn a session runs, its model calls and tool calls, with usage. A
+ * turn that goes on in a later invocation (out of time, a crash, a wake)
+ * stays one turn: its checkpoint is kept with the session. Declaring it does
+ * nothing; `register()` starts it. Its tracer provider is its own, so the
+ * app's OpenTelemetry setup, if any, is left as it is.
+ * Tracing requires Node.js 24 and its optional peers; other entrypoints support Node.js 22.
*/
-export function agentRuns(options: AgentRunsOptions = {}): AgentRunsIntegration {
- const { BasicTracerProvider: TracerProvider, resourceFromAttributes, JsonTraceSerializer } = requireSdk();
+export function agentRuns(options: AgentRunsOptions = {}): AgentRuns {
+ if ('missing' in sdk) throw sdk.missing;
+ const { BasicTracerProvider, resourceFromAttributes, JsonTraceSerializer, AgentSpanIdGenerator, createAgentRun, otelTelemetry } = sdk;
+ const onError: TraceErrorHandler = (error, at) => {
+ try {
+ if (options.onError) void Promise.resolve(options.onError(error, at)).catch(() => {});
+ else console.warn(`[durable-harness] Agent Runs: ${at.phase} failed`, error instanceof Error ? error.message : error);
+ } catch { /* Diagnostics must not fail agent work. */ }
+ };
+ const capture = (audience: TraceAudience) => {
+ try {
+ return options.capture?.(audience) ?? defaultCapture(audience);
+ } catch (error) {
+ onError(error, { phase: 'start' });
+ return METADATA;
+ }
+ };
+ const audience = options.audience ?? 'unknown';
let provider: BasicTracerProvider | undefined;
- let seed = '';
- const metadataWrites = new Set<Promise<void>>();
+ const worlds = new WeakMap<World, { run: AgentRun; streams: TraceStreams }>();
+ const live = new Set<WeakRef<TraceStreams>>();
+
return {
register() {
if (provider) return;
- const downstream = [vercelProcessor(JsonTraceSerializer), ...(options.spanProcessors ?? [])];
- provider = new TracerProvider({
+ const idGenerator = new AgentSpanIdGenerator();
+ provider = new BasicTracerProvider({
resource: resourceFromAttributes({ 'service.name': options.serviceName ?? 'durable-harness', 'agent.framework.name': 'durable-harness' }),
- idGenerator: {
- generateTraceId: () => seed || randomBytes(16).toString('hex'),
- generateSpanId: () => randomBytes(8).toString('hex'),
- },
- spanLimits: { attributeValueLengthLimit: 64_000, attributeCountLimit: 128 },
- spanProcessors: downstream.map(p => filteringProcessor(p, options.exportPolicy)),
+ idGenerator,
+ spanProcessors: [vercelSpanProcessor(JsonTraceSerializer, (error) => onError(error, { phase: 'complete' })), ...(options.spanProcessors ?? [])],
});
- // The deployed warehouse currently selects this scope explicitly. The
- // framework identity stays durable-harness; this is the v4 wire contract.
- const tracer = provider.getTracer('eve.agent', '4');
- const session = (sessionId: string, harness: string, turnId: string, input?: unknown, audience = audienceOf(options.audience), world?: World): TraceScope => {
- seed = hash(`durable-harness:${sessionId}`).slice(0, 32);
- const common: Attributes = {
- 'agent.framework.name': 'durable-harness', 'agent.name': harness,
- 'gen_ai.agent.name': harness, 'agent.run.id': sessionId, 'agent.run.type': 'session',
- 'gen_ai.conversation.id': sessionId, 'vercel.session_id': sessionId,
- 'agent.trace.schema.version': 4, 'agent.turn.id': turnId,
- 'agent.channel.audience': audience, 'agent.channel.kind': 'http',
- 'agent.session.origin': 'channel', 'agent.trace.content.input': true, 'agent.trace.content.output': true,
- };
- const report = requestReporter();
- const rootContext = report ? ROOT_CONTEXT.setValue(REPORTER, report) : ROOT_CONTEXT;
- const root = tracer.startSpan(`invoke_agent ${harness}`, { root: true, attributes: { ...common, 'gen_ai.operation.name': 'invoke_agent' } }, rootContext);
- (root as Span & ReportedSpan).__durableReporter = report;
- let metadataWrite: Promise<void> | undefined;
- if (world?.runs.experimentalSetAttributes) {
- (root as Span & ReportedSpan).__durableMetadata = (filtered) => {
- // Front still reads Eve's Workflow metadata for schema-4 content
- // visibility and discovery. These are compatibility tags, not
- // content storage or a claim that the harness framework is Eve.
- const visible = filtered.attributes['agent.trace.content.input'] === true
- && filtered.attributes['agent.trace.content.output'] === true;
- const title = filtered.attributes['agent.session.title'];
- const attributes: Record<string, string | null> = {
- '$eve.type': 'session', '$eve.is_otel_trace_enabled': 'true',
- '$eve.is_trace_content_visible': String(visible),
- '$eve.trace_id': filtered.spanContext().traceId, '$eve.trigger': 'http',
- '$eve.title': typeof title === 'string' ? title : null,
- 'agent.framework.name': 'durable-harness', 'agent.name': harness,
- };
- metadataWrite = Promise.resolve().then(() => world.runs.experimentalSetAttributes!(sessionId,
- Object.entries(attributes).map(([key, value]) => ({ key, value })), { allowReservedAttributes: true }
- )).then(() => {}, () => { console.warn('durable-harness: Agent Runs Workflow metadata export failed'); });
- metadataWrites.add(metadataWrite);
- void metadataWrite.then(() => metadataWrites.delete(metadataWrite!));
- };
+ context.setGlobalContextManager(new AsyncContextManager());
+ // Agent Runs reads spans of the `eve.agent` scope at schema version 4: the library writes the schema.
+ const telemetry = otelTelemetry({ provider, idGenerator, tracerName: 'eve.agent', tracerVersion: VERSION });
+ const forWorld = (world: World) => {
+ let traced = worlds.get(world);
+ if (!traced) {
+ const streams = new TraceStreams(world, (error) => onError(error, { phase: 'checkpoint' }));
+ traced = { streams, run: createAgentRun({ telemetry, checkpointer: streams.checkpointer, onError }) };
+ worlds.set(world, traced);
+ live.add(new WeakRef(streams));
}
- seed = '';
- root.addEvent('turn.started');
- const inputText = json(input);
- if (inputText) root.setAttribute('agent.channel.delivery.input', inputText);
- const title = typeof input === 'string' ? input : record(input).content;
- if (typeof title === 'string') root.setAttribute('agent.session.title', title.slice(0, 160));
- const parent = trace.setSpan(rootContext, root);
- const open = new Set<TraceOperation>();
- let closed = false;
- let stepIndex = 0;
- // The tool calls this turn's model responses asked for, not yet run.
- // A tool span takes its call's id, so Agent Runs shows the model's
- // call and its execution as one tool call.
- const asked: { id: string; name: string; args: string }[] = [];
- return {
- async flush() { await metadataWrite; },
- start(name, input, key) {
- const model = name === 'model';
- const tool = name.startsWith('tool.');
- const data = record(input);
- const requestData = record(data.requestBody ?? data.request);
- const requestModel = data.model ?? requestData.model;
- const modelId = typeof requestModel === 'string' ? gatewayModelId(requestModel) : 'unknown';
- const operation = model ? 'chat' : tool ? 'execute_tool' : 'step';
- const stepId = key ?? randomBytes(16).toString('hex');
- const step = tracer.startSpan('agent.step', { attributes: { ...common, 'agent.step.id': stepId, 'agent.step.index': stepIndex++, 'agent.step.attempt': 1, ...(model ? { 'agent.model.id': modelId } : {}) } }, parent);
- const span = tracer.startSpan(model ? `chat ${modelId}` : tool ? `execute_tool ${name.slice(5)}` : name, {
- kind: model ? SpanKind.CLIENT : SpanKind.INTERNAL,
- attributes: { ...common, 'gen_ai.operation.name': operation, ...(model ? { 'gen_ai.request.model': modelId } : {}), ...(tool ? { 'gen_ai.tool.name': name.slice(5), 'gen_ai.tool.call.id': toolCallId(asked, name.slice(5), input, stepId) } : {}) },
- }, trace.setSpan(parent, step));
- (step as Span & ReportedSpan).__durableReporter = report;
- (span as ReportedSpan).__durableReporter = report;
- if (model) {
- setJson(span, 'gen_ai.input.messages', messages(data.messages ?? data.appended ?? requestMessages(requestData)));
- if (requestData.system ?? requestData.instructions) setJson(span, 'gen_ai.system_instructions', requestData.system ?? requestData.instructions);
- if (requestData.tools) setJson(span, 'gen_ai.tool.definitions', requestData.tools);
- }
- else if (tool) setJson(span, 'gen_ai.tool.call.arguments', input);
- let ended = false;
- const handle: TraceOperation = { end(output, error) {
- if (ended) return;
- ended = true; open.delete(handle);
- if (model) {
- const result = modelResponse(output);
- const request = record(record(output).requestBody ?? data.requestBody ?? data.request);
- if (request.model) { const id = gatewayModelId(String(request.model)); span.setAttribute('gen_ai.request.model', id); step.setAttribute('agent.model.id', id); span.updateName(`chat ${id}`); }
- const prompt = requestMessages(request);
- if (prompt !== undefined) setJson(span, 'gen_ai.input.messages', messages(prompt));
- if (request.system ?? request.instructions) setJson(span, 'gen_ai.system_instructions', request.system ?? request.instructions);
- if (result.model) span.setAttribute('gen_ai.response.model', String(result.model));
- const reply = messages([result.message ?? result], 'assistant');
- setJson(span, 'gen_ai.output.messages', reply);
- for (const part of reply.flatMap(m => record(m).parts as unknown[] ?? [])) {
- const call = record(part);
- if (call.type === 'tool_call' && typeof call.id === 'string' && typeof call.name === 'string') asked.push({ id: call.id, name: call.name, args: canonical(call.arguments) });
- }
- usage(span, step, result.usage ?? record(result.message).usage);
- const gatewayCost = record(record(result.providerMetadata).gateway).gatewayCost;
- if (gatewayCost !== undefined && Number.isFinite(Number(gatewayCost))) {
- step.setAttribute('gen_ai.usage.gateway_cost', Number(gatewayCost));
- span.setAttribute('gen_ai.usage.gateway_cost', Number(gatewayCost));
- }
- } else if (tool) setJson(span, 'gen_ai.tool.call.result', output);
- if (error !== undefined) { fail(span, error); fail(step, error); }
- span.end(); step.end();
- } };
- open.add(handle);
- return handle;
- },
- end(error, requestedOutcome) {
- if (closed) return; closed = true;
- const outcome = requestedOutcome ?? (error === undefined ? 'completed' : 'failed');
- for (const operation of open) operation.end(undefined, outcome === 'failed' ? error : undefined);
- root.setAttribute('agent.turn.outcome', outcome);
- root.addEvent(`turn.${outcome}`);
- if (error !== undefined && outcome === 'failed') fail(root, error);
- root.end();
- },
- };
+ return traced;
};
- const runtime: InstrumentationRuntime = {
- session,
- async drive(harness: Harness, ctx: DriveContext) {
- let submission = ctx.pending().find(s => s.text !== undefined)
- ?? ctx.state().submissions.filter(s => s.text !== undefined).at(-1);
- let scope: TraceScope | undefined;
- const priorScopes: TraceScope[] = [];
- let currentTurn: string | undefined;
- const audience = audienceOf(record(ctx.config).traceAudience ?? options.audience);
- const finish = (error?: unknown) => {
- const state = ctx.state();
- const reason = error instanceof Fatal ? error : ctx.signal.aborted ? ctx.signal.reason : error;
- const name = record(reason).name;
- const outcome = state.status === 'cancelled' ? 'cancelled'
- : reason instanceof Fatal || state.status === 'failed' ? 'failed'
- : name === 'Yield' || name === 'Restart' || ctx.signal.aborted ? 'running'
- : reason !== undefined ? 'failed' : 'completed';
- scope?.end(reason, outcome);
- };
- const bridge: TraceScope = {
- start(name, input, key) {
- if (!submission) return { end() {} };
- if (scope && currentTurn !== submission.id) { scope.end(); priorScopes.push(scope); }
- if (!scope || currentTurn !== submission.id) {
- currentTurn = submission.id;
- scope = session(ctx.runId, harness.name, submission.id, submission.text, audience, ctx.world);
- }
- return scope.start(name, input, key);
- },
- end: (error, outcome) => scope?.end(error, outcome),
- };
- const wrapped: DriveContext = {
- ...ctx, instrumentation: bridge,
- effect(key, effect, fn) {
- // Placement follows durable turn identity, including memoized placement.
- // Steers belong to the open turn; a fresh prompt starts another one.
- const placed = ctx.state().submissions.find(s => effect.placed?.includes(s.id) && s.kind !== 'steer' && s.text !== undefined);
- if (placed) submission = placed;
- return ctx.effect(key, effect, async io => {
- // Process model proxy callbacks own their model spans. The
- // synthetic chaos effect only records crash/recovery facts.
- const proxyModel = effect.name === 'model' && (typeof record(effect.input).method === 'string' || record(effect.input).instrumentation === 'adapter');
- if (proxyModel || (effect.name !== 'model' && !effect.name.startsWith('tool.'))) return fn(io);
- const op = bridge.start(effect.name, effect.input, key);
- try { const result = await fn(io); op.end(result); return result; }
- catch (error) { op.end(undefined, ctx.signal.aborted ? undefined : error); throw error; }
+ const hook: AgentRunsHook = {
+ capture: given => capture(given ?? audience),
+ onError,
+ drive: (harness, ctx) => {
+ const { run, streams } = forWorld(ctx.world);
+ return traceDrive({ run, streams, audience, capture, version: VERSION }, harness, ctx);
+ },
+ session: ({ world, runId, agentName, audience: given }): SessionTracing => {
+ const { run, streams } = forWorld(world);
+ const decision = capture(given ?? audience);
+ 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. */
+ const steps = new Map<string, { drive: Promise<number>; next: number }>();
+ return {
+ async turn({ turnId, sequence, title }) {
+ streams.forget(runId, turnId);
+ if (await streams.finished(runId, turnId)) return undefined;
+ sequence ??= (await run.resume({ identity: identity(turnId) })) ? 0 : await streams.nextSequence(runId);
+ return run.turn({
+ identity: identity(turnId),
+ agentName,
+ sequence,
+ framework: { name: 'durable-harness', version: VERSION },
+ capture: decision,
+ channel: { kind: 'http', origin: 'channel' },
+ attributes: { 'agent.channel.audience': given ?? audience, ...(title && decision.recordInputs ? { 'agent.session.title': title.slice(0, 160) } : {}) },
});
},
+ async resume(turnId) {
+ streams.forget(runId, turnId);
+ if (!(await run.resume({ identity: identity(turnId) }))) return undefined;
+ // resume() restores the saved permissions; turn() narrows the whole tree to today's decision.
+ const turn = await run.turn({ identity: identity(turnId), sequence: 0, capture: decision });
+ turn.attributes({ 'agent.channel.audience': given ?? audience });
+ return turn;
+ },
+ async step(turn, turnId) {
+ let numbered = steps.get(turnId);
+ 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));
+ }
+ const stepIndex = numbered.next++;
+ return turn.attempt({ stepIndex, attempt: await numbered.drive });
+ },
+ flush: () => streams.flush(runId),
};
- try { await harness.drive(wrapped); finish(); }
- catch (error) { finish(error); throw error; }
- finally { await Promise.all([...priorScopes, ...(scope ? [scope] : [])].map(s => s.flush?.())); }
},
};
- (globalThis as { [INSTRUMENTATION]?: InstrumentationRuntime })[INSTRUMENTATION] = runtime;
+ (globalThis as { [AGENT_RUNS]?: AgentRunsHook })[AGENT_RUNS] = hook;
},
- async forceFlush() { await provider?.forceFlush(); await Promise.all([...metadataWrites]); },
- };
-}
-
-/** Arguments as comparable text: a model may send them as a JSON string or an object. */
-function canonical(args: unknown): string {
- let value = args;
- if (typeof args === 'string') { try { value = JSON.parse(args); } catch { return args; } }
- const sort = (v: unknown): unknown => Array.isArray(v) ? v.map(sort)
- : v !== null && typeof v === 'object' ? Object.fromEntries(Object.entries(v).sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0).map(([k, x]) => [k, sort(x)])) : v;
- return JSON.stringify(sort(value)) ?? '';
-}
-/**
- * A tool span's `gen_ai.tool.call.id`: the id the model gave the call, so
- * Agent Runs joins the call in the model's reply with its execution. Most
- * harnesses key a tool effect `tool:<call id>`; the fx kernel keys it by
- * position and input, and pi-durable by its task, so a call the model asked
- * for this turn is found by its id, else by name and arguments, else by name.
- * Without one, the key (less a `tool:` prefix).
- */
-function toolCallId(asked: { id: string; name: string; args: string }[], name: string, input: unknown, key: string): string {
- const fromKey = key.startsWith('tool:') ? key.slice(5).split('@')[0]! : key;
- const args = canonical(input);
- const index = [
- (c: typeof asked[number]) => c.id === fromKey,
- (c: typeof asked[number]) => c.name === name && c.args === args,
- (c: typeof asked[number]) => c.name === name,
- ].reduce((found, test) => found >= 0 ? found : asked.findIndex(test), -1);
- if (index < 0) return fromKey;
- return asked.splice(index, 1)[0]!.id;
-}
-/** pi-ai names a Gateway model `vercel-ai-gateway/<id>`; every other harness, and the Gateway, name it `<id>`. */
-function gatewayModelId(id: string): string { return id.startsWith('vercel-ai-gateway/') ? id.slice('vercel-ai-gateway/'.length) : id; }
-function setJson(span: Span, key: string, value: unknown) { const s = json(value); if (s !== undefined) span.setAttribute(key, s); }
-function fail(span: Span, error: unknown) { span.setStatus({ code: SpanStatusCode.ERROR, message: error instanceof Error ? error.message : String(error) }); }
-function requestMessages(request: Record<string, unknown>): unknown { return request.messages ?? request.input ?? request.prompt; }
-function messages(input: unknown, fallbackRole = 'user'): unknown[] {
- if (typeof input === 'string') input = [{ role: fallbackRole, content: input }];
- if (!Array.isArray(input)) return [];
- return input.map(m => {
- const v = record(m);
- if (v.type === 'function_call') return { role: 'assistant', parts: [{ type: 'tool_call', id: v.call_id, name: v.name, arguments: v.arguments }] };
- if (v.type === 'function_call_output') return { role: 'tool', parts: [{ type: 'tool_call_response', id: v.call_id, response: v.output }] };
- const content = v.content ?? v.text;
- const parts = typeof content === 'string' ? [{ type: 'text', content }] : Array.isArray(content) ? content.map(p => {
- const part = record(p);
- if (part.type === 'text' || part.type === 'input_text' || part.type === 'output_text') return { type: 'text', content: part.text ?? part.content };
- if (part.type === 'toolCall' || part.type === 'tool-call' || part.type === 'tool_use') return { type: 'tool_call', id: part.id ?? part.toolCallId, name: part.name ?? part.toolName, arguments: part.arguments ?? part.input ?? part.args };
- if (part.type === 'tool-result' || part.type === 'tool_result') {
- const output = part.output ?? part.result ?? part.content;
- return { type: 'tool_call_response', id: part.toolCallId ?? part.tool_use_id, response: record(output).value ?? output };
- }
- return part;
- }) : [];
- return { role: v.role === 'toolResult' ? 'tool' : v.role ?? fallbackRole, parts };
- });
-}
-function usage(span: Span, step: Span, input: unknown) {
- const u = record(input);
- const cacheRead = u.cacheRead ?? u.cacheReadTokens ?? u.cache_read_input_tokens ?? record(u.inputTokens).cacheRead ?? record(u.input_tokens_details).cached_tokens ?? record(u.prompt_tokens_details).cached_tokens;
- const cacheWrite = u.cacheWrite ?? u.cacheWriteTokens ?? u.cache_creation_input_tokens ?? record(u.inputTokens).cacheWrite;
- // Pi/Anthropic report uncached input separately; Agent Runs subtracts
- // cache tokens from the canonical inclusive input count.
- const inputTokens = u.input ?? record(u.inputTokens).total ?? u.inputTokens ?? u.input_tokens ?? u.prompt_tokens;
- const inclusiveInput = typeof inputTokens === 'number' && (typeof u.input === 'number' || typeof u.cache_read_input_tokens === 'number' || typeof u.cache_creation_input_tokens === 'number')
- ? inputTokens + (typeof cacheRead === 'number' ? cacheRead : 0) + (typeof cacheWrite === 'number' ? cacheWrite : 0) : inputTokens;
- const fields: [string, unknown][] = [
- ['input_tokens', inclusiveInput],
- ['output_tokens', u.output ?? record(u.outputTokens).total ?? u.outputTokens ?? u.output_tokens ?? u.completion_tokens],
- ['cache_read_tokens', cacheRead],
- ['cache_write_tokens', cacheWrite],
- ['reasoning_tokens', u.reasoningTokens ?? record(u.outputTokens).reasoning ?? record(u.output_tokens_details).reasoning_tokens ?? record(u.completion_tokens_details).reasoning_tokens],
- ];
- // The model span carries the same usage in gen_ai's names (the inclusive
- // input and its cached parts), so Agent Runs reads one usage from either.
- const genAi: Record<string, string> = { input_tokens: 'input_tokens', output_tokens: 'output_tokens', cache_read_tokens: 'cache_read.input_tokens', cache_write_tokens: 'cache_write.input_tokens' };
- for (const [key, value] of fields) if (typeof value === 'number' && Number.isFinite(value)) {
- step.setAttribute(`agent.usage.${key}`, value);
- if (genAi[key]) span.setAttribute(`gen_ai.usage.${genAi[key]}`, value);
- }
- const cost = record(u.cost).total;
- if (typeof cost === 'number') { step.setAttribute('gen_ai.usage.cost', cost); span.setAttribute('gen_ai.usage.cost', cost); }
-}
-
-/** Filter a destination's copy, including status and events; never mutate a shared span. */
-export function filteringProcessor(downstream: SpanProcessor, policy?: SpanExportPolicy): SpanProcessor {
- return {
- onStart(span, ctx) { try { downstream.onStart(span, ctx); } catch { /* Observability cannot reject agent work. */ } }, forceFlush: () => downstream.forceFlush(), shutdown: () => downstream.shutdown(),
- onEnd(span) {
- const sc = span.spanContext();
- const context: SpanExportContext = { ...sc, name: span.name, attributes: { ...span.attributes }, audience: audienceOf(span.attributes['agent.channel.audience']) };
- let decision: SpanExportDecision;
- try { decision = policy?.span?.(context) ?? (context.audience === 'public' ? { emit: true } : { redact: true, inputs: true, outputs: true }); }
- catch { return; }
- if (!decision || typeof decision !== 'object' || ('emit' in decision && 'redact' in decision)) return;
- if ('emit' in decision ? decision.emit !== true : decision.redact !== true || (!decision.inputs && !decision.outputs)) return;
- const inputs = 'redact' in decision && decision.inputs === true;
- const outputs = 'redact' in decision && decision.outputs === true;
- const attributes: Attributes = {};
- for (const [key, value] of Object.entries(span.attributes)) {
- if ((inputs && INPUTS.has(key)) || (outputs && OUTPUTS.has(key))) continue;
- try {
- const d = policy?.attribute?.({ key, value, span: context }) ?? { emit: true };
- if ('replace' in d && d.replace === true) attributes[key] = d.value;
- else if ('emit' in d && d.emit === true) attributes[key] = value;
- } catch { /* Attribute policies fail closed. */ }
- }
- if (inputs) attributes['agent.trace.content.input'] = false;
- if (outputs) attributes['agent.trace.content.output'] = false;
- try { downstream.onEnd({ ...span, spanContext: () => sc, attributes,
- status: outputs ? { code: span.status.code } : { ...span.status },
- events: outputs ? span.events.filter(e => e.name !== 'exception').map(e => ({ ...e, attributes: undefined })) : span.events,
- } as ReadableSpan); } catch { /* Observability cannot reject agent work. */ }
+ async forceFlush() {
+ await Promise.all([...live].map((reference) => {
+ const streams = reference.deref();
+ if (streams) return streams.flush();
+ live.delete(reference);
+ }));
+ await provider?.forceFlush();
},
- };
-}
-function vercelProcessor(JsonTraceSerializer: typeof import('@opentelemetry/otlp-transformer').JsonTraceSerializer): SpanProcessor {
- return {
- onStart(span, ctx) { (span as Span & ReportedSpan).__durableReporter = ctx.getValue(REPORTER) as Reporter | undefined; }, forceFlush: async () => {}, shutdown: async () => {},
- onEnd(span) {
- (span as ReadableSpan & ReportedSpan).__durableMetadata?.(span);
- const report = (span as ReadableSpan & ReportedSpan).__durableReporter ?? requestReporter();
- if (!report) return;
- try {
- const bytes = JsonTraceSerializer.serializeRequest([span]);
- if (bytes) report(JSON.parse(new TextDecoder().decode(bytes)));
- } catch { console.warn('durable-harness: Agent Runs span export failed'); }
+ async shutdown() {
+ await this.forceFlush();
+ await provider?.shutdown();
},
};
}
-
-function modelResponse(output: unknown): Record<string, unknown> {
- const result = record(output);
- const body = result.responseBody ?? result.body;
- if (typeof body !== 'string') return result;
- let text = '';
- let model: string | undefined;
- const parts: unknown[] = [];
- const anthropicTools = new Map<number, { part: Record<string, unknown>; json: string }>();
- let providerMetadata: unknown;
- const usage: Record<string, unknown> = {};
- let parsed: unknown;
- try { parsed = JSON.parse(body); } catch {}
- const events = parsed ? [parsed] : body.split('\n').filter((line: string) => line.startsWith('data:')).flatMap((line: string) => {
- try { return [JSON.parse(line.slice(5))]; } catch { return []; }
- });
- for (const event of events) {
- const e = record(event);
- const candidateModel = e.model ?? e.modelId ?? record(e.message).model ?? record(e.response).model;
- if (typeof candidateModel === 'string') model ??= candidateModel;
- providerMetadata = e.providerMetadata ?? providerMetadata;
- if (e.type === 'tool-call') parts.push({ type: 'toolCall', id: e.toolCallId, name: e.toolName, arguments: e.input });
- // OpenAI Responses (Codex): each finished function call is one output item.
- if (e.type === 'response.output_item.done' && record(e.item).type === 'function_call') {
- const item = record(e.item);
- parts.push({ type: 'toolCall', id: item.call_id, name: item.name, arguments: item.arguments });
- }
- if (e.type === 'content_block_start' && record(e.content_block).type === 'tool_use') {
- const part = { ...record(e.content_block) };
- parts.push(part);
- if (typeof e.index === 'number') anthropicTools.set(e.index, { part, json: '' });
- }
- if (e.type === 'content_block_delta' && record(e.delta).type === 'input_json_delta' && typeof e.index === 'number') {
- const tool = anthropicTools.get(e.index);
- const fragment = record(e.delta).partial_json;
- if (tool && typeof fragment === 'string') tool.json += fragment;
- }
- Object.assign(usage, record(e.usage ?? record(e.message).usage ?? record(e.response).usage));
- const delta = record(e.delta).text ?? (e.type === 'response.output_text.delta' || e.type === 'text-delta' ? e.delta ?? e.textDelta : undefined);
- if (typeof delta === 'string') text += delta;
- if (e.type === 'finish') Object.assign(usage, e.totalUsage ?? e.usage ?? {});
- for (const choice of Array.isArray(e.choices) ? e.choices : []) {
- const c = record(choice);
- const content = record(c.delta).content ?? record(c.message).content;
- if (typeof content === 'string') text += content;
- }
- for (const part of Array.isArray(e.content) ? e.content : []) {
- const c = record(part);
- if (c.type === 'text' && typeof c.text === 'string') text += c.text;
- }
- }
- for (const { part, json } of anthropicTools.values()) {
- if (!json) continue;
- try { part.input = JSON.parse(json); } catch { part.input = json; }
- }
- if (text) parts.unshift({ type: 'text', text });
- return { model, usage, providerMetadata, role: 'assistant', content: parts };
-}
diff --git a/packages/durable-harness/src/instrumentation/vercel.ts b/packages/durable-harness/src/instrumentation/vercel.ts
new file mode 100644
index 0000000..c11e1c2
--- /dev/null
+++ b/packages/durable-harness/src/instrumentation/vercel.ts
@@ -0,0 +1,46 @@
+import { TraceFlags } from '@opentelemetry/api';
+import type { ReadableSpan, SpanProcessor } from '@opentelemetry/sdk-trace-base';
+
+type Reporter = (payload: unknown) => void;
+type Serializer = typeof import('@opentelemetry/otlp-transformer').JsonTraceSerializer;
+
+/** The current invocation's span reporter (Vercel's request context, where @vercel/otel's automatic exporter reports). */
+function requestReporter(): Reporter | undefined {
+ const reader = (globalThis as Record<symbol, { get?: () => { telemetry?: { reportSpans?: Reporter } } | undefined } | undefined>)[Symbol.for('@vercel/request-context')];
+ try {
+ const telemetry = reader?.get?.()?.telemetry;
+ return telemetry?.reportSpans?.bind(telemetry);
+ } catch {
+ return undefined;
+ }
+}
+
+/**
+ * Vercel's Agent Runs destination: each sampled span, as it ends, reported
+ * through the request context of the invocation that started it (else the
+ * one it ends in). Off Vercel there is no request context and it reports
+ * nothing.
+ */
+export function vercelSpanProcessor(serializer: Serializer, onError: (error: unknown) => void): SpanProcessor {
+ const reporters = new WeakMap<object, Reporter>();
+ return {
+ onStart(span) {
+ const report = requestReporter();
+ if (report) reporters.set(span, report);
+ },
+ onEnd(span: ReadableSpan) {
+ if ((span.spanContext().traceFlags & TraceFlags.SAMPLED) === 0) return;
+ const report = reporters.get(span) ?? requestReporter();
+ if (!report) return;
+ try {
+ const bytes = serializer.serializeRequest([span]);
+ if (!bytes) throw new Error('could not serialize the span');
+ report(JSON.parse(new TextDecoder().decode(bytes)));
+ } catch (error) {
+ onError(error);
+ }
+ },
+ forceFlush: async () => {},
+ shutdown: async () => {},
+ };
+}
diff --git a/packages/durable-harness/src/pi.ts b/packages/durable-harness/src/pi.ts
index 9a33ef3..ba42cd0 100644
--- a/packages/durable-harness/src/pi.ts
+++ b/packages/durable-harness/src/pi.ts
@@ -84,6 +84,7 @@ export function pi(options: PiOptions): Agent {
};
const harness: Harness = {
name,
+ modelCalls: 'self',
async drive(ctx) {
return (await (built ??= build().catch((error) => {
built = undefined;
diff --git a/packages/durable-harness/test/agent-runs-checkpoints.test.ts b/packages/durable-harness/test/agent-runs-checkpoints.test.ts
new file mode 100644
index 0000000..0593522
--- /dev/null
+++ b/packages/durable-harness/test/agent-runs-checkpoints.test.ts
@@ -0,0 +1,223 @@
+import type { TraceSnapshot } from '@vercel/agent-runs';
+import type { World } from '@workflow/world';
+import { encodeLine } from 'harness-world/streams';
+import { afterEach, describe, expect, it, vi } from 'vitest';
+import { checkpointStreamName, TraceStreams } from '../src/instrumentation/checkpoints.ts';
+
+afterEach(() => { vi.useRealTimers(); vi.restoreAllMocks(); });
+
+function memoryWorld() {
+ const chunks = new Map<string, Uint8Array[]>();
+ const reads: { name: string; start: number }[] = [];
+ const streams = {
+ async getInfo(_runId: string, name: string) { return { tailIndex: (chunks.get(name)?.length ?? 0) - 1, done: false }; },
+ async get(_runId: string, name: string, start = 0) {
+ reads.push({ name, start });
+ return new ReadableStream<Uint8Array>({ start(controller) { for (const chunk of (chunks.get(name) ?? []).slice(start)) controller.enqueue(chunk); controller.close(); } });
+ },
+ async getChunks(_runId: string, name: string) { return { data: (chunks.get(name) ?? []).map((data, index) => ({ data, index })), cursor: null, hasMore: false, done: false }; },
+ async write(_runId: string, name: string, data: Uint8Array) { chunks.set(name, [...(chunks.get(name) ?? []), data]); },
+ };
+ return { world: { streams } as unknown as World, streams, chunks, reads };
+}
+const snapshot = (value: string) => ({ value }) as unknown as TraceSnapshot;
+
+describe('Agent Runs checkpoint storage', () => {
+ it.each(['snapshot', 'delete', 'drive', 'sequence'] as const)('quarantines a timed-out %s write until the actual World write settles', async kind => {
+ vi.useFakeTimers();
+ const { world, streams, chunks } = memoryWorld();
+ const put = streams.write.bind(streams);
+ let release!: () => void;
+ let writing = false;
+ vi.spyOn(streams, 'write').mockImplementation(async (runId, name, data) => {
+ if (runId === 'slow' && !writing) {
+ writing = true;
+ await new Promise<void>(resolve => { release = resolve; });
+ }
+ await put(runId, name, data);
+ });
+ const writer = new TraceStreams(world, () => {}, 10);
+ let failed: Promise<unknown> | undefined;
+ if (kind === 'snapshot') writer.checkpointer.set('turn:slow:turn', snapshot('old'));
+ else if (kind === 'delete') writer.checkpointer.delete('turn:slow:turn');
+ else failed = expect(kind === 'drive' ? writer.nextDrive('slow', 'turn') : writer.nextSequence('slow')).rejects.toThrow('timed out');
+ const flushing = writer.flush('slow');
+ await vi.advanceTimersByTimeAsync(11);
+ await failed;
+ await flushing;
+ writer.forget('slow');
+ // Cache pressure and finished-entry pruning must not drop the outstanding write either.
+ for (let i = 0; i < 130; i++) await writer.checkpointer.get(`turn:other:${i}`);
+ const all = writer.flush();
+ await vi.advanceTimersByTimeAsync(11);
+ await all;
+ await expect(kind === 'sequence' ? writer.nextSequence('slow') : writer.checkpointer.get('turn:slow:turn')).rejects.toThrow('timed out');
+ if (kind === 'snapshot' || kind === 'drive') writer.checkpointer.set('turn:slow:turn', snapshot('queued latest'));
+ const queued = writer.flush('slow');
+ await vi.advanceTimersByTimeAsync(11);
+ await queued;
+ expect([...chunks.keys()].filter(name => name.startsWith('slow_'))).toEqual([]);
+ release();
+ await vi.advanceTimersByTimeAsync(0);
+ writer.forget('slow');
+ if (kind === 'sequence') expect(await writer.nextSequence('slow')).toBe(1);
+ else {
+ expect(await writer.checkpointer.get('turn:slow:turn')).toEqual(kind === 'delete' ? undefined : snapshot('queued latest'));
+ writer.checkpointer.set('turn:slow:turn', snapshot('latest'));
+ await writer.flush('slow');
+ const recovered = new TraceStreams(world, () => {});
+ expect(await recovered.checkpointer.get('turn:slow:turn')).toEqual(snapshot('latest'));
+ }
+ });
+
+ it.each(['snapshot', 'finished'] as const)('coalesces the newest %s state behind a timed-out write and keeps it alive', async latest => {
+ vi.useFakeTimers();
+ const { world, streams, chunks } = memoryWorld();
+ const put = streams.write.bind(streams);
+ let release!: () => void;
+ const slow = new Promise<void>(resolve => { release = resolve; });
+ let writes = 0;
+ vi.spyOn(streams, 'write').mockImplementation(async (...args) => {
+ if (++writes === 1) await slow;
+ await put(...args);
+ });
+ const context = Symbol.for('@vercel/request-context');
+ const previous = Reflect.get(globalThis, context);
+ const held: Promise<void>[] = [];
+ Reflect.set(globalThis, context, { get: () => ({ waitUntil: (work: Promise<void>) => held.push(work) }) });
+ try {
+ const writer = new TraceStreams(world, () => {}, 10);
+ writer.checkpointer.set('turn:run:turn', snapshot('first'));
+ const flushing = writer.flush('run');
+ await vi.advanceTimersByTimeAsync(11);
+ await flushing;
+ writer.checkpointer.set('turn:run:turn', snapshot('intermediate'));
+ writer.checkpointer.set('turn:run:turn', snapshot('latest'));
+ if (latest === 'finished') writer.checkpointer.delete('turn:run:turn');
+ writer.forget('run');
+ await vi.advanceTimersByTimeAsync(0);
+ expect(writes).toBe(1);
+ expect(chunks.size).toBe(0);
+ let stored = false;
+ const storing = Promise.all(held).then(() => { stored = true; });
+ await vi.advanceTimersByTimeAsync(0);
+ expect(stored).toBe(false);
+ release();
+ await storing;
+ expect(writes).toBe(2);
+ const reader = new TraceStreams(world, () => {});
+ expect(await reader.finished('run', 'turn')).toBe(latest === 'finished');
+ expect(await reader.checkpointer.get('turn:run:turn')).toEqual(latest === 'finished' ? undefined : snapshot('latest'));
+ if (latest === 'snapshot') {
+ writer.checkpointer.set('turn:run:turn', snapshot('after recovery'));
+ expect(await writer.checkpointer.get('turn:run:turn')).toEqual(snapshot('after recovery'));
+ await writer.flush('run');
+ }
+ } finally {
+ release();
+ if (previous === undefined) Reflect.deleteProperty(globalThis, context);
+ else Reflect.set(globalThis, context, previous);
+ }
+ });
+
+ it('keeps turn sequence numbers across workers without sharing a turn key', async () => {
+ const { world } = memoryWorld();
+ const first = new TraceStreams(world, () => {});
+ expect(await first.nextSequence('run')).toBe(0);
+ expect(await first.nextSequence('run')).toBe(1);
+ const second = new TraceStreams(world, () => {});
+ expect(await second.nextSequence('run')).toBe(2);
+ expect(await first.nextSequence('run')).toBe(3);
+ expect(await first.checkpointer.get('turn:run:sequence')).toBeUndefined();
+ });
+
+ it('recovers the latest checkpoint and drive number from only the last chunk', async () => {
+ const { world, streams, chunks, reads } = memoryWorld();
+ const writer = new TraceStreams(world, () => {});
+ writer.checkpointer.set('turn:run:turn', snapshot('first'));
+ await writer.flush('run');
+ expect(await writer.nextDrive('run', 'turn')).toBe(1);
+ writer.checkpointer.set('turn:run:turn', snapshot('latest'));
+ await writer.flush('run');
+ const history = vi.spyOn(streams, 'getChunks');
+ const reader = new TraceStreams(world, () => {});
+ expect(await reader.checkpointer.get('turn:run:turn')).toEqual(snapshot('latest'));
+ const name = checkpointStreamName('run', 'turn');
+ expect(reads.at(-1)).toEqual({ name, start: chunks.get(name)!.length - 1 });
+ expect(history).not.toHaveBeenCalled();
+ expect(await reader.nextDrive('run', 'turn')).toBe(2);
+ });
+
+ it('continues existing separate snapshot/drive records and writes self-contained records afterward', async () => {
+ const { world, streams } = memoryWorld();
+ const name = checkpointStreamName('run', 'turn');
+ for (const line of [{ v: snapshot('existing') }, { drive: 4 }]) await streams.write('run', name, new TextEncoder().encode(`${encodeLine(line)}\n`));
+ const reader = new TraceStreams(world, () => {});
+ expect(await reader.checkpointer.get('turn:run:turn')).toEqual(snapshot('existing'));
+ expect(await reader.nextDrive('run', 'turn')).toBe(5);
+ reader.forget('run');
+ const history = vi.spyOn(streams, 'getChunks');
+ expect(await reader.checkpointer.get('turn:run:turn')).toEqual(snapshot('existing'));
+ expect(history).not.toHaveBeenCalled();
+ });
+
+ it('distinguishes an absent checkpoint from a failed read and never overwrites the latter', async () => {
+ const { world, streams, chunks } = memoryWorld();
+ const reader = new TraceStreams(world, () => {});
+ expect(await reader.checkpointer.get('turn:missing:turn')).toBeUndefined();
+ vi.spyOn(streams, 'getInfo').mockRejectedValue(new Error('stream read unavailable'));
+ await expect(reader.checkpointer.get('turn:unavailable:turn')).rejects.toThrow('stream read unavailable');
+ reader.checkpointer.set('turn:unavailable:turn', snapshot('must not overwrite'));
+ await reader.flush('unavailable');
+ expect(chunks.has(checkpointStreamName('unavailable', 'turn'))).toBe(false);
+ });
+
+ it('does not treat a failed legacy history read as an empty checkpoint', async () => {
+ const { world, streams } = memoryWorld();
+ await streams.write('run', checkpointStreamName('run', 'turn'), new TextEncoder().encode(`${encodeLine({ drive: 1 })}\n`));
+ vi.spyOn(streams, 'getChunks').mockRejectedValue(new Error('history unavailable'));
+ const reader = new TraceStreams(world, () => {});
+ await expect(reader.checkpointer.get('turn:run:turn')).rejects.toThrow('history unavailable');
+ });
+
+ it('bounds a stuck read by the remaining drive budget', async () => {
+ vi.useFakeTimers();
+ const { world, streams } = memoryWorld();
+ vi.spyOn(streams, 'getInfo').mockImplementation(() => new Promise(() => {}));
+ const reader = new TraceStreams(world, () => {}, 1000);
+ reader.setDeadline('run', Date.now() + 10);
+ const failed = expect(reader.checkpointer.get('turn:run:turn')).rejects.toThrow('timed out');
+ await vi.advanceTimersByTimeAsync(11);
+ await failed;
+ });
+
+ it('flushes one session without waiting for another session or an endless writer', async () => {
+ vi.useFakeTimers();
+ const { world, streams } = memoryWorld();
+ const put = streams.write.bind(streams);
+ vi.spyOn(streams, 'write').mockImplementation((runId, name, data) => runId === 'slow' ? new Promise(() => {}) : put(runId, name, data));
+ const writer = new TraceStreams(world, () => { throw new Error('diagnostics unavailable'); }, 25);
+ writer.checkpointer.set('turn:slow:turn', snapshot('slow'));
+ writer.checkpointer.set('turn:fast:turn', snapshot('fast'));
+ let finished = false;
+ const fast = writer.flush('fast').then(() => { finished = true; });
+ await vi.advanceTimersByTimeAsync(0);
+ expect(finished).toBe(true);
+ await fast;
+ const slow = writer.flush('slow');
+ await vi.advanceTimersByTimeAsync(26);
+ await slow;
+ });
+
+ it('reloads drive numbers after idle checkpoint cache entries are evicted', async () => {
+ const { world, reads } = memoryWorld();
+ const writer = new TraceStreams(world, () => {});
+ for (let i = 0; i < 3; i++) await writer.nextDrive('old', 'turn');
+ for (let i = 0; i < 150; i++) {
+ writer.checkpointer.set(`turn:run${i}:turn`, snapshot('value'));
+ await writer.flush(`run${i}`);
+ }
+ expect(await writer.nextDrive('old', 'turn')).toBe(4);
+ expect(reads.some((read) => read.name === checkpointStreamName('old', 'turn'))).toBe(true);
+ });
+});
diff --git a/packages/durable-harness/test/agent-runs-model-errors.test.ts b/packages/durable-harness/test/agent-runs-model-errors.test.ts
new file mode 100644
index 0000000..2683028
--- /dev/null
+++ b/packages/durable-harness/test/agent-runs-model-errors.test.ts
@@ -0,0 +1,48 @@
+import type { AgentRun } from '@vercel/agent-runs';
+import type { DriveContext, Harness, SessionState } from 'harness-world';
+import { describe, expect, it, vi } from 'vitest';
+import type { TraceStreams } from '../src/instrumentation/checkpoints.ts';
+import { traceDrive } from '../src/instrumentation/drive.ts';
+
+function setup(failure: 'start' | 'run' | 'complete' | 'fail') {
+ const unavailable = new Error('tracing unavailable');
+ const model = {
+ run: <T>(execute: () => T): T => { if (failure === 'run') throw unavailable; return execute(); },
+ complete: async () => { if (failure === 'complete') throw unavailable; },
+ fail: async () => { if (failure === 'fail') throw unavailable; },
+ };
+ const step = { complete: async () => {}, fail: async () => {}, modelCall: async () => { if (failure === 'start') throw unavailable; return model; } };
+ const turn = { finished: false, attempt: async () => step, complete: async () => {} };
+ const run = { turn: async () => turn, resume: async () => turn } as unknown as AgentRun;
+ const streams = { forget() {}, setDeadline() {}, finished: async () => false, flush: async () => {} } as unknown as TraceStreams;
+ const prompt = { id: 'prompt', kind: 'prompt', text: 'hello' };
+ const state = { status: 'running', submissions: [prompt], placed: new Set([prompt.id]), effects: new Map(), effectOrder: [] } as unknown as SessionState;
+ const ctx = {
+ runId: 'run', config: { traceAudience: 'public' }, signal: new AbortController().signal,
+ state: () => state, pending: () => [], effect: async (_key: string, _options: unknown, execute: (io: unknown) => Promise<unknown>) => execute({}),
+ } as unknown as DriveContext;
+ return { options: { run, streams, audience: 'public' as const, capture: () => ({ emit: true, recordInputs: true, recordOutputs: true }), version: 'test' }, ctx };
+}
+
+describe('model effects with failing tracing', () => {
+ it.each(['start', 'run', 'complete'] as const)('preserves the model result and executes once when tracing fails during %s', async failure => {
+ const { options, ctx } = setup(failure);
+ const execute = vi.fn(async () => 'model reply');
+ const harness: Harness = { name: 'test', async drive(ctx) {
+ expect(await ctx.effect('model:1', { name: 'model', replay: 'safe', input: { model: 'test/model' } }, execute)).toBe('model reply');
+ } };
+ await traceDrive(options, harness, ctx);
+ expect(execute).toHaveBeenCalledTimes(1);
+ });
+
+ it('preserves the model error when recording that error fails', async () => {
+ const { options, ctx } = setup('fail');
+ const original = new Error('model unavailable');
+ const execute = vi.fn(async () => { throw original; });
+ const harness: Harness = { name: 'test', async drive(ctx) {
+ await ctx.effect('model:1', { name: 'model', replay: 'safe', input: { model: 'test/model' } }, execute);
+ } };
+ await expect(traceDrive(options, harness, ctx)).rejects.toBe(original);
+ expect(execute).toHaveBeenCalledTimes(1);
+ });
+});
diff --git a/packages/durable-harness/test/agent-runs-packaging.test.ts b/packages/durable-harness/test/agent-runs-packaging.test.ts
new file mode 100644
index 0000000..a2071b5
--- /dev/null
+++ b/packages/durable-harness/test/agent-runs-packaging.test.ts
@@ -0,0 +1,41 @@
+import { readFileSync } from 'node:fs';
+import { afterEach, describe, expect, it, vi } from 'vitest';
+import { AGENT_RUNS, agentRunsHook } from 'harness-world/agent-runs';
+
+const peers = ['@opentelemetry/sdk-trace-base', '@opentelemetry/resources', '@opentelemetry/otlp-transformer', '@vercel/agent-runs'];
+const pkg = JSON.parse(readFileSync(new URL('../package.json', import.meta.url), 'utf8'));
+afterEach(() => { for (const peer of peers) vi.doUnmock(peer); vi.resetModules(); });
+
+describe('optional Agent Runs setup', () => {
+ it('contains rejected async diagnostic callbacks when a capture policy fails', async () => {
+ const previous = (globalThis as Record<symbol, unknown>)[AGENT_RUNS];
+ const { agentRuns } = await import('../src/instrumentation/otel.ts');
+ const integration = agentRuns({ capture: () => { throw new Error('policy unavailable'); }, onError: async () => { throw new Error('diagnostics unavailable'); } });
+ integration.register();
+ try {
+ expect(agentRunsHook()!.capture('private')).toEqual({ emit: true, recordInputs: false, recordOutputs: false });
+ await Promise.resolve();
+ } finally {
+ await integration.shutdown();
+ if (previous) (globalThis as Record<symbol, unknown>)[AGENT_RUNS] = previous;
+ else delete (globalThis as Record<symbol, unknown>)[AGENT_RUNS];
+ }
+ });
+
+ it('keeps the baseline package on Node 22 without installing tracing libraries', () => {
+ expect(pkg.engines.node).toBe('>=22');
+ for (const peer of peers) {
+ expect(pkg.dependencies[peer]).toBeUndefined();
+ expect(pkg.peerDependencies[peer]).toBeDefined();
+ expect(pkg.peerDependenciesMeta[peer]).toEqual({ optional: true });
+ }
+ expect(pkg.devDependencies['@vercel/agent-runs']).toBe('0.0.1');
+ });
+
+ it.each(peers)('names the install line when %s is missing', async peer => {
+ vi.doMock(peer, () => { throw Object.assign(new Error(`Cannot find package '${peer}'`), { code: 'ERR_MODULE_NOT_FOUND' }); });
+ const { agentRuns } = await import('../src/instrumentation/otel.ts');
+ expect(() => agentRuns()).toThrow(`${peer} is not installed`);
+ expect(() => agentRuns()).toThrow(`pnpm add ${peers.map(name => `${name}@${pkg.devDependencies[name]}`).join(' ')}`);
+ });
+});
diff --git a/packages/durable-harness/test/agent-runs-pi-recovery.test.ts b/packages/durable-harness/test/agent-runs-pi-recovery.test.ts
new file mode 100644
index 0000000..33b2d1e
--- /dev/null
+++ b/packages/durable-harness/test/agent-runs-pi-recovery.test.ts
@@ -0,0 +1,76 @@
+import { mkdtemp } from 'node:fs/promises';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { BACKGROUND_CONTEXT as ctx } from '@earendil-works/chord/context';
+import { Type } from '@earendil-works/pi-ai';
+import { createModels } from '@earendil-works/pi-ai/models';
+import { fauxAssistantMessage, fauxProvider, fauxText, fauxToolCall } from '@earendil-works/pi-ai/providers/faux';
+import { createRegistry, defineExtension, defineTool, Harness, type ToolRegistration } from '@earendil-works/pi-durable';
+import { InMemorySpanExporter, SimpleSpanProcessor } from '@opentelemetry/sdk-trace-base';
+import { createWorld } from '@workflow/world-local';
+import { readJsonLines } from 'harness-world/streams';
+import { untilSettled, worldStorage } from 'pi-world';
+import { describe, expect, it } from 'vitest';
+import { agentRuns } from '../src/instrumentation/otel.ts';
+
+describe('pi-durable capture policy on actual storage recovery', () => {
+ it('reopens an unfinished public turn privately before fresh tool and model commits', async () => {
+ const world = createWorld({ dataDir: await mkdtemp(join(tmpdir(), 'pi-private-recovery-')), recoverActiveRuns: false });
+ const exporter = new InMemorySpanExporter();
+ const runs = agentRuns({ spanProcessors: [new SimpleSpanProcessor(exporter)] });
+ runs.register();
+ const privateTool = 'restricted recovered tool output';
+ const privateModel = 'restricted recovered model output';
+ let started!: () => void;
+ const running = new Promise<void>(resolve => { started = resolve; });
+ let calls = 0;
+ const lookup = defineTool({
+ name: 'lookup', description: 'Look up a record', replay: 'safe', parameters: Type.Object({}),
+ async execute(_args, _api, context) {
+ calls++;
+ if (calls === 1) {
+ started();
+ await new Promise<never>((_, reject) => context.abortSignal?.addEventListener('abort', () => reject(context.abortSignal?.reason), { once: true }));
+ }
+ return { content: [{ type: 'text', text: privateTool }] };
+ },
+ }) as ToolRegistration;
+ const faux = fauxProvider();
+ faux.setResponses([
+ fauxAssistantMessage([fauxToolCall('lookup', {}, { id: 'call_1' })], { stopReason: 'toolUse' }),
+ context => { expect(JSON.stringify(context)).toContain(privateTool); return fauxAssistantMessage([fauxText(privateModel)]); },
+ ]);
+ const models = createModels();
+ models.setProvider(faux.provider);
+ const registry = createRegistry();
+ registry.install(defineExtension({ name: 'test', tools: [lookup] }));
+ const sessionId = await worldStorage.create(world, { name: 'pi-private' });
+ const first = await Harness.open(await worldStorage(world, sessionId, { traceAudience: 'public' }), { models, registry }, ctx);
+ let second: Harness | undefined;
+ try {
+ const model = faux.getModel();
+ const root = await first.root(ctx, { agent: { model: { provider: model.provider, modelId: model.id } } });
+ await root.submit({ type: 'input', content: 'Look up the record.' }, ctx);
+ await running;
+ await first.close(ctx);
+ second = await Harness.open(await worldStorage(world, sessionId, { traceAudience: 'private' }), { models, registry }, ctx);
+ expect(await untilSettled(second, Date.now() + 5000)).toBe(false);
+ await second.close(ctx);
+ await runs.forceFlush();
+ expect(calls).toBe(2);
+ const spans = exporter.getFinishedSpans().filter(span => span.attributes['agent.run.id'] === sessionId);
+ expect(spans.filter(span => span.name === 'execute_tool lookup')).toHaveLength(1);
+ const turn = spans.find(span => span.name === 'invoke_agent pi-durable')!;
+ expect(turn.attributes).toMatchObject({ 'agent.trace.content.input': false, 'agent.trace.content.output': false, 'agent.turn.outcome': 'completed' });
+ const content = JSON.stringify(spans.map(span => ({ attributes: span.attributes, events: span.events, status: span.status })));
+ for (const marker of [privateTool, privateModel]) expect(content).not.toContain(marker);
+ const streams = (await world.streams.list(sessionId)).filter(name => name.includes('_agent-runs_'));
+ expect(streams.length).toBeGreaterThan(0);
+ for (const name of streams) {
+ const lines = await readJsonLines(world, sessionId, name);
+ expect(lines.length).toBeGreaterThan(0);
+ for (const marker of [privateTool, privateModel]) expect(JSON.stringify(lines)).not.toContain(marker);
+ }
+ } finally { await first.close(ctx); await second?.close(ctx); await runs.shutdown(); await world.close?.(); }
+ }, 15_000);
+});
diff --git a/packages/durable-harness/test/agent-runs-recovery.test.ts b/packages/durable-harness/test/agent-runs-recovery.test.ts
new file mode 100644
index 0000000..d84bae7
--- /dev/null
+++ b/packages/durable-harness/test/agent-runs-recovery.test.ts
@@ -0,0 +1,361 @@
+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 type { World } from '@workflow/world';
+import { createWorld, type LocalWorld } from '@workflow/world-local';
+import type { DriveContext, EffectRecord, Harness, SessionState, Submission } from 'harness-world';
+import { agentRunsHook } from 'harness-world/agent-runs';
+import { Parked, Yield } from 'harness-world/errors';
+import { readJsonLines } from 'harness-world/streams';
+import { gatewayModelOptions } from '../../harness-process/src/agent-runs.ts';
+import { afterAll, afterEach, describe, expect, it, vi } from 'vitest';
+import { checkpointStreamName } from '../src/instrumentation/checkpoints.ts';
+import { agentRuns } from '../src/instrumentation/otel.ts';
+
+const exporter = new InMemorySpanExporter();
+const runs = agentRuns({ spanProcessors: [new SimpleSpanProcessor(exporter)], onError: () => {} });
+runs.register();
+const hook = agentRunsHook()!;
+
+const worlds: LocalWorld[] = [];
+afterEach(() => { vi.useRealTimers(); });
+afterAll(async () => {
+ for (const w of worlds) await w.close?.();
+});
+
+async function localWorld(): Promise<LocalWorld> {
+ const world = createWorld({ dataDir: await mkdtemp(join(tmpdir(), 'dh-agent-runs-recovery-')), recoverActiveRuns: false });
+ worlds.push(world);
+ return world;
+}
+
+/** The same World as another process sees it: its own Agent Runs state. With `write`, its stream writes go there. */
+function processOf(world: World, write?: World['streams']['write'], overrides: Partial<World['streams']> = {}): World {
+ const bound = (target: object, key: string | symbol) => {
+ const value = Reflect.get(target, key);
+ return typeof value === 'function' ? value.bind(target) : value;
+ };
+ const streams = new Proxy(world.streams, { get: (target, key) => key in overrides ? Reflect.get(overrides, key) : key === 'write' && write ? write : bound(target, key) });
+ return new Proxy(world, { get: (target, key) => (key === 'streams' ? streams : bound(target, key)) });
+}
+
+/** A drive of one prompt's session, its effects run as they come (the kernel's log is not under test). */
+function driveContext(world: World, runId: string): DriveContext {
+ const prompt: Submission = { id: 'sub_1', kind: 'prompt', text: 'hello', receivedAt: new Date() };
+ const state = { status: 'running', submissions: [prompt], placed: new Set([prompt.id]), effects: new Map(), effectOrder: [] } as unknown as SessionState;
+ return {
+ runId,
+ world,
+ config: { traceAudience: 'public' },
+ signal: new AbortController().signal,
+ state: () => state,
+ pending: () => [],
+ async effect(key: string, effect: { name: string; placed?: string[] }, fn: (io: never) => Promise<unknown>) {
+ const record = { key, name: effect.name, placed: effect.placed ?? [], status: 'running', attempt: 1 } as unknown as EffectRecord;
+ state.effects.set(key, record);
+ state.effectOrder.push(record);
+ return fn({} as never);
+ },
+ } as unknown as DriveContext;
+}
+
+const harness = (drive: (ctx: DriveContext) => Promise<void>): Harness => ({ name: 'recovery', drive }) as Harness;
+const of = (runId: string) => exporter.getFinishedSpans().filter((s) => s.attributes['agent.run.id'] === runId);
+
+describe('Agent Runs across drives and processes', () => {
+ it('checkpoints a model cut by the soft deadline before another process continues its turn', async () => {
+ const world = await localWorld();
+ const runId = 'wrun_soft_deadline';
+ const abort = new AbortController();
+ const ctx = driveContext(world, runId);
+ const deadline = Date.now() + 5000;
+ vi.useFakeTimers({ toFake: ['Date'] });
+ try {
+ await expect(hook.drive(harness(async ctx => {
+ await ctx.effect('model:cut', { name: 'model', replay: 'safe', placed: ['sub_1'], input: { model: 'test/model' } }, async () => {
+ await runs.forceFlush();
+ vi.setSystemTime(deadline + 1);
+ const reason = new Yield('budget');
+ abort.abort(reason);
+ throw reason;
+ });
+ }), { ...ctx, deadline, signal: abort.signal })).rejects.toBeInstanceOf(Yield);
+ } finally { vi.useRealTimers(); }
+ await runs.forceFlush();
+ const cut = of(runId);
+ expect(cut.filter(span => span.name === 'agent.step')).toHaveLength(1);
+ expect(cut.filter(span => span.attributes['gen_ai.operation.name'] === 'chat')).toHaveLength(1);
+ expect(cut.every(span => span.status.code === 2)).toBe(true);
+
+ const continued = driveContext(processOf(world), runId);
+ continued.state().effectOrder.push(...ctx.state().effectOrder);
+ await hook.drive(harness(async ctx => {
+ await ctx.effect('model:next', { name: 'model', replay: 'safe', input: { model: 'test/model' } }, async () => 'continued answer');
+ }), continued);
+ await runs.forceFlush();
+ const spans = of(runId);
+ expect(spans.filter(span => span.name === 'invoke_agent recovery')).toHaveLength(1);
+ expect(spans.filter(span => span.name === 'agent.step')).toHaveLength(2);
+ expect(spans.filter(span => span.attributes['gen_ai.operation.name'] === 'chat')).toHaveLength(2);
+ expect(new Set(spans.map(span => span.spanContext().spanId)).size).toBe(spans.length);
+ });
+
+ it('stores the finished marker after a slow write instead of exporting the completed turn again', async () => {
+ const original = await localWorld();
+ const runId = 'wrun_slow_finished';
+ let release!: () => void;
+ const delayed = new Promise<void>(resolve => { release = resolve; });
+ let writes = 0;
+ const world = processOf(original, async (...args) => {
+ if (++writes === 1) await delayed;
+ await original.streams.write(...args);
+ });
+ try {
+ await hook.drive(harness(async ctx => {
+ await ctx.effect('model:0', { name: 'model', replay: 'safe', placed: ['sub_1'], input: { model: 'test/model' } }, async () => 'finished answer');
+ }), driveContext(world, runId));
+ } finally { release(); }
+ await runs.forceFlush();
+ const lines = await readJsonLines(original, runId, checkpointStreamName(runId, 'sub_1'));
+ expect(lines.at(-1)).toMatchObject({ v: null });
+ await hook.drive(harness(async () => {}), driveContext(processOf(original), runId));
+ await runs.forceFlush();
+ const spans = of(runId);
+ expect(spans.filter(span => span.name === 'invoke_agent recovery')).toHaveLength(1);
+ expect(new Set(spans.map(span => span.spanContext().spanId)).size).toBe(spans.length);
+ });
+
+ it('records public tool definitions without persisting provider credentials', async () => {
+ const world = await localWorld();
+ const runId = 'wrun_tool_definitions';
+ const session = hook.session({ world, runId, agentName: 'public-tools', audience: 'public' });
+ const turn = (await session.turn({ turnId: 'turn', sequence: 0 }))!;
+ const step = await session.step(turn, 'turn');
+ const options = gatewayModelOptions({ path: '/v1/responses', body: {
+ model: 'test/model', input: 'Look up the record',
+ tools: [{ type: 'mcp', name: 'remote_lookup', authorization: 'test-only-credential', headers: { 'x-api-key': 'test-only-credential' }, parameters: { type: 'object' } }],
+ } });
+ const model = await step.modelCall(options);
+ await session.flush();
+ const lines = await readJsonLines(world, runId, checkpointStreamName(runId, 'turn'));
+ expect(JSON.stringify(lines)).toContain('remote_lookup');
+ expect(JSON.stringify(lines)).not.toContain('test-only-credential');
+ await model.complete({ outcome: 'completed', result: { usage: {}, finishReason: 'stop', content: [{ type: 'text', text: 'done' }] } });
+ await step.complete();
+ await turn.complete({ outcome: 'completed' });
+ await session.flush();
+ await runs.forceFlush();
+ const recorded = of(runId).find(span => span.attributes['gen_ai.operation.name'] === 'chat')!;
+ expect(recorded.attributes['gen_ai.tool.definitions']).toContain('remote_lookup');
+ expect(JSON.stringify(recorded.attributes)).not.toContain('test-only-credential');
+ });
+
+ it('runs untraced without overwriting a checkpoint when its read fails', async () => {
+ const original = await localWorld();
+ let writes = 0;
+ const world = processOf(original, async () => { writes++; }, { getInfo: async () => { throw new Error('checkpoint unavailable'); } });
+ let ran = false;
+ await hook.drive(harness(async ctx => {
+ expect(await ctx.effect('model:0', { name: 'model', replay: 'safe', input: { model: 'test/model' } }, async () => { ran = true; return 'model reply'; })).toBe('model reply');
+ }), driveContext(world, 'wrun_read_failed'));
+ expect(ran).toBe(true);
+ expect(writes).toBe(0);
+ });
+
+ it('lets a drive finish when its checkpoint read never answers', async () => {
+ const world = processOf(await localWorld(), undefined, { getInfo: () => new Promise(() => {}) });
+ let ran = false;
+ const ctx = { ...driveContext(world, 'wrun_read_stuck'), deadline: Date.now() + 10 };
+ await hook.drive(harness(async ctx => {
+ await ctx.effect('model:0', { name: 'model', replay: 'safe', input: { model: 'test/model' } }, async () => { ran = true; return 'model reply'; });
+ }), ctx);
+ expect(ran).toBe(true);
+ }, 1000);
+
+ it('continues the placed turn before switching to a queued follow-up', async () => {
+ const world = await localWorld();
+ const runId = 'wrun_followup';
+ const session = hook.session({ world, runId, agentName: 'recovery', audience: 'public' });
+ await session.turn({ turnId: 'sub_1', sequence: 0, title: 'hello' });
+ await session.flush();
+ const ctx = driveContext(processOf(world), runId);
+ const followUp: Submission = { id: 'sub_2', kind: 'followUp', text: 'next prompt', receivedAt: new Date() };
+ ctx.state().submissions.push(followUp);
+ await hook.drive(harness(async ctx => {
+ await ctx.effect('model:continued', { name: 'model', replay: 'safe', input: { model: 'test/model' } }, async () => 'continued first answer');
+ await ctx.effect('model:next', { name: 'model', replay: 'safe', input: { model: 'test/model' }, placed: ['sub_2'] }, async () => 'follow-up answer');
+ }), { ...ctx, pending: () => [followUp] });
+ await runs.forceFlush();
+ const turns = of(runId).filter(span => span.name === 'invoke_agent recovery');
+ expect(turns).toHaveLength(2);
+ const first = turns.find(span => span.attributes['agent.turn.id'] === 'sub_1')!;
+ const second = turns.find(span => span.attributes['agent.turn.id'] === 'sub_2')!;
+ expect(first.attributes['gen_ai.output.messages']).toContain('continued first answer');
+ expect(second.attributes['gen_ai.output.messages']).toContain('follow-up answer');
+ expect(first.attributes['agent.turn.outcome']).toBe('completed');
+ expect(second.attributes['agent.turn.outcome']).toBe('completed');
+ });
+
+ it.each([
+ { audience: 'private' as const, freshProcess: false },
+ { audience: 'private' as const, freshProcess: true },
+ { audience: 'unknown' as const, freshProcess: true },
+ ])('narrows a resumed public turn and its children for $audience capture (fresh process: $freshProcess)', async ({ audience, freshProcess }) => {
+ const world = await localWorld();
+ const runId = `wrun_capture_${audience}_${freshProcess}`;
+ const initial = hook.session({ world, runId, agentName: 'pi', audience: 'public' });
+ const turn = (await initial.turn({ turnId: 't1', sequence: 0, title: 'initial public title' }))!;
+ const step = await initial.step(turn, 't1');
+ await step.tool({ callId: 'call_1', name: 'lookup', arguments: { q: 'initial public argument' } });
+ await initial.flush();
+
+ // Pi recovery resumes before it records fresh generations or settles an earlier tool.
+ const resumedSession = hook.session({ world: freshProcess ? processOf(world) : world, runId, agentName: 'pi', audience });
+ const resumed = (await resumedSession.resume('t1'))!;
+ const tool = resumed.findTool('call_1')!;
+ const metadata = { emit: true, recordInputs: false, recordOutputs: false };
+ expect(resumed.reference).toEqual(turn.reference);
+ expect(resumed.capture).toEqual(metadata);
+ expect(tool.capture).toEqual(metadata);
+
+ const markers = ['restricted model input', 'restricted model output', 'restricted tool result', 'restricted new tool input', 'restricted new tool result'];
+ await tool.complete({ outcome: 'completed', output: markers[2] });
+ const next = await resumedSession.step(resumed, 't1');
+ const model = await next.modelCall({ provider: 'test', modelId: 'model', messages: [{ role: 'user', content: markers[0] }] });
+ expect(model.capture).toEqual(metadata);
+ await model.complete({ outcome: 'completed', result: { usage: { inputTokens: 2, outputTokens: 3 }, finishReason: 'stop', content: [{ type: 'text', text: markers[1]! }] } });
+ const nextTool = await next.tool({ callId: 'call_2', name: 'lookup', arguments: { q: markers[3] } });
+ await nextTool.complete({ outcome: 'completed', output: markers[4] });
+ await resumedSession.flush();
+
+ const lines = await readJsonLines(world, runId, checkpointStreamName(runId, 't1'));
+ const snapshot = (lines.filter((line) => line && typeof line === 'object' && 'v' in line).at(-1) as { v: unknown }).v;
+ expect(snapshot).toMatchObject({ capture: metadata });
+ const stored = JSON.stringify(snapshot);
+ for (const marker of [...markers, 'initial public title', 'initial public argument']) expect(stored).not.toContain(marker);
+
+ await next.complete();
+ await resumed.complete({ outcome: 'completed' });
+ await resumedSession.flush();
+ await runs.forceFlush();
+ const spans = of(runId);
+ expect(spans.filter((span) => span.attributes['gen_ai.operation.name'] === 'chat')).toHaveLength(1);
+ expect(spans.filter((span) => span.attributes['gen_ai.operation.name'] === 'execute_tool')).toHaveLength(2);
+ for (const marker of markers) expect(JSON.stringify(spans.map((span) => ({ attributes: span.attributes, events: span.events, status: span.status })))).not.toContain(marker);
+ const root = spans.find((span) => span.name === 'invoke_agent pi')!;
+ expect(root.attributes).toMatchObject({ 'agent.channel.audience': audience, 'agent.trace.content.input': false, 'agent.trace.content.output': false });
+ });
+
+ it('does not start a turn when resume finds no checkpoint', async () => {
+ const world = await localWorld();
+ const runId = 'wrun_resume_missing';
+ const session = hook.session({ world, runId, agentName: 'pi', audience: 'private' });
+ expect(await session.resume('missing')).toBeUndefined();
+ await session.flush();
+ await runs.forceFlush();
+ expect(of(runId)).toEqual([]);
+ });
+
+ it('narrows restored tools settled from memoized kernel effects', async () => {
+ const world = await localWorld();
+ const runId = 'wrun_memoized_capture';
+ const initial = hook.session({ world, runId, agentName: 'recovery', audience: 'public' });
+ const turn = (await initial.turn({ turnId: 'sub_1', sequence: 0, title: 'hello' }))!;
+ await (await initial.step(turn, 'sub_1')).tool({ callId: 'call_1', name: 'lookup', arguments: {} });
+ await initial.flush();
+
+ const ctx = driveContext(processOf(world), runId);
+ const marker = 'restricted recovered tool result';
+ const resumed = { ...ctx, config: { traceAudience: 'private' }, effect: async () => marker } as unknown as DriveContext;
+ await hook.drive(harness(async (ctx) => {
+ expect(await ctx.effect('tool:call_1', { name: 'tool.lookup', replay: 'safe', input: {} }, async () => { throw new Error('memoized work must not run'); })).toBe(marker);
+ }), resumed);
+ await runs.forceFlush();
+ const spans = of(runId);
+ const tool = spans.find((span) => span.name === 'execute_tool lookup')!;
+ expect(tool).toBeDefined();
+ expect(tool.attributes['gen_ai.tool.call.result']).toBeUndefined();
+ expect(JSON.stringify(spans.map((span) => ({ attributes: span.attributes, events: span.events, status: span.status })))).not.toContain(marker);
+ expect(spans.find((span) => span.name === 'invoke_agent recovery')!.attributes).toMatchObject({ 'agent.trace.content.input': false, 'agent.trace.content.output': false });
+ });
+
+ it('keeps a parked tool call open for the drive that settles it', async () => {
+ const world = await localWorld();
+ const runId = 'wrun_parked';
+ const model = (ctx: DriveContext, key: string) => ctx.effect(key, { name: 'model', replay: 'safe', input: { model: 'test/model' }, placed: ['sub_1'] }, async () => 'ok');
+ const first = harness(async (ctx) => {
+ await model(ctx, 'model:0');
+ await ctx.effect('tool:call_1', { name: 'tool.lookup', replay: 'safe', input: { q: 'x' } }, async () => {
+ throw new Parked();
+ });
+ });
+ await expect(hook.drive(first, driveContext(world, runId))).rejects.toBeInstanceOf(Parked);
+ const second = harness(async (ctx) => {
+ await ctx.effect('tool:call_1', { name: 'tool.lookup', replay: 'safe', input: { q: 'x' } }, async () => 'found');
+ await model(ctx, 'model:1');
+ });
+ await hook.drive(second, driveContext(world, runId));
+ await runs.forceFlush();
+
+ const spans = of(runId);
+ const tools = spans.filter((s) => s.name === 'execute_tool lookup');
+ expect(tools).toHaveLength(1);
+ expect(tools[0]!.status.code).not.toBe(2);
+ expect(tools[0]!.attributes['gen_ai.tool.call.result']).toContain('found');
+ // Under the step whose model call asked for it, in the first drive.
+ const firstStep = spans.find((s) => s.name === 'agent.step' && s.spanContext().spanId === tools[0]!.parentSpanContext?.spanId);
+ expect(firstStep?.attributes['agent.step.index']).toBe(0);
+ expect(spans.find((s) => s.name === 'invoke_agent recovery')?.attributes['agent.turn.outcome']).toBe('completed');
+ }, 30_000);
+
+ it('runs a tool call untraced when its step cannot be recorded', async () => {
+ const world = processOf(await localWorld(), async () => {
+ throw new Error('stream store unavailable');
+ });
+ let ran = false;
+ const drive = harness(async (ctx) => {
+ const value = await ctx.effect('tool:call_1', { name: 'tool.lookup', replay: 'safe', input: {} }, async () => ((ran = true), 'found'));
+ expect(value).toBe('found');
+ });
+ await hook.drive(drive, driveContext(world, 'wrun_store_down'));
+ expect(ran).toBe(true);
+ }, 30_000);
+
+ it("continues a turn from another process's checkpoint when the session comes back", async () => {
+ const world = await localWorld();
+ const a = processOf(world);
+ const b = processOf(world);
+ const runId = 'wrun_handoff';
+ const session = (w: World) => hook.session({ world: w, runId, agentName: 'pi', audience: 'public' });
+
+ const onA = session(a);
+ const turn = (await onA.turn({ turnId: 't1', sequence: 0, title: 'hello' }))!;
+ await (await (await onA.step(turn, 't1')).modelCall({ provider: 'test', modelId: 'model' })).complete({ outcome: 'completed' });
+ await onA.flush();
+
+ const onB = session(b);
+ const resumed = (await onB.resume('t1'))!;
+ await (await onB.step(resumed, 't1')).tool({ callId: 'call_b', name: 'lookup' });
+ await onB.flush();
+
+ // The same session object, asked for the turn again (libfx's next execution on a warm worker).
+ const again = (await onA.turn({ turnId: 't1', sequence: 0 }))!;
+ expect(again.findTool('call_b')).toBeDefined();
+
+ // A new acquisition on the warm worker: its steps are numbered after B's.
+ const back = session(a);
+ const latest = (await back.resume('t1'))!;
+ expect(latest.findTool('call_b')).toBeDefined();
+ await (await back.step(latest, 't1')).modelCall({ provider: 'test', modelId: 'model' }).then((m) => m.complete({ outcome: 'completed' }));
+ await latest.findTool('call_b')!.complete({ outcome: 'completed' });
+ await latest.complete({ outcome: 'completed' });
+ await back.flush();
+ await runs.forceFlush();
+
+ const steps = of(runId).filter((s) => s.name === 'agent.step');
+ expect(steps).toHaveLength(3);
+ expect(new Set(steps.map((s) => s.spanContext().spanId)).size).toBe(3);
+ expect(new Set(steps.map((s) => s.attributes['agent.step.attempt'])).size).toBe(3);
+ }, 30_000);
+});
diff --git a/packages/durable-harness/test/agent-runs.test.ts b/packages/durable-harness/test/agent-runs.test.ts
new file mode 100644
index 0000000..298f561
--- /dev/null
+++ b/packages/durable-harness/test/agent-runs.test.ts
@@ -0,0 +1,146 @@
+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 { type DriveContext, durableSessions, type Harness, QUEUE_PREFIX, type Submission, Yield } from 'harness-world';
+import { readJsonLines } from 'harness-world/streams';
+import { afterAll, beforeAll, describe, expect, it } from 'vitest';
+import { checkpointStreamName } from '../src/instrumentation/checkpoints.ts';
+import { agentRuns } from '../src/instrumentation/otel.ts';
+
+const exporter = new InMemorySpanExporter();
+const runs = agentRuns({ spanProcessors: [new SimpleSpanProcessor(exporter)] });
+runs.register();
+
+/**
+ * Per prompt: a model call that asks for `lookup`, the tool call, and a model
+ * call that answers. With `yieldAfterTool`, its first drive stops (out of
+ * time) after the tool call, so the turn goes on in a second drive.
+ */
+function scripted(opts: { yieldAfterTool?: boolean } = {}): Harness & { drives: number } {
+ const harness = {
+ name: 'scripted',
+ drives: 0,
+ async drive(ctx: DriveContext) {
+ harness.drives++;
+ const prompts = ctx.state().submissions.filter((s): s is Submission & { text: string } => s.text !== undefined && s.kind !== 'steer');
+ for (const s of prompts) {
+ await ctx.effect(`model:${s.id}:0`, { name: 'model', replay: 'safe', input: { model: 'test/model' }, placed: [s.id] }, async () => ({ finishReason: 'tool-calls' }));
+ await ctx.effect(`tool:call_${s.id}`, { name: 'tool.lookup', replay: 'safe', input: { q: s.text } }, async () => `found ${s.text}`);
+ if (opts.yieldAfterTool && harness.drives === 1) throw new Yield('budget');
+ await ctx.effect(`model:${s.id}:1`, { name: 'model', replay: 'safe', input: { model: 'test/model' } }, async () => `answer to ${s.text}`);
+ }
+ },
+ };
+ return harness;
+}
+
+const worlds: LocalWorld[] = [];
+afterAll(async () => {
+ for (const w of worlds) await w.close?.();
+});
+
+async function session(harness: Harness, config: Record<string, unknown> = {}) {
+ const world = createWorld({ dataDir: await mkdtemp(join(tmpdir(), 'dh-agent-runs-')), recoverActiveRuns: false });
+ worlds.push(world);
+ const sessions = durableSessions({ world, harness });
+ world.registerHandler(QUEUE_PREFIX, sessions.handler);
+ return { world, sessions, config };
+}
+
+async function idle(sessions: ReturnType<typeof durableSessions>, id: string, models: number) {
+ for (let i = 0; i < 300; i++) {
+ const state = await sessions.inspect(id);
+ if (state.effectOrder.filter((e) => e.name === 'model' && e.status === 'completed').length >= models) return state;
+ await new Promise((r) => setTimeout(r, 50));
+ }
+ throw new Error('timed out');
+}
+
+const of = (runId: string) => exporter.getFinishedSpans().filter((s) => s.attributes['agent.run.id'] === runId);
+const parentOf = (span: ReadableSpan) => span.parentSpanContext?.spanId;
+
+async function finishedTurns(runId: string, count: number): Promise<ReadableSpan[]> {
+ // An effect's log commit precedes the drive's tracing finalizer.
+ for (let i = 0; i < 300; i++) {
+ await runs.forceFlush();
+ const spans = of(runId);
+ if (spans.filter(span => span.name.startsWith('invoke_agent')).length === count) return spans;
+ await new Promise(resolve => setTimeout(resolve, 20));
+ }
+ throw new Error('timed out waiting for turn spans');
+}
+
+describe('Agent Runs with @vercel/agent-runs', () => {
+ let first: { runId: string; spans: ReadableSpan[] };
+ beforeAll(async () => {
+ const harness = scripted({ yieldAfterTool: true });
+ const { sessions, world } = await session(harness);
+ const { sessionId } = await sessions.start({ prompt: 'hello', config: { traceAudience: 'public' } });
+ await idle(sessions, sessionId, 2);
+ await sessions.send(sessionId, 'again');
+ await idle(sessions, sessionId, 4);
+ expect(harness.drives).toBeGreaterThan(1);
+ first = { runId: sessionId, spans: await finishedTurns(sessionId, 2) };
+ // Both turns finished, so their checkpoints were deleted.
+ const state = await sessions.inspect(sessionId);
+ for (const s of state.submissions.filter((x) => x.text !== undefined)) {
+ const lines = (await readJsonLines(world, sessionId, checkpointStreamName(sessionId, s.id))) as { v?: unknown }[];
+ expect(lines.filter((l) => 'v' in l).at(-1)).toMatchObject({ v: null });
+ }
+ }, 60_000);
+
+ it('writes the spans Agent Runs reads: the eve.agent scope at schema 4, keyed by the session', () => {
+ expect(first.spans.length).toBeGreaterThan(0);
+ for (const span of first.spans) {
+ expect(span.instrumentationScope.name).toBe('eve.agent');
+ expect(span.attributes['agent.trace.schema.version']).toBe(4);
+ expect(span.attributes['agent.run.id']).toBe(first.runId);
+ }
+ const names = first.spans.map((s) => s.name).sort();
+ expect(names.filter((n) => n === 'invoke_agent scripted')).toHaveLength(2);
+ expect(names.filter((n) => n === 'agent.step')).toHaveLength(4);
+ expect(names.filter((n) => n === 'chat model')).toHaveLength(4);
+ expect(names.filter((n) => n === 'execute_tool lookup')).toHaveLength(2);
+ });
+
+ it('keeps a turn that went on in a second drive one invoke_agent span, with its steps and tools under it', () => {
+ const turns = first.spans.filter((s) => s.name === 'invoke_agent scripted');
+ const ids = new Set(turns.map((t) => t.spanContext().spanId));
+ expect(ids.size).toBe(2);
+ for (const step of first.spans.filter((s) => s.name === 'agent.step')) expect(ids.has(parentOf(step)!)).toBe(true);
+ const steps = new Set(first.spans.filter((s) => s.name === 'agent.step').map((s) => s.spanContext().spanId));
+ for (const span of first.spans.filter((s) => s.name === 'chat model' || s.name === 'execute_tool lookup')) expect(steps.has(parentOf(span)!)).toBe(true);
+ // Every span of a turn is in the turn's trace.
+ for (const turn of turns) {
+ const trace = turn.spanContext().traceId;
+ const under = first.spans.filter((s) => s.spanContext().traceId === trace);
+ expect(under.map((s) => s.name).sort()).toEqual(['agent.step', 'agent.step', 'chat model', 'chat model', 'execute_tool lookup', 'invoke_agent scripted']);
+ }
+ for (const turn of turns) expect(turn.attributes['agent.turn.outcome']).toBe('completed');
+ });
+
+ it("records a public session's content, and the tool call's id", () => {
+ const tool = first.spans.find((s) => s.name === 'execute_tool lookup')!;
+ expect(tool.attributes['gen_ai.tool.call.id']).toMatch(/^call_/);
+ expect(tool.attributes['gen_ai.tool.call.arguments']).toContain('"q"');
+ const turn = first.spans.find((s) => s.name === 'invoke_agent scripted' && s.attributes['agent.turn.sequence'] === 0)!;
+ expect(turn.attributes['agent.trace.content.input']).toBe(true);
+ expect(turn.attributes['agent.trace.content.output']).toBe(true);
+ expect(turn.attributes['agent.session.title']).toBe('hello');
+ expect(turn.attributes['agent.channel.audience']).toBe('public');
+ });
+
+ it("records only metadata for a session that is not public", async () => {
+ const { sessions } = await session(scripted());
+ const { sessionId } = await sessions.start({ prompt: 'a secret', config: { traceAudience: 'private' } });
+ await idle(sessions, sessionId, 2);
+ const spans = await finishedTurns(sessionId, 1);
+ expect(spans.map((s) => s.name)).toContain('execute_tool lookup');
+ expect(JSON.stringify(spans.map((s) => s.attributes))).not.toContain('secret');
+ const turn = spans.find((s) => s.name === 'invoke_agent scripted')!;
+ expect(turn.attributes['agent.trace.content.input']).toBe(false);
+ expect(turn.attributes['agent.session.title']).toBeUndefined();
+ }, 30_000);
+});
diff --git a/packages/durable-harness/test/canary.test.ts b/packages/durable-harness/test/canary.test.ts
index f6b996c..c97f1c4 100644
--- a/packages/durable-harness/test/canary.test.ts
+++ b/packages/durable-harness/test/canary.test.ts
@@ -141,7 +141,8 @@ afterAll(() => {
// ---------- Agent Runs: every span, content visible ----------
const spans = new InMemorySpanExporter();
-agentRuns({ audience: 'public', exportPolicy: { span: () => ({ emit: true }) }, spanProcessors: [new SimpleSpanProcessor(spans)] }).register();
+// Content recorded for every audience: the search sees everything a span could carry.
+agentRuns({ capture: () => ({ emit: true, recordInputs: true, recordOutputs: true }), spanProcessors: [new SimpleSpanProcessor(spans)] }).register();
const spansOf = (runIds: Set<string>) => spans.getFinishedSpans().filter((s) => runIds.has(String(s.attributes['agent.run.id'])));
const spanTexts = (list: ReturnType<typeof spansOf>) => list.map((s) => JSON.stringify({ name: s.name, attributes: s.attributes, events: s.events, status: s.status, links: s.links }));
diff --git a/packages/durable-harness/test/otel-sdk.test.ts b/packages/durable-harness/test/otel-sdk.test.ts
deleted file mode 100644
index d5e35c3..0000000
--- a/packages/durable-harness/test/otel-sdk.test.ts
+++ /dev/null
@@ -1,77 +0,0 @@
-import { readdirSync, readFileSync } from 'node:fs';
-import { join } from 'node:path';
-import { fileURLToPath } from 'node:url';
-import { afterEach, describe, expect, it, vi } from 'vitest';
-
-// OpenTelemetry's SDK is an optional peer that only /instrumentation/otel loads.
-const SDK = ['@opentelemetry/sdk-trace-base', '@opentelemetry/resources', '@opentelemetry/otlp-transformer'];
-const pkg = JSON.parse(readFileSync(new URL('../package.json', import.meta.url), 'utf8'));
-const notFound = (name: string) => Object.assign(new Error(`Cannot find package '${name}' imported from /app/node_modules/durable-harness/dist/instrumentation/otel.js`), { code: 'ERR_MODULE_NOT_FOUND' });
-
-afterEach(() => {
- for (const name of SDK) vi.doUnmock(name);
- vi.resetModules();
-});
-
-describe("OpenTelemetry's SDK", () => {
- it('is an optional peer dependency, tested at the versions the install line names', async () => {
- for (const name of SDK) {
- expect(pkg.dependencies[name]).toBeUndefined();
- expect(pkg.peerDependencies[name]).toBeDefined();
- expect(pkg.peerDependenciesMeta[name]).toEqual({ optional: true });
- }
- // @opentelemetry/api stays a dependency: spans go through it, and are no-ops until agentRuns() registers.
- expect(pkg.dependencies['@opentelemetry/api']).toBeDefined();
- vi.doMock('@opentelemetry/sdk-trace-base', () => {
- throw notFound('@opentelemetry/sdk-trace-base');
- });
- const { agentRuns } = await import('../src/instrumentation/otel.ts');
- let error: Error | undefined;
- try {
- agentRuns();
- } catch (e) {
- error = e as Error;
- }
- expect(error?.message).toContain('@opentelemetry/sdk-trace-base is not installed');
- expect(error?.message).toContain(`pnpm add ${SDK.map((name) => `${name}@${pkg.devDependencies[name]}`).join(' ')}`);
- });
-
- it('missing, the entry still loads, and agentRuns() names the install line', async () => {
- vi.doMock('@opentelemetry/otlp-transformer', () => {
- throw notFound('@opentelemetry/otlp-transformer');
- });
- const otel = await import('../src/instrumentation/otel.ts');
- expect(() => otel.agentRuns({ audience: 'public' })).toThrow(/@opentelemetry\/otlp-transformer is not installed\. Install them: pnpm add @opentelemetry\/sdk-trace-base@/);
- // An export policy for a processor of your own needs no SDK.
- const ended: unknown[] = [];
- const processor = otel.filteringProcessor({ onStart() {}, onEnd: (span) => ended.push(span), forceFlush: async () => {}, shutdown: async () => {} });
- expect(typeof processor.onEnd).toBe('function');
- });
-
- it('failing to load for another reason, fails the import', async () => {
- vi.doMock('@opentelemetry/resources', () => {
- throw new SyntaxError('Unexpected token in @opentelemetry/resources');
- });
- const error = await import('../src/instrumentation/otel.ts').then(() => undefined, (e: unknown) => e);
- // vitest wraps a mock factory's error: the factory's is a cause.
- const chain: string[] = [];
- for (let e = error as { message?: string; cause?: unknown } | undefined; e; e = e.cause as typeof e) chain.push(String(e.message));
- expect(chain.join(' <- ')).toMatch(/Unexpected token in @opentelemetry\/resources/);
- expect(chain.join(' <- ')).not.toMatch(/is not installed/);
- });
-
- it('is imported by src/instrumentation/otel.ts alone', () => {
- const packages = fileURLToPath(new URL('../..', import.meta.url));
- const importers: string[] = [];
- for (const dir of ['durable-harness', 'harness-world', 'harness-process', 'harness-hands', 'harness-claude-code', 'harness-codex', 'harness-opencode', 'harness-pi', 'pi-world']) {
- const src = join(packages, dir, 'src');
- for (const file of readdirSync(src, { recursive: true }) as string[]) {
- if (!/\.ts$/.test(file) || /\.test\.ts$/.test(file)) continue;
- // A type-only import loads nothing.
- const text = readFileSync(join(src, file), 'utf8').split('\n').filter((line) => !/^\s*import\s+type\b/.test(line)).join('\n');
- if (SDK.some((name) => new RegExp(String.raw`(?:from|import\()\s*['"]${name}['"]`).test(text))) importers.push(`${dir}/src/${file}`);
- }
- }
- expect(importers).toEqual(['durable-harness/src/instrumentation/otel.ts']);
- });
-});
diff --git a/packages/durable-harness/test/otel.test.ts b/packages/durable-harness/test/otel.test.ts
deleted file mode 100644
index b7cdf1e..0000000
--- a/packages/durable-harness/test/otel.test.ts
+++ /dev/null
@@ -1,319 +0,0 @@
-import { afterEach, describe, expect, it } from 'vitest';
-import { InMemorySpanExporter, SimpleSpanProcessor } from '@opentelemetry/sdk-trace-base';
-import { INSTRUMENTATION, instrumentation } from 'harness-world/instrumentation';
-import type { DriveContext } from 'harness-world';
-import type { World } from '@workflow/world';
-import { Fatal, Yield } from 'harness-world';
-import { agentRuns } from '../src/instrumentation/otel.ts';
-
-const requestContext = Symbol.for('@vercel/request-context');
-afterEach(() => { delete (globalThis as any)[INSTRUMENTATION]; delete (globalThis as any)[requestContext]; });
-function setup(options: Parameters<typeof agentRuns>[0] = {}) {
- const exporter = new InMemorySpanExporter();
- const integration = agentRuns({ audience: 'public', ...options, spanProcessors: [new SimpleSpanProcessor(exporter)] });
- integration.register();
- return { exporter, integration };
-}
-function ctx(sessionId = 'wrun_test', memo = false): DriveContext {
- const submission = { id: 'submission_1', text: 'private prompt', kind: 'prompt', receivedAt: new Date() };
- return {
- runId: sessionId, signal: new AbortController().signal, config: {}, attempt: 0,
- pending: () => [submission], state: () => ({ submissions: [submission] }),
- effect: async (key: string, _options: unknown, fn: any) => memo ? 'memoized' : fn({ stepId: key }),
- } as unknown as DriveContext;
-}
-describe('Agent Runs', () => {
- it('writes Eve-compatible Workflow visibility metadata after applying the export policy', async () => {
- const writes: { runId: string; attributes: Record<string, string | null>; reserved?: boolean }[] = [];
- const world = { runs: { async experimentalSetAttributes(runId: string, changes: { key: string; value: string | null }[], options: { allowReservedAttributes?: boolean }) {
- writes.push({ runId, attributes: Object.fromEntries(changes.map(c => [c.key, c.value])), reserved: options.allowReservedAttributes });
- return { attributes: {} };
- } } } as unknown as World;
- const { integration } = setup({ exportPolicy: { span: ({ audience }) => audience === 'public' ? { emit: true } : { redact: true, inputs: true, outputs: true } } });
- const publicScope = instrumentation()!.session('public', 'pi', 'turn', 'Public title', 'public', world);
- publicScope.start('model', { model: 'test' }).end({ role: 'assistant', content: 'public output' });
- publicScope.end();
- await publicScope.flush?.();
- const privateScope = instrumentation()!.session('private', 'pi', 'turn', 'Private title', 'private', world);
- privateScope.start('model', { model: 'test' }).end({ role: 'assistant', content: 'private output' });
- privateScope.end();
- await integration.forceFlush();
- expect(writes[0]).toMatchObject({ runId: 'public', reserved: true, attributes: {
- '$eve.type': 'session', '$eve.is_otel_trace_enabled': 'true', '$eve.is_trace_content_visible': 'true', '$eve.title': 'Public title',
- 'agent.framework.name': 'durable-harness',
- } });
- expect(writes[0].attributes['$eve.trace_id']).toMatch(/^[a-f0-9]{32}$/);
- expect(writes[1].attributes).toMatchObject({ '$eve.is_trace_content_visible': 'false', '$eve.title': null });
- expect(JSON.stringify(writes)).not.toContain('Private title');
- expect(JSON.stringify(writes)).not.toContain('private output');
- expect(JSON.stringify(writes)).not.toContain('public output');
- });
- it('awaits Workflow metadata for every turn in a drive and tolerates a metadata destination failure', async () => {
- const written: string[] = [];
- const world = { runs: { async experimentalSetAttributes(runId: string) {
- await Promise.resolve(); written.push(runId); throw new Error('metadata unavailable');
- } } } as unknown as World;
- setup();
- const c = ctx('metadata');
- const second = { ...c.pending()[0], id: 'submission_2', text: 'next' };
- await expect(instrumentation()!.drive({ name: 'fx', async drive(c) {
- await c.effect('first', { name: 'model', replay: 'safe', input: {}, placed: ['submission_1'] }, async () => 'done');
- await c.effect('next', { name: 'model', replay: 'safe', input: {}, placed: ['submission_2'] }, async () => 'done');
- } }, { ...c, world, state: () => ({ ...c.state(), submissions: [...c.state().submissions, second] }) })).resolves.toBeUndefined();
- expect(written).toEqual(['metadata', 'metadata']);
- });
- it('emits the deployed warehouse v4 contract with canonical step usage and nested model/tool spans', async () => {
- const { exporter, integration } = setup();
- await instrumentation()!.drive({ name: 'pi', async drive(c) {
- await c.effect('model:1', { name: 'model', replay: 'safe', input: { model: 'anthropic/test', appended: [{ role: 'user', content: 'hello' }] } }, async () => ({ role: 'assistant', content: [{ type: 'text', text: 'hi' }], usage: { input: 12, output: 4 } }));
- await c.effect('tool:1', { name: 'tool.read', replay: 'safe', input: { path: 'a.txt' } }, async () => 'file contents');
- } }, ctx());
- await integration.forceFlush();
- const spans = exporter.getFinishedSpans();
- const root = spans.find(s => s.name === 'invoke_agent pi')!;
- expect(root.attributes).toMatchObject({ 'agent.framework.name': 'durable-harness', 'agent.run.id': 'wrun_test', 'vercel.session_id': 'wrun_test', 'agent.trace.schema.version': 4, 'agent.turn.id': 'submission_1', 'agent.turn.outcome': 'completed' });
- expect(spans.every(s => s.instrumentationScope.name === 'eve.agent')).toBe(true);
- expect(spans.every(s => s.spanContext().traceId === root.spanContext().traceId)).toBe(true);
- const model = spans.find(s => s.name === 'chat anthropic/test')!;
- expect(JSON.parse(model.attributes['gen_ai.output.messages'] as string)[0].parts[0]).toEqual({ type: 'text', content: 'hi' });
- expect(spans.find(s => s.spanContext().spanId === model.parentSpanContext?.spanId)?.attributes['agent.usage.input_tokens']).toBe(12);
- expect(spans.find(s => s.name === 'execute_tool read')!.attributes['gen_ai.tool.call.result']).toBe('"file contents"');
- });
- it('does not emit model/tool spans for memoized work and preserves session trace identity across invocations', async () => {
- const { exporter } = setup();
- const harness = { name: 'test', async drive(c: DriveContext) { await c.effect('done', { name: 'tool.read', replay: 'safe', input: {} }, async () => 'new'); } };
- await instrumentation()!.drive(harness, ctx('same', true));
- await instrumentation()!.drive(harness, ctx('same', true));
- const spans = exporter.getFinishedSpans();
- expect(spans).toHaveLength(0);
- const a = instrumentation()!.session('same', 'test', 'turn'); a.end();
- const b = instrumentation()!.session('same', 'test', 'turn'); b.end();
- const roots = exporter.getFinishedSpans();
- expect(roots[0].spanContext().traceId).toBe(roots[1].spanContext().traceId);
- expect(roots[0].spanContext().spanId).not.toBe(roots[1].spanContext().spanId);
- });
- it('redacts inputs, outputs and status messages for unknown audiences', async () => {
- const { exporter } = setup({ audience: 'unknown' });
- const scope = instrumentation()!.session('private', 'codex', 'turn', 'private title');
- scope.start('tool.bash', { command: 'secret' }).end('secret result', new Error('secret error'));
- scope.end();
- for (const span of exporter.getFinishedSpans()) {
- expect(JSON.stringify({ attributes: span.attributes, status: span.status })).not.toContain('secret');
- expect(span.attributes['agent.trace.content.input']).toBe(false);
- expect(span.attributes['agent.trace.content.output']).toBe(false);
- expect(span.attributes['agent.session.title']).toBeUndefined();
- }
- });
- it('drops spans when a policy throws, and can replace attributes', () => {
- const a = setup({ exportPolicy: { span() { throw new Error('no'); } } });
- instrumentation()!.session('one', 'pi', 'turn').end();
- expect(a.exporter.getFinishedSpans()).toHaveLength(0);
- const b = setup({ exportPolicy: { attribute: ({ key }) => key === 'agent.name' ? { replace: true, value: 'custom' } : { emit: true } } });
- instrumentation()!.session('two', 'pi', 'turn').end();
- expect(b.exporter.getFinishedSpans()[0].attributes['agent.name']).toBe('custom');
- });
- it('keeps budget continuations running and creates no trace for idle drives', async () => {
- const { exporter } = setup();
- const c = ctx();
- const abort = new AbortController();
- const reason = Object.assign(new Error('budget'), { name: 'Yield' });
- const harness = { name: 'pi', async drive(c: DriveContext) {
- c.instrumentation!.start('model', { model: 'test' }).end({ usage: { input: 4, output: 2, cacheRead: 100 } });
- abort.abort(reason); throw reason;
- } };
- await expect(instrumentation()!.drive(harness, { ...c, signal: abort.signal })).rejects.toBe(reason);
- const root = exporter.getFinishedSpans().find(s => s.name.startsWith('invoke_agent'))!;
- expect(root.attributes['agent.turn.outcome']).toBe('running');
- expect(root.status.code).not.toBe(2);
- expect(exporter.getFinishedSpans().find(s => s.name === 'agent.step')!.attributes['agent.usage.input_tokens']).toBe(104);
- const count = exporter.getFinishedSpans().length;
- await instrumentation()!.drive({ name: 'pi', async drive() {} }, c);
- expect(exporter.getFinishedSpans()).toHaveLength(count);
- });
- it('splits fresh prompt turns but keeps one session trace identity', async () => {
- const { exporter } = setup();
- const c = ctx();
- const second = { ...c.pending()[0], id: 'submission_2', text: 'second prompt' };
- const state = { ...c.state(), submissions: [...c.state().submissions, second] };
- await instrumentation()!.drive({ name: 'fx', async drive(c) {
- await c.effect('one', { name: 'model', replay: 'safe', input: { model: 'test' }, placed: ['submission_1'] }, async () => ({}));
- await c.effect('two', { name: 'model', replay: 'safe', input: { model: 'test' }, placed: ['submission_2'] }, async () => ({}));
- } }, { ...c, state: () => state });
- const roots = exporter.getFinishedSpans().filter(s => s.name.startsWith('invoke_agent'));
- expect(roots.map(s => s.attributes['agent.turn.id'])).toEqual(['submission_1', 'submission_2']);
- expect(roots[0].spanContext().traceId).toBe(roots[1].spanContext().traceId);
- });
- it.each(['halt', 'throw'] as const)('marks a fatal %s as failed even when the drive is aborted', async (mode) => {
- const { exporter } = setup();
- const abort = new AbortController();
- const fatal = new Fatal('incompatible session log');
- const thrown = mode === 'halt' ? new Error('child aborted') : fatal;
- await expect(instrumentation()!.drive({ name: 'test', async drive(c) {
- c.instrumentation!.start('model', { model: 'test' });
- abort.abort(mode === 'halt' ? fatal : new Yield('budget'));
- throw thrown;
- } }, { ...ctx(), signal: abort.signal })).rejects.toBe(thrown);
- const spans = exporter.getFinishedSpans();
- const root = spans.find(s => s.name.startsWith('invoke_agent'))!;
- expect(root.attributes['agent.turn.outcome']).toBe('failed');
- expect(root.status).toMatchObject({ code: 2, message: fatal.message });
- expect(spans.find(s => s.name === 'chat test')!.status.code).toBe(2);
- });
- it('normalizes Gateway v4 and OpenAI Responses usage and content', () => {
- const { exporter } = setup();
- const scope = instrumentation()!.session('sse', 'fx', 'turn');
- scope.start('model', { model: 'test' }).end({ responseBody: [
- { type: 'tool-call', toolName: 'read', toolCallId: 'call_1', input: '{}' },
- { type: 'text-delta', delta: 'hello' },
- { type: 'finish', usage: { inputTokens: { total: 104, cacheRead: 100 }, outputTokens: { total: 2 } }, providerMetadata: { gateway: { gatewayCost: '0.01' } } },
- ].map(e => `data: ${JSON.stringify(e)}\n\n`).join('') });
- scope.start('model', { model: 'openai' }).end({ responseBody: 'data: {"type":"response.output_text.delta","delta":"response text"}\n\ndata: {"type":"response.completed","response":{"usage":{"input_tokens":12,"output_tokens":3}}}\n\n' });
- scope.end();
- const steps = exporter.getFinishedSpans().filter(s => s.name === 'agent.step');
- expect(new Set(steps.map(s => s.attributes['agent.step.id'])).size).toBe(2);
- expect(steps[0].attributes).toMatchObject({ 'agent.usage.input_tokens': 104, 'agent.usage.output_tokens': 2, 'gen_ai.usage.gateway_cost': 0.01 });
- // The model span: the same inclusive input with its cached part, as Agent Runs reads gen_ai usage.
- expect(exporter.getFinishedSpans().find(s => s.name === 'chat test')!.attributes)
- .toMatchObject({ 'gen_ai.usage.input_tokens': 104, 'gen_ai.usage.cache_read.input_tokens': 100, 'gen_ai.usage.output_tokens': 2 });
- expect(steps[1].attributes['agent.usage.input_tokens']).toBe(12);
- expect(JSON.stringify(exporter.getFinishedSpans().map(s => s.attributes))).toContain('response text');
- });
- it('captures Gateway prompt messages and Responses inputs supplied when a proxy call ends', () => {
- const { exporter } = setup();
- const scope = instrumentation()!.session('wire-inputs', 'test', 'turn');
- scope.start('model', {}).end({ requestBody: { model: 'gateway', prompt: [
- { role: 'user', content: [{ type: 'text', text: 'List 世界' }] },
- { role: 'tool', content: [{ type: 'tool-result', toolCallId: 'call', output: { type: 'text', value: 'a.txt' } }] },
- ] } });
- scope.start('model', {}).end({ requestBody: { model: 'responses', instructions: 'System context', input: [
- { role: 'user', content: [{ type: 'input_text', text: 'List files' }] },
- { type: 'function_call', call_id: 'call', name: 'shell', arguments: '{"command":"ls"}' },
- { type: 'function_call_output', call_id: 'call', output: 'a.txt' },
- ] } });
- scope.start('model', { requestBody: { model: 'responses', input: 'String input' } }).end();
- scope.end();
- const models = exporter.getFinishedSpans().filter(s => s.attributes['gen_ai.operation.name'] === 'chat');
- const inputs = models.map(s => JSON.parse(s.attributes['gen_ai.input.messages'] as string));
- expect(inputs[0]).toEqual([
- { role: 'user', parts: [{ type: 'text', content: 'List 世界' }] },
- { role: 'tool', parts: [{ type: 'tool_call_response', id: 'call', response: 'a.txt' }] },
- ]);
- expect(inputs[1]).toEqual([
- { role: 'user', parts: [{ type: 'text', content: 'List files' }] },
- { role: 'assistant', parts: [{ type: 'tool_call', id: 'call', name: 'shell', arguments: '{"command":"ls"}' }] },
- { role: 'tool', parts: [{ type: 'tool_call_response', id: 'call', response: 'a.txt' }] },
- ]);
- expect(models[1].attributes['gen_ai.system_instructions']).toBe('"System context"');
- expect(inputs[2]).toEqual([{ role: 'user', parts: [{ type: 'text', content: 'String input' }] }]);
- });
- it('reassembles interleaved Anthropic streamed tool arguments by content block', () => {
- const { exporter } = setup();
- const scope = instrumentation()!.session('anthropic-tools', 'claude-code', 'turn');
- scope.start('model', { model: 'anthropic/test' }).end({ responseBody: [
- { type: 'content_block_start', index: 1, content_block: { type: 'tool_use', id: 'read_1', name: 'read', input: {} } },
- { type: 'content_block_start', index: 2, content_block: { type: 'tool_use', id: 'read_2', name: 'read', input: {} } },
- { type: 'content_block_delta', index: 1, delta: { type: 'input_json_delta', partial_json: '{"path":' } },
- { type: 'content_block_delta', index: 2, delta: { type: 'input_json_delta', partial_json: '{"path":"b.txt"}' } },
- { type: 'content_block_delta', index: 1, delta: { type: 'input_json_delta', partial_json: '"世界.txt"}' } },
- { type: 'content_block_stop', index: 1 },
- { type: 'content_block_stop', index: 2 },
- ].map(e => `data: ${JSON.stringify(e)}\n\n`).join('') });
- scope.end();
- const model = exporter.getFinishedSpans().find(s => s.name.startsWith('chat '))!;
- expect(JSON.parse(model.attributes['gen_ai.output.messages'] as string)[0].parts).toEqual([
- { type: 'tool_call', id: 'read_1', name: 'read', arguments: { path: '世界.txt' } },
- { type: 'tool_call', id: 'read_2', name: 'read', arguments: { path: 'b.txt' } },
- ]);
- });
- it('preserves incomplete Anthropic arguments without failing the export', () => {
- const { exporter } = setup();
- const scope = instrumentation()!.session('partial-tools', 'claude-code', 'turn');
- scope.start('model', { model: 'anthropic/test' }).end({ responseBody: [
- { type: 'content_block_start', index: 0, content_block: { type: 'tool_use', id: 'call', name: 'read', input: {} } },
- { type: 'content_block_delta', index: 0, delta: { type: 'input_json_delta', partial_json: '{"path":"partial' } },
- ].map(e => `data: ${JSON.stringify(e)}\n\n`).join('') });
- scope.end();
- const model = exporter.getFinishedSpans().find(s => s.name.startsWith('chat '))!;
- expect(JSON.parse(model.attributes['gen_ai.output.messages'] as string)[0].parts[0].arguments).toBe('{"path":"partial');
- });
- it("gives a tool span the id the model gave its call, so Agent Runs shows one tool call", () => {
- const { exporter } = setup();
- const scope = instrumentation()!.session('tool-ids', 'test', 'turn');
- const sse = (events: unknown[]) => events.map(e => `data: ${JSON.stringify(e)}\n\n`).join('');
- // Claude Code, Pi, OpenCode, the AI SDK: the effect is keyed `tool:<call id>`.
- scope.start('model', { model: 'anthropic/test' }).end({ responseBody: sse([
- { type: 'content_block_start', index: 0, content_block: { type: 'tool_use', id: 'toolu_1', name: 'read', input: {} } },
- { type: 'content_block_delta', index: 0, delta: { type: 'input_json_delta', partial_json: '{"path":"a.txt"}' } },
- ]) });
- scope.start('tool.read', { path: 'a.txt' }, 'tool:toolu_1').end('a');
- // The fx kernel keys a call by position and input, pi-durable by its task: matched by name and arguments.
- scope.start('model', { model: 'test' }).end({ responseBody: sse([
- { type: 'tool-call', toolName: 'write_file', toolCallId: 'call_w', input: '{"path":"b.txt","content":"hi"}' },
- ]) });
- scope.start('tool.write_file', { content: 'hi', path: 'b.txt' }, 'tool:1:write_file:0123:0').end('ok');
- // Codex: an OpenAI Responses stream names its function calls in output items.
- scope.start('model', { model: 'openai/test' }).end({ responseBody: sse([
- { type: 'response.output_item.done', item: { type: 'function_call', call_id: 'call_r', name: 'shell', arguments: '{"command":"ls"}' } },
- ]) });
- scope.start('tool.shell', { command: 'ls' }, 'tool:call_r').end('a.txt');
- // No model call asked for it: the key, less its prefix.
- scope.start('tool.read', { path: 'c.txt' }, 'tool:orphan').end('c');
- scope.end();
- const spans = exporter.getFinishedSpans();
- expect(spans.filter(s => s.attributes['gen_ai.operation.name'] === 'execute_tool').map(s => s.attributes['gen_ai.tool.call.id']))
- .toEqual(['toolu_1', 'call_w', 'call_r', 'orphan']);
- const codex = spans.filter(s => s.attributes['gen_ai.operation.name'] === 'chat')[2]!;
- expect(JSON.parse(codex.attributes['gen_ai.output.messages'] as string)[0].parts)
- .toEqual([{ type: 'tool_call', id: 'call_r', name: 'shell', arguments: '{"command":"ls"}' }]);
- // The durable step keeps the effect's key.
- expect(spans.filter(s => s.name === 'agent.step').map(s => s.attributes['agent.step.id'])).toContain('tool:1:write_file:0123:0');
- });
- it('exports using the initiating Vercel request context even when a loopback callback has no context', () => {
- const reported: any[] = [];
- (globalThis as any)[requestContext] = { get: () => ({ telemetry: { reportSpans: (data: unknown) => reported.push(data) } }) };
- setup();
- const scope = instrumentation()!.session('callback', 'opencode', 'turn');
- delete (globalThis as any)[requestContext];
- scope.start('model', {}).end({ requestBody: { model: 'test', messages: [{ role: 'user', content: 'hi' }] }, responseBody: 'data: {"choices":[{"delta":{"content":"hello"}}],"usage":{"prompt_tokens":10,"completion_tokens":2}}\n\n' });
- scope.end();
- expect(reported).toHaveLength(3);
- expect(JSON.stringify(reported)).toContain('hello');
- expect(JSON.stringify(reported)).toContain('agent.usage.input_tokens');
- });
- it('keeps the proxy model ID when Gateway request bodies contain only prompt options', () => {
- const { exporter } = setup();
- const scope = instrumentation()!.session('gateway-model', 'opencode', 'turn');
- scope.start('model', { method: 'POST', path: '/v3/ai/language-model', model: 'anthropic/claude-haiku-4.5' }).end({
- requestBody: { prompt: [{ role: 'user', content: [{ type: 'text', text: 'hello' }] }] },
- responseBody: 'data: {"type":"response-metadata","modelId":"claude-haiku-4-5-20251001"}\n\ndata: {"type":"text-delta","delta":"hi"}\n\n',
- });
- scope.end();
- const spans = exporter.getFinishedSpans();
- const model = spans.find(s => s.attributes['gen_ai.operation.name'] === 'chat')!;
- expect(model.name).toBe('chat anthropic/claude-haiku-4.5');
- expect(model.attributes).toMatchObject({ 'gen_ai.request.model': 'anthropic/claude-haiku-4.5', 'gen_ai.response.model': 'claude-haiku-4-5-20251001' });
- expect(spans.find(s => s.name === 'agent.step')!.attributes['agent.model.id']).toBe('anthropic/claude-haiku-4.5');
- expect(JSON.parse(model.attributes['gen_ai.input.messages'] as string)).toEqual([{ role: 'user', parts: [{ type: 'text', content: 'hello' }] }]);
- });
- it("names a Gateway model by its Gateway id, without pi-ai's provider prefix", () => {
- const { exporter } = setup();
- const scope = instrumentation()!.session('pi-gateway', 'pi', 'turn');
- scope.start('model', { model: 'vercel-ai-gateway/anthropic/claude-haiku-4.5' }).end({ role: 'assistant', content: 'hi' });
- scope.start('model', {}).end({ requestBody: { model: 'vercel-ai-gateway/openai/gpt-5.4-mini' } });
- scope.end();
- const spans = exporter.getFinishedSpans();
- expect(spans.filter(s => s.name.startsWith('chat ')).map(s => s.name)).toEqual(['chat anthropic/claude-haiku-4.5', 'chat openai/gpt-5.4-mini']);
- expect(spans.filter(s => s.name === 'agent.step').map(s => s.attributes['agent.model.id'])).toEqual(['anthropic/claude-haiku-4.5', 'openai/gpt-5.4-mini']);
- });
- it('keeps agent work successful when an additional trace destination throws', async () => {
- const integration = agentRuns({ spanProcessors: [{
- onStart() { throw new Error('destination unavailable'); },
- onEnd() { throw new Error('destination unavailable'); },
- async forceFlush() {}, async shutdown() {},
- }] });
- integration.register();
- await expect(instrumentation()!.drive({ name: 'test', async drive(c) {
- expect(await c.effect('read', { name: 'tool.read', replay: 'safe', input: {} }, async () => 'file contents')).toBe('file contents');
- } }, ctx())).resolves.toBeUndefined();
- });
-});
diff --git a/packages/durable-harness/test/pi-durable-otel.test.ts b/packages/durable-harness/test/pi-durable-otel.test.ts
deleted file mode 100644
index 9d7a3b5..0000000
--- a/packages/durable-harness/test/pi-durable-otel.test.ts
+++ /dev/null
@@ -1,248 +0,0 @@
-import { mkdtempSync } from 'node:fs';
-import { tmpdir } from 'node:os';
-import { join } from 'node:path';
-import { BACKGROUND_CONTEXT as ctx } from '@earendil-works/chord/context';
-import { Type } from '@earendil-works/pi-ai';
-import { createModels } from '@earendil-works/pi-ai/models';
-import { fauxAssistantMessage, fauxProvider, fauxText, fauxToolCall } from '@earendil-works/pi-ai/providers/faux';
-import { createRegistry, defineExtension, defineTool, Harness, type Storage, type ToolRegistration } from '@earendil-works/pi-durable';
-import { InMemorySpanExporter, type ReadableSpan, SimpleSpanProcessor } from '@opentelemetry/sdk-trace-base';
-import { INSTRUMENTATION } from 'harness-world/instrumentation';
-import { afterAll, beforeAll, beforeEach, describe, expect, it } from 'vitest';
-import { agentRuns, filteringProcessor } from '../src/instrumentation/otel.ts';
-import { CodingTools, chatRoute, openWorldReader, openWorldStorage, resumeWith, virtualEnv } from '../src/pi-durable.ts';
-import { getWorld } from '../src/world.ts';
-
-/**
- * Agent Runs for pi-durable, the additive way: a Pi app's own code on
- * `openWorldStorage` (and `resumeWith`, and the optional `chatRoute`) traces
- * its turns through durable-harness's OpenTelemetry integration with no
- * wrapper around Pi's API. Spans go to an in-memory span processor.
- */
-
-const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms));
-async function until<T>(fn: () => Promise<T | undefined | false> | T | undefined | false, timeoutMs = 30_000): Promise<T> {
- const start = Date.now();
- for (;;) {
- const value = await fn();
- if (value !== undefined && value !== false) return value;
- if (Date.now() - start > timeoutMs) throw new Error('timed out');
- await sleep(50);
- }
-}
-
-/** A Pi app's own setup: a scripted faux model, a registry with `tools`, and its opener. */
-function piApp(answers: Parameters<ReturnType<typeof fauxProvider>['setResponses']>[0], tools: ToolRegistration[] = []) {
- const faux = fauxProvider();
- faux.setResponses(answers);
- const models = createModels();
- models.setProvider(faux.provider);
- const model = faux.getModel();
- const registry = createRegistry();
- if (tools.length) registry.install(defineExtension({ name: 'app', tools }));
- const open = (storage: Storage) => Harness.open(storage, { models, registry }, ctx);
- return { open, model: `${model.provider}/${model.id}`, agent: { model: { provider: model.provider, modelId: model.id } } };
-}
-
-const MARKER = 'zebra-7f3a';
-const shout = defineTool({
- name: 'shout',
- description: 'Uppercase some text.',
- parameters: Type.Object({ text: Type.String() }),
- replay: 'safe',
- execute: async (args: { text: string }) => ({ content: [{ type: 'text', text: args.text.toUpperCase() }] }),
-}) as ToolRegistration;
-const shoutTurn = () => [fauxAssistantMessage([fauxToolCall('shout', { text: MARKER })], { stopReason: 'toolUse' }), fauxAssistantMessage([fauxText('Shouted.')])];
-
-/** A tool that waits until `release()` (or its call is aborted). */
-function gate(name: string) {
- let release!: () => void;
- const released = new Promise<void>((r) => (release = r));
- let started = 0;
- const tool = defineTool({
- name,
- description: `${name}.`,
- parameters: Type.Object({ text: Type.String() }),
- replay: 'safe',
- execute: async (_args, _api, context) => {
- started++;
- await Promise.race([released, new Promise((r) => context.abortSignal?.addEventListener('abort', r, { once: true }))]);
- return { content: [{ type: 'text', text: `${name} done` }] };
- },
- }) as ToolRegistration;
- return { tool, started: () => started, release: () => release() };
-}
-
-const exporter = new InMemorySpanExporter();
-const integration = agentRuns({ audience: 'public', exportPolicy: { span: () => ({ emit: true }) }, spanProcessors: [new SimpleSpanProcessor(exporter)] });
-const spansOf = (sessionId: string) => exporter.getFinishedSpans().filter((s) => s.attributes['agent.run.id'] === sessionId);
-const roots = (spans: ReadableSpan[]) => spans.filter((s) => s.attributes['gen_ai.operation.name'] === 'invoke_agent');
-
-describe('Agent Runs for pi-durable, additive (openWorldStorage, resumeWith, chatRoute)', () => {
- beforeAll(() => {
- process.env.WORKFLOW_TARGET_WORLD = 'local';
- process.env.WORKFLOW_LOCAL_DATA_DIR = mkdtempSync(join(tmpdir(), 'dh-pi-durable-otel-'));
- integration.register();
- });
- afterAll(async () => {
- await integration.forceFlush();
- delete (globalThis as Record<symbol, unknown>)[INSTRUMENTATION];
- await ((await getWorld()) as { close?: () => Promise<void> }).close?.();
- });
- beforeEach(() => exporter.reset());
-
- it("traces a turn of a Pi app's own code on openWorldStorage: the root, steps, model and tool spans, with its audience", async () => {
- const app = piApp(shoutTurn(), [shout]);
- const open = resumeWith(app.open, { name: 'otel-own-code' });
- const storage = await openWorldStorage(undefined, { name: 'otel-own-code', traceAudience: 'private' });
- const harness = await open(storage);
- const root = await harness.root(ctx, { agent: app.agent });
- expect((await (await root.submit({ type: 'input', content: `shout ${MARKER}` }, ctx)).wait(ctx)).status).toBe('done');
- await harness.close(ctx);
- await integration.forceFlush();
-
- const spans = spansOf(storage.sessionId);
- const byId = new Map(spans.map((s) => [s.spanContext().spanId, s]));
- const parentOf = (s: ReadableSpan) => (s.parentSpanContext ? byId.get(s.parentSpanContext.spanId) : undefined);
- const [turn, ...more] = roots(spans);
- expect(more).toEqual([]);
- expect(turn!.name).toBe('invoke_agent otel-own-code');
- expect(turn!.attributes).toMatchObject({
- 'agent.framework.name': 'durable-harness',
- 'agent.run.id': storage.sessionId,
- 'agent.channel.audience': 'private',
- 'agent.turn.outcome': 'completed',
- });
- expect(String(turn!.attributes['agent.session.title'])).toContain(MARKER);
- expect(new Set(spans.map((s) => s.spanContext().traceId)).size).toBe(1);
- const models = spans.filter((s) => s.attributes['gen_ai.operation.name'] === 'chat');
- expect(models.map((s) => s.name)).toEqual([`chat ${app.model}`, `chat ${app.model}`]);
- expect(String(models[0]!.attributes['gen_ai.input.messages'])).toContain(MARKER);
- const tool = spans.find((s) => s.name === 'execute_tool shout')!;
- expect(String(tool.attributes['gen_ai.tool.call.arguments'])).toContain(MARKER);
- expect(String(tool.attributes['gen_ai.tool.call.result'])).toContain(MARKER.toUpperCase());
- for (const s of [...models, tool]) {
- expect(parentOf(s)!.name).toBe('agent.step');
- expect(parentOf(parentOf(s)!)).toBe(turn);
- }
- expect(models.every((m) => typeof parentOf(m)!.attributes['agent.usage.input_tokens'] === 'number')).toBe(true);
-
- // The default export policy: a private session's spans carry no content.
- const out: ReadableSpan[] = [];
- const policy = filteringProcessor({ onStart() {}, onEnd: (s) => void out.push(s), forceFlush: async () => {}, shutdown: async () => {} });
- for (const s of spans) policy.onEnd(s);
- expect(out).toHaveLength(spans.length);
- for (const s of out) expect(JSON.stringify({ attributes: s.attributes, status: s.status, events: s.events })).not.toMatch(new RegExp(MARKER, 'i'));
-
- // Reading the session back replays its journal: no new spans.
- const count = exporter.getFinishedSpans().length;
- const again = await open(await openWorldStorage(storage.sessionId, { name: 'otel-own-code' }));
- await again.close(ctx);
- await integration.forceFlush();
- expect(exporter.getFinishedSpans()).toHaveLength(count);
- });
-
- it('a turn a wake finishes traces with the audience the session recorded, in the same trace', async () => {
- const work = gate('work');
- const app = piApp([fauxAssistantMessage([fauxToolCall('work', { text: MARKER })], { stopReason: 'toolUse' }), fauxAssistantMessage([fauxText('Worked.')])], [work.tool]);
- // resumeWith's audience is only for sessions that recorded none: this one recorded private.
- const open = resumeWith(app.open, { name: 'otel-wake', traceAudience: 'public' });
- const storage = await openWorldStorage(undefined, { name: 'otel-wake', traceAudience: 'private' });
- const harness = await open(storage);
- await (await harness.root(ctx, { agent: app.agent })).submit({ type: 'input', content: `work on ${MARKER}` }, ctx);
- await until(() => work.started() === 1);
- // Closing mid-turn hands the session to a wake, which reruns the safe tool and finishes the turn.
- await harness.close(ctx);
- work.release();
- const reader = openWorldReader(storage.sessionId);
- await until(async () => {
- await reader.refresh();
- const s = await reader.snapshot();
- return !s.unfinished && JSON.stringify(s.entries).includes('Worked.');
- });
- const turns = await until(async () => {
- await integration.forceFlush();
- const r = roots(spansOf(storage.sessionId));
- return r.some((s) => s.attributes['agent.turn.outcome'] === 'completed') ? r : undefined;
- });
- // The request's root ends running (it closed with work left); the wake's completes the turn.
- expect(turns.map((s) => s.attributes['agent.turn.outcome'])).toEqual(['running', 'completed']);
- expect(turns.every((s) => s.attributes['agent.channel.audience'] === 'private')).toBe(true);
- const spans = spansOf(storage.sessionId);
- expect(new Set(spans.map((s) => s.spanContext().traceId)).size).toBe(1);
- expect(spans.filter((s) => s.name === 'execute_tool work').length).toBeGreaterThanOrEqual(1);
- });
-
- it("a wake of a session that recorded no audience uses resumeWith's", async () => {
- const work = gate('slow');
- const app = piApp([fauxAssistantMessage([fauxToolCall('slow', { text: MARKER })], { stopReason: 'toolUse' }), fauxAssistantMessage([fauxText('Slow done.')])], [work.tool]);
- const open = resumeWith(app.open, { name: 'otel-wake-default', traceAudience: 'unknown' });
- const storage = await openWorldStorage(undefined, { name: 'otel-wake-default' });
- const harness = await open(storage);
- await (await harness.root(ctx, { agent: app.agent })).submit({ type: 'input', content: 'go' }, ctx);
- await until(() => work.started() === 1);
- await harness.close(ctx);
- work.release();
- const turns = await until(async () => {
- await integration.forceFlush();
- const r = roots(spansOf(storage.sessionId));
- return r.some((s) => s.attributes['agent.turn.outcome'] === 'completed') ? r : undefined;
- });
- // The request's storage had no audience: the integration's (public). The wake's: resumeWith's.
- expect(turns.map((s) => [s.attributes['agent.turn.outcome'], s.attributes['agent.channel.audience']])).toEqual([
- ['running', 'public'],
- ['completed', 'unknown'],
- ]);
- });
-
- it("chatRoute's sessions are public on a public route, unknown on an authorized one, and an explicit audience wins", async () => {
- const post = (body: unknown) => new Request('http://local/api/chat', { method: 'POST', body: JSON.stringify(body), headers: { 'content-type': 'application/json' } });
- const cases = [
- { name: 'otel-chat-public', options: { authorize: 'public' as const }, audience: 'public' },
- { name: 'otel-chat-auth', options: { authorize: async () => true }, audience: 'unknown' },
- { name: 'otel-chat-private', options: { authorize: 'public' as const, traceAudience: 'private' as const }, audience: 'private' },
- ];
- for (const c of cases) {
- const app = piApp(shoutTurn(), [shout]);
- const open = resumeWith(app.open, { name: c.name });
- const route = chatRoute({ open, agent: app.agent, name: c.name, ...c.options });
- const res = await route.POST(post({ text: `shout ${MARKER}` }));
- expect(res.status).toBe(200);
- const sessionId = res.headers.get('x-session-id')!;
- await res.text();
- const [turn] = await until(async () => {
- await integration.forceFlush();
- const r = roots(spansOf(sessionId));
- return r.length ? r : undefined;
- });
- expect([c.name, turn!.attributes['agent.channel.audience']]).toEqual([c.name, c.audience]);
- expect(spansOf(sessionId).some((s) => s.name === 'execute_tool shout')).toBe(true);
- }
- }, 60_000);
-
- it('Pi\'s coding tools on a virtual workspace (CodingTools, virtualEnv) trace as tool spans, with what the model saw', async () => {
- const faux = fauxProvider();
- faux.setResponses([
- fauxAssistantMessage([fauxToolCall('write', { path: 'note.txt', content: MARKER })], { stopReason: 'toolUse' }),
- fauxAssistantMessage([fauxToolCall('bash', { command: 'cat note.txt' })], { stopReason: 'toolUse' }),
- fauxAssistantMessage([fauxText('Read it.')]),
- ]);
- const models = createModels();
- models.setProvider(faux.provider);
- const registry = createRegistry();
- registry.install(CodingTools);
- const open = resumeWith((storage: Storage) => Harness.open(storage, { models, registry, env: virtualEnv() }, ctx), { name: 'otel-coding-tools' });
- const storage = await openWorldStorage(undefined, { name: 'otel-coding-tools', traceAudience: 'public' });
- const harness = await open(storage);
- const root = await harness.root(ctx, { agent: { model: { provider: faux.getModel().provider, modelId: faux.getModel().id } } });
- expect((await (await root.submit({ type: 'input', content: 'write and read' }, ctx)).wait(ctx)).status).toBe('done');
- await harness.close(ctx);
- await integration.forceFlush();
- const spans = spansOf(storage.sessionId);
- const write = spans.find((s) => s.name === 'execute_tool write')!;
- const bash = spans.find((s) => s.name === 'execute_tool bash')!;
- expect(String(write.attributes['gen_ai.tool.call.arguments'])).toContain(MARKER);
- expect(String(bash.attributes['gen_ai.tool.call.result'])).toContain(MARKER);
- expect(roots(spans)).toHaveLength(1);
- });
-});
diff --git a/packages/harness-claude-code/src/harness.ts b/packages/harness-claude-code/src/harness.ts
index f066b03..5666c64 100644
--- a/packages/harness-claude-code/src/harness.ts
+++ b/packages/harness-claude-code/src/harness.ts
@@ -400,6 +400,8 @@ export function claudeCodeHarness(options: ClaudeCodeHarnessOptions = {}): Harne
return {
name: options.name ?? 'claude-code',
+ // Each model request reaches Agent Runs from the Gateway proxy (`ModelSteps.request`).
+ modelCalls: 'self',
async drive(ctx: DriveContext) {
// Nothing to do (an idle wake, a chaos arming): no VM. A model step a
// crash left open after its turn ended is closed (no request will retry it).
diff --git a/packages/harness-codex/src/harness.ts b/packages/harness-codex/src/harness.ts
index 0630083..3465484 100644
--- a/packages/harness-codex/src/harness.ts
+++ b/packages/harness-codex/src/harness.ts
@@ -387,6 +387,8 @@ export function codexHarness(options: CodexHarnessOptions = {}): Harness {
return {
name: options.name ?? 'codex',
+ // Each model request reaches Agent Runs from the Gateway proxy (`ModelSteps.request`).
+ modelCalls: 'self',
async drive(ctx: DriveContext) {
// Nothing to do (an idle wake, a chaos arming): no VM. A model step a
// crash left open after its turn ended is closed (no request will retry it).
diff --git a/packages/harness-fx/package.json b/packages/harness-fx/package.json
index f2e9472..5d4cfdb 100644
--- a/packages/harness-fx/package.json
+++ b/packages/harness-fx/package.json
@@ -13,7 +13,8 @@
"typecheck": "tsc --noEmit"
},
"dependencies": {
- "harness-world": "workspace:*"
+ "harness-world": "workspace:*",
+ "@vercel/agent-runs": "0.0.1"
},
"peerDependencies": {
"libfx": "catalog:"
diff --git a/packages/harness-fx/src/agent-runs.test.ts b/packages/harness-fx/src/agent-runs.test.ts
new file mode 100644
index 0000000..ddfc436
--- /dev/null
+++ b/packages/harness-fx/src/agent-runs.test.ts
@@ -0,0 +1,10 @@
+import { describe, expect, it } from 'vitest';
+import { fxModelOptions } from './agent-runs.ts';
+
+describe('fx trace tool definitions', () => {
+ it('keeps only a tool definition, not its provider configuration', () => {
+ const options = fxModelOptions('test/model', { prompt: [], tools: [{ name: 'remote_lookup', inputSchema: { type: 'object' }, args: { authorization: 'test-only-credential' }, headers: { 'x-api-key': 'test-only-credential' } }] });
+ expect(options.tools).toEqual([{ name: 'remote_lookup', inputSchema: { type: 'object' } }]);
+ expect(JSON.stringify(options)).not.toContain('test-only-credential');
+ });
+});
diff --git a/packages/harness-fx/src/agent-runs.ts b/packages/harness-fx/src/agent-runs.ts
new file mode 100644
index 0000000..810a28a
--- /dev/null
+++ b/packages/harness-fx/src/agent-runs.ts
@@ -0,0 +1,85 @@
+import type { Attributes } from '@vercel/agent-runs';
+import type { ContentPart, ModelOptions, ModelResult } from 'harness-world/agent-runs';
+import { modelMessages, modelTools } from 'harness-world/agent-runs';
+
+/**
+ * fx's model calls as Agent Runs records them: libfx's kernel sends AI
+ * Gateway language-model calls (an AI SDK prompt, which `@vercel/agent-runs`
+ * reads as it is) and reads back the Gateway's stream of AI SDK parts.
+ */
+
+const record = (v: unknown): Record<string, unknown> => (v !== null && typeof v === 'object' ? (v as Record<string, unknown>) : {});
+
+/** The call on AI Gateway: its model id (`provider/model`, as Agent Runs links it), and the call's prompt and tools. */
+export function fxModelOptions(model: string | undefined, request: unknown): ModelOptions {
+ const body = record(request);
+ const prompt = Array.isArray(body.prompt) ? (body.prompt as Record<string, unknown>[]) : [];
+ const instructions = prompt.filter((m) => m.role === 'system').map((m) => (typeof m.content === 'string' ? m.content : '')).filter(Boolean);
+ return {
+ provider: 'gateway',
+ modelId: model ?? 'unknown',
+ messages: modelMessages(prompt.filter((m) => m.role !== 'system')),
+ ...(instructions.length ? { instructions: instructions.join('\n\n') } : {}),
+ ...(Array.isArray(body.tools) ? { tools: modelTools(body.tools) } : {}),
+ };
+}
+
+/** The stream's parts (`data: {...}` events). */
+function parts(body: string): Record<string, unknown>[] {
+ return body.split('\n\n').flatMap((block) => {
+ const data = block.trim().replace(/^data: /, '');
+ if (!data.startsWith('{')) return [];
+ try {
+ return [JSON.parse(data) as Record<string, unknown>];
+ } catch {
+ return [];
+ }
+ });
+}
+
+const tokens = (v: unknown): number | undefined => (typeof v === 'number' ? v : typeof record(v).total === 'number' ? (record(v).total as number) : undefined);
+
+export function fxModelResult(output: { body: string; text: string; toolCalls: { toolCallId: string; toolName: string; input: unknown }[]; finishReason?: string }): ModelResult {
+ const all = parts(output.body);
+ const finish = record(all.findLast((p) => p.type === 'finish'));
+ const usage = record(finish.usage);
+ const meta = record(all.find((p) => p.type === 'response-metadata'));
+ let reasoning = '';
+ for (const p of all) if (p.type === 'reasoning-delta' && typeof p.delta === 'string') reasoning += p.delta;
+ const content: ContentPart[] = [
+ ...(reasoning ? [{ type: 'reasoning' as const, text: reasoning }] : []),
+ ...(output.text ? [{ type: 'text' as const, text: output.text }] : []),
+ ...output.toolCalls.map((c) => ({ type: 'tool-call' as const, callId: c.toolCallId, toolName: c.toolName, input: typeof c.input === 'string' ? safeJson(c.input) : c.input })),
+ ];
+ const cacheRead = record(usage.inputTokens).cacheRead;
+ const cacheWrite = record(usage.inputTokens).cacheWrite;
+ return {
+ finishReason: output.finishReason ?? 'unknown',
+ usage: {
+ inputTokens: tokens(usage.inputTokens),
+ outputTokens: tokens(usage.outputTokens),
+ inputTokenDetails: {
+ ...(typeof cacheRead === 'number' ? { cacheReadTokens: cacheRead } : {}),
+ ...(typeof cacheWrite === 'number' ? { cacheWriteTokens: cacheWrite } : {}),
+ },
+ },
+ ...(typeof meta.id === 'string' ? { responseId: meta.id } : {}),
+ ...(typeof meta.modelId === 'string' ? { responseModelId: meta.modelId } : {}),
+ content,
+ };
+}
+
+/** What the Gateway charged for the call (its `finish` part's provider metadata), where Agent Runs reads it. */
+export function fxStepAttributes(body: string): Attributes {
+ const gateway = record(record(record(parts(body).findLast((p) => p.type === 'finish')).providerMetadata).gateway);
+ const usd = (v: unknown) => (v === undefined || v === null || v === '' || !Number.isFinite(Number(v)) ? undefined : Number(v));
+ return { 'gen_ai.usage.cost': usd(gateway.cost), 'gen_ai.usage.gateway_cost': usd(gateway.gatewayCost) };
+}
+
+function safeJson(text: string): unknown {
+ try {
+ return JSON.parse(text);
+ } catch {
+ return text;
+ }
+}
diff --git a/packages/harness-fx/src/index.ts b/packages/harness-fx/src/index.ts
index 5f93022..2767e10 100644
--- a/packages/harness-fx/src/index.ts
+++ b/packages/harness-fx/src/index.ts
@@ -12,6 +12,7 @@ import {
Yield,
} from 'harness-world';
import type { FxEngineOptions } from 'libfx';
+import { fxModelOptions, fxModelResult, fxStepAttributes } from './agent-runs.ts';
/**
* libfx's `createFxEngine` (from `libfx` on Node, `libfx/browser` in a tab):
@@ -216,6 +217,7 @@ export function fxHarness(options: FxHarnessOptions): Harness {
let config: Promise<string> | undefined;
return {
name: 'fx',
+ modelCalls: 'self',
drive: async (ctx) => new FxDrive(options, ctx, await (config ??= fxConfigHash(options))).run(),
};
}
@@ -747,70 +749,81 @@ class FxDrive {
},
async (io) => {
if (this.stop) throw this.stop;
- this.inFlight.add(abort);
+ const traced = await this.ctx.tracing?.modelCall(fxModelOptions(model, request));
try {
- const attempts = this.options.modelAttempts ?? 3;
- let response: Response | undefined;
- for (let attempt = 1; ; attempt++) {
+ const output = await (async () => {
+ this.inFlight.add(abort);
try {
- response = await abortable(realFetch(url, { ...init, body: bodyText, signal: abort.signal }), abort.signal);
- } catch (err) {
- if (this.stop) throw this.stop;
- if (attempt >= attempts) throw err;
- await sleep(500 * attempt);
- continue;
- }
- if (response.ok && response.body) break;
- const detail = await response.text().catch(() => '');
- if (this.stop) throw this.stop;
- if (attempt >= attempts || !(response.status === 429 || response.status >= 500)) {
- throw new Error(`model request failed: ${response.status} ${detail}`);
- }
- await sleep(500 * attempt);
- }
- const decoder = new TextDecoder();
- const reader = response.body!.getReader();
- let first = false;
- let body = '';
- let pending = '';
- let holding = false;
- for (;;) {
- let read: ReadableStreamReadResult<Uint8Array>;
- try {
- read = await abortable(reader.read(), abort.signal);
- } catch (err) {
- if (this.stop) throw this.stop;
- throw err;
- }
- if (this.stop) throw this.stop;
- const { value, done } = read;
- if (done) break;
- const chunk = decoder.decode(value, { stream: true });
- body += chunk;
- pending += chunk;
- // TTFT: the first model output event of this request (text, reasoning or a tool call).
- if (!first && hasOutput(pending)) {
- first = true;
- this.ctx.mark?.('model.first_token', { key });
- }
- // Forward whole events only, until the first one worth holding.
- let boundary = pending.indexOf('\n\n');
- while (!holding && boundary !== -1) {
- const event = pending.slice(0, boundary + 2);
- if (!isDelta(event)) {
- holding = true;
- break;
+ const attempts = this.options.modelAttempts ?? 3;
+ let response: Response | undefined;
+ for (let attempt = 1; ; attempt++) {
+ try {
+ response = await abortable(realFetch(url, { ...init, body: bodyText, signal: abort.signal }), abort.signal);
+ } catch (err) {
+ if (this.stop) throw this.stop;
+ if (attempt >= attempts) throw err;
+ await sleep(500 * attempt);
+ continue;
+ }
+ if (response.ok && response.body) break;
+ const detail = await response.text().catch(() => '');
+ if (this.stop) throw this.stop;
+ if (attempt >= attempts || !(response.status === 429 || response.status >= 500)) {
+ throw new Error(`model request failed: ${response.status} ${detail}`);
+ }
+ await sleep(500 * attempt);
}
- pending = pending.slice(boundary + 2);
- await forward(event);
- io.progress(event);
- boundary = pending.indexOf('\n\n');
+ const decoder = new TextDecoder();
+ const reader = response.body!.getReader();
+ let first = false;
+ let body = '';
+ let pending = '';
+ let holding = false;
+ for (;;) {
+ let read: ReadableStreamReadResult<Uint8Array>;
+ try {
+ read = await abortable(reader.read(), abort.signal);
+ } catch (err) {
+ if (this.stop) throw this.stop;
+ throw err;
+ }
+ if (this.stop) throw this.stop;
+ const { value, done } = read;
+ if (done) break;
+ const chunk = decoder.decode(value, { stream: true });
+ body += chunk;
+ pending += chunk;
+ // TTFT: the first model output event of this request (text, reasoning or a tool call).
+ if (!first && hasOutput(pending)) {
+ first = true;
+ this.ctx.mark?.('model.first_token', { key });
+ }
+ // Forward whole events only, until the first one worth holding.
+ let boundary = pending.indexOf('\n\n');
+ while (!holding && boundary !== -1) {
+ const event = pending.slice(0, boundary + 2);
+ if (!isDelta(event)) {
+ holding = true;
+ break;
+ }
+ pending = pending.slice(boundary + 2);
+ await forward(event);
+ io.progress(event);
+ boundary = pending.indexOf('\n\n');
+ }
+ }
+ held = pending;
+ return summarize(response!.status, body);
+ } finally {
+ this.inFlight.delete(abort);
}
- }
- held = pending;
- return summarize(response!.status, body);
- } finally {
- this.inFlight.delete(abort);
+ })();
+ await traced?.model.complete({ outcome: 'completed', result: fxModelResult(output) });
+ traced?.attempt.attributes(fxStepAttributes(output.body));
+ return output;
+ } catch (error) {
+ await traced?.model.fail(error);
+ throw error;
}
}
);
diff --git a/packages/harness-opencode/src/harness.ts b/packages/harness-opencode/src/harness.ts
index f4f077e..eb89634 100644
--- a/packages/harness-opencode/src/harness.ts
+++ b/packages/harness-opencode/src/harness.ts
@@ -205,6 +205,8 @@ export function opencodeHarness(options: OpenCodeHarnessOptions = {}): Harness {
return {
name: options.name ?? 'opencode',
+ // Each model request reaches Agent Runs from the Gateway proxy (`ModelSteps.request`).
+ modelCalls: 'self',
async drive(ctx: DriveContext) {
// Another OpenCode or effect than the pins fails the turn here, with both versions, instead of hanging it.
assertOpenCodeVersions();
@@ -246,7 +248,7 @@ export function opencodeHarness(options: OpenCodeHarnessOptions = {}): Harness {
// so the proxy takes that too (whoever holds it needs no proxy).
const key = gatewayToken();
const envKey = !options.connect ? process.env.AI_GATEWAY_API_KEY : undefined;
- proxy = await gatewayProxy({ credential, track: steps.request, token: envKey ? [key, envKey] : key, ...(options.gatewayUrl ? { target: options.gatewayUrl } : {}) });
+ proxy = await gatewayProxy({ credential, track: steps.request, captureRequest: ctx.tracing !== undefined, token: envKey ? [key, envKey] : key, ...(options.gatewayUrl ? { target: options.gatewayUrl } : {}) });
await mkdir(here, { recursive: true, mode: 0o700 });
await writeFile(join(here, OWNER), JSON.stringify({ pid: process.pid }), { mode: 0o600 });
init = {
diff --git a/packages/harness-pi/package.json b/packages/harness-pi/package.json
index 33e190f..9760962 100644
--- a/packages/harness-pi/package.json
+++ b/packages/harness-pi/package.json
@@ -5,7 +5,8 @@
"type": "module",
"description": "Pi (@earendil-works/pi-agent-core) on a Workflow World.",
"exports": {
- ".": "./src/index.ts"
+ ".": "./src/index.ts",
+ "./agent-runs": "./src/agent-runs.ts"
},
"scripts": {
"test": "vitest run",
@@ -15,7 +16,8 @@
"@earendil-works/pi-agent-core": "1.0.4",
"@earendil-works/pi-ai": "1.0.4",
"harness-world": "workspace:*",
- "typebox": "1.3.27"
+ "typebox": "1.3.27",
+ "@vercel/agent-runs": "0.0.1"
},
"devDependencies": {
"@workflow/world-local": "catalog:"
diff --git a/packages/harness-pi/src/agent-runs.ts b/packages/harness-pi/src/agent-runs.ts
new file mode 100644
index 0000000..c9fe735
--- /dev/null
+++ b/packages/harness-pi/src/agent-runs.ts
@@ -0,0 +1,76 @@
+import type { AssistantMessage, Message, Model } from '@earendil-works/pi-ai';
+import type { Attributes, ContentPart } from '@vercel/agent-runs';
+import type { ModelOptions, ModelResult } from 'harness-world/agent-runs';
+
+/**
+ * Pi's messages and responses as Agent Runs records them
+ * (`@vercel/agent-runs`, which reads AI SDK model messages). Shared by the
+ * kernel harness (harness-pi) and pi-durable's storage (pi-world).
+ */
+
+type ModelMessage = { role: string; content: string | Record<string, unknown>[] };
+
+const text = (content: string | readonly { type: string; text?: string }[]) =>
+ typeof content === 'string' ? content : content.flatMap((p) => (p.type === 'text' && typeof p.text === 'string' ? [{ type: 'text', text: p.text }] : []));
+
+/** The request's messages, in AI SDK form; its system messages are the instructions and the tools it offers. */
+export function piModelMessages(messages: readonly Message[]): { messages: ModelMessage[]; instructions?: string; tools?: unknown[] } {
+ const out: ModelMessage[] = [];
+ const system: string[] = [];
+ const tools = new Map<string, unknown>();
+ for (const m of messages) {
+ if (m.role === 'system') {
+ const content = typeof m.content === 'string' ? m.content : m.content.map((p) => p.text).join('\n');
+ if (content) system.push(content);
+ for (const section of Object.values(m.sections ?? {})) if (section) system.push(section);
+ for (const tool of m.toolsAdded ?? []) tools.set(tool.name, { type: 'function', name: tool.name, description: tool.description, inputSchema: tool.parameters });
+ for (const tool of m.toolsRemoved ?? []) tools.delete(tool.name);
+ } else if (m.role === 'user') {
+ out.push({ role: 'user', content: text(m.content) });
+ } else if (m.role === 'assistant') {
+ out.push({ role: 'assistant', content: m.content.map(piPart).map((p) => (p.type === 'tool-call' ? { type: p.type, toolCallId: p.callId, toolName: p.toolName, input: p.input } : p)) });
+ } else {
+ const value = m.content.flatMap((p) => (p.type === 'text' ? [p.text] : [])).join('\n');
+ out.push({ role: 'tool', content: [{ type: 'tool-result', toolCallId: m.toolCallId, toolName: m.toolName, output: { type: m.isError ? 'error-text' : 'text', value } }] });
+ }
+ }
+ return { messages: out, ...(system.length ? { instructions: system.join('\n\n') } : {}), ...(tools.size ? { tools: [...tools.values()] } : {}) };
+}
+
+function piPart(p: AssistantMessage['content'][number]): ContentPart {
+ if (p.type === 'text') return { type: 'text', text: p.text };
+ if (p.type === 'thinking') return { type: 'reasoning', text: p.thinking };
+ return { type: 'tool-call', callId: p.id, toolName: p.name, input: p.arguments };
+}
+
+/** A model call's options: the model, and the request's messages. */
+export function piModelOptions(model: Pick<Model<never>, 'provider' | 'id'> | { provider: string; modelId: string }, messages: readonly Message[]): ModelOptions {
+ return { provider: model.provider, modelId: 'id' in model ? model.id : model.modelId, ...piModelMessages(messages) };
+}
+
+const FINISH: Record<string, string> = { stop: 'stop', length: 'length', toolUse: 'tool-calls', error: 'error', aborted: 'other' };
+
+/**
+ * A response as a model call's result. Pi counts input without the cached
+ * part; Agent Runs counts it with it (and subtracts the cache).
+ */
+export function piModelResult(message: AssistantMessage): ModelResult {
+ const u = message.usage;
+ return {
+ finishReason: FINISH[message.stopReason] ?? message.stopReason,
+ usage: {
+ inputTokens: u.input + u.cacheRead + u.cacheWrite,
+ outputTokens: u.output,
+ inputTokenDetails: { cacheReadTokens: u.cacheRead, cacheWriteTokens: u.cacheWrite },
+ ...(u.cost.total ? { costUsd: u.cost.total } : {}),
+ },
+ ...(message.responseId ? { responseId: message.responseId } : {}),
+ responseModelId: message.responseModel ?? message.model,
+ content: message.content.map(piPart),
+ };
+}
+
+/** The step's cost, where Agent Runs reads it. */
+export function piStepAttributes(message: AssistantMessage): Attributes {
+ return message.usage.cost.total ? { 'gen_ai.usage.cost': message.usage.cost.total } : {};
+}
diff --git a/packages/harness-pi/src/index.ts b/packages/harness-pi/src/index.ts
index cec7046..de2880d 100644
--- a/packages/harness-pi/src/index.ts
+++ b/packages/harness-pi/src/index.ts
@@ -33,6 +33,7 @@ import {
type UnavailableInput,
Yield,
} from 'harness-world';
+import { piModelOptions, piModelResult, piStepAttributes } from './agent-runs.ts';
export interface PiHarnessOptions {
/** The pi-ai model to drive. */
@@ -97,7 +98,6 @@ interface ModelInput {
/** Total messages in the request context (a replay divergence check). */
contextLength: number;
model: string;
- instrumentation?: 'adapter';
}
/**
@@ -114,6 +114,7 @@ interface ModelInput {
export function piHarness(options: PiHarnessOptions): Harness {
return {
name: 'pi',
+ modelCalls: 'self',
drive: (ctx) => new PiDrive(options, ctx).run(),
};
}
@@ -279,7 +280,6 @@ class PiDrive {
appended,
contextLength: messages.length,
model: `${model.provider}/${model.id}`,
- ...(this.ctx.instrumentation ? { instrumentation: 'adapter' as const } : {}),
} satisfies ModelInput,
},
async (io): Promise<ModelOutput> => {
@@ -294,11 +294,9 @@ class PiDrive {
const request = hook ? withDocuments(context, shown, at, docs) : context;
const record = (message: AssistantMessage): ModelOutput =>
hook && at >= 0 && docs !== (shown.get(at) ?? '') ? { ...message, promptDocs: { at, text: docs } } : message;
- const operation = this.ctx.instrumentation?.start('model', {
- model: `${model.provider}/${model.id}`, messages: request.messages,
- }, key);
+ const traced = await this.ctx.tracing?.modelCall(piModelOptions(model, request.messages));
+ let last: AssistantMessage | undefined;
try {
- let last: AssistantMessage | undefined;
for (let attempt = 1; attempt <= attempts; attempt++) {
const inner = await this.options.streamFn(model, request, opts);
let first = attempt > 1;
@@ -318,11 +316,18 @@ class PiDrive {
last = await inner.result();
// Halted mid-stream: the cut-off response is not this step's outcome.
if (this.stop) throw this.stop;
- if (last.stopReason !== 'error') { operation?.end(last); return record(last); }
+ if (last.stopReason !== 'error') {
+ traced?.attempt.attributes(piStepAttributes(last));
+ await traced?.model.complete({ outcome: 'completed', result: piModelResult(last) });
+ return record(last);
+ }
await sleep(500 * attempt);
}
throw new Error(last?.errorMessage ?? 'model call failed');
- } catch (error) { operation?.end(undefined, this.stop ? undefined : error); throw error; }
+ } catch (error) {
+ await traced?.model.fail(error);
+ throw error;
+ }
}
);
};
diff --git a/packages/harness-pi/src/pi.test.ts b/packages/harness-pi/src/pi.test.ts
index 566787e..c80abdb 100644
--- a/packages/harness-pi/src/pi.test.ts
+++ b/packages/harness-pi/src/pi.test.ts
@@ -13,7 +13,6 @@ import {
import { createWorld, type LocalWorld } from '@workflow/world-local';
import { chatRoute, defineDoc, durableSessions, type HostTool, isMark, liveStreamName, QUEUE_PREFIX, rawSessions, readJsonLines, Unavailable, UNAVAILABLE_STEP, vercelAnchors, workRemains } from 'harness-world';
import { hostProcess, leasedWorld } from 'harness-world/testing';
-import { INSTRUMENTATION, type InstrumentationRuntime } from 'harness-world/instrumentation';
import { Type } from 'typebox';
import { afterEach, describe, expect, it } from 'vitest';
import { type PiHarnessOptions, piHarness } from './index.ts';
@@ -62,32 +61,6 @@ async function localWorld(dataDir: string, recoverActiveRuns = false) {
}
describe('pi timing marks', () => {
- it('traces the full live model context while keeping journal inputs incremental', async () => {
- const inputs: any[] = [];
- const outputs: unknown[] = [];
- const scope = { start(_name: string, input: unknown) { inputs.push(JSON.parse(JSON.stringify(input))); return { end(output: unknown) { outputs.push(output); } }; }, end() {} };
- const global = globalThis as { [INSTRUMENTATION]?: InstrumentationRuntime };
- global[INSTRUMENTATION] = { session: () => scope, drive: (harness, ctx) => harness.drive({ ...ctx, instrumentation: scope }) };
- try {
- const a = setupModel();
- a.faux.setResponses([fauxAssistantMessage(fauxToolCall('shout', { text: 'hi' }), { stopReason: 'toolUse' }), fauxAssistantMessage(fauxText('I shouted HI.'))]);
- const world = await localWorld(await mkdtemp(join(tmpdir(), 'hw-pi-trace-')));
- const sessions = durableSessions({ world, harness: piHarness({ model: a.model, streamFn: a.streamFn, tools: [shoutTool()] }) });
- world.registerHandler(QUEUE_PREFIX, sessions.handler);
- const { sessionId } = await sessions.start({ prompt: 'shout hi' });
- const state = await until(async () => {
- const state = await sessions.inspect(sessionId);
- return state.effectOrder.filter(effect => effect.status === 'completed').length === 3 ? state : undefined;
- });
- expect(inputs).toHaveLength(2);
- expect(inputs[1].messages.map((message: Message) => message.role)).toEqual(['system', 'user', 'assistant', 'toolResult']);
- expect(JSON.stringify(inputs[1])).toContain('shout hi');
- expect(outputs).toHaveLength(2);
- const second = state.effectOrder.filter(effect => effect.name === 'model')[1]!;
- expect((second.input as any).appended.map((message: Message) => message.role)).toEqual(['toolResult']);
- expect((second.input as any).messages).toBeUndefined();
- } finally { delete global[INSTRUMENTATION]; }
- });
it('marks the first model output, durable and with durability off', async () => {
const script = () => [fauxAssistantMessage(fauxToolCall('shout', { text: 'hi' }), { stopReason: 'toolUse' }), fauxAssistantMessage(fauxText('I shouted HI.'))];
const a = setupModel();
diff --git a/packages/harness-process/README.md b/packages/harness-process/README.md
index 6c36558..02b2ca0 100644
--- a/packages/harness-process/README.md
+++ b/packages/harness-process/README.md
@@ -395,7 +395,7 @@ await host.killStale(runId), host.reset(runId), host.pidRecord(runId)
```ts
const steps = new ModelSteps(ctx, { log? });
const token = gatewayToken(); // the child's key
-const proxy = await gatewayProxy({ credential, token, track: steps.request });
+const proxy = await gatewayProxy({ credential, token, track: steps.request, captureRequest: ctx.tracing !== undefined });
// ... the drive ...
await steps.close(); // before the drive returns, then proxy.close()
```
diff --git a/packages/harness-process/package.json b/packages/harness-process/package.json
index eb6a9bc..b836cec 100644
--- a/packages/harness-process/package.json
+++ b/packages/harness-process/package.json
@@ -18,7 +18,8 @@
"dependencies": {
"@vercel/oidc": "3.2.0",
"@workflow/world": "catalog:",
- "harness-world": "workspace:*"
+ "harness-world": "workspace:*",
+ "@vercel/agent-runs": "0.0.1"
},
"devDependencies": {
"@workflow/world-local": "catalog:",
diff --git a/packages/harness-process/reference/harness.ts b/packages/harness-process/reference/harness.ts
index 7d4e5d5..4604b20 100644
--- a/packages/harness-process/reference/harness.ts
+++ b/packages/harness-process/reference/harness.ts
@@ -101,6 +101,8 @@ export function referenceHarness(options: ReferenceHarnessOptions): Harness {
const host = options.host ?? new ProcessHost();
return {
name: options.name ?? 'reference',
+ // Each model request reaches Agent Runs from the Gateway proxy (`ModelSteps.request`).
+ modelCalls: 'self',
async drive(ctx: DriveContext) {
// Nothing to do (an idle wake, a chaos arming): no child. A model step a
// crash left open after its turn ended is closed (no request will retry it).
@@ -129,7 +131,7 @@ export function referenceHarness(options: ReferenceHarnessOptions): Harness {
let proxy: GatewayProxy | undefined;
// The child's key: a fresh one per drive, the only one the proxy forwards.
const key = gatewayToken();
- if (options.modelUrl) proxy = await gatewayProxy({ target: options.modelUrl, credential: async () => 'reference', token: key, track: steps.request });
+ if (options.modelUrl) proxy = await gatewayProxy({ target: options.modelUrl, credential: async () => 'reference', token: key, track: steps.request, captureRequest: ctx.tracing !== undefined });
const env = { ...options.env, ...(proxy ? { FAKE_CLI_MODEL_URL: `${proxy.url}/v1/model`, FAKE_CLI_MODEL_KEY: key } : {}) };
const proc = await host
.spawn(ctx.runId, {
diff --git a/packages/harness-process/src/agent-runs.test.ts b/packages/harness-process/src/agent-runs.test.ts
new file mode 100644
index 0000000..15a386d
--- /dev/null
+++ b/packages/harness-process/src/agent-runs.test.ts
@@ -0,0 +1,134 @@
+import { describe, expect, it } from 'vitest';
+import { gatewayModelOptions, gatewayModelResult, ResponseCapture } from './agent-runs.ts';
+
+const sse = (events: unknown[]) => events.map((e) => `event: x\ndata: ${JSON.stringify(e)}\n\n`).join('');
+
+describe("a CLI's model requests for Agent Runs", () => {
+ it("reads Anthropic's Messages API (Claude Code)", () => {
+ const options = gatewayModelOptions({
+ path: '/v1/messages?beta=true',
+ body: {
+ model: 'anthropic/claude-haiku-4.5',
+ system: [{ type: 'text', text: 'Be brief.' }],
+ tools: [{ name: 'write_file', input_schema: {} }],
+ messages: [
+ { role: 'user', content: 'write it' },
+ { role: 'assistant', content: [{ type: 'tool_use', id: 'toolu_1', name: 'write_file', input: { path: 'a' } }] },
+ { role: 'user', content: [{ type: 'tool_result', tool_use_id: 'toolu_1', content: 'ok' }] },
+ ],
+ },
+ });
+ expect(options).toMatchObject({ provider: 'anthropic', modelId: 'anthropic/claude-haiku-4.5', instructions: 'Be brief.' });
+ expect(options.messages).toEqual([
+ { role: 'user', content: 'write it' },
+ { role: 'assistant', content: [{ type: 'tool-call', toolCallId: 'toolu_1', toolName: 'write_file', input: { path: 'a' } }] },
+ { role: 'tool', content: [{ type: 'tool-result', toolCallId: 'toolu_1', output: { type: 'text', value: 'ok' } }] },
+ ]);
+ const { result } = gatewayModelResult(
+ '/v1/messages',
+ sse([
+ { type: 'message_start', message: { id: 'msg_1', model: 'claude-haiku-4-5', usage: { input_tokens: 10, cache_read_input_tokens: 90, cache_creation_input_tokens: 5 } } },
+ { type: 'content_block_start', index: 0, content_block: { type: 'text', text: '' } },
+ { type: 'content_block_delta', index: 0, delta: { type: 'text_delta', text: 'Writing.' } },
+ { type: 'content_block_start', index: 1, content_block: { type: 'tool_use', id: 'toolu_2', name: 'write_file', input: {} } },
+ { type: 'content_block_delta', index: 1, delta: { type: 'input_json_delta', partial_json: '{"path":' } },
+ { type: 'content_block_delta', index: 1, delta: { type: 'input_json_delta', partial_json: '"b"}' } },
+ { type: 'message_delta', delta: { stop_reason: 'tool_use' }, usage: { output_tokens: 7 } },
+ ])
+ );
+ expect(result).toEqual({
+ finishReason: 'tool-calls',
+ usage: { inputTokens: 105, outputTokens: 7, inputTokenDetails: { cacheReadTokens: 90, cacheWriteTokens: 5 } },
+ responseId: 'msg_1',
+ responseModelId: 'claude-haiku-4-5',
+ content: [
+ { type: 'text', text: 'Writing.' },
+ { type: 'tool-call', callId: 'toolu_2', toolName: 'write_file', input: { path: 'b' } },
+ ],
+ });
+ });
+
+ it("reads OpenAI's Responses API (Codex)", () => {
+ const options = gatewayModelOptions({
+ path: '/v1/responses',
+ body: {
+ model: 'openai/gpt-5.4-mini',
+ instructions: 'Be brief.',
+ input: [
+ { type: 'message', role: 'user', content: [{ type: 'input_text', text: 'list files' }] },
+ { type: 'function_call', call_id: 'call_1', name: 'shell', arguments: '{"cmd":"ls"}' },
+ { type: 'function_call_output', call_id: 'call_1', output: 'a.txt' },
+ ],
+ },
+ });
+ expect(options).toMatchObject({ provider: 'openai', modelId: 'openai/gpt-5.4-mini', instructions: 'Be brief.' });
+ expect(options.messages).toEqual([
+ { role: 'user', content: [{ type: 'text', text: 'list files' }] },
+ { role: 'assistant', content: [{ type: 'tool-call', toolCallId: 'call_1', toolName: 'shell', input: { cmd: 'ls' } }] },
+ { role: 'tool', content: [{ type: 'tool-result', toolCallId: 'call_1', output: { type: 'text', value: 'a.txt' } }] },
+ ]);
+ const { result } = gatewayModelResult(
+ '/v1/responses',
+ sse([
+ { type: 'response.output_text.delta', delta: 'One file.' },
+ { type: 'response.output_item.done', item: { type: 'function_call', call_id: 'call_2', name: 'shell', arguments: '{"cmd":"cat a.txt"}' } },
+ { type: 'response.completed', response: { id: 'resp_1', model: 'gpt-5.4-mini', status: 'completed', output: [{ type: 'function_call' }], usage: { input_tokens: 50, input_tokens_details: { cached_tokens: 40 }, output_tokens: 6 } } },
+ ])
+ );
+ expect(result).toMatchObject({
+ finishReason: 'tool-calls',
+ usage: { inputTokens: 50, outputTokens: 6, inputTokenDetails: { cacheReadTokens: 40 } },
+ responseId: 'resp_1',
+ content: [
+ { type: 'text', text: 'One file.' },
+ { type: 'tool-call', callId: 'call_2', toolName: 'shell', input: { cmd: 'cat a.txt' } },
+ ],
+ });
+ });
+
+ it('reads chat completions, tool calls streamed in pieces', () => {
+ const { result } = gatewayModelResult(
+ '/v1/chat/completions',
+ sse([
+ { id: 'c1', model: 'm', choices: [{ delta: { content: 'Hi' } }] },
+ { id: 'c1', choices: [{ delta: { tool_calls: [{ index: 0, id: 'call_9', function: { name: 'f', arguments: '{"a"' } }] } }] },
+ { id: 'c1', choices: [{ delta: { tool_calls: [{ index: 0, function: { arguments: ':1}' } }] }, finish_reason: 'tool_calls' }] },
+ { id: 'c1', choices: [], usage: { prompt_tokens: 12, completion_tokens: 3 } },
+ ]) + 'data: [DONE]\n\n'
+ );
+ expect(result).toMatchObject({
+ finishReason: 'tool-calls',
+ usage: { inputTokens: 12, outputTokens: 3 },
+ content: [{ type: 'text', text: 'Hi' }, { type: 'tool-call', callId: 'call_9', toolName: 'f', input: { a: 1 } }],
+ });
+ });
+
+ it("reads AI Gateway's language-model protocol (OpenCode), its model in a header, its cost", () => {
+ const options = gatewayModelOptions({
+ path: '/v3/ai/language-model',
+ model: 'anthropic/claude-haiku-4.5',
+ body: { prompt: [{ role: 'system', content: 'Be brief.' }, { role: 'user', content: [{ type: 'text', text: 'hi' }] }] },
+ });
+ expect(options).toEqual({ provider: 'gateway', modelId: 'anthropic/claude-haiku-4.5', instructions: 'Be brief.', messages: [{ role: 'user', content: [{ type: 'text', text: 'hi' }] }] });
+ const { result, attributes } = gatewayModelResult(
+ '/v3/ai/language-model',
+ sse([
+ { type: 'response-metadata', id: 'gen_1', modelId: 'anthropic/claude-haiku-4.5' },
+ { type: 'text-delta', delta: 'Hello.' },
+ { type: 'finish', finishReason: { unified: 'stop', raw: 'end_turn' }, usage: { inputTokens: { total: 20, cacheRead: 15 }, outputTokens: { total: 2 } }, providerMetadata: { gateway: { cost: '0.0001' } } },
+ ])
+ );
+ expect(result).toMatchObject({ finishReason: 'stop', usage: { inputTokens: 20, outputTokens: 2, inputTokenDetails: { cacheReadTokens: 15 } }, responseId: 'gen_1', content: [{ type: 'text', text: 'Hello.' }] });
+ expect(attributes['gen_ai.usage.cost']).toBe(0.0001);
+ });
+
+ it("keeps a long response's start and its end, where usage is", () => {
+ const capture = new ResponseCapture(100, 200);
+ capture.push(sse([{ type: 'message_start', message: { usage: { input_tokens: 1 } } }]));
+ for (let i = 0; i < 50; i++) capture.push(sse([{ type: 'content_block_delta', index: 0, delta: { type: 'text_delta', text: 'x' } }]));
+ capture.push(sse([{ type: 'message_delta', delta: { stop_reason: 'end_turn' }, usage: { output_tokens: 50 } }]));
+ const { result } = gatewayModelResult('/v1/messages', capture.text());
+ expect(result.usage).toMatchObject({ inputTokens: 1, outputTokens: 50 });
+ expect(result.finishReason).toBe('stop');
+ });
+});
diff --git a/packages/harness-process/src/agent-runs.ts b/packages/harness-process/src/agent-runs.ts
new file mode 100644
index 0000000..6ff7d09
--- /dev/null
+++ b/packages/harness-process/src/agent-runs.ts
@@ -0,0 +1,272 @@
+import type { Attributes } from '@vercel/agent-runs';
+import type { ContentPart, ModelOptions, ModelResult } from 'harness-world/agent-runs';
+import { modelMessages, modelTools } from 'harness-world/agent-runs';
+
+/**
+ * A CLI's model requests, as Agent Runs records them: the CLIs speak
+ * Anthropic's Messages API (Claude Code), OpenAI's Responses API and chat
+ * completions (Codex), and AI Gateway's language-model protocol (OpenCode),
+ * all through the Gateway proxy. Requests become AI SDK messages, which
+ * `@vercel/agent-runs` reads; responses become its content parts and usage.
+ */
+
+const record = (v: unknown): Record<string, unknown> => (v !== null && typeof v === 'object' ? (v as Record<string, unknown>) : {});
+const list = (v: unknown): Record<string, unknown>[] => (Array.isArray(v) ? v.map(record) : []);
+/** An AI SDK model message, as the library reads it. */
+type Msg = { role: string; content: string | Record<string, unknown>[] };
+const num = (v: unknown): number | undefined => (typeof v === 'number' && Number.isFinite(v) ? v : undefined);
+
+export const isModelRequest = (request: { method: string; path: string }) => request.method === 'POST' && !request.path.includes('count_tokens');
+
+/** A response's text as it streams: its start, and its end (where usage and the finish are), within bounds. */
+export class ResponseCapture {
+ private head = '';
+ private tail = '';
+ private truncated = false;
+ constructor(
+ private readonly headBytes = 1_000_000,
+ private readonly tailBytes = 65_536
+ ) {}
+ push(text: string): void {
+ if (!this.truncated && this.head.length + text.length <= this.headBytes) {
+ this.head += text;
+ return;
+ }
+ this.truncated = true;
+ this.tail = (this.tail + text).slice(-this.tailBytes);
+ }
+ text(): string {
+ if (!this.truncated) return this.head;
+ // The tail from its first whole event.
+ const at = this.tail.indexOf('\n\n');
+ return `${this.head}\n\n${at < 0 ? '' : this.tail.slice(at + 2)}`;
+ }
+}
+
+function parseJson(text: unknown): unknown {
+ if (typeof text !== 'string') return text;
+ try {
+ return JSON.parse(text);
+ } catch {
+ return text;
+ }
+}
+
+/** The protocol a request path speaks. */
+function protocolOf(path: string): 'anthropic' | 'responses' | 'chat' | 'gateway' | undefined {
+ if (/\/messages(\?|$)/.test(path)) return 'anthropic';
+ if (/\/responses(\?|$)/.test(path)) return 'responses';
+ if (/\/chat\/completions(\?|$)/.test(path)) return 'chat';
+ if (/\/ai\/language-model(\?|$)/.test(path)) return 'gateway';
+ return undefined;
+}
+
+const textParts = (content: unknown, types: readonly string[]) =>
+ typeof content === 'string' ? content : list(content).flatMap((p) => (types.includes(String(p.type)) && typeof p.text === 'string' ? [{ type: 'text', text: p.text }] : []));
+
+function anthropicMessages(body: Record<string, unknown>): Msg[] {
+ return list(body.messages).map((m): Msg => {
+ if (typeof m.content === 'string') return { role: String(m.role), content: m.content };
+ const parts = list(m.content).flatMap((p): Record<string, unknown>[] => {
+ if (p.type === 'text') return [{ type: 'text', text: p.text }];
+ if (p.type === 'thinking') return [{ type: 'reasoning', text: p.thinking }];
+ if (p.type === 'tool_use') return [{ type: 'tool-call', toolCallId: p.id, toolName: p.name, input: p.input }];
+ if (p.type === 'tool_result') {
+ const value = typeof p.content === 'string' ? p.content : list(p.content).flatMap((c) => (c.type === 'text' ? [String(c.text)] : [])).join('\n');
+ return [{ type: 'tool-result', toolCallId: p.tool_use_id, output: { type: p.is_error ? 'error-text' : 'text', value } }];
+ }
+ return [];
+ });
+ return { role: parts.every((p) => p.type === 'tool-result') && parts.length ? 'tool' : String(m.role), content: parts };
+ });
+}
+
+function responsesMessages(body: Record<string, unknown>): Msg[] {
+ const input = typeof body.input === 'string' ? [{ type: 'message', role: 'user', content: body.input }] : list(body.input);
+ return input.flatMap((item): Msg[] => {
+ if (item.type === 'function_call') return [{ role: 'assistant', content: [{ type: 'tool-call', toolCallId: item.call_id, toolName: item.name, input: parseJson(item.arguments) }] }];
+ if (item.type === 'function_call_output') return [{ role: 'tool', content: [{ type: 'tool-result', toolCallId: item.call_id, output: { type: 'text', value: typeof item.output === 'string' ? item.output : JSON.stringify(item.output) } }] }];
+ if (item.type === 'message' || item.role !== undefined) {
+ if (item.role === 'system' || item.role === 'developer') return [];
+ return [{ role: String(item.role), content: textParts(item.content, ['input_text', 'output_text', 'text']) }];
+ }
+ return [];
+ });
+}
+
+function chatMessages(body: Record<string, unknown>): Msg[] {
+ return list(body.messages).flatMap((m): Msg[] => {
+ if (m.role === 'system' || m.role === 'developer') return [];
+ if (m.role === 'tool') return [{ role: 'tool', content: [{ type: 'tool-result', toolCallId: m.tool_call_id, output: { type: 'text', value: typeof m.content === 'string' ? m.content : JSON.stringify(m.content) } }] }];
+ const calls = list(m.tool_calls).map((c) => ({ type: 'tool-call', toolCallId: c.id, toolName: record(c.function).name, input: parseJson(record(c.function).arguments) }));
+ const text = textParts(m.content, ['text']);
+ return [{ role: String(m.role), content: calls.length ? [...(typeof text === 'string' ? (text ? [{ type: 'text', text }] : []) : text), ...calls] : text }];
+ });
+}
+
+function instructionsOf(protocol: ReturnType<typeof protocolOf>, body: Record<string, unknown>): string | undefined {
+ const text = (v: unknown) => (typeof v === 'string' ? v : list(v).flatMap((p) => (typeof p.text === 'string' ? [p.text] : [])).join('\n'));
+ if (protocol === 'anthropic') return text(body.system) || undefined;
+ if (protocol === 'responses') return [text(body.instructions), ...list(body.input).filter((i) => i.role === 'system' || i.role === 'developer').map((i) => text(i.content))].filter(Boolean).join('\n\n') || undefined;
+ if (protocol === 'chat') return list(body.messages).filter((m) => m.role === 'system' || m.role === 'developer').map((m) => text(m.content)).join('\n\n') || undefined;
+ if (protocol === 'gateway') return list(body.prompt).filter((m) => m.role === 'system').map((m) => text(m.content)).join('\n\n') || undefined;
+ return undefined;
+}
+
+/** A request's model call: `model` is the body's, or the Gateway protocol's header. */
+export function gatewayModelOptions(request: { path: string; model?: string; body?: unknown }): ModelOptions {
+ const body = record(request.body);
+ const protocol = protocolOf(request.path);
+ // pi-ai names a Gateway model `vercel-ai-gateway/<id>`; the Gateway and the CLIs name it `<provider>/<id>` or `<id>`.
+ // The model id stays whole: Agent Runs links a Gateway id (`<provider>/<model>`) to its model page.
+ const id = String(body.model ?? request.model ?? 'unknown').replace(/^vercel-ai-gateway\//, '');
+ const provider = protocol === 'anthropic' ? 'anthropic' : protocol === 'responses' || protocol === 'chat' ? 'openai' : 'gateway';
+ const messages =
+ protocol === 'anthropic' ? anthropicMessages(body)
+ : protocol === 'responses' ? responsesMessages(body)
+ : protocol === 'chat' ? chatMessages(body)
+ : protocol === 'gateway' ? modelMessages(list(body.prompt).filter((m) => m.role !== 'system'))
+ : undefined;
+ const instructions = instructionsOf(protocol, body);
+ return {
+ provider,
+ modelId: id,
+ ...(messages ? { messages } : {}),
+ ...(instructions ? { instructions } : {}),
+ ...(Array.isArray(body.tools) ? { tools: modelTools(body.tools) } : {}),
+ };
+}
+
+/** A response body's events: server-sent events, or one JSON body. */
+function events(text: string): Record<string, unknown>[] {
+ const whole = parseJson(text.trim());
+ if (whole !== null && typeof whole === 'object') return [record(whole)];
+ return text.split('\n').flatMap((line) => {
+ if (!line.startsWith('data:')) return [];
+ const value = parseJson(line.slice(5).trim());
+ return value !== null && typeof value === 'object' ? [record(value)] : [];
+ });
+}
+
+/** A model call's result, from the response the CLI got, and its step's cost where the Gateway reports one. */
+export function gatewayModelResult(path: string, response: string): { result: ModelResult; attributes: Attributes } {
+ const protocol = protocolOf(path);
+ const content: ContentPart[] = [];
+ let text = '';
+ let reasoning = '';
+ let finishReason = 'unknown';
+ let responseId: string | undefined;
+ let responseModelId: string | undefined;
+ let input: number | undefined;
+ let output: number | undefined;
+ let cacheRead: number | undefined;
+ let cacheWrite: number | undefined;
+ let gateway: Record<string, unknown> = {};
+ const anthropicTools = new Map<number, { callId: string; toolName: string; json: string; input: unknown }>();
+ const chatTools = new Map<number, { callId: string; toolName: string; json: string }>();
+ for (const e of events(response)) {
+ const meta = record(e.providerMetadata ?? record(e.response).providerMetadata);
+ if (meta.gateway) gateway = record(meta.gateway);
+ if (protocol === 'anthropic') {
+ const message = record(e.type === 'message_start' ? e.message : e.type === undefined ? e : undefined);
+ if (typeof message.id === 'string') responseId = message.id;
+ if (typeof message.model === 'string') responseModelId = message.model;
+ const usage = record(message.usage ?? e.usage);
+ const base = num(usage.input_tokens);
+ cacheRead = num(usage.cache_read_input_tokens) ?? cacheRead;
+ cacheWrite = num(usage.cache_creation_input_tokens) ?? cacheWrite;
+ if (base !== undefined) input = base + (cacheRead ?? 0) + (cacheWrite ?? 0);
+ output = num(usage.output_tokens) ?? output;
+ const stop = record(e.delta).stop_reason ?? message.stop_reason;
+ if (typeof stop === 'string') finishReason = stop === 'tool_use' ? 'tool-calls' : stop === 'end_turn' ? 'stop' : stop;
+ for (const block of list(message.content)) {
+ if (block.type === 'text') text += String(block.text ?? '');
+ if (block.type === 'tool_use') content.push({ type: 'tool-call', callId: String(block.id), toolName: String(block.name), input: block.input });
+ }
+ if (e.type === 'content_block_start' && record(e.content_block).type === 'tool_use' && typeof e.index === 'number') {
+ const block = record(e.content_block);
+ anthropicTools.set(e.index, { callId: String(block.id), toolName: String(block.name), json: '', input: block.input });
+ }
+ const delta = record(e.delta);
+ if (e.type === 'content_block_delta' && delta.type === 'text_delta') text += String(delta.text ?? '');
+ if (e.type === 'content_block_delta' && delta.type === 'thinking_delta') reasoning += String(delta.thinking ?? '');
+ if (e.type === 'content_block_delta' && delta.type === 'input_json_delta' && typeof e.index === 'number') {
+ const tool = anthropicTools.get(e.index);
+ if (tool) tool.json += String(delta.partial_json ?? '');
+ }
+ } else if (protocol === 'responses') {
+ const done = record(e.type === 'response.completed' || e.type === 'response.incomplete' || e.type === 'response.failed' ? e.response : e.type === undefined ? e : undefined);
+ if (e.type === 'response.output_text.delta' && typeof e.delta === 'string') text += e.delta;
+ if (e.type === 'response.reasoning_summary_text.delta' && typeof e.delta === 'string') reasoning += e.delta;
+ if (e.type === 'response.output_item.done' && record(e.item).type === 'function_call') {
+ const item = record(e.item);
+ content.push({ type: 'tool-call', callId: String(item.call_id), toolName: String(item.name), input: parseJson(item.arguments) });
+ }
+ if (Object.keys(done).length) {
+ if (typeof done.id === 'string') responseId = done.id;
+ if (typeof done.model === 'string') responseModelId = done.model;
+ const usage = record(done.usage);
+ input = num(usage.input_tokens) ?? input;
+ output = num(usage.output_tokens) ?? output;
+ cacheRead = num(record(usage.input_tokens_details).cached_tokens) ?? cacheRead;
+ const calls = list(done.output).filter((i) => i.type === 'function_call');
+ finishReason = calls.length ? 'tool-calls' : done.status === 'completed' ? 'stop' : String(done.status ?? finishReason);
+ if (e.type === undefined) {
+ for (const item of list(done.output)) {
+ if (item.type === 'message') for (const p of list(item.content)) if (typeof p.text === 'string') text += p.text;
+ if (item.type === 'function_call') content.push({ type: 'tool-call', callId: String(item.call_id), toolName: String(item.name), input: parseJson(item.arguments) });
+ }
+ }
+ }
+ } else if (protocol === 'chat') {
+ if (typeof e.id === 'string') responseId = e.id;
+ if (typeof e.model === 'string') responseModelId = e.model;
+ const usage = record(e.usage);
+ input = num(usage.prompt_tokens) ?? input;
+ output = num(usage.completion_tokens) ?? output;
+ cacheRead = num(record(usage.prompt_tokens_details).cached_tokens) ?? cacheRead;
+ for (const choice of list(e.choices)) {
+ const delta = record(choice.delta ?? choice.message);
+ if (typeof delta.content === 'string') text += delta.content;
+ for (const call of list(delta.tool_calls)) {
+ const fn = record(call.function);
+ const index = typeof call.index === 'number' ? call.index : chatTools.size;
+ const tool = chatTools.get(index);
+ if (tool) tool.json += String(fn.arguments ?? '');
+ else chatTools.set(index, { callId: String(call.id ?? index), toolName: String(fn.name ?? 'unknown'), json: String(fn.arguments ?? '') });
+ }
+ if (typeof choice.finish_reason === 'string') finishReason = choice.finish_reason === 'tool_calls' ? 'tool-calls' : choice.finish_reason;
+ }
+ } else {
+ if (e.type === 'text-delta') text += String(e.delta ?? e.textDelta ?? '');
+ if (e.type === 'reasoning-delta') reasoning += String(e.delta ?? '');
+ if (e.type === 'tool-call') content.push({ type: 'tool-call', callId: String(e.toolCallId), toolName: String(e.toolName), input: parseJson(e.input) });
+ if (e.type === 'response-metadata') {
+ if (typeof e.id === 'string') responseId = e.id;
+ if (typeof e.modelId === 'string') responseModelId = e.modelId;
+ }
+ if (e.type === 'finish') {
+ const reason = e.finishReason;
+ finishReason = typeof reason === 'string' ? reason : String(record(reason).unified ?? finishReason);
+ const usage = record(e.usage ?? e.totalUsage);
+ input = num(usage.inputTokens) ?? num(record(usage.inputTokens).total) ?? input;
+ output = num(usage.outputTokens) ?? num(record(usage.outputTokens).total) ?? output;
+ cacheRead = num(record(usage.inputTokens).cacheRead) ?? num(usage.cachedInputTokens) ?? cacheRead;
+ cacheWrite = num(record(usage.inputTokens).cacheWrite) ?? cacheWrite;
+ }
+ }
+ }
+ for (const tool of anthropicTools.values()) content.push({ type: 'tool-call', callId: tool.callId, toolName: tool.toolName, input: tool.json ? parseJson(tool.json) : tool.input });
+ for (const tool of chatTools.values()) content.push({ type: 'tool-call', callId: tool.callId, toolName: tool.toolName, input: parseJson(tool.json) });
+ const usd = (v: unknown) => (v === undefined || v === null || v === '' || !Number.isFinite(Number(v)) ? undefined : Number(v));
+ return {
+ result: {
+ finishReason,
+ usage: { inputTokens: input, outputTokens: output, inputTokenDetails: { cacheReadTokens: cacheRead, cacheWriteTokens: cacheWrite } },
+ ...(responseId ? { responseId } : {}),
+ ...(responseModelId ? { responseModelId } : {}),
+ content: [...(reasoning ? [{ type: 'reasoning' as const, text: reasoning }] : []), ...(text ? [{ type: 'text' as const, text }] : []), ...content],
+ },
+ attributes: { 'gen_ai.usage.cost': usd(gateway.cost), 'gen_ai.usage.gateway_cost': usd(gateway.gatewayCost) },
+ };
+}
diff --git a/packages/harness-process/src/gateway.test.ts b/packages/harness-process/src/gateway.test.ts
index 4dea5ab..acb938d 100644
--- a/packages/harness-process/src/gateway.test.ts
+++ b/packages/harness-process/src/gateway.test.ts
@@ -1,7 +1,7 @@
-import { createServer, type IncomingHttpHeaders } from 'node:http';
+import { createServer, request as httpRequest, type IncomingHttpHeaders } from 'node:http';
import type { AddressInfo } from 'node:net';
import { afterEach, describe, expect, it } from 'vitest';
-import { FIRST_OUTPUT, gatewayCredential, gatewayProxy, gatewayToken } from './gateway.ts';
+import { FIRST_OUTPUT, gatewayCredential, gatewayProxy, gatewayToken, MODEL_BODY_MAX_BYTES } from './gateway.ts';
const closers: (() => Promise<void>)[] = [];
afterEach(async () => {
@@ -32,6 +32,52 @@ const KEY = 'child-key';
const keyed = { authorization: `Bearer ${KEY}` };
describe('gatewayProxy', () => {
+ it.each([
+ { captureRequest: false, path: '/v1/messages' },
+ { captureRequest: true, path: '/v1/messages/count_tokens' },
+ ])('streams request bytes before the body ends when no trace payload is needed: $path ($captureRequest)', async ({ captureRequest, path }) => {
+ let arrived!: () => void;
+ const first = new Promise<void>(resolve => { arrived = resolve; });
+ let received = '';
+ const server = createServer((req, res) => {
+ req.on('data', chunk => { received += chunk; arrived(); });
+ req.on('end', () => res.end('ok'));
+ });
+ await new Promise<void>(resolve => server.listen(0, '127.0.0.1', resolve));
+ closers.push(() => { server.closeAllConnections(); return new Promise(resolve => server.close(() => resolve())); });
+ const tracked: unknown[] = [];
+ const proxy = await gatewayProxy({ target: `http://127.0.0.1:${(server.address() as AddressInfo).port}`, credential: async () => 'test', token: KEY, captureRequest, track: info => { tracked.push(info); } });
+ closers.push(proxy.close);
+ const outgoing = httpRequest(`${proxy.url}${path}`, { method: 'POST', headers: keyed });
+ const response = new Promise<string>((resolve, reject) => {
+ outgoing.on('error', reject);
+ outgoing.on('response', res => { let text = ''; res.on('data', chunk => { text += chunk; }); res.on('end', () => resolve(text)); });
+ });
+ response.catch(() => {});
+ let timer: ReturnType<typeof setTimeout> | undefined;
+ try {
+ outgoing.write('first');
+ await Promise.race([first, new Promise<never>((_, reject) => { timer = setTimeout(() => reject(new Error('request was buffered')), 1000); })]);
+ outgoing.end('second');
+ expect(await response).toBe('ok');
+ expect(received).toBe('firstsecond');
+ expect(tracked).toEqual([{ method: 'POST', path }]);
+ } finally { clearTimeout(timer); outgoing.destroy(); }
+ });
+
+ it('forwards a model request beyond the capture limit without retaining or parsing its body', async () => {
+ const target = await upstream(['ok']);
+ const tracked: { body?: unknown }[] = [];
+ const proxy = await gatewayProxy({ target: target.url, credential: async () => 'test', token: KEY, captureRequest: true, track: info => { tracked.push(info); } });
+ closers.push(proxy.close);
+ const body = JSON.stringify({ model: 'test', messages: 'x'.repeat(MODEL_BODY_MAX_BYTES + 100) });
+ const response = await fetch(`${proxy.url}/v1/messages`, { method: 'POST', headers: keyed, body });
+ expect(await response.text()).toBe('ok');
+ expect(target.seen[0]!.body).toBe(body);
+ expect(tracked).toHaveLength(1);
+ expect(tracked[0]!.body).toBeUndefined();
+ });
+
it('forwards with a fresh credential per request, replacing the placeholder, and streams the reply', async () => {
const target = await upstream();
let n = 0;
@@ -139,19 +185,19 @@ describe('gatewayProxy', () => {
await new Promise<void>((ok) => server.listen(0, '127.0.0.1', ok));
closers.push(() => new Promise((done) => server.close(() => done())));
const seen: string[] = [];
- let finish!: (outcome: { responseBody?: string }) => void;
- const finished = new Promise<{ responseBody?: string }>((resolve) => { finish = resolve; });
+ let finish!: (outcome: { response?: string }) => void;
+ const finished = new Promise<{ response?: string }>((resolve) => { finish = resolve; });
const proxy = await gatewayProxy({
target: `http://127.0.0.1:${(server.address() as AddressInfo).port}`,
credential: async () => 'secret',
token: KEY,
- track: () => Object.assign((outcome: { responseBody?: string }) => { seen.push('end'); finish(outcome); }, { capture, firstToken: () => seen.push('first') }),
+ track: () => Object.assign((outcome: { response?: string }) => { seen.push('end'); finish(outcome); }, { capture, firstToken: () => seen.push('first') }),
});
closers.push(proxy.close);
const res = await fetch(`${proxy.url}/v1/messages`, { method: 'POST', headers: keyed, body: '{}' });
const response = await res.text();
const outcome = await finished;
- expect(outcome.responseBody).toBe(capture ? response : undefined);
+ expect(outcome.response).toBe(capture ? response : undefined);
expect(seen).toEqual(['first', 'end']);
});
@@ -182,11 +228,13 @@ describe('gatewayProxy', () => {
const target = await upstream();
let finish!: (value: Record<string, unknown>) => void;
const finished = new Promise<Record<string, unknown>>((resolve) => { finish = resolve; });
+ const tracked: unknown[] = [];
const proxy = await gatewayProxy({
target: target.url,
credential: async () => 'secret-upstream-key',
token: KEY,
- track: () => Object.assign(finish, { capture: true }),
+ captureRequest: true,
+ track: (request) => (tracked.push(request), Object.assign(finish, { capture: true })),
});
closers.push(proxy.close);
const response = await fetch(`${proxy.url}/v1/messages`, {
@@ -196,22 +244,22 @@ describe('gatewayProxy', () => {
});
expect(await response.text()).toBe('data: one\n\ndata: two\n\n');
const capture = await finished;
- expect(capture).toMatchObject({ status: 200, requestBody: { model: 'test', messages: [{ role: 'user', content: 'hello 🌍' }] }, responseBody: 'data: one\n\ndata: two\n\n' });
- expect(JSON.stringify(capture)).not.toContain('secret-upstream-key');
+ expect(tracked).toEqual([{ method: 'POST', path: '/v1/messages', body: { model: 'test', messages: [{ role: 'user', content: 'hello 🌍' }] } }]);
+ expect(capture).toMatchObject({ status: 200, response: 'data: one\n\ndata: two\n\n' });
+ expect(JSON.stringify([tracked, capture])).not.toContain('secret-upstream-key');
+ expect(JSON.stringify([tracked, capture])).not.toContain(KEY);
});
- it('bounds capture while forwarding oversized bodies completely', async () => {
+ it('forwards a large request and response whole while it tracks them', async () => {
const text = 'x'.repeat(300_000);
const target = await upstream([text]);
- let finish!: (value: { requestBody?: unknown; responseBody?: string }) => void;
- const finished = new Promise<{ requestBody?: unknown; responseBody?: string }>(resolve => { finish = resolve; });
+ let finish!: (value: { response?: string }) => void;
+ const finished = new Promise<{ response?: string }>(resolve => { finish = resolve; });
const proxy = await gatewayProxy({ target: target.url, credential: async () => 'secret', token: KEY, track: () => Object.assign(finish, { capture: true }) });
closers.push(proxy.close);
const body = JSON.stringify({ messages: text });
const response = await fetch(`${proxy.url}/v1/messages`, { method: 'POST', headers: keyed, body });
expect(await response.text()).toBe(text);
- const capture = await finished;
- expect(capture.responseBody).toHaveLength(256_000);
- expect(capture.requestBody).toBeUndefined();
+ expect((await finished).response).toBe(text);
expect(target.seen[0]!.body).toBe(body);
});
it('passes the Gateway model header to tracking without exposing other headers', async () => {
@@ -221,6 +269,7 @@ describe('gatewayProxy', () => {
target: target.url,
credential: async () => 'upstream-secret',
token: 'child-secret',
+ captureRequest: true,
track: request => { starts.push(request); },
});
closers.push(proxy.close);
@@ -230,7 +279,8 @@ describe('gatewayProxy', () => {
body: JSON.stringify({ prompt: [{ role: 'user', content: [{ type: 'text', text: 'hello' }] }] }),
});
await response.text();
- expect(starts).toEqual([{ method: 'POST', path: '/v3/ai/language-model', model: 'anthropic/claude-haiku-4.5' }]);
+ expect(starts).toEqual([{ method: 'POST', path: '/v3/ai/language-model', model: 'anthropic/claude-haiku-4.5', body: { prompt: [{ role: 'user', content: [{ type: 'text', text: 'hello' }] }] } }]);
+ expect(JSON.stringify(starts)).not.toContain('private-header');
expect(target.seen[0]!.headers?.['ai-language-model-id']).toBe('anthropic/claude-haiku-4.5');
});
});
diff --git a/packages/harness-process/src/gateway.ts b/packages/harness-process/src/gateway.ts
index c499336..226da89 100644
--- a/packages/harness-process/src/gateway.ts
+++ b/packages/harness-process/src/gateway.ts
@@ -2,7 +2,7 @@ import { randomUUID } from 'node:crypto';
import { createServer, type IncomingMessage, type ServerResponse } from 'node:http';
import type { AddressInfo } from 'node:net';
import { Readable } from 'node:stream';
-import { TransformStream } from 'node:stream/web';
+import { isModelRequest, ResponseCapture } from './agent-runs.ts';
import type { GatewayErrorCode, GatewayHandler } from './environment.ts';
/**
@@ -49,9 +49,11 @@ export interface GatewayProxyOptions {
* forwarded. The function it returns, if any, is called once that request
* is over: its response ended, failed, or its connection closed (the child
* died, the proxy closed). `ModelSteps.request` is one: the drive's model
- * steps.
+ * steps.
*/
- track?: (request: { method: string; path: string; model?: string }) => TrackEnd | void;
+ track?: (request: TrackedRequest) => TrackEnd | void;
+ /** Read a bounded model request for tracing. Otherwise requests stream straight through. Default false. */
+ captureRequest?: boolean;
/**
* Forward only requests that carry this value (`authorization: Bearer
* <token>` or `x-api-key: <token>`), or one of these values; anything
@@ -72,12 +74,22 @@ export interface GatewayProxyOptions {
/** A fresh placeholder key for a child, to give `gatewayProxy` as its `token`: one per proxy, never reused. */
export const gatewayToken = (prefix = 'harness-world'): string => `${prefix}-${randomUUID()}`;
+/** A model request as `track` sees it: `model` is the Gateway protocol's header (`ai-language-model-id`), `body` the parsed request. */
+export interface TrackedRequest {
+ method: string;
+ path: string;
+ model?: string;
+ body?: unknown;
+}
+
/**
* What `track` returns for a request: called once the request is over. With
* `firstToken`, the proxy also calls that when the response streams its
- * first output (text, reasoning or a tool call: `FIRST_OUTPUT`).
+ * first output (text, reasoning or a tool call: `FIRST_OUTPUT`). With
+ * `capture`, the end carries the response's text (`ResponseCapture`'s
+ * bounds: its start and its end); never a credential or a header.
*/
-export type TrackEnd = ((end: { status?: number; error?: string; requestBody?: unknown; responseBody?: string }) => void) & { firstToken?: () => void; capture?: boolean };
+export type TrackEnd = ((end: { status?: number; error?: string; response?: string }) => void) & { firstToken?: () => void; capture?: boolean };
/**
* A response's first output, in any of the APIs the CLIs speak through the
@@ -122,18 +134,26 @@ export async function gatewayProxy(options: GatewayProxyOptions): Promise<Gatewa
res.writeHead(401, { 'content-type': 'text/plain' });
return void res.end('harness-world-process gateway proxy: the request does not carry the key this proxy gave its child');
}
- // The AI SDK Gateway protocol (used by OpenCode) sends the model in
- // this header, not the JSON body. Pass only that identifier to tracing;
- // never capture the request's credential or other headers.
+ const hasBody = req.method !== 'GET' && req.method !== 'HEAD';
+ const request = { method: req.method ?? 'GET', path: req.url ?? '/' };
+ const captured = options.track && options.captureRequest && isModelRequest(request) ? await readRequest(req) : undefined;
+ const body = captured?.body;
const model = req.headers['ai-language-model-id'];
- const ended = options.track?.({ method: req.method ?? 'GET', path: req.url ?? '/', ...(typeof model === 'string' && model ? { model } : {}) });
- let requestBody = '';
- let responseBody = '';
- const capture = !!ended && !!ended.capture;
- const requestDecoder = new TextDecoder();
- const captureLimit = 256_000;
+ const ended = options.track?.({
+ ...request,
+ ...(typeof model === 'string' && model ? { model } : {}),
+ ...(body?.length ? { body: parseBody(body) } : {}),
+ });
+ const capture = ended?.capture ? new ResponseCapture() : undefined;
// `close` comes after the response ended, or when its connection went first.
- if (ended) res.once('close', () => ended({ ...(res.writableFinished ? { status: res.statusCode } : { error: 'the connection closed before the response ended' }), ...(capture ? { requestBody: parseBody(requestBody), responseBody } : {}) }));
+ if (ended) {
+ res.once('close', () =>
+ ended({
+ ...(res.writableFinished ? { status: res.statusCode } : { error: 'the connection closed before the response ended' }),
+ ...(capture ? { response: capture.text() } : {}),
+ })
+ );
+ }
let firstToken = ended ? ended.firstToken : undefined;
const headers = new Headers();
for (const [k, v] of Object.entries(req.headers)) {
@@ -143,17 +163,10 @@ export async function gatewayProxy(options: GatewayProxyOptions): Promise<Gatewa
for (const [k, v] of Object.entries(auth(await credential()))) headers.set(k, v);
const abort = new AbortController();
res.on('close', () => abort.abort());
- const hasBody = req.method !== 'GET' && req.method !== 'HEAD';
const upstream = await fetch(`${target}${req.url ?? '/'}`, {
method: req.method ?? 'GET',
headers,
- ...(hasBody ? { body: Readable.toWeb(req).pipeThrough(new TransformStream({
- transform(chunk, controller) {
- if (capture && requestBody.length < captureLimit) requestBody += requestDecoder.decode(chunk, { stream: true }).slice(0, captureLimit - requestBody.length);
- controller.enqueue(chunk);
- },
- flush() { if (capture) requestBody += requestDecoder.decode().slice(0, captureLimit - requestBody.length); },
- })) as ReadableStream, duplex: 'half' } : {}),
+ ...(body ? { body } : hasBody ? { body: (captured?.stream ?? Readable.toWeb(req)) as ReadableStream, duplex: 'half' } : {}),
signal: abort.signal,
} as RequestInit);
const out: Record<string, string> = {};
@@ -164,14 +177,13 @@ export async function gatewayProxy(options: GatewayProxyOptions): Promise<Gatewa
res.writeHead(upstream.status, out);
options.onRequest?.({ method: req.method ?? 'GET', path: req.url ?? '/', status: upstream.status });
if (!upstream.body) return void res.end();
- // Decode once for policy-controlled capture and the first-output mark.
// A short tail carries a first-output match across chunk boundaries.
- const decoder = capture || firstToken ? new TextDecoder() : undefined;
+ const decoder = firstToken || capture ? new TextDecoder() : undefined;
let tail = '';
for await (const chunk of upstream.body as unknown as AsyncIterable<Uint8Array>) {
- if (decoder && (capture || firstToken)) {
+ if (decoder) {
const text = decoder.decode(chunk, { stream: true });
- if (capture && responseBody.length < captureLimit) responseBody += text.slice(0, captureLimit - responseBody.length);
+ capture?.push(text);
if (firstToken) {
const output = tail + text;
if (FIRST_OUTPUT.test(output)) {
@@ -182,7 +194,7 @@ export async function gatewayProxy(options: GatewayProxyOptions): Promise<Gatewa
}
res.write(chunk);
}
- if (capture && decoder) responseBody += decoder.decode().slice(0, captureLimit - responseBody.length);
+ if (decoder) capture?.push(decoder.decode());
res.end();
}
await new Promise<void>((ok) => server.listen(0, '127.0.0.1', ok));
@@ -198,7 +210,6 @@ export async function gatewayProxy(options: GatewayProxyOptions): Promise<Gatewa
};
}
-function parseBody(text: string): unknown { try { return JSON.parse(text); } catch { return undefined; } }
// ---------------------------------------------------------------------------
// gatewayHandler: the VM path (docs/workspaces.md §5.5)
@@ -309,7 +320,7 @@ export interface GatewayHandlerOptions {
/** The headers that carry the credential. Default `authorization: Bearer` and `x-api-key`. */
auth?: (credential: string) => Record<string, string>;
/** As `gatewayProxy`'s: `ModelSteps.request`. */
- track?: (request: { method: string; path: string; model?: string }) => TrackEnd | void;
+ track?: (request: TrackedRequest) => TrackEnd | void;
/** Requests in flight at once. Default 8 (§5.5). */
concurrency?: number;
/**
@@ -960,12 +971,14 @@ export function gatewayHandler(options: GatewayHandlerOptions): GatewayHandler {
}
if (body.length > MODEL_BODY_MAX_BYTES) throw refuse('bad_request', 'the body is over 4 MiB');
let forward: string | undefined;
+ let trackedBody: Record<string, unknown> | undefined;
let model: string | undefined;
let outputLimit: number | undefined;
if (route.body) {
const parsed = parseStrictJson(body);
if (typeof parsed !== 'object' || parsed === null || Array.isArray(parsed)) throw refuse('bad_request', 'the body must be a JSON object');
const out = route.body(parsed as Record<string, unknown>, check);
+ trackedBody = out;
model = typeof out.model === 'string' ? out.model : undefined;
const limitOf = out.max_tokens ?? out.max_output_tokens;
outputLimit = typeof limitOf === 'number' ? limitOf : undefined;
@@ -999,7 +1012,8 @@ export function gatewayHandler(options: GatewayHandlerOptions): GatewayHandler {
inflight++;
const info = { method, path: route.path, ...(model ? { model } : {}) };
- const end = options.track?.(info) || undefined;
+ const end = options.track?.({ ...info, ...(trackedBody ? { body: trackedBody } : {}) }) || undefined;
+ const capture = end?.capture ? new ResponseCapture() : undefined;
const billed = !!route.body && !route.free;
const requestBytes = forward === undefined ? 0 : Buffer.byteLength(forward);
const seen: Seen = { head: '', window: '', streamed: 0 };
@@ -1034,7 +1048,7 @@ export function gatewayHandler(options: GatewayHandlerOptions): GatewayHandler {
log('the ledger refused a charge', { path: route.path, error: String((err as Error)?.message ?? err).slice(0, 200) });
}
try {
- end?.(outcome);
+ end?.({ ...outcome, ...(capture ? { response: capture.text() } : {}) });
} catch (err) {
log("the model step's end failed", { error: String((err as Error)?.message ?? err).slice(0, 200) });
}
@@ -1087,6 +1101,7 @@ export function gatewayHandler(options: GatewayHandlerOptions): GatewayHandler {
try {
for await (const chunk of stream as unknown as AsyncIterable<Uint8Array>) {
const text = decoder.decode(chunk, { stream: true });
+ capture?.push(text);
seen.streamed += chunk.length;
if (seen.head.length < 16_384) seen.head += text.slice(0, 16_384 - seen.head.length);
seen.window = (seen.window + text).slice(-65_536);
@@ -1110,3 +1125,34 @@ export function gatewayHandler(options: GatewayHandlerOptions): GatewayHandler {
}
};
}
+
+async function readRequest(req: IncomingMessage): Promise<{ body?: Buffer; stream?: ReturnType<typeof Readable.toWeb> }> {
+ const chunks: Buffer[] = [];
+ const iterator = req[Symbol.asyncIterator]();
+ let size = 0;
+ for (;;) {
+ const next = await iterator.next();
+ if (next.done) return { body: Buffer.concat(chunks, size) };
+ const chunk = next.value as Buffer;
+ chunks.push(chunk);
+ size += chunk.length;
+ if (size > MODEL_BODY_MAX_BYTES) {
+ // Reuse the prefix and the same iterator: breaking a for-await would close the request.
+ const stream = Readable.from((async function* () {
+ try {
+ yield* chunks;
+ for (;;) { const next = await iterator.next(); if (next.done) return; yield next.value; }
+ } finally { await iterator.return?.(); }
+ })());
+ return { stream: Readable.toWeb(stream) };
+ }
+ }
+}
+
+function parseBody(body: Buffer): unknown {
+ try {
+ return JSON.parse(body.toString('utf8'));
+ } catch {
+ return undefined;
+ }
+}
diff --git a/packages/harness-process/src/index.ts b/packages/harness-process/src/index.ts
index 4b095b5..312ce8e 100644
--- a/packages/harness-process/src/index.ts
+++ b/packages/harness-process/src/index.ts
@@ -52,7 +52,7 @@ export {
} from './gateway.ts';
export { isModelRequest, modelCrashArmed, ModelSteps, settleAbandonedModelSteps, unfinishedModelStep } from './model.ts';
export type { ModelStepOutput, ModelStepsOptions } from './model.ts';
-export type { BodyCheck, BodyPolicy, GatewayCap, GatewayHandlerOptions, GatewayLedger, GatewayProxy, GatewayProxyOptions, GatewayRoute, ProviderTool, TrackEnd } from './gateway.ts';
+export type { BodyCheck, BodyPolicy, GatewayCap, GatewayHandlerOptions, GatewayLedger, GatewayProxy, GatewayProxyOptions, GatewayRoute, ProviderTool, TrackedRequest, TrackEnd } from './gateway.ts';
export { FileTail } from './tail.ts';
export { journalLedger, SPEND_STREAM } from './ledger.ts';
export type { JournalLedger, SpendRecord } from './ledger.ts';
@@ -84,3 +84,4 @@ export type {
SessionMachine,
SessionProcess,
} from './environment.ts';
+export { gatewayModelOptions, gatewayModelResult, ResponseCapture } from './agent-runs.ts';
diff --git a/packages/harness-process/src/model.test.ts b/packages/harness-process/src/model.test.ts
index 19373f0..a2a1b22 100644
--- a/packages/harness-process/src/model.test.ts
+++ b/packages/harness-process/src/model.test.ts
@@ -13,12 +13,11 @@ function stateWith(opts: { armed?: 'tool' | 'model' | 'any' | 'sandbox'; kind?:
}
/** A drive context whose effects only record that they ran and what they returned. */
-function stubCtx(state: SessionState, instrumentation?: DriveContext['instrumentation']) {
+function stubCtx(state: SessionState) {
const abort = new AbortController();
const effects: { key: string; options: EffectOptions; output?: unknown; error?: unknown }[] = [];
const ctx = {
runId: 'run',
- instrumentation,
state: () => state,
signal: abort.signal,
halt: (err: unknown) => abort.abort(err),
@@ -41,6 +40,30 @@ const tick = () => new Promise((r) => setTimeout(r, 0));
const post = { method: 'POST', path: '/v1/messages' };
describe('ModelSteps', () => {
+ it('waits for completed request tracing before closing the drive', async () => {
+ const { ctx } = stubCtx(stateWith());
+ let release!: () => void;
+ const saved = new Promise<void>(resolve => { release = resolve; });
+ const tracing = { modelCall: async () => ({ model: { complete: () => saved }, attempt: { attributes() {} } }) } as unknown as DriveContext['tracing'];
+ const steps = new ModelSteps({ ...ctx, tracing });
+ steps.request(post)!({ status: 200 });
+ let closed = false;
+ const closing = steps.close().then(() => { closed = true; });
+ await tick();
+ expect(closed).toBe(false);
+ release();
+ await closing;
+ expect(closed).toBe(true);
+ });
+
+ it('does not let an unfinished trace keep a drive past its deadline', async () => {
+ const { ctx } = stubCtx(stateWith());
+ const tracing = { modelCall: async () => ({ model: { complete: () => new Promise(() => {}) }, attempt: { attributes() {} } }) } as unknown as DriveContext['tracing'];
+ const steps = new ModelSteps({ ...ctx, tracing, deadline: Date.now() + 10 });
+ steps.request(post)!({ status: 200 });
+ await steps.close();
+ }, 1000);
+
it('counts POSTs as model requests, not token counts or reads', () => {
expect(isModelRequest(post)).toBe(true);
expect(isModelRequest({ method: 'POST', path: '/v1/messages/count_tokens' })).toBe(false);
@@ -77,33 +100,6 @@ describe('ModelSteps', () => {
expect(marks).toEqual(['model.request request:0', 'model.first_token request:0', 'model.done request:0 200', 'model.request request:1', 'model.done request:1']);
});
- it('traces model content alongside live marks, without storing it in the chaos step', async () => {
- const starts: unknown[] = [];
- const outputs: unknown[] = [];
- const marks: string[] = [];
- const { ctx, effects } = stubCtx(stateWith({ armed: 'model' }), {
- start(name, input) {
- starts.push({ name, input });
- return { end(output) { outputs.push(output); } };
- },
- end() {},
- });
- ctx.mark = (name) => { marks.push(name); };
- const steps = new ModelSteps(ctx);
- const request = { ...post, model: 'anthropic/test' };
- const end = steps.request(request)!;
- expect(end.capture).toBe(true);
- end.firstToken?.();
- const outcome = { status: 200, requestBody: { messages: ['private prompt'] }, responseBody: 'private response' };
- end(outcome);
- await steps.close();
- expect(starts).toEqual([{ name: 'model', input: request }]);
- expect(outputs).toEqual([outcome]);
- expect(marks).toEqual(['model.request', 'model.first_token', 'model.done']);
- expect(effects[0]!.output).toEqual({ requests: 1, status: 200 });
- expect(JSON.stringify(effects)).not.toContain('private');
- });
-
it('writes nothing when no drill is armed', async () => {
const { ctx, effects } = stubCtx(stateWith({ armed: 'tool' }));
const steps = new ModelSteps(ctx);
diff --git a/packages/harness-process/src/model.ts b/packages/harness-process/src/model.ts
index d09bd81..1e37dfd 100644
--- a/packages/harness-process/src/model.ts
+++ b/packages/harness-process/src/model.ts
@@ -1,6 +1,7 @@
import { randomUUID } from 'node:crypto';
import { armedChaos, chaosKind, chaosMatches, type DriveContext, EffectFailure, type SessionState } from 'harness-world';
-import type { TrackEnd } from './gateway.ts';
+import { gatewayModelOptions, gatewayModelResult, isModelRequest } from './agent-runs.ts';
+import type { TrackedRequest, TrackEnd } from './gateway.ts';
/**
* Model steps: a record-only `model` effect around a process harness's model
@@ -58,8 +59,7 @@ export interface ModelStepOutput {
}
/** Whether a request is a model call: a POST (not a token count). */
-export const isModelRequest = (request: { method: string; path: string }) =>
- request.method === 'POST' && !request.path.includes('count_tokens');
+export { isModelRequest } from './agent-runs.ts';
/** A crash armed in `state` would fire in a model step: a Kill Function, or a dropped relay on the session's sandbox (D4: `/model` dropped mid-stream). */
export function modelCrashArmed(state: SessionState): boolean {
@@ -136,9 +136,10 @@ export class ModelSteps {
* output, `model.done`), as a Pi or fx model step is, so a page can take
* the model's own time out of the turn: the CLI's model call is not a step.
*/
- readonly request = (request: { method: string; path: string; model?: string }): TrackEnd | undefined => {
+ readonly request = (request: TrackedRequest): TrackEnd | undefined => {
if (!isModelRequest(request) || this.closed) return undefined;
- const trace = this.ctx.instrumentation?.start('model', request);
+ // Agent Runs: each request is a model call, a step of its own, with what was asked and answered.
+ const traced = this.ctx.tracing?.modelCall(gatewayModelOptions(request)).catch(() => undefined);
const key = `request:${this.ordinal++}`;
this.ctx.mark?.('model.request', { key });
this.inflight++;
@@ -149,12 +150,22 @@ export class ModelSteps {
const end: TrackEnd = (outcome) => {
if (over) return;
over = true;
- trace?.end(outcome, outcome.error ?? (outcome.status && outcome.status >= 400 ? new Error(`Model request failed (${outcome.status})`) : undefined));
+ const recording = traced?.then(async (call) => {
+ if (!call) return;
+ const failed = outcome.error ?? (outcome.status !== undefined && outcome.status >= 400 ? `the model request failed (${outcome.status})` : undefined);
+ if (failed !== undefined) return call.model.fail(new Error(failed));
+ const { result, attributes } = gatewayModelResult(request.path, outcome.response ?? '');
+ call.attempt.attributes(attributes);
+ await call.model.complete({ outcome: 'completed', result });
+ }).catch(() => {});
+ if (recording) {
+ this.running.add(recording);
+ void recording.then(() => this.running.delete(recording));
+ }
this.ctx.mark?.('model.done', { key, ...(outcome.status !== undefined ? { status: outcome.status } : {}), ...(outcome.error ? { error: outcome.error } : {}) });
this.inflight--;
const step = this.step;
if (!step) return;
- // Content belongs to the policy-controlled trace, not the chaos journal.
step.last = { status: outcome.status, error: outcome.error };
if (this.inflight > 0) return;
// The step is over: a request that starts now gets a step of its own.
@@ -162,7 +173,7 @@ export class ModelSteps {
step.done();
};
return Object.assign(end, {
- capture: !!trace,
+ capture: this.ctx.tracing !== undefined,
firstToken: () => {
if (first || over) return;
first = true;
@@ -193,7 +204,8 @@ export class ModelSteps {
step?.done();
if (!this.running.size) return;
let timer: ReturnType<typeof setTimeout> | undefined;
- await Promise.race([Promise.allSettled([...this.running]), new Promise<void>((r) => (timer = setTimeout(r, waitMs)))]);
+ const remaining = Math.max(0, Math.min(waitMs, (this.ctx.deadline ?? Infinity) - Date.now()));
+ await Promise.race([Promise.allSettled([...this.running]), new Promise<void>((r) => (timer = setTimeout(r, remaining)))]);
clearTimeout(timer);
}
diff --git a/packages/harness-world/package.json b/packages/harness-world/package.json
index 6d958d7..9f3fa7c 100644
--- a/packages/harness-world/package.json
+++ b/packages/harness-world/package.json
@@ -16,7 +16,7 @@
"./fence": "./src/fence.ts",
"./queue": "./src/queue.ts",
"./testing": "./src/testing/index.ts",
- "./instrumentation": "./src/instrumentation.ts",
+ "./agent-runs": "./src/agent-runs.ts",
"./errors": "./src/errors.ts"
},
"scripts": {
@@ -24,6 +24,7 @@
"typecheck": "tsc --noEmit"
},
"dependencies": {
+ "@vercel/agent-runs": "0.0.1",
"@workflow/world": "catalog:",
"devalue": "^5.9.4",
"ulid": "^3.0.1"
diff --git a/packages/harness-world/src/agent-runs.test.ts b/packages/harness-world/src/agent-runs.test.ts
new file mode 100644
index 0000000..3f30c1b
--- /dev/null
+++ b/packages/harness-world/src/agent-runs.test.ts
@@ -0,0 +1,27 @@
+import { describe, expect, it } from 'vitest';
+import { modelMessages, modelTools } from './agent-runs.ts';
+
+describe('trace tool definitions', () => {
+ it('removes SDK transport options from messages and parts without changing the prompt', () => {
+ const prompt = [{ role: 'user', providerOptions: { authorization: 'test-only-credential' }, content: [{ type: 'text', text: 'hello', providerMetadata: { authorization: 'test-only-credential' } }] }];
+ expect(modelMessages(prompt)).toEqual([{ role: 'user', content: [{ type: 'text', text: 'hello' }] }]);
+ expect(JSON.stringify(prompt)).toContain('test-only-credential');
+ });
+ it('projects supported schemas without retaining provider credentials or transport configuration', () => {
+ const schema = { type: 'object', properties: { query: { type: 'string' } } };
+ const tools = [
+ { type: 'function', function: { name: 'lookup', description: 'Look up a record', parameters: schema }, headers: { authorization: 'test-only-credential' } },
+ { name: 'anthropic_lookup', input_schema: schema, authorization: 'test-only-credential' },
+ { type: 'provider', id: 'openai.mcp', name: 'remote_lookup', args: { authorization: 'test-only-credential', headers: { 'x-api-key': 'test-only-credential' } } },
+ { type: 'mcp', server_label: 'remote', authorization: 'test-only-credential' },
+ ];
+ const result = modelTools(tools);
+ expect(result).toEqual([
+ { name: 'lookup', description: 'Look up a record', inputSchema: schema },
+ { name: 'anthropic_lookup', inputSchema: schema },
+ { name: 'remote_lookup' },
+ ]);
+ expect(JSON.stringify(result)).not.toContain('test-only-credential');
+ expect(tools[0]!.headers?.authorization).toBe('test-only-credential');
+ });
+});
diff --git a/packages/harness-world/src/agent-runs.ts b/packages/harness-world/src/agent-runs.ts
new file mode 100644
index 0000000..fdd4aae
--- /dev/null
+++ b/packages/harness-world/src/agent-runs.ts
@@ -0,0 +1,113 @@
+import type { World } from '@workflow/world';
+import type { AttemptOperation, CaptureDecision, ModelCallReturn, ModelOperation, TraceErrorHandler, TurnOperation } from '@vercel/agent-runs';
+import type { DriveContext, Harness } from './types.ts';
+
+export type { ContentPart } from '@vercel/agent-runs';
+
+/** What a model call records when it starts: the model, and (when content is captured) the request. */
+export type ModelOptions = Parameters<AttemptOperation['modelCall']>[0];
+/** What a model call records when it completes (`model.complete({ outcome, result })`). */
+export type ModelResult = Omit<ModelCallReturn<unknown>, 'result'>;
+
+/** Who may read a session's trace content in Agent Runs: `public` records model and tool content, the others metadata only. */
+export type TraceAudience = 'public' | 'private' | 'unknown';
+
+export const traceAudienceOf = (value: unknown): TraceAudience | undefined =>
+ value === 'public' || value === 'private' || value === 'unknown' ? value : undefined;
+
+/** Only tool definitions belong in traces, never provider credentials or transport options. */
+export function modelTools(input: unknown): { name: string; description?: string; inputSchema?: unknown }[] {
+ if (!Array.isArray(input)) return [];
+ return input.flatMap((value) => {
+ if (!value || typeof value !== 'object') return [];
+ const tool = value as Record<string, unknown>;
+ const definition = (tool.function && typeof tool.function === 'object' ? tool.function : tool) as Record<string, unknown>;
+ if (typeof definition.name !== 'string') return [];
+ const schema = definition.inputSchema ?? definition.input_schema ?? definition.parameters;
+ return [{ name: definition.name, ...(typeof definition.description === 'string' ? { description: definition.description } : {}), ...(schema !== undefined ? { inputSchema: schema } : {}) }];
+ });
+}
+
+/** Provider options and replay metadata are not conversation content. */
+export function modelMessages(input: readonly unknown[]): unknown[] {
+ const copy = (value: unknown): unknown => {
+ if (!value || typeof value !== 'object' || Array.isArray(value)) return value;
+ const result = { ...value as Record<string, unknown> };
+ delete result.providerOptions;
+ delete result.providerMetadata;
+ return result;
+ };
+ return input.map(value => {
+ const message = copy(value) as Record<string, unknown>;
+ if (message && Array.isArray(message.content)) message.content = message.content.map(copy);
+ return message;
+ });
+}
+
+/** A model call recorded as its own step of the open turn (an Agent Runs `agent.step`). */
+export interface TracedModelCall {
+ readonly model: ModelOperation;
+ /** The step the call belongs to: the tool calls its response asks for join it. */
+ readonly attempt: AttemptOperation;
+}
+
+/**
+ * Agent Runs tracing for one drive (`DriveContext.tracing`), when
+ * durable-harness's `agentRuns()` is registered in this process.
+ */
+export interface DriveTracing {
+ /**
+ * Record a model call. Inside a `model` effect's body it is that effect's
+ * step, which is then not recorded again from the effect; anywhere else
+ * (a CLI's request through the Gateway proxy) it starts a step of its own.
+ * Undefined when the drive has no open turn, or the turn is not traced.
+ * Complete or fail `model`; the step ends with the next model call or the
+ * drive.
+ */
+ modelCall(options: ModelOptions): Promise<TracedModelCall | undefined>;
+}
+
+export interface SessionTracingInput {
+ readonly world: World;
+ readonly runId: string;
+ /** Names the agent (`invoke_agent <agentName>`). */
+ readonly agentName: string;
+ readonly audience?: TraceAudience;
+}
+
+/**
+ * Agent Runs turns for a session that is not driven by the kernel (pi-durable,
+ * libfx's own durable agent), checkpointed with the session.
+ */
+export interface SessionTracing {
+ /** The turn, started if this is its first operation, else continued where an earlier process left it. */
+ turn(input: { readonly turnId: string; readonly sequence?: number; readonly title?: string }): Promise<TurnOperation | undefined>;
+ /** 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.
+ */
+ step(turn: TurnOperation, turnId: string): Promise<AttemptOperation>;
+ /** Wait for this session's queued checkpoint writes, within the tracing I/O budget. */
+ flush(): Promise<void>;
+}
+
+/** What `agentRuns().register()` installs. The kernel and adapters reach it only through this symbol, so they load no tracing code. */
+export interface AgentRunsHook {
+ capture(audience?: TraceAudience): CaptureDecision;
+ readonly onError: TraceErrorHandler;
+ drive(harness: Harness, ctx: DriveContext): Promise<void>;
+ session(input: SessionTracingInput): SessionTracing;
+}
+
+export const AGENT_RUNS = Symbol.for('durable-harness.agent-runs');
+
+export function agentRunsHook(): AgentRunsHook | undefined {
+ return (globalThis as { [AGENT_RUNS]?: AgentRunsHook })[AGENT_RUNS];
+}
+
+export function tracedDrive(harness: Harness, ctx: DriveContext): Promise<void> {
+ return agentRunsHook()?.drive(harness, ctx) ?? harness.drive(ctx);
+}
diff --git a/packages/harness-world/src/driver.ts b/packages/harness-world/src/driver.ts
index a106b17..6373fb4 100644
--- a/packages/harness-world/src/driver.ts
+++ b/packages/harness-world/src/driver.ts
@@ -1,5 +1,5 @@
import type { World } from '@workflow/world';
-import { instrumentedDrive } from './instrumentation.ts';
+import { tracedDrive } from './agent-runs.ts';
import { monotonicFactory } from 'ulid';
import { encode } from './codec.ts';
import type { StepEnvelope } from './fold.ts';
@@ -1015,7 +1015,7 @@ async function deliverOpen(
current = drive;
let exit: Exit | undefined;
try {
- await instrumentedDrive(harness, drive.ctx);
+ await tracedDrive(harness, drive.ctx);
// A rejection that stopped the drive while the harness wound down.
const halted = drive.halted();
if (halted) throw halted;
diff --git a/packages/harness-world/src/instrumentation.ts b/packages/harness-world/src/instrumentation.ts
deleted file mode 100644
index d0adabe..0000000
--- a/packages/harness-world/src/instrumentation.ts
+++ /dev/null
@@ -1,29 +0,0 @@
-import type { DriveContext, Harness } from './types.ts';
-import type { World } from '@workflow/world';
-
-export interface TraceOperation {
- end(output?: unknown, error?: unknown): void;
-}
-
-export interface TraceScope {
- start(name: string, input?: unknown, key?: string): TraceOperation;
- end(error?: unknown, outcome?: 'completed' | 'running' | 'cancelled' | 'failed'): void;
- /** Wait for best-effort Workflow trace metadata writes owned by this invocation. */
- flush?(): Promise<void>;
-}
-
-export interface InstrumentationRuntime {
- drive(harness: Harness, ctx: DriveContext): Promise<void>;
- session(sessionId: string, harness: string, turnId: string, input?: unknown, audience?: 'public' | 'private' | 'unknown', world?: World): TraceScope;
-}
-
-export const INSTRUMENTATION = Symbol.for('durable-harness.instrumentation');
-
-/** Browser-safe bridge: the Node exporter is installed by the app, never by the kernel. */
-export function instrumentation(): InstrumentationRuntime | undefined {
- return (globalThis as { [INSTRUMENTATION]?: InstrumentationRuntime })[INSTRUMENTATION];
-}
-
-export function instrumentedDrive(harness: Harness, ctx: DriveContext): Promise<void> {
- return instrumentation()?.drive(harness, ctx) ?? harness.drive(ctx);
-}
diff --git a/packages/harness-world/src/types.ts b/packages/harness-world/src/types.ts
index 9836cfd..d12a050 100644
--- a/packages/harness-world/src/types.ts
+++ b/packages/harness-world/src/types.ts
@@ -195,8 +195,8 @@ export interface SessionState {
/** Everything a harness adapter gets from the kernel while it drives a session. */
export interface DriveContext {
- /** Installed by durable-harness's optional tracing integration. */
- readonly instrumentation?: import('./instrumentation.ts').TraceScope;
+ /** Agent Runs tracing, when durable-harness's `agentRuns()` is registered. */
+ readonly tracing?: import('./agent-runs.ts').DriveTracing;
readonly runId: string;
readonly world: World;
/** The fold of everything read so far. */
@@ -429,6 +429,15 @@ export interface Harness {
* In-memory state is disposable: the next invocation rebuilds from the log.
*/
drive(ctx: DriveContext): Promise<void>;
+ /**
+ * How Agent Runs learns this harness's model calls (durable-harness's
+ * `agentRuns()`). `effects` (the default): each `model` effect is one model
+ * call, recorded from its input (`model`: `provider/id`) and output. `self`:
+ * the harness records each call with `ctx.tracing.modelCall`, inside its
+ * `model` effect when it has one (the effect is then the call's step), or
+ * wherever it learns of the request (a CLI behind the Gateway proxy).
+ */
+ modelCalls?: 'effects' | 'self';
/**
* Lanes for this harness's sessions only, overriding the driver's
* `lanes`. Lets one flow route host lane-hopping sessions (a hybrid
diff --git a/packages/hybrid/src/harness.ts b/packages/hybrid/src/harness.ts
index 201c3da..5ab9bd1 100644
--- a/packages/hybrid/src/harness.ts
+++ b/packages/hybrid/src/harness.ts
@@ -74,6 +74,8 @@ function byHands(name: string, lanes: LaneOptions | undefined, build: (hands: Hy
const built = new Map<HybridHands, Harness>();
return {
name,
+ // Pi and fx, whichever the hands build, record their own model calls.
+ modelCalls: 'self',
...(lanes ? { lanes } : {}),
drive(ctx) {
const hands = hybridHandsOf(ctx);
@@ -248,6 +250,7 @@ export function hybridFxHarness(options: HybridFxHarnessOptions): Harness {
const fx = byHands(HYBRID_FX_HARNESS, undefined, (hands) => fxHarness(hybridFxOptions(options, hands)));
return {
name: HYBRID_FX_HARNESS,
+ modelCalls: 'self',
...(options.lanes ? { lanes: options.lanes } : {}),
async drive(ctx) {
const why = ctx.lane === 'browser' ? await options.cannotDrive?.() : undefined;
diff --git a/packages/pi-world/package.json b/packages/pi-world/package.json
index 356d9fe..275deee 100644
--- a/packages/pi-world/package.json
+++ b/packages/pi-world/package.json
@@ -26,7 +26,9 @@
"harness-world": "workspace:*",
"ulid": "^3.0.1",
"harness-world-hands": "workspace:*",
- "harness-world-process": "workspace:*"
+ "harness-world-process": "workspace:*",
+ "@vercel/agent-runs": "0.0.1",
+ "harness-world-pi": "workspace:*"
},
"devDependencies": {
"@workflow/world-local": "catalog:",
diff --git a/packages/pi-world/src/agent-runs.ts b/packages/pi-world/src/agent-runs.ts
new file mode 100644
index 0000000..cae7a3d
--- /dev/null
+++ b/packages/pi-world/src/agent-runs.ts
@@ -0,0 +1,171 @@
+import type { Context } from '@earendil-works/chord';
+import type { AssistantMessage, Message } from '@earendil-works/pi-ai';
+import type { MemoryStorage, StorageWrite } from '@earendil-works/pi-durable';
+import type { AttemptOperation, ModelOperation, ToolOperation, TurnOperation } from '@vercel/agent-runs';
+import type { SessionTracing } from 'harness-world/agent-runs';
+import { piModelOptions, piModelResult, piStepAttributes } from 'harness-world-pi/agent-runs';
+
+type Entry = Awaited<ReturnType<MemoryStorage['scanEntries']>>['items'][number];
+type TaskWrite = Extract<StorageWrite, { type: 'task' }>['value'];
+
+const record = (v: unknown): Record<string, unknown> => (v !== null && typeof v === 'object' ? (v as Record<string, unknown>) : {});
+const userText = (message: Message | undefined) =>
+ message?.role !== 'user' ? undefined : typeof message.content === 'string' ? message.content : message.content.flatMap((p) => (p.type === 'text' ? [p.text] : [])).join('\n');
+
+/**
+ * Agent Runs for a pi-durable session, from the commits its storage accepts:
+ * a turn per input, a step per generation task with its model call, and a
+ * tool call per tool task. A step's index is its assistant entry's place in
+ * the journal, so a wake in another process finds the same step (and its open
+ * tool calls) in the turn's checkpoint. Replaying a journal traces nothing.
+ */
+export class PiTracing {
+ private readonly turns = new Map<string, Promise<TurnOperation | undefined>>();
+ /** Open steps by turn, newest last, with their model call while it runs. */
+ private readonly steps = new Map<string, { index: number; op: AttemptOperation; model?: ModelOperation; task?: string }[]>();
+ private readonly tools = new Map<string, ToolOperation>();
+ /** The input each conversation is answering (the turn its tasks belong to), as this process saw it placed. */
+ private readonly active = new Map<string, string>();
+
+ constructor(
+ private readonly session: SessionTracing,
+ private readonly memory: MemoryStorage
+ ) {}
+
+ async commit(writes: readonly StorageWrite[], context: Context): Promise<void> {
+ for (const write of writes) {
+ if (write.type === 'submission' && write.value.type === 'input' && write.value.status === 'placed') this.active.set(String(write.value.conversationId), String(write.value.id));
+ }
+ for (const write of writes) {
+ if (write.type !== 'task') continue;
+ const task = write.value;
+ if (task.kind !== 'pi.generation' && task.kind !== 'pi.tool') continue;
+ const checkpoint = task.state.status === 'running' ? record(task.state.checkpoint) : undefined;
+ if (task.kind === 'pi.generation' && checkpoint?.phase === 'request') await this.startGeneration(task, checkpoint, context);
+ if (task.kind === 'pi.tool' && checkpoint?.phase === 'execute') await this.startTool(task, checkpoint, context);
+ if (task.state.status === 'terminal') {
+ const outcome = task.state.outcome;
+ const entry = writes.find((w) => w.type === 'entry' && w.value.byTaskId === task.id && (w.value.kind === 'pi.assistant' || w.value.kind === 'pi.tool-result'));
+ const output = entry?.type === 'entry' ? entry.value.model : outcome.status === 'completed' ? outcome.result : undefined;
+ await this.end(task, output, context, outcome.status === 'completed' ? undefined : new Error(String(record(outcome).error ?? `Pi task ${outcome.status}`)));
+ }
+ }
+ // A generation can wait for its tools before its task is terminal: its model call ends when the response commits.
+ for (const write of writes) {
+ if (write.type !== 'entry' || write.value.byTaskId === undefined) continue;
+ if (write.value.kind === 'pi.assistant') await this.endModel(String(write.value.byTaskId), write.value.model?.[0] as AssistantMessage | undefined);
+ }
+ for (const write of writes) {
+ if (write.type !== 'submission' || write.value.type !== 'input') continue;
+ if (write.value.status !== 'done' && write.value.status !== 'unanswered') continue;
+ const turnId = String(write.value.id);
+ if (this.active.get(String(write.value.conversationId)) === turnId) this.active.delete(String(write.value.conversationId));
+ const turn = await this.turnFor(turnId);
+ for (const step of this.steps.get(turnId) ?? []) await step.op.complete();
+ this.steps.delete(turnId);
+ if (write.value.status === 'unanswered') await turn?.complete({ outcome: 'failed', failed: true, error: new Error('Pi input ended without an answer') });
+ else await turn?.complete({ outcome: 'completed' });
+ this.turns.delete(turnId);
+ }
+ }
+
+ flush(): Promise<void> {
+ return this.session.flush();
+ }
+
+ /** The turn: continued from its checkpoint, else started (with the session's first input as its title). */
+ private turnFor(turnId: string, entries?: readonly Entry[]): Promise<TurnOperation | undefined> {
+ let turn = this.turns.get(turnId);
+ if (!turn) {
+ turn = (async () => {
+ const saved = await this.session.resume(turnId);
+ if (saved || !entries) return saved;
+ const users = entries.filter((e) => e.kind === 'pi.user');
+ const title = userText(users.at(-1)?.model?.[0] as Message | undefined);
+ return this.session.turn({ turnId, sequence: Math.max(0, users.length - 1), ...(title ? { title } : {}) });
+ })();
+ this.turns.set(turnId, turn);
+ }
+ return turn;
+ }
+
+ /** The input a task works for: Pi answers one input at a time, so the one placed in its conversation (a wake that did not see it placed asks the storage). */
+ private async turnIdOf(task: TaskWrite, context: Context): Promise<string | undefined> {
+ const conversation = String(task.conversationId);
+ const known = this.active.get(conversation);
+ if (known) return known;
+ const placed = (await this.memory.scanSubmissions({ conversationId: task.conversationId, status: 'placed' }, 100, undefined, context)).items.filter((s) => s.type === 'input');
+ const id = placed.at(-1)?.id;
+ if (id !== undefined) this.active.set(conversation, String(id));
+ return id === undefined ? undefined : String(id);
+ }
+
+ private async entries(task: TaskWrite, context: Context): Promise<readonly Entry[]> {
+ return (await this.memory.scanEntries({ conversationId: task.conversationId }, 1000, undefined, context)).items;
+ }
+
+ private async startGeneration(task: TaskWrite, checkpoint: Record<string, unknown>, context: Context): Promise<void> {
+ const turnId = await this.turnIdOf(task, context);
+ if (!turnId) return;
+ const steps = this.steps.get(turnId) ?? [];
+ if (steps.some((s) => s.task === String(task.id))) return;
+ const entries = await this.entries(task, context);
+ const turn = await this.turnFor(turnId, entries);
+ if (!turn || turn.finished) return;
+ const index = entries.filter((e) => e.kind === 'pi.assistant').length;
+ for (const step of steps.filter((s) => s.model === undefined)) await step.op.complete();
+ const open = steps.filter((s) => s.model !== undefined);
+ const op = turn.findAttempt({ stepIndex: index, attempt: 0 }) ?? (await turn.attempt({ stepIndex: index, attempt: 0 }));
+ const model = record(checkpoint.model);
+ const messages = entries.slice().reverse().flatMap((e) => (e.model ?? []) as Message[]);
+ const call = await op.modelCall(piModelOptions({ provider: String(model.provider ?? 'unknown'), modelId: String(model.modelId ?? 'unknown') }, messages));
+ this.steps.set(turnId, [...open, { index, op, model: call, task: String(task.id) }]);
+ }
+
+ private async startTool(task: TaskWrite, checkpoint: Record<string, unknown>, context: Context): Promise<void> {
+ if (this.tools.has(String(task.id))) return;
+ const turnId = await this.turnIdOf(task, context);
+ if (!turnId) return;
+ const entries = await this.entries(task, context);
+ const turn = await this.turnFor(turnId, entries);
+ if (!turn || turn.finished) return;
+ const input = record(task.input);
+ const callId = String(input.callId ?? task.id);
+ const assistants = entries.filter((e) => e.kind === 'pi.assistant');
+ const at = assistants.findIndex((e) => e.id === input.assistant);
+ const message = assistants[at]?.model?.[0] as AssistantMessage | undefined;
+ const call = message?.content.find((p) => p.type === 'toolCall' && p.id === callId);
+ // Entries are newest first: the step's index counts the assistant entries before this one.
+ const index = at < 0 ? assistants.length - 1 : assistants.length - 1 - at;
+ const step = (this.steps.get(turnId) ?? []).find((s) => s.index === index)?.op ?? turn.findAttempt({ stepIndex: index, attempt: 0 });
+ const tool = turn.findTool(callId) ?? (await step?.tool({ callId, name: call?.type === 'toolCall' ? call.name : 'unknown', arguments: checkpoint.arguments }));
+ if (tool) this.tools.set(String(task.id), tool);
+ }
+
+ private async endModel(taskId: string, message: AssistantMessage | undefined, error?: unknown): Promise<void> {
+ for (const steps of this.steps.values()) {
+ const step = steps.find((s) => s.task === taskId && s.model);
+ if (!step?.model) continue;
+ const model = step.model;
+ step.model = undefined;
+ if (error !== undefined || !message) await model.fail(error ?? new Error('Pi generation ended without a response'));
+ else {
+ step.op.attributes(piStepAttributes(message));
+ await model.complete({ outcome: 'completed', result: piModelResult(message) });
+ }
+ }
+ }
+
+ private async end(task: TaskWrite, output: unknown, context: Context, error?: unknown): Promise<void> {
+ if (task.kind === 'pi.generation') return this.endModel(String(task.id), (output as AssistantMessage[] | undefined)?.[0] ?? (record(output).role === 'assistant' ? (output as AssistantMessage) : undefined), error);
+ let tool = this.tools.get(String(task.id));
+ this.tools.delete(String(task.id));
+ if (!tool) {
+ const turnId = await this.turnIdOf(task, context);
+ tool = turnId ? (await this.turnFor(turnId))?.findTool(String(record(task.input).callId ?? task.id)) : undefined;
+ }
+ if (!tool) return;
+ if (error !== undefined) await tool.fail(error);
+ else await tool.complete({ outcome: 'completed', output });
+ }
+}
diff --git a/packages/pi-world/src/harness.test.ts b/packages/pi-world/src/harness.test.ts
index 6bc18bc..99933ca 100644
--- a/packages/pi-world/src/harness.test.ts
+++ b/packages/pi-world/src/harness.test.ts
@@ -11,7 +11,6 @@ import { createWorld, type LocalWorld } from '@workflow/world-local';
import { afterEach, describe, expect, it, vi } from 'vitest';
import { type Anchor, claimDrive, localAnchors, releaseDrive, vercelAnchors } from 'harness-world/anchor';
import { leasedWorld } from 'harness-world/testing';
-import { INSTRUMENTATION, type InstrumentationRuntime } from 'harness-world/instrumentation';
import { hasUnfinishedWork, journalHead, QUEUE_PREFIX, runWake, StorageFenced, WAKE_QUEUE, type WorldStorage, type WorldStorageOptions, worldStorage } from './index.ts';
const ctx = BACKGROUND_CONTEXT;
@@ -66,63 +65,6 @@ async function transcript(harness: Harness): Promise<string> {
}
describe('Pi Harness on worldStorage', () => {
- it('traces accepted model and tool commits, and emits nothing when the journal is replayed', async () => {
- const operations: { name: string; input: unknown; output?: unknown }[] = [];
- const sessions: unknown[][] = [];
- const ended = vi.fn();
- const globals = globalThis as { [INSTRUMENTATION]?: InstrumentationRuntime };
- const previous = globals[INSTRUMENTATION];
- globals[INSTRUMENTATION] = {
- drive: (h, c) => h.drive(c),
- session(...args) {
- sessions.push(args);
- return {
- start(name, input) {
- const operation = { name, input } as typeof operations[number];
- operations.push(operation);
- return { end(output) { operation.output = output; } };
- },
- end: ended,
- };
- },
- };
- try {
- const { world } = await newWorld();
- const a = agent(world, [
- fauxAssistantMessage([fauxToolCall('read', { path: 'a.txt' })], { stopReason: 'toolUse' }),
- fauxAssistantMessage([fauxText('Read it.')]),
- ], [defineTool({ name: 'read', description: 'Read.', parameters: Type.Object({ path: Type.String() }), replay: 'safe', execute: async () => ({ content: [{ type: 'text', text: 'file contents' }] }) })], { traceAudience: 'private' });
- const sessionId = await worldStorage.create(world);
- const harness = await a.openAgent(sessionId);
- const root = await harness.root(ctx, { agent: a.agentChoice });
- await (await root.submit({ type: 'input', content: 'Read a.txt.' }, ctx)).wait(ctx);
- await harness.close(ctx);
- expect(operations.map(o => o.name)).toEqual(['model', 'tool.read', 'model']);
- expect(operations[0]!.input).toMatchObject({ messages: expect.arrayContaining([expect.objectContaining({ role: 'user', content: 'Read a.txt.' })]) });
- expect(operations[0]!.output).toMatchObject({ role: 'assistant', usage: expect.any(Object) });
- expect(operations[1]!.input).toEqual({ path: 'a.txt' });
- expect(JSON.stringify(operations[1]!.output)).toContain('file contents');
- expect(sessions).toHaveLength(1);
- expect(sessions[0]![4]).toBe('private');
- expect(ended).toHaveBeenCalled();
- const count = operations.length;
- const reopened = await a.openAgent(sessionId);
- await transcript(reopened);
- await reopened.close(ctx);
- expect(operations).toHaveLength(count);
-
- const failing = agent(world, [fauxAssistantMessage([], { stopReason: 'error', errorMessage: 'provider failed' })], []);
- const failedHarness = await failing.openAgent(await worldStorage.create(world));
- const failedRoot = await failedHarness.root(ctx, { agent: failing.agentChoice });
- expect((await (await failedRoot.submit({ type: 'input', content: 'Fail this turn.' }, ctx)).wait(ctx)).status).toBe('unanswered');
- await failedHarness.close(ctx);
- expect(ended).toHaveBeenLastCalledWith(expect.any(Error), 'failed');
- } finally {
- if (previous) globals[INSTRUMENTATION] = previous;
- else delete globals[INSTRUMENTATION];
- }
- });
-
it('answers an input, and a fresh process reads the same session back', async () => {
const { world, dataDir } = await newWorld();
const a = agent(world, [fauxAssistantMessage([fauxText('Paris.')])], []);
diff --git a/packages/pi-world/src/storage.ts b/packages/pi-world/src/storage.ts
index 1564635..e4338cc 100644
--- a/packages/pi-world/src/storage.ts
+++ b/packages/pi-world/src/storage.ts
@@ -1,4 +1,3 @@
-import { instrumentation, type TraceScope, type TraceOperation } from 'harness-world/instrumentation';
import type { Context } from '@earendil-works/chord';
import { createContextKey } from '@earendil-works/chord/context';
import {
@@ -28,8 +27,10 @@ import { decode, encode } from 'harness-world/codec';
import { type Anchor, type AnchorPolicy, anchorKey, holdAnchor } from 'harness-world/anchor';
import { covers, type InBandCounters, inBandFenceSupported, isDefinitiveRefusal, isInBandSuperseded, probeInBandCounters } from 'harness-world/fence';
import { workflowNameFor } from 'harness-world/names';
+import { agentRunsHook, type TraceAudience, traceAudienceOf } from 'harness-world/agent-runs';
import { EXECUTION_CONTEXT, PI_WAKE_QUEUE } from 'harness-world/queue';
import { monotonicFactory } from 'ulid';
+import { PiTracing } from './agent-runs.ts';
import { SessionFiles } from './files.ts';
import { type SandboxRecordValue, SessionSandbox } from './sandbox-record.ts';
import type { DriveFence } from 'harness-world';
@@ -132,9 +133,7 @@ interface SandboxEntry {
anchor?: Anchor;
}
-/** Who may read a session's trace content in Agent Runs (durable-harness/instrumentation/otel). */
-export type TraceAudience = 'public' | 'private' | 'unknown';
-const traceAudienceOf = (v: unknown): TraceAudience | undefined => (v === 'public' || v === 'private' || v === 'unknown' ? v : undefined);
+export type { TraceAudience } from 'harness-world/agent-runs';
export interface WorldStorageOptions {
/**
@@ -491,8 +490,8 @@ async function hasLiveTasks(memory: Storage, context: Context): Promise<boolean>
* its commits itself (see `Backstop`).
*/
export class WorldStorage implements Storage {
- private tracing?: TraceScope;
- private readonly operations = new Map<string, TraceOperation>();
+ /** Agent Runs for the commits this storage makes, when `agentRuns()` is registered (undefined until the first commit, null without it). */
+ private tracing?: PiTracing | null;
private readonly traceName: string;
private readonly traceAudience: WorldStorageOptions['traceAudience'];
private queue: Promise<unknown> = Promise.resolve();
@@ -862,56 +861,12 @@ export class WorldStorage implements Storage {
}
private async traceWrites(writes: readonly StorageWrite[], context: Context): Promise<void> {
- const runtime = instrumentation();
- if (!runtime) return;
- // Only accepted writes are observed. Replaying a journal emits no spans.
- for (const write of writes) {
- if (write.type !== 'task') continue;
- const task = write.value;
- const key = String(task.id);
- const checkpoint = task.state.status === 'running' ? task.state.checkpoint as Record<string, unknown> : undefined;
- const generation = task.kind === 'pi.generation';
- const tool = task.kind === 'pi.tool';
- if (!generation && !tool) continue;
- if (task.state.status === 'running' && !this.operations.has(key)
- && (generation ? checkpoint?.phase === 'request' : checkpoint?.phase === 'execute')) {
- const entries = (await this.memory.scanEntries({ conversationId: task.conversationId }, 1000, undefined, context)).items;
- const input = task.input as Record<string, unknown>;
- const assistant = entries.find(entry => entry.id === input.assistant)?.model?.[0];
- const call = assistant && 'content' in assistant && Array.isArray(assistant.content)
- ? assistant.content.find(part => part.type === 'toolCall' && part.id === input.callId) : undefined;
- const name = generation ? 'model' : `tool.${call && 'name' in call ? call.name : 'unknown'}`;
- const model = checkpoint?.model as { provider?: string; modelId?: string } | undefined;
- this.tracing ??= runtime.session(this.sessionId, this.traceName, String(task.owner ?? task.id), entries.find(entry => entry.kind === 'pi.user')?.model?.[0], this.traceAudience, this.world);
- this.operations.set(key, this.tracing.start(name, generation ? {
- model: model ? `${model.provider}/${model.modelId}` : 'unknown',
- messages: entries.slice().reverse().flatMap(entry => entry.model ?? []),
- } : checkpoint?.arguments, key));
- }
- if (task.state.status === 'terminal') {
- const outcome = task.state.outcome;
- const resultEntry = writes.find(w => w.type === 'entry' && w.value.byTaskId === task.id && (w.value.kind === 'pi.assistant' || w.value.kind === 'pi.tool-result'));
- const output = resultEntry?.type === 'entry' ? (generation ? resultEntry.value.model?.[0] : resultEntry.value.model) : outcome.status === 'completed' ? outcome.result : undefined;
- this.operations.get(key)?.end(output, outcome.status === 'completed' ? undefined : outcome);
- this.operations.delete(key);
- }
- }
- for (const write of writes) {
- if (write.type !== 'entry' || write.value.byTaskId === undefined) continue;
- const entry = write.value;
- if (entry.kind !== 'pi.assistant' && entry.kind !== 'pi.tool-result') continue;
- const key = String(entry.byTaskId);
- // A generation can wait for tools before its task becomes terminal;
- // end the model span when the actual provider result commits.
- this.operations.get(key)?.end(entry.kind === 'pi.assistant' ? entry.model?.[0] : entry.model);
- this.operations.delete(key);
- }
- if (writes.some(w => w.type === 'submission' && w.value.type === 'input' && (w.value.status === 'done' || w.value.status === 'unanswered')) && this.operations.size === 0) {
- const unanswered = writes.some(w => w.type === 'submission' && w.value.type === 'input' && w.value.status === 'unanswered');
- this.tracing?.end(unanswered ? new Error('Pi input ended without an answer') : undefined, unanswered ? 'failed' : 'completed');
- await this.tracing?.flush?.();
- this.tracing = undefined;
+ if (this.tracing === undefined) {
+ const session = agentRunsHook()?.session({ world: this.world, runId: this.sessionId, agentName: this.traceName, ...(this.traceAudience ? { audience: this.traceAudience } : {}) });
+ this.tracing = session ? new PiTracing(session, this.memory) : null;
}
+ // Only accepted writes are observed. Replaying a journal emits no spans.
+ await this.tracing?.commit(writes, context);
}
/**
@@ -1010,9 +965,8 @@ export class WorldStorage implements Storage {
// A crashed process closes nothing: it writes no close entry.
if (this.dead) return (this.closing ??= Promise.resolve());
this.closing ??= this.queue.then(async () => {
- const unfinished = await hasLiveTasks(this.memory, context).catch(() => true);
try {
- if (this.committed && !this.fenced && unfinished) {
+ if (this.committed && !this.fenced && (await hasLiveTasks(this.memory, context).catch(() => true))) {
const anchor = this.anchor;
const entry: CloseEntry = { v: 1, close: true, after: -1, by: this.writer, ...(anchor ? { anchor } : {}) };
// Best effort: without it a wake judges the last commit's anchor, which
@@ -1035,10 +989,8 @@ export class WorldStorage implements Storage {
} finally {
this.letGo();
}
- this.tracing?.end(undefined, unfinished ? 'running' : 'completed');
- await this.tracing?.flush?.();
- this.tracing = undefined;
- this.operations.clear();
+ // A turn with work left goes on in the storage a wake opens, from its checkpoint.
+ await this.tracing?.flush().catch(() => {});
await this.memory.close(context);
});
return this.closing;
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index eaffeb8..695eb99 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -343,6 +343,9 @@ importers:
'@ai-sdk/provider':
specifier: 4.0.22
version: 4.0.22
+ '@vercel/agent-runs':
+ specifier: 0.0.1
+ version: 0.0.1(@opentelemetry/[email protected])([email protected]([email protected]))
'@workflow/world':
specifier: 5.0.4
version: 5.0.4
@@ -571,13 +574,13 @@ importers:
version: 2.0.22([email protected])
'@opencode/core':
specifier: 2.0.22
'@opencode/schema':
specifier: 2.0.22
version: 2.0.22
'@opencode/server':
specifier: 2.0.22
'@opentelemetry/otlp-transformer':
specifier: 0.208.0
version: 0.208.0(@opentelemetry/[email protected])
@@ -587,6 +590,9 @@ importers:
'@opentelemetry/sdk-trace-base':
specifier: 2.2.0
version: 2.2.0(@opentelemetry/[email protected])
+ '@vercel/agent-runs':
+ specifier: 0.0.1
+ version: 0.0.1(@opentelemetry/[email protected])
effect:
specifier: 4.0.0-rc.112
version: 4.0.0-rc.112
@@ -626,6 +632,12 @@ importers:
pi-world:
specifier: workspace:*
version: link:../pi-world
+ rollup:
+ specifier: 4.63.5
+ version: 4.63.5
+ rollup-plugin-dts:
+ specifier: 6.2.3
tsup:
specifier: 8.5.1
@@ -697,6 +709,9 @@ importers:
packages/harness-fx:
dependencies:
+ '@vercel/agent-runs':
+ specifier: 0.0.1
+ version: 0.0.1(@opentelemetry/[email protected])([email protected]([email protected]))
harness-world:
specifier: workspace:*
version: link:../harness-world
@@ -799,6 +814,9 @@ importers:
'@earendil-works/pi-ai':
specifier: 1.0.4
+ '@vercel/agent-runs':
+ specifier: 0.0.1
+ version: 0.0.1(@opentelemetry/[email protected])([email protected]([email protected]))
harness-world:
specifier: workspace:*
version: link:../harness-world
@@ -812,6 +830,9 @@ importers:
packages/harness-process:
dependencies:
+ '@vercel/agent-runs':
+ specifier: 0.0.1
+ version: 0.0.1(@opentelemetry/[email protected])([email protected]([email protected]))
'@vercel/oidc':
specifier: 3.2.0
version: 3.2.0
@@ -865,6 +886,9 @@ importers:
packages/harness-world:
dependencies:
+ '@vercel/agent-runs':
+ specifier: 0.0.1
+ version: 0.0.1(@opentelemetry/[email protected])([email protected]([email protected]))
'@workflow/world':
specifier: 5.0.4
version: 5.0.4
@@ -927,6 +951,9 @@ importers:
'@earendil-works/pi-durable':
specifier: 1.0.4
+ '@vercel/agent-runs':
+ specifier: 0.0.1
+ version: 0.0.1(@opentelemetry/[email protected])([email protected]([email protected]))
'@workflow/world':
specifier: 5.0.4
version: 5.0.4
@@ -936,6 +963,9 @@ importers:
harness-world-hands:
specifier: workspace:*
version: link:../harness-hands
+ harness-world-pi:
+ specifier: workspace:*
+ version: link:../harness-pi
harness-world-process:
specifier: workspace:*
version: link:../harness-process
@@ -3643,6 +3673,16 @@ packages:
resolution: {integrity: sha512-67MQl+fpWKVTT1NYdnmo3U4sc/xPo/zQBncVnI74qmQa0z/b+1g6iYqNmGCPbxO+zz2aklb08a0oHfegiVd0/w==}
+ '@vercel/[email protected]':
+ resolution: {integrity: sha512-U1QPtND8uUSMYw1t68rbWP7R16AspO3XQOE4xt4f2BFuOFP1VZud/zKDiqUFi4cUMeiW+V55LKfMViXeC1UIyQ==}
+ engines: {node: '>=24'}
+ peerDependencies:
+ '@opentelemetry/api': ^1.9.0
+ ai: ^7.0.137
+ peerDependenciesMeta:
+ ai:
+ optional: true
+
'@vercel/[email protected]':
resolution: {integrity: sha512-CnqiuMlZ4pjs2LCPYiR6aLKPPd3Xb8SBI1Y7eotXKgpx6qgrGNY+E7EIyUt5ErGHJGIrCZyGG5WEo4bHtVmz2Q==}
@@ -6096,6 +6136,13 @@ packages:
engines: {node: ^20.19.0 || >=22.12.0}
hasBin: true
+ resolution: {integrity: sha512-UgnEsfciXSPpASuOelix7m4DrmyQgiaWBnvI0TM4GxuDh5FkqW8E5hu57bCxXB90VvR1WNfLV80yEDN18UogSA==}
+ engines: {node: '>=16'}
+ peerDependencies:
+ rollup: ^3.29.4 || ^4
+ typescript: ^4.5 || ^5.0
+
resolution: {integrity: sha512-KRWwmNLlPw5M7HcdYfm15oBv9n9LPtjzpzCIxS/phwqvPyxHSoKX6Y2YU3pxSPfy0CLquVgsx/j/hBi6OvH1Nw==}
engines: {node: '>=18.0.0', npm: '>=8.0.0'}
@@ -8653,7 +8700,7 @@ snapshots:
acorn: 8.15.0
effect: 4.0.0-rc.112
dependencies:
'@ai-sdk/cohere': 3.0.27([email protected])
'@ai-sdk/gateway': 3.0.104([email protected])
@@ -8694,7 +8741,7 @@ snapshots:
mime-types: 3.0.2
tree-sitter-bash: 0.25.0
tree-sitter-powershell: 0.25.10
- venice-ai-sdk-provider: 2.1.1([email protected]([email protected]))([email protected])
+ venice-ai-sdk-provider: 2.1.1([email protected]([email protected]))([email protected])
web-tree-sitter: 0.25.10
which: 6.0.1
zod: 4.1.8
@@ -8765,7 +8812,7 @@ snapshots:
- valibot
- ws
dependencies:
'@ai-sdk/cohere': 3.0.27([email protected])
'@ai-sdk/gateway': 3.0.104([email protected])
@@ -8806,7 +8853,7 @@ snapshots:
mime-types: 3.0.2
tree-sitter-bash: 0.25.0
tree-sitter-powershell: 0.25.10
- venice-ai-sdk-provider: 2.1.1([email protected]([email protected]))([email protected])
+ venice-ai-sdk-provider: 2.1.1([email protected]([email protected]))([email protected])
web-tree-sitter: 0.25.10
which: 6.0.1
zod: 4.1.8
@@ -8877,7 +8924,7 @@ snapshots:
- valibot
- ws
dependencies:
'@ai-sdk/cohere': 3.0.27([email protected])
'@ai-sdk/gateway': 3.0.104([email protected])
@@ -8918,7 +8965,7 @@ snapshots:
mime-types: 3.0.2
tree-sitter-bash: 0.25.0
tree-sitter-powershell: 0.25.10
- venice-ai-sdk-provider: 2.1.1([email protected]([email protected]))([email protected])
+ venice-ai-sdk-provider: 2.1.1([email protected])
web-tree-sitter: 0.25.10
which: 6.0.1
zod: 4.1.8
@@ -8989,7 +9036,7 @@ snapshots:
- valibot
- ws
dependencies:
'@ai-sdk/cohere': 3.0.27([email protected])
'@ai-sdk/gateway': 3.0.104([email protected])
@@ -9030,7 +9077,7 @@ snapshots:
mime-types: 3.0.2
tree-sitter-bash: 0.25.0
tree-sitter-powershell: 0.25.10
- venice-ai-sdk-provider: 2.1.1([email protected]([email protected]))([email protected])
+ venice-ai-sdk-provider: 2.1.1([email protected])
web-tree-sitter: 0.25.10
which: 6.0.1
zod: 4.1.8
@@ -9490,14 +9537,14 @@ snapshots:
- ws
- zod
dependencies:
'@effect/platform-node': 4.0.0-rc.112([email protected])([email protected](@opentelemetry/[email protected]))
'@effect/platform-node-shared': 4.0.0-rc.112([email protected])
'@opencode/protocol': 2.0.22
'@opencode/schema': 2.0.22
'@opencode/util': 2.0.22(@opentelemetry/[email protected])([email protected](@opentelemetry/[email protected]))([email protected])
effect: 4.0.0-rc.112
@@ -9571,14 +9618,14 @@ snapshots:
- ws
- zod
dependencies:
'@effect/platform-node': 4.0.0-rc.112([email protected])([email protected](@opentelemetry/[email protected]))
'@effect/platform-node-shared': 4.0.0-rc.112([email protected])
'@opencode/protocol': 2.0.22
'@opencode/schema': 2.0.22
'@opencode/util': 2.0.22(@opentelemetry/[email protected])([email protected](@opentelemetry/[email protected]))([email protected])
effect: 4.0.0-rc.112
@@ -9733,10 +9780,10 @@ snapshots:
- ws
- zod
dependencies:
'@opencode/ai': 2.0.22([email protected])
'@opencode/protocol': 2.0.22
'@opencode/util': 2.0.22(@opentelemetry/[email protected])([email protected](@opentelemetry/[email protected]))([email protected])
@@ -9810,10 +9857,10 @@ snapshots:
- valibot
- web-tree-sitter
dependencies:
'@opencode/ai': 2.0.22([email protected])
'@opencode/protocol': 2.0.22
'@opencode/util': 2.0.22(@opentelemetry/[email protected])([email protected](@opentelemetry/[email protected]))([email protected])
@@ -10705,6 +10752,16 @@ snapshots:
dependencies:
'@types/node': 22.20.4
+ '@vercel/[email protected](@opentelemetry/[email protected])':
+ dependencies:
+ '@opentelemetry/api': 1.9.0
+
+ dependencies:
+ '@opentelemetry/api': 1.9.1
+ optionalDependencies:
+ ai: 7.0.128([email protected])
+
'@vercel/[email protected]':
dependencies:
async-listen: 3.0.0
@@ -13595,6 +13652,14 @@ snapshots:
'@rolldown/binding-win32-arm64-msvc': 1.2.11
'@rolldown/binding-win32-x64-msvc': 1.2.11
+ dependencies:
+ magic-string: 0.30.21
+ rollup: 4.63.5
+ typescript: 5.9.3
+ optionalDependencies:
+ '@babel/code-frame': 7.29.7
+
dependencies:
'@types/estree': 1.0.9
@@ -14245,6 +14310,14 @@ snapshots:
transitivePeerDependencies:
- zod
+ dependencies:
+ '@ai-sdk/openai-compatible': 2.0.81([email protected])
+ '@ai-sdk/provider': 3.0.18
+ '@ai-sdk/provider-utils': 4.0.59([email protected])
+ transitivePeerDependencies:
+ - zod
+
dependencies:
lightningcss: 1.33.0
diff --git a/pnpm-workspace.yaml b/pnpm-workspace.yaml
index 11998bd..947a734 100644
--- a/pnpm-workspace.yaml
+++ b/pnpm-workspace.yaml
@@ -21,6 +21,7 @@ minimumReleaseAgeExclude:
- '@earendil-works/*'
- '@ai-sdk/[email protected]'
+ - '@vercel/[email protected]'
# Workflow SDK: the npm release of 2026-10-12 (workflow, @workflow/core and
# @workflow/world-vercel 5.2.1, @workflow/world-local 5.1.1, @workflow/world,
# @workflow/world-postgres, @workflow/next and @workflow/cli 5.0.4,