@apo-ai/sdk 0.2.2 → 0.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/agent-task/integrations/ai-sdk.d.ts +1 -2
- package/dist/agent-task/integrations/anthropic.d.ts +1 -2
- package/dist/agent-task/integrations/openai.d.ts +1 -2
- package/dist/agent-task/public.d.ts +81 -3
- package/dist/agent-task/public.js +282 -3
- package/dist/agent-task/public.js.map +1 -1
- package/dist/{types-C-nrDEVf.d.ts → tracing-BE53Q8Ru.d.ts} +20 -56
- package/package.json +2 -10
- package/dist/index.d.ts +0 -95
- package/dist/index.js +0 -39
- package/dist/index.js.map +0 -1
- package/dist/tracing-DtbhYQV6.d.ts +0 -26
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/agent-task/trace-projection/view.ts","../../src/agent-task/checks/matchers.ts","../../src/agent-task/checks/judge.ts","../../src/agent-task/checks/t.ts","../../src/agent-task/checks/recorder.ts","../../src/agent-task/checks/location.ts","../../src/agent-task/checks/flow-runner.ts","../../src/agent-task/task/defineTask.ts","../../src/agent-task/task/loadTask.ts","../../src/agent-task/turn.ts","../../src/agent-task/task/TaskFiles.ts","../../src/agent-task/adapter/defineAdapter.ts","../../src/agent-task/deliverables/artifact.ts","../../src/agent-task/deliverables/upload.ts","../../src/agent-task/flow/view.ts","../../src/agent-task/flow/sources.ts","../../src/agent-task/run/run-configuration.ts","../../src/agent-task/deliverables/validate.ts","../../src/agent-task/trace-projection/projection-tee.ts","../../src/agent-task/trace-projection/remote-capture.ts","../../src/semconv.ts","../../src/agent-task/run/aggregate.ts","../../src/agent-task/tracing.ts","../../src/agent-task/run/runTask.ts","../../src/agent-task/cli.ts","../../src/agent-task/discovery.ts","../../src/agent-task/otel-trace-client.ts","../../src/agent-task/task-runtime.ts","../../src/agent-task/task-revision-manifest.ts"],"sourcesContent":["/**\n * TraceView — typed, capability-gated, derived access over a\n * {@link TraceProjectionSnapshot}. This is the read model the projection-first\n * assertion surface queries. It is the projection analogue of `FlowView`.\n *\n * The defining difference from `FlowView` is **capability honesty**: when the\n * snapshot declares a category of evidence `unavailable`, the derived numeric\n * facts (`durationMs`, `failedActions`, `turnCount`) return `undefined` rather\n * than zero — so an assertion like `t.maxDurationMs` can record an explicit\n * `unsupported` outcome instead of vacuously passing against a fabricated 0ms.\n *\n * `toolNamesInOrder` sorts by observation invocation time (`startedAt`) with a\n * deterministic span-ID tie-breaker — NOT array/completion order. This fixes\n * the drift where concurrent tools appeared in completion order.\n */\n\nimport type {\n EvidenceAvailability,\n ObservationStatus,\n TraceProjectionCapabilities,\n TraceProjectionMessage,\n TraceProjectionObservation,\n TraceProjectionSnapshot,\n} from \"./types.ts\";\n\n/** A tool call derived from a `TOOL` observation. */\nexport interface TraceToolCall {\n spanId: string;\n name: string;\n input?: unknown;\n output?: unknown;\n status: ObservationStatus;\n startedAt?: string;\n}\n\n/** A skill load derived from a `SKILL` observation. */\nexport interface TraceSkillLoad {\n spanId: string;\n skill: string;\n startedAt?: string;\n}\n\n/** A subagent delegation derived from an `AGENT` observation. */\nexport interface TraceSubagentCall {\n spanId: string;\n agent: string;\n output?: unknown;\n status: ObservationStatus;\n startedAt?: string;\n}\n\n/** Sentinel that sorts before every real timestamp in string comparison. */\nconst TIMESTAMPED_MIN = \"\";\n\n/**\n * Comparison key for deterministic ordering by invocation time then span ID.\n * Missing `startedAt` sorts AFTER every timestamped observation.\n */\nfunction invocationOrderKey(obs: TraceProjectionObservation): [number, string, string] {\n const hasTs = obs.startedAt != null ? 0 : 1;\n return [hasTs, obs.startedAt ?? \"\", obs.spanId];\n}\n\nexport class TraceView {\n readonly snapshot: TraceProjectionSnapshot;\n\n constructor(snapshot: TraceProjectionSnapshot) {\n this.snapshot = snapshot;\n }\n\n /** Evidence availability for a capability. */\n requireCapability(\n capability: keyof TraceProjectionCapabilities,\n ): EvidenceAvailability {\n return this.snapshot.capabilities[capability];\n }\n\n /** Whether a capability is reported as available (not partial/unavailable). */\n private isAvailable(capability: keyof TraceProjectionCapabilities): boolean {\n return this.snapshot.capabilities[capability] === \"available\";\n }\n\n /** All chat messages flattened across generation observations, in order. */\n get messages(): readonly TraceProjectionMessage[] {\n const out: TraceProjectionMessage[] = [];\n for (const obs of this.sortedObservations) {\n if (obs.messages) out.push(...obs.messages);\n }\n return out;\n }\n\n /** Tool calls derived from `TOOL` observations, in invocation order. */\n get toolCalls(): readonly TraceToolCall[] {\n return this.sortedObservations\n .filter((o): o is TraceProjectionObservation & { type: \"TOOL\" } => o.type === \"TOOL\")\n .map((o) => ({\n spanId: o.spanId,\n name: o.toolName ?? o.name,\n input: o.toolParameters ?? o.input,\n output: o.toolResult ?? o.output,\n status: o.status,\n startedAt: o.startedAt,\n }));\n }\n\n /** Tool names in invocation order with deterministic span-ID tie-breaking. */\n get toolNamesInOrder(): readonly string[] {\n return this.toolCalls.map((c) => c.name);\n }\n\n /** Skill loads derived from `SKILL` observations, in invocation order. */\n get skillLoads(): readonly TraceSkillLoad[] {\n return this.sortedObservations\n .filter((o): o is TraceProjectionObservation & { type: \"SKILL\" } => o.type === \"SKILL\")\n .map((o) => ({ spanId: o.spanId, skill: o.name, startedAt: o.startedAt }));\n }\n\n /** Subagent delegations derived from `AGENT` observations, in invocation order. */\n get subagentCalls(): readonly TraceSubagentCall[] {\n return this.sortedObservations\n .filter((o): o is TraceProjectionObservation & { type: \"AGENT\" } => o.type === \"AGENT\")\n .map((o) => ({\n spanId: o.spanId,\n agent: o.name,\n output: o.output,\n status: o.status,\n startedAt: o.startedAt,\n }));\n }\n\n /** Last assistant message content — the agent's \"reply\". Empty if none. */\n get reply(): string {\n const msgs = this.messages;\n for (let i = msgs.length - 1; i >= 0; i--) {\n if (msgs[i]!.role === \"assistant\") return msgs[i]!.content;\n }\n return \"\";\n }\n\n /**\n * Number of completed assistant turns, or `undefined` when message evidence\n * is unavailable (capability honesty).\n */\n get turnCount(): number | undefined {\n if (!this.isAvailable(\"messages\")) return undefined;\n return this.messages.filter((m) => m.role === \"assistant\").length;\n }\n\n /**\n * Number of tool/subagent observations that reported an error, or `undefined`\n * when error evidence is unavailable (capability honesty).\n */\n get failedActions(): number | undefined {\n if (!this.isAvailable(\"errors\")) return undefined;\n return this.sortedObservations.filter(\n (o) => (o.type === \"TOOL\" || o.type === \"AGENT\") && o.status === \"error\",\n ).length;\n }\n\n /**\n * Total execution duration in milliseconds, or `undefined` when timing\n * evidence is unavailable (capability honesty). Uses trace-level\n * startedAt/endedAt when present.\n */\n get durationMs(): number | undefined {\n if (!this.isAvailable(\"timing\")) return undefined;\n const { startedAt, endedAt } = this.snapshot.trace;\n if (startedAt != null && endedAt != null) {\n const ms = Date.parse(endedAt) - Date.parse(startedAt);\n return Number.isNaN(ms) ? undefined : Math.max(0, ms);\n }\n return undefined;\n }\n\n /**\n * Observations sorted deterministically by invocation time then span ID.\n * Memoized per TraceView instance since the snapshot is immutable.\n */\n private get sortedObservations(): readonly TraceProjectionObservation[] {\n if (this._sorted !== undefined) return this._sorted;\n // Copy to a mutable array, then sort by invocation key: missing timestamps\n // (key prefix 1) sort after timestamped ones (prefix 0), then by span ID\n // for determinism.\n const sorted = [...this.snapshot.observations].sort((a, b) => {\n const ka = invocationOrderKey(a);\n const kb = invocationOrderKey(b);\n return (\n ka[0] - kb[0] ||\n ka[1].localeCompare(kb[1]) ||\n ka[2].localeCompare(kb[2])\n );\n });\n this._sorted = sorted;\n return sorted;\n }\n private _sorted: readonly TraceProjectionObservation[] | undefined;\n}\n\n// Keep the timestamp sentinel referenced for clarity — documents that empty\n// string is the \"earliest\" timestamp in lexicographic ordering.\nvoid TIMESTAMPED_MIN;\n","/**\n * Value matchers for `t.check(value, matcher)`. Small, composable, and the\n * single way to assert on deliverables/values (replaces the old `expect`).\n *\n * A matcher is just `{ label, test }` — easy to build custom ones inline with\n * `satisfies(fn, label)`.\n */\n\nexport type Matcher<T> = { label: string; test: (value: T) => boolean };\n\nfunction asString(value: unknown): string {\n if (typeof value === \"string\") return value;\n if (value === undefined) return \"undefined\";\n if (value === null) return \"null\";\n try {\n return JSON.stringify(value);\n } catch {\n return String(value);\n }\n}\n\n/** Serialize any value for compact \"Received:\" display. */\nexport function describeValue(value: unknown): string {\n return asString(value);\n}\n\nfunction escapeRegExp(s: string): string {\n return s.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\");\n}\n\nfunction deepEqual(a: unknown, b: unknown): boolean {\n if (a === b) return true;\n if (a === null || b === null || typeof a !== \"object\" || typeof b !== \"object\") {\n return false;\n }\n if (Array.isArray(a) !== Array.isArray(b)) return false;\n if (Array.isArray(a) && Array.isArray(b)) {\n if (a.length !== b.length) return false;\n return a.every((v, i) => deepEqual(v, b[i]));\n }\n const ao = a as Record<string, unknown>;\n const bo = b as Record<string, unknown>;\n const ak = Object.keys(ao);\n const bk = Object.keys(bo);\n if (ak.length !== bk.length) return false;\n return ak.every(\n (k) => Object.prototype.hasOwnProperty.call(bo, k) && deepEqual(ao[k], bo[k]),\n );\n}\n\n/** Coerces the value to a string and checks it contains a substring or RegExp. Gate. */\nexport function includes(needle: string | RegExp): Matcher<unknown> {\n const re = typeof needle === \"string\" ? new RegExp(escapeRegExp(needle)) : needle;\n return {\n label: `includes ${needle instanceof RegExp ? needle.source : needle}`,\n test: (v) => re.test(asString(v)),\n };\n}\n\n/** Deep structural equality. Gate. */\nexport function equals<T>(expected: T): Matcher<T> {\n return {\n label: `equals ${asString(expected)}`,\n test: (v) => deepEqual(v, expected),\n };\n}\n\n/**\n * Validates against a Standard-Schema-shaped validator (Zod, Valibot, …) —\n * anything exposing `safeParse`. Gate.\n */\nexport function matches<T = unknown>(\n schema: {\n safeParse: (value: unknown) => { success: boolean };\n },\n): Matcher<T> {\n return {\n label: \"matches schema\",\n test: (v) => schema.safeParse(v).success === true,\n };\n}\n\n/** Custom boolean predicate. Gate. */\nexport function satisfies<T>(\n predicate: (value: T) => boolean,\n label: string,\n): Matcher<T> {\n return { label, test: predicate };\n}\n\n// ── Value matching (for tool-call input/output fields) ───────────────────\n// A value can be matched by a literal (partial-deep for objects), a RegExp\n// (string-coerced), or a predicate function. Used by calledTool/notCalledTool\n// to match a tool call's input/output/status.\n\nexport type ValueMatcher<T> = T | RegExp | ((value: T) => boolean);\n\nexport function matchValue<T>(actual: T, matcher: ValueMatcher<T>): boolean {\n if (matcher instanceof RegExp) return matcher.test(asString(actual));\n if (typeof matcher === \"function\") {\n return (matcher as (value: T) => boolean)(actual);\n }\n if (matcher !== null && typeof matcher === \"object\") {\n // Partial-deep match: every key on the matcher must be present and match.\n if (actual === null || typeof actual !== \"object\") return false;\n const a = actual as Record<string, unknown>;\n const m = matcher as Record<string, unknown>;\n return Object.keys(m).every(\n (k) =>\n Object.prototype.hasOwnProperty.call(a, k) && matchValue(a[k], m[k]),\n );\n }\n return deepEqual(actual, matcher);\n}\n\n// ── Fuzzy similarity ─────────────────────────────────────────────────────\n\n/** Normalized Levenshtein similarity. Pass when score ≥ threshold (default 0.8). */\nexport function similarity(expected: string, threshold = 0.8): Matcher<unknown> {\n return {\n label: `similar to \"${expected}\" (≥ ${threshold})`,\n test: (v) => normalizedSimilarity(asString(v), expected) >= threshold,\n };\n}\n\nfunction normalizedSimilarity(a: string, b: string): number {\n const maxLen = Math.max(a.length, b.length);\n if (maxLen === 0) return 1;\n return 1 - levenshtein(a, b) / maxLen;\n}\n\nfunction levenshtein(a: string, b: string): number {\n const m = a.length;\n const n = b.length;\n if (m === 0) return n;\n if (n === 0) return m;\n let prev = Array.from({ length: n + 1 }, () => 0);\n let curr = Array.from({ length: n + 1 }, () => 0);\n for (let j = 0; j <= n; j++) prev[j] = j;\n for (let i = 1; i <= m; i++) {\n curr[0] = i;\n for (let j = 1; j <= n; j++) {\n const cost = a[i - 1] === b[j - 1] ? 0 : 1;\n curr[j] = Math.min(prev[j] + 1, curr[j - 1] + 1, prev[j - 1] + cost);\n }\n [prev, curr] = [curr, prev];\n }\n return prev[n];\n}\n","/**\n * LLM-as-judge call. Used by `t.judge(values, instruction)` to evaluate\n * deliverables against a natural-language rubric. Calls an OpenAI-compatible\n * endpoint (OpenRouter, OpenAI, etc.) via fetch and parses the verdict.\n */\n\nimport type { JudgeMetadata } from \"../run/types.ts\";\n\nexport type JudgeCallResult = {\n pass: boolean;\n reasoning: string;\n judge: JudgeMetadata;\n};\n\nconst JUDGE_SYSTEM_PROMPT =\n \"You are an evaluation judge. Evaluate the given value(s) against the \" +\n 'instruction. Respond with ONLY a JSON object: {\"pass\": true/false, \"reasoning\": \"your reasoning\"}';\n\nfunction formatValue(value: unknown, depth = 0): string {\n const indent = \" \".repeat(depth);\n if (value === null || value === undefined) return String(value);\n if (typeof value === \"string\") return value;\n if (typeof value === \"number\" || typeof value === \"boolean\") return String(value);\n if (Array.isArray(value)) {\n return value\n .map((item) => `${indent}${formatValue(item, depth + 1)}`)\n .join(\"\\n\");\n }\n if (typeof value === \"object\") {\n return Object.entries(value as Record<string, unknown>)\n .map(([key, val]) => {\n if (val && typeof val === \"object\") {\n return `${indent}${key}:\\n${formatValue(val, depth + 1)}`;\n }\n return `${indent}${key}: ${formatValue(val, depth + 1)}`;\n })\n .join(\"\\n\");\n }\n return String(value);\n}\n\nfunction formatJudgeValues(values: unknown[]): string {\n if (values.length === 1) return formatValue(values[0]);\n return values\n .map((v, i) => `--- Value ${i + 1} ---\\n${formatValue(v)}`)\n .join(\"\\n\\n\");\n}\n\n/**\n * Tolerantly parse the judge model's response into `{pass, reasoning}`.\n *\n * Despite `response_format: json_object`, models sometimes wrap output in\n * markdown code fences (```` ```json … ``` ````) or add surrounding prose.\n * Falling back to a raw `\"invalid JSON\"` string on the first parse failure\n * buries the verdict and reasoning the user actually needs. Instead: try the\n * raw text, strip fences, then extract the first balanced `{...}` block.\n */\n\n// Provider token usage for a judge call. Cached-prefix accounting arrives in\n// two shapes depending on the route: direct Anthropic exposes\n// cache_creation_input_tokens / cache_read_input_tokens, while OpenRouter\n// (and OpenAI) normalize them into prompt_tokens_details.cache_write_tokens /\n// prompt_tokens_details.cached_tokens. Their presence proves the cached\n// deliverable prefix was written once and read on subsequent criteria (#21).\ntype JudgeUsage = {\n prompt_tokens?: number;\n completion_tokens?: number;\n cache_creation_input_tokens?: number;\n cache_read_input_tokens?: number;\n prompt_tokens_details?: {\n cached_tokens?: number;\n cache_write_tokens?: number;\n };\n};\n\ntype JudgeTokens = {\n input: number;\n output: number;\n cache_creation?: number;\n cache_read?: number;\n};\n\nfunction parseJudgeUsage(usage: JudgeUsage | undefined): JudgeTokens | undefined {\n if (!usage) return undefined;\n const cacheCreation =\n usage.cache_creation_input_tokens ?? usage.prompt_tokens_details?.cache_write_tokens;\n const cacheRead =\n usage.cache_read_input_tokens ?? usage.prompt_tokens_details?.cached_tokens;\n const tokens: JudgeTokens = {\n input: usage.prompt_tokens ?? 0,\n output: usage.completion_tokens ?? 0,\n };\n if (typeof cacheCreation === \"number\") tokens.cache_creation = cacheCreation;\n if (typeof cacheRead === \"number\") tokens.cache_read = cacheRead;\n return tokens;\n}\n\nfunction parseJudgeJson(raw: string): { pass?: boolean; reasoning?: string } {\n // 1. Direct parse (the common, well-behaved case).\n try {\n return JSON.parse(raw);\n } catch {\n // fall through to tolerant strategies\n }\n // 2. Strip a single markdown code fence: ```json\\n{...}\\n``` -> {...}.\n const fenced = raw.match(/```(?:json)?\\s*([\\s\\S]*?)```/);\n if (fenced) {\n try {\n return JSON.parse(fenced[1].trim());\n } catch {\n // fall through\n }\n }\n // 3. Pull the first balanced {...} block out of surrounding prose.\n const block = raw.match(/\\{[\\s\\S]*\\}/);\n if (block) {\n try {\n return JSON.parse(block[0]);\n } catch {\n // fall through\n }\n }\n // 4. Unparseable. The verdict is genuinely unknown, so we treat it as a\n // failure (can't confirm pass) and explain what happened in plain language.\n // Dumping the raw response as \"reasoning\" is unhelpful — it's usually a\n // truncated or malformed blob the model emitted, and presenting it as an\n // explanation misleads. The raw response stays available on the judge\n // metadata for anyone who needs to debug the model output itself.\n return {\n pass: false,\n reasoning:\n \"Judge response could not be parsed as JSON — the verdict is unknown, \" +\n \"so this check is treated as a failure. The model's raw response is \" +\n \"available in the judge metadata.\",\n };\n}\n\n/**\n * Per-prefix serialization. Checks run concurrently (flow-runner uses\n * Promise.all), so without coordination N criteria judging the same\n * deliverable would all dispatch against a cold cache and mostly miss. This\n * chains calls that share a cached prefix: the first warms the provider's\n * prompt cache and the rest dispatch only after it resolves (and hit it).\n * Calls with different prefixes are independent and stay concurrent.\n */\nconst prefixQueues = new Map<string, Promise<unknown>>();\n\nfunction runWithSharedPrefix<T>(key: string, task: () => Promise<T>): Promise<T> {\n const prev = prefixQueues.get(key) ?? Promise.resolve();\n // Run `task` once the previous same-prefix call settles, regardless of\n // whether it succeeded — a failed warmer must not block its siblings.\n const next = prev.then(task, task);\n // Keep the chain alive through errors so one rejection can't poison the queue.\n prefixQueues.set(\n key,\n next.then(\n () => undefined,\n () => undefined,\n ),\n );\n return next;\n}\n\nexport async function callJudge(args: {\n values: unknown[];\n instruction: string;\n model: string;\n baseURL?: string;\n apiKey?: string;\n}): Promise<JudgeCallResult> {\n const baseURL = args.baseURL ?? process.env.OPENROUTER_BASE_URL ?? \"https://openrouter.ai/api/v1\";\n const apiKey = args.apiKey ?? process.env.OPENROUTER_API_KEY ?? process.env.OPENAI_API_KEY;\n\n // Structure the request so the (often huge) deliverable is a cacheable\n // prefix and only the small per-criterion instruction varies. Many criteria\n // judge the same deliverable; without a cache breakpoint the deliverable is\n // re-billed in full on every call. cache_control is an Anthropic/Gemini\n // extension that OpenRouter passes through, and is ignored harmlessly by\n // providers without prompt caching. See issue #21.\n const deliverableText = `Values to evaluate:\\n${formatJudgeValues(args.values)}`;\n const instructionText = `Instruction:\\n${args.instruction}`;\n const systemPromptText = `${JUDGE_SYSTEM_PROMPT}\\n\\n${deliverableText}`;\n\n // The cached prefix is model + system blocks; the varying instruction lives\n // in the user message, so it's excluded from the key.\n const cacheKey = `${args.model}\\u0000${deliverableText}`;\n\n return runWithSharedPrefix(cacheKey, async () => {\n const startedAt = Date.now();\n\n const response = await fetch(`${baseURL}/chat/completions`, {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n ...(apiKey ? { Authorization: `Bearer ${apiKey}` } : {}),\n },\n body: JSON.stringify({\n model: args.model,\n messages: [\n {\n role: \"system\",\n content: [\n { type: \"text\", text: JUDGE_SYSTEM_PROMPT },\n {\n type: \"text\",\n text: deliverableText,\n cache_control: { type: \"ephemeral\" },\n },\n ],\n },\n { role: \"user\", content: instructionText },\n ],\n temperature: 0,\n response_format: { type: \"json_object\" },\n }),\n });\n\n if (!response.ok) {\n const body = await response.text().catch(() => \"\");\n throw new Error(`Judge API ${response.status}: ${body.slice(0, 200)}`);\n }\n\n const data = (await response.json()) as {\n choices?: Array<{ message?: { content?: string } }>;\n usage?: JudgeUsage;\n };\n\n const text = data.choices?.[0]?.message?.content ?? \"\";\n const outputTokens = data.usage?.completion_tokens;\n\n // Guard: a response that is empty, OR that the provider reports as having\n // generated zero output tokens, is a transient/provider failure — not a\n // model verdict. This happens when a provider cuts a stream mid-generation\n // and returns a stub like \"[\" with completion_tokens: 0. Treat it as a\n // failure with a clear explanation rather than feeding garbage to the\n // parser. (Only guard on tokens when the provider actually reported usage;\n // absent usage means \"unknown\", not \"zero\".)\n const isEmpty = !text.trim();\n const reportedZeroTokens = data.usage !== undefined && outputTokens === 0;\n if (isEmpty || reportedZeroTokens) {\n return {\n pass: false,\n reasoning:\n \"Judge returned an empty or truncated response — likely a transient \" +\n \"provider failure. The verdict is unknown, so this check is treated \" +\n \"as a failure.\",\n judge: {\n model: args.model,\n prompt: { system: systemPromptText, user: instructionText },\n response: text,\n tokens: parseJudgeUsage(data.usage),\n latency_ms: Date.now() - startedAt,\n },\n };\n }\n\n // Models routinely wrap their JSON in markdown fences (```json … ```) or\n // add prose around it despite the json_object response_format. Parse\n // tolerantly so the verdict + reasoning aren't lost to a parse error:\n // try the raw text, then strip fences, then extract the first {...}.\n const parsed = parseJudgeJson(text);\n\n return {\n pass: parsed.pass === true,\n reasoning: typeof parsed.reasoning === \"string\" ? parsed.reasoning : \"\",\n judge: {\n model: args.model,\n prompt: { system: systemPromptText, user: instructionText },\n response: text,\n tokens: parseJudgeUsage(data.usage),\n latency_ms: Date.now() - startedAt,\n },\n };\n });\n}\n","/**\n * The assertion surface — `t`. Flat and eve-style: reads the trace (via\n * {@link TraceView}) for behavioural checks and grades explicit values via\n * `t.check`. Everything records (never throws), so a check reports all of its\n * failures, not just the first.\n *\n * Every assertion records structured ``expected`` / ``received`` values so\n * the dashboard can render testing-framework-style failures (Expected /\n * Received) instead of only a prose message.\n */\n\nimport { TraceView } from \"../trace-projection/view.ts\";\nimport type { TraceProjectionCapabilities } from \"../trace-projection/types.ts\";\nimport type { AssertionOutcome } from \"../run/types.ts\";\nimport type { Recorder } from \"./recorder.ts\";\nimport type { Matcher, ValueMatcher } from \"./matchers.ts\";\nimport { describeValue, matchValue } from \"./matchers.ts\";\nimport { callJudge } from \"./judge.ts\";\n\n/** A tool/agent name matcher: literal (exact), RegExp, or predicate. */\nexport type NameMatcher = string | RegExp | ((name: string) => boolean);\n\n/** Options for matching tool calls by count and recorded fields. */\nexport type ToolCallOptions = {\n count?: number;\n input?: ValueMatcher<unknown>;\n output?: ValueMatcher<unknown>;\n status?: \"ok\" | \"error\";\n};\n\n/**\n * LLM judge model config for `t.judge(...)` calls in checks.ts. Threaded\n * through `runTask({ judge })` from the caller — the runner has no opinion\n * about which model grades a deliverable.\n */\nexport type JudgeConfig = {\n /** Model id, e.g. ``\"google/gemini-2.5-flash-lite\"``. */\n model: string;\n /** Override the OpenRouter/OpenAI-compatible base URL. */\n baseURL?: string;\n /** Override the API key (defaults to env). */\n apiKey?: string;\n};\n\n/**\n * Resolves the judge config for a single ``t.judge`` call: merges a per-call\n * ``opts.judge`` override onto the run-level ``judgeConfig``, field-by-field.\n * Returns ``undefined`` when the result has no model — callers should treat\n * that as \"no judge configured\" and record the env-setup guidance. (The model\n * is the only required field, so it's the one worth gating on.)\n */\nfunction resolveJudgeConfig(\n judgeConfig: JudgeConfig | undefined,\n override: Partial<JudgeConfig> | undefined,\n): JudgeConfig | undefined {\n const model = override?.model ?? judgeConfig?.model;\n if (!model) return undefined;\n return {\n model,\n baseURL: override?.baseURL ?? judgeConfig?.baseURL,\n apiKey: override?.apiKey ?? judgeConfig?.apiKey,\n };\n}\n\nexport interface TestContext {\n // ── trace / \"did it run well\" ──────────────────────────────────────────\n /** Asserts a matching tool was called. Pass `{ count }` for an exact count. */\n calledTool(name: NameMatcher, opts?: ToolCallOptions): void;\n /** Asserts no tool call matches the supplied name and field constraints. */\n notCalledTool(name: NameMatcher, opts?: Omit<ToolCallOptions, \"count\">): void;\n /** Asserts the named tools appear, in this order (as a subsequence). */\n toolOrder(names: string[]): void;\n /** Asserts no tool calls happened at all. */\n usedNoTools(): void;\n /** Asserts at most `n` tool calls — anti-flail. */\n maxToolCalls(n: number): void;\n /** Asserts no tool/subagent call reported an error — anti-flail. */\n noFailedActions(): void;\n /** Asserts a skill was loaded. */\n loadedSkill(skill: string): void;\n /** Asserts a subagent delegation happened. */\n calledSubagent(agent: string): void;\n /** Asserts the agent's reply contains a substring or RegExp. */\n messageIncludes(token: string | RegExp): void;\n /** Asserts the run took at most `n` turns — anti-flail. */\n maxTurns(n: number): void;\n /** Asserts the run took at most `n` milliseconds — anti-flail. */\n maxDurationMs(n: number): void;\n /** Escape hatch for a named predicate over the complete normalized run. */\n assert(label: string, predicate: (flow: TraceView) => boolean): void;\n\n // ── values / deliverables ──────────────────────────────────────────────\n /** Grades any value (a deliverable, parsed JSON, anything) with a matcher. */\n check<T>(value: T, matcher: Matcher<T>, label?: string): void;\n /**\n * LLM-as-judge: asks the configured judge model to grade ``value`` against\n * ``instruction`` (a natural-language rubric). Async — the check function\n * must `await` it. Records a single assertion tagged\n * ``evaluator_type: \"llm\"`` with judge metadata (model, prompt, response,\n * tokens, latency) attached.\n *\n * ``opts.judge`` overrides the run's judge config **for this call only**,\n * merging field-by-field onto the config threaded in via ``runTask({ judge })``\n * — set ``{ model }`` to escalate a finicky criterion to a stronger model\n * without switching the whole run. Absent fields inherit from the base config.\n */\n judge(\n values: unknown | unknown[],\n instruction: string,\n opts?: { label?: string; judge?: Partial<JudgeConfig> },\n ): Promise<void>;\n}\n\n/**\n * Canonical names of every assertion method on {@link TestContext}.\n *\n * Single source of truth for \"what is a ``t.<method>`` call?\" — consumers that\n * highlight, lint, or otherwise detect `t.*` usage in check source read this\n * array instead of keeping their own copy (which historically drifted out of\n * sync with the interface, leaving methods like ``t.maxTurns`` unstyled).\n *\n * The literal below is compile-time-checked against ``keyof TestContext``:\n * adding a method to the interface without registering it here is a type\n * error, and vice versa. See ``tests/test-context-methods.test.ts``.\n */\nexport const TEST_METHOD_NAMES = [\n \"calledTool\",\n \"notCalledTool\",\n \"toolOrder\",\n \"usedNoTools\",\n \"maxToolCalls\",\n \"noFailedActions\",\n \"loadedSkill\",\n \"calledSubagent\",\n \"messageIncludes\",\n \"maxTurns\",\n \"maxDurationMs\",\n \"assert\",\n \"check\",\n \"judge\",\n] as const satisfies readonly (keyof TestContext)[];\n\n/**\n * Compile-time exhaustiveness guard: errors if any {@link TestContext} method\n * is missing from {@link TEST_METHOD_NAMES}. A method on the interface with no\n * matching array entry makes the conditional type resolve to the offending\n * key instead of ``never``, which fails to assign to ``TEST_METHOD_NAMES``.\n * Kept out of the public type surface (no export) — it's a build-time check.\n */\ntype _TestMethodNamesComplete<T = keyof TestContext> =\n Exclude<T, (typeof TEST_METHOD_NAMES)[number]> extends never ? true : never;\n// If this line errors, a TestContext method is not listed in TEST_METHOD_NAMES.\nconst _testMethodNamesComplete: _TestMethodNamesComplete = true;\n\nfunction describeName(m: NameMatcher): string {\n if (typeof m === \"string\") return `\"${m}\"`;\n if (m instanceof RegExp) return m.source;\n return \"<predicate>\";\n}\n\nfunction matchName(name: string, m: NameMatcher): boolean {\n if (typeof m === \"string\") return name === m;\n if (m instanceof RegExp) return m.test(name);\n return m(name);\n}\n\nexport function createTestContext(\n view: TraceView,\n rec: Recorder,\n judgeConfig?: JudgeConfig,\n): TestContext {\n return {\n calledTool(name, opts) {\n const count = view.toolCalls.filter((call) =>\n matchesToolCall(call, name, opts),\n ).length;\n const want = opts?.count;\n const pass = want === undefined ? count > 0 : count === want;\n rec.record(\n `calledTool(${describeName(name)})`,\n pass,\n pass\n ? \"\"\n : want === undefined\n ? `expected at least one ${describeName(name)} call, got ${count}`\n : `expected exactly ${want} ${describeName(name)} calls, got ${count}`,\n {\n expected:\n want === undefined\n ? `≥1 ${describeName(name)} call`\n : `exactly ${want} ${describeName(name)} calls`,\n received: `${count}`,\n },\n );\n },\n\n notCalledTool(name, opts) {\n const count = view.toolCalls.filter((call) =>\n matchesToolCall(call, name, opts),\n ).length;\n rec.record(\n `notCalledTool(${describeName(name)})`,\n count === 0,\n count === 0 ? \"\" : `expected no ${describeName(name)} calls, got ${count}`,\n { expected: `0 ${describeName(name)} calls`, received: `${count}` },\n );\n },\n\n toolOrder(names) {\n const order = view.toolNamesInOrder;\n let cursor = 0;\n let missingIdx = -1;\n for (let i = 0; i < names.length; i++) {\n const found = order.indexOf(names[i], cursor);\n if (found === -1) {\n missingIdx = i;\n break;\n }\n cursor = found + 1;\n }\n const ok = missingIdx === -1;\n // Arrow separators read better than commas, and \"expected X after Y\"\n // pinpoints WHICH tool broke the order — clearer than dumping both lists\n // and asking the reader to do the visual diff.\n const expectedStr = names.join(\" → \");\n const actualStr = order.length > 0 ? order.join(\" → \") : \"(no tools)\";\n const message = ok\n ? \"\"\n : missingIdx === 0\n ? `expected \"${names[0]}\" first; actual order ${actualStr}`\n : `expected \"${names[missingIdx]}\" after \"${names[missingIdx - 1]}\"; actual order ${actualStr}`;\n rec.record(`toolOrder(${expectedStr})`, ok, message, {\n expected: expectedStr,\n received: actualStr,\n });\n },\n\n usedNoTools() {\n const count = view.toolCalls.length;\n rec.record(\"usedNoTools\", count === 0, count === 0 ? \"\" : `expected no tool calls, got ${count}`, {\n expected: \"0 tool calls\",\n received: `${count}`,\n });\n },\n\n maxToolCalls(n) {\n const count = view.toolCalls.length;\n rec.record(`maxToolCalls(${n})`, count <= n, count <= n ? \"\" : `expected ≤ ${n} tool calls, got ${count}`, {\n expected: `≤ ${n} tool calls`,\n received: `${count}`,\n });\n },\n\n noFailedActions() {\n const failed = view.failedActions;\n rec.record(\"noFailedActions\", failed === 0, failed === 0 ? \"\" : `${failed} failed action(s)`, {\n expected: \"0 failed actions\",\n received: `${failed}`,\n });\n },\n\n loadedSkill(skill) {\n const ok = view.skillLoads.some((s) => s.skill === skill);\n rec.record(`loadedSkill(\"${skill}\")`, ok, ok ? \"\" : `skill \"${skill}\" was not loaded`, {\n expected: `skill \"${skill}\" loaded`,\n received: view.skillLoads.map((s) => s.skill).join(\", \") || \"none\",\n });\n },\n\n calledSubagent(agent) {\n const ok = view.subagentCalls.some((s) => s.agent === agent);\n rec.record(`calledSubagent(\"${agent}\")`, ok, ok ? \"\" : `subagent \"${agent}\" was not called`, {\n expected: `subagent \"${agent}\" called`,\n received: view.subagentCalls.map((s) => s.agent).join(\", \") || \"none\",\n });\n },\n\n messageIncludes(token) {\n const re = typeof token === \"string\" ? new RegExp(token) : token;\n const ok = re.test(view.reply);\n rec.record(`messageIncludes(${token instanceof RegExp ? token.source : token})`, ok, ok ? \"\" : `reply did not include ${token}`, {\n expected: `reply includes ${token instanceof RegExp ? token.source : token}`,\n received: describeValue(view.reply).slice(0, 200),\n });\n },\n\n maxTurns(n) {\n const turns = view.turnCount;\n const pass = turns !== undefined && turns <= n;\n rec.record(`maxTurns(${n})`, pass, pass ? \"\" : `expected ≤ ${n} turns, got ${turns}`, {\n expected: `≤ ${n} turns`,\n received: `${turns}`,\n });\n },\n\n maxDurationMs(n) {\n const ms = view.durationMs;\n const pass = ms !== undefined && ms <= n;\n rec.record(`maxDurationMs(${n})`, pass, pass ? \"\" : `expected ≤ ${n}ms, took ${ms}ms`, {\n expected: `≤ ${n}ms`,\n received: `${ms}ms`,\n });\n },\n\n check(value, matcher, label) {\n const pass = matcher.test(value);\n rec.record(\n label ?? \"check\",\n pass,\n pass ? \"\" : `expected ${label ?? \"value\"} ${matcher.label}`,\n // Expected = the matcher's own description; received = the actual value.\n { expected: matcher.label, received: describeValue(value) },\n );\n },\n\n assert(label, predicate) {\n const pass = predicate(view);\n rec.record(label, pass, pass ? \"\" : `assertion \"${label}\" failed`, {\n expected: label,\n received: pass ? \"true\" : \"false\",\n });\n },\n\n async judge(values, instruction, opts) {\n const label = opts?.label ?? \"judge\";\n // Capture the call site BEFORE any await. After `await callJudge` resumes,\n // V8 reports this caller's frame at an unreliable line (often the\n // statement's closing `});`), which placed the failure marker on the\n // wrong line. Pinning it here lands the marker on `await t.judge(`.\n const location = rec.captureLocation();\n const valueArray = Array.isArray(values) ? values : [values];\n const effective = resolveJudgeConfig(judgeConfig, opts?.judge);\n if (!effective) {\n rec.record(\n label,\n false,\n \"No judge model configured. Set one of:\\n\" +\n \"• OPENROUTER_MODEL + OPENROUTER_API_KEY (OpenRouter — works with 200+ models, one account)\\n\" +\n \"• OPENAI_MODEL + OPENAI_API_KEY (OpenAI direct)\\n\" +\n \"Or pass { judge } to runTask() programmatically.\",\n { evaluator_type: \"llm\", location },\n );\n return;\n }\n try {\n const { pass, reasoning, judge } = await callJudge({\n values: valueArray,\n instruction,\n model: effective.model,\n baseURL: effective.baseURL,\n apiKey: effective.apiKey,\n });\n rec.record(label, pass, reasoning, {\n evaluator_type: \"llm\",\n judge,\n expected: instruction,\n // Store the raw evaluated value (not a truncated string) so the\n // dashboard can render it with the right viewer — Markdown for\n // prose, a JSON tree for structured objects.\n received: valueArray.length === 1 ? valueArray[0] : valueArray,\n location,\n });\n } catch (error) {\n rec.record(\n label,\n false,\n `judge failed: ${error instanceof Error ? error.message : String(error)}`,\n {\n evaluator_type: \"llm\",\n expected: instruction,\n received: valueArray.length === 1 ? valueArray[0] : valueArray,\n location,\n },\n );\n }\n },\n };\n}\n\n/**\n * Capability key → human description, for unsupported-outcome reasoning.\n */\nconst CAPABILITY_LABELS: Record<keyof TraceProjectionCapabilities, string> = {\n messages: \"message\",\n tools: \"tool\",\n errors: \"error\",\n timing: \"timing\",\n skills: \"skill\",\n subagents: \"subagent\",\n} as const;\n\n/**\n * Create a projection-first test context from a {@link TraceView}. Mirrors {@link createTestContext} but gates trace-dependent\n * assertions on capabilities: when the projection declares a capability\n * ``unavailable``, the assertion records ``outcome=\"unsupported\"`` (pass=false)\n * instead of vacuously passing against fabricated zero/empty evidence.\n *\n * Value assertions (``t.check``) and LLM assertions (``t.judge``) do not\n * consult capabilities and retain their existing behavior.\n */\nexport function createTraceTestContext(\n view: TraceView,\n rec: Recorder,\n judgeConfig?: JudgeConfig,\n): TestContext {\n const unsupported = (\n id: string,\n capability: keyof TraceProjectionCapabilities,\n ): void => {\n const label = CAPABILITY_LABELS[capability];\n rec.record(id, false, `${label} evidence is unavailable in this trace projection`, {\n outcome: \"unsupported\" as AssertionOutcome,\n expected: `${label} evidence available`,\n received: view.requireCapability(capability),\n });\n };\n\n const isAvailable = (c: keyof TraceProjectionCapabilities): boolean =>\n view.requireCapability(c) === \"available\";\n\n return {\n calledTool(name, opts) {\n if (!isAvailable(\"tools\")) {\n unsupported(`calledTool(${describeName(name)})`, \"tools\");\n return;\n }\n // Matching by { status } additionally requires errors evidence.\n if (opts?.status !== undefined && !isAvailable(\"errors\")) {\n unsupported(`calledTool(${describeName(name)}, { status })`, \"errors\");\n return;\n }\n const count = view.toolCalls.filter((call) =>\n matchesTraceToolCall(call, name, opts),\n ).length;\n const want = opts?.count;\n const pass = want === undefined ? count > 0 : count === want;\n rec.record(\n `calledTool(${describeName(name)})`,\n pass,\n pass\n ? \"\"\n : want === undefined\n ? `expected at least one ${describeName(name)} call, got ${count}`\n : `expected exactly ${want} ${describeName(name)} calls, got ${count}`,\n {\n expected:\n want === undefined\n ? `≥1 ${describeName(name)} call`\n : `exactly ${want} ${describeName(name)} calls`,\n received: `${count}`,\n },\n );\n },\n\n notCalledTool(name, opts) {\n if (!isAvailable(\"tools\")) {\n unsupported(`notCalledTool(${describeName(name)})`, \"tools\");\n return;\n }\n const count = view.toolCalls.filter((call) =>\n matchesTraceToolCall(call, name, opts),\n ).length;\n rec.record(\n `notCalledTool(${describeName(name)})`,\n count === 0,\n count === 0 ? \"\" : `expected no ${describeName(name)} calls, got ${count}`,\n { expected: `0 ${describeName(name)} calls`, received: `${count}` },\n );\n },\n\n toolOrder(names) {\n if (!isAvailable(\"tools\")) {\n unsupported(`toolOrder(${names.join(\" → \")})`, \"tools\");\n return;\n }\n const order = view.toolNamesInOrder;\n let cursor = 0;\n let missingIdx = -1;\n for (let i = 0; i < names.length; i++) {\n const found = order.indexOf(names[i], cursor);\n if (found === -1) {\n missingIdx = i;\n break;\n }\n cursor = found + 1;\n }\n const ok = missingIdx === -1;\n const expectedStr = names.join(\" → \");\n const actualStr = order.length > 0 ? order.join(\" → \") : \"(no tools)\";\n const message = ok\n ? \"\"\n : missingIdx === 0\n ? `expected \"${names[0]}\" first; actual order ${actualStr}`\n : `expected \"${names[missingIdx]}\" after \"${names[missingIdx - 1]}\"; actual order ${actualStr}`;\n rec.record(`toolOrder(${expectedStr})`, ok, message, {\n expected: expectedStr,\n received: actualStr,\n });\n },\n\n usedNoTools() {\n if (!isAvailable(\"tools\")) {\n unsupported(\"usedNoTools\", \"tools\");\n return;\n }\n const count = view.toolCalls.length;\n rec.record(\"usedNoTools\", count === 0, count === 0 ? \"\" : `expected no tool calls, got ${count}`, {\n expected: \"0 tool calls\",\n received: `${count}`,\n });\n },\n\n maxToolCalls(n) {\n if (!isAvailable(\"tools\")) {\n unsupported(`maxToolCalls(${n})`, \"tools\");\n return;\n }\n const count = view.toolCalls.length;\n rec.record(`maxToolCalls(${n})`, count <= n, count <= n ? \"\" : `expected ≤ ${n} tool calls, got ${count}`, {\n expected: `≤ ${n} tool calls`,\n received: `${count}`,\n });\n },\n\n noFailedActions() {\n if (!isAvailable(\"errors\")) {\n unsupported(\"noFailedActions\", \"errors\");\n return;\n }\n const failed = view.failedActions ?? 0;\n rec.record(\"noFailedActions\", failed === 0, failed === 0 ? \"\" : `${failed} failed action(s)`, {\n expected: \"0 failed actions\",\n received: `${failed}`,\n });\n },\n\n loadedSkill(skill) {\n if (!isAvailable(\"skills\")) {\n unsupported(`loadedSkill(\"${skill}\")`, \"skills\");\n return;\n }\n const ok = view.skillLoads.some((s) => s.skill === skill);\n rec.record(`loadedSkill(\"${skill}\")`, ok, ok ? \"\" : `skill \"${skill}\" was not loaded`, {\n expected: `skill \"${skill}\" loaded`,\n received: view.skillLoads.map((s) => s.skill).join(\", \") || \"none\",\n });\n },\n\n calledSubagent(agent) {\n if (!isAvailable(\"subagents\")) {\n unsupported(`calledSubagent(\"${agent}\")`, \"subagents\");\n return;\n }\n const ok = view.subagentCalls.some((s) => s.agent === agent);\n rec.record(`calledSubagent(\"${agent}\")`, ok, ok ? \"\" : `subagent \"${agent}\" was not called`, {\n expected: `subagent \"${agent}\" called`,\n received: view.subagentCalls.map((s) => s.agent).join(\", \") || \"none\",\n });\n },\n\n messageIncludes(token) {\n if (!isAvailable(\"messages\")) {\n unsupported(`messageIncludes(${token instanceof RegExp ? token.source : token})`, \"messages\");\n return;\n }\n const re = typeof token === \"string\" ? new RegExp(token) : token;\n const ok = re.test(view.reply);\n rec.record(`messageIncludes(${token instanceof RegExp ? token.source : token})`, ok, ok ? \"\" : `reply did not include ${token}`, {\n expected: `reply includes ${token instanceof RegExp ? token.source : token}`,\n received: describeValue(view.reply).slice(0, 200),\n });\n },\n\n maxTurns(n) {\n if (!isAvailable(\"messages\")) {\n unsupported(`maxTurns(${n})`, \"messages\");\n return;\n }\n const turns = view.turnCount ?? 0;\n rec.record(`maxTurns(${n})`, turns <= n, turns <= n ? \"\" : `expected ≤ ${n} turns, got ${turns}`, {\n expected: `≤ ${n} turns`,\n received: `${turns}`,\n });\n },\n\n maxDurationMs(n) {\n if (!isAvailable(\"timing\")) {\n unsupported(`maxDurationMs(${n})`, \"timing\");\n return;\n }\n const ms = view.durationMs;\n if (ms === undefined) {\n unsupported(`maxDurationMs(${n})`, \"timing\");\n return;\n }\n rec.record(`maxDurationMs(${n})`, ms <= n, ms <= n ? \"\" : `expected ≤ ${n}ms, took ${ms}ms`, {\n expected: `≤ ${n}ms`,\n received: `${ms}ms`,\n });\n },\n\n assert(label, predicate) {\n // The author is responsible for checking capabilities inside the predicate.\n const pass = predicate(view as unknown as TraceView);\n rec.record(label, pass, pass ? \"\" : `assertion \"${label}\" failed`, {\n expected: label,\n received: pass ? \"true\" : \"false\",\n });\n },\n\n check(value, matcher, label) {\n const pass = matcher.test(value);\n rec.record(\n label ?? \"check\",\n pass,\n pass ? \"\" : `expected ${label ?? \"value\"} ${matcher.label}`,\n { expected: matcher.label, received: describeValue(value) },\n );\n },\n\n async judge(values, instruction, opts) {\n // judge does not consult trace capabilities.\n const label = opts?.label ?? \"judge\";\n const location = rec.captureLocation();\n const valueArray = Array.isArray(values) ? values : [values];\n const effective = resolveJudgeConfig(judgeConfig, opts?.judge);\n if (!effective) {\n rec.record(\n label,\n false,\n \"No judge model configured. Set one of:\\n\" +\n \"• OPENROUTER_MODEL + OPENROUTER_API_KEY (OpenRouter — works with 200+ models, one account)\\n\" +\n \"• OPENAI_MODEL + OPENAI_API_KEY (OpenAI direct)\\n\" +\n \"Or pass { judge } to runTask() programmatically.\",\n { evaluator_type: \"llm\", location },\n );\n return;\n }\n try {\n const { pass, reasoning, judge } = await callJudge({\n values: valueArray,\n instruction,\n model: effective.model,\n baseURL: effective.baseURL,\n apiKey: effective.apiKey,\n });\n rec.record(label, pass, reasoning, {\n evaluator_type: \"llm\",\n judge,\n expected: instruction,\n received: valueArray.length === 1 ? valueArray[0] : valueArray,\n location,\n });\n } catch (error) {\n rec.record(\n label,\n false,\n `judge failed: ${error instanceof Error ? error.message : String(error)}`,\n {\n evaluator_type: \"llm\",\n expected: instruction,\n received: valueArray.length === 1 ? valueArray[0] : valueArray,\n location,\n },\n );\n }\n },\n };\n}\n\nfunction matchesTraceToolCall(\n call: { name: string; input?: unknown; output?: unknown; status?: string },\n name: NameMatcher,\n opts?: Omit<ToolCallOptions, \"count\">,\n): boolean {\n if (!matchName(call.name, name)) return false;\n if (opts?.input !== undefined && !matchValue(call.input, opts.input)) {\n return false;\n }\n if (opts?.output !== undefined && !matchValue(call.output, opts.output)) {\n return false;\n }\n if (opts?.status !== undefined && call.status !== opts.status) {\n return false;\n }\n return true;\n}\n\nfunction matchesToolCall(\n call: TraceView[\"toolCalls\"][number],\n name: NameMatcher,\n opts?: Omit<ToolCallOptions, \"count\">,\n): boolean {\n if (!matchName(call.name, name)) return false;\n if (opts?.input !== undefined && !matchValue(call.input, opts.input)) {\n return false;\n }\n if (opts?.output !== undefined && !matchValue(call.output, opts.output)) {\n return false;\n }\n if (opts?.status !== undefined && call.status !== opts.status) {\n return false;\n }\n return true;\n}\n","/**\n * Recorder — collects assertion outcomes within a single check so every\n * failure is reported (nothing throws/dies on the first miss). Aggregated\n * per-check by the runner into one evaluation result.\n */\n\nimport type { AssertionResult, CheckLocation } from \"../run/types.ts\";\n\n/** Back-compat alias; {@link AssertionResult} is the canonical type. */\nexport type AssertionRecord = AssertionResult;\n\n/**\n * Optional hook the runner installs when it knows how to map a stack to the\n * task/check module. The Recorder captures ``new Error().stack`` at the\n * assertion call site and hands it to ``locate``.\n */\nexport type LocateFn = (stack: string) => CheckLocation | undefined;\n\nexport class Recorder {\n private records: AssertionResult[] = [];\n private readonly locate?: LocateFn;\n\n constructor(locate?: LocateFn) {\n this.locate = locate;\n }\n\n /**\n * Record an assertion.\n *\n * - ``extra.location`` overrides auto-capture (used by the runner for thrown\n * errors, whose relevant stack is the error's own, not the call site).\n * - ``extra.expected`` / ``extra.received`` carry the structured values for\n * testing-framework-style display.\n */\n /**\n * Capture the call site location synchronously. Use this when a record will\n * happen AFTER an `await` (e.g. `t.judge`): once an async function resumes,\n * `new Error().stack` reports the caller's frame at an unreliable line\n * (often the statement's closing brace). Capturing here, before the await,\n * pins the location to the actual call line; pass it to ``record`` via\n * ``extra.location``.\n */\n captureLocation(): CheckLocation | undefined {\n return this.locate ? this.locate(new Error().stack ?? \"\") : undefined;\n }\n\n record(\n id: string,\n pass: boolean,\n reasoning: string,\n extra?: {\n location?: CheckLocation;\n expected?: string;\n received?: unknown;\n evaluator_type?: \"llm\" | \"code\";\n judge?: import(\"../run/types.ts\").JudgeMetadata;\n outcome?: import(\"../run/types.ts\").AssertionOutcome;\n },\n ): void {\n const location =\n extra?.location\n ?? (this.locate ? this.locate(new Error().stack ?? \"\") : undefined);\n this.records.push({\n id,\n pass,\n reasoning,\n location,\n expected: extra?.expected,\n received: extra?.received,\n evaluator_type: extra?.evaluator_type,\n judge: extra?.judge,\n outcome: extra?.outcome,\n });\n }\n\n get all(): readonly AssertionResult[] {\n return this.records;\n }\n}\n","/**\n * Parses a failure's stack trace into a {@link CheckLocation} anchored inside\n * the user's task/check module.\n *\n * Task modules and legacy checks modules load from verbatim temporary copies,\n * so frame line/column values map 1:1 to the original source. The display\n * ``file`` is the original filename, allowing the dashboard to fetch it.\n */\n\nimport type { CheckLocation } from \"../run/types.ts\";\n\nconst FRAME_TAIL = /:(\\d+):(\\d+)\\)?\\s*$/;\n\nexport function parseCheckLocation(\n stack: string | undefined,\n moduleUrl: string,\n displayFile: string,\n): CheckLocation | undefined {\n if (!stack || !moduleUrl) return undefined;\n // Match either the full module URL (native Node stacks) or its de-schemed\n // path (source-mapped / transformed stacks, e.g. under test runners), so\n // the locator is robust to how the frame URL is rendered.\n const needle = moduleUrl.replace(/^file:\\/\\//, \"\");\n for (const line of stack.split(\"\\n\")) {\n if (!line.includes(moduleUrl) && !line.includes(needle)) continue;\n const m = line.match(FRAME_TAIL);\n if (m) {\n return { file: displayFile, line: Number(m[1]), column: Number(m[2]) };\n }\n }\n return undefined;\n}\n","/**\n * Check runner — builds a {@link TestContext} (`t`) per registered check from\n * a {@link TraceProjectionSnapshot}, runs it, and aggregates every recorded\n * assertion into one evaluation result per check.\n */\n\nimport { TraceView } from \"../trace-projection/view.ts\";\nimport type { TraceProjectionSnapshot } from \"../trace-projection/types.ts\";\nimport type { CheckLocation, EvaluationItemResult } from \"../run/types.ts\";\nimport { createTraceTestContext, type TestContext, type JudgeConfig } from \"./t.ts\";\nimport { Recorder, type LocateFn } from \"./recorder.ts\";\nimport { parseCheckLocation } from \"./location.ts\";\nimport { copyFileSync, existsSync, unlinkSync } from \"fs\";\nimport { basename } from \"path\";\nimport { pathToFileURL } from \"url\";\n\n/**\n * The check context — deliberately framework-agnostic. `deliverables` is the\n * output; `files`/`task` are optional and untyped here so the core never\n * depends on any agent-framework's types. apo passes its own typed values;\n * other frameworks pass whatever they have (or omit).\n *\n * A task-scoped ``test`` gets typed deliverables from the adapter automatically:\n *\n * ```ts\n * const { test } = task(\"review\", {\n * adapter: reviewAdapter,\n * deliverables: [\"result\"],\n * });\n * test(\"id\", (t, { deliverables }) => {\n * deliverables.result // typed as ReviewResult\n * });\n * ```\n *\n * The generic overload of {@link defineCheck} remains available for\n * framework-agnostic checks that have no task scope.\n */\nexport type CheckContext<TDeliverables = Record<string, unknown>> = {\n deliverables: TDeliverables;\n files?: unknown;\n task?: unknown;\n};\n\nexport function filePaths(files: unknown): string[] {\n if (!Array.isArray(files)) return [];\n return (files as Array<{ relativePath: string }>).map((f) => f.relativePath);\n}\n\nexport type CheckFn<TDeliverables = Record<string, unknown>> = (\n t: TestContext,\n ctx: CheckContext<TDeliverables>,\n) => Promise<void> | void;\n\nexport type TestRegistration<TDeliverables = Record<string, unknown>> = (\n id: string,\n fn: CheckFn<TDeliverables>,\n) => void;\n\n/**\n * A registered `describe()` group — single-level, organizational only. See\n * {@link describe}.\n */\nexport type CheckGroup = {\n /** Stable, unique group id (kebab-case). Grouping key + React key. */\n id: string;\n /** Human-readable label shown in the dashboard. Defaults to the id. */\n name: string;\n};\n\n/** Signature of the `describe` registration primitive. */\nexport type DescribeRegistration = {\n (id: string, fn: () => void): void;\n (id: string, name: string, fn: () => void): void;\n};\n\ntype RegisteredCheck = { id: string; fn: CheckFn; group_id?: string; group_name?: string };\n\nconst REGISTRY_KEY = Symbol.for(\"@apo-ai/sdk/agent-task/check-registry\");\nconst registryStore = globalThis as typeof globalThis & {\n [key: symbol]: unknown;\n};\nconst registry = (registryStore[REGISTRY_KEY] ??= []) as RegisteredCheck[];\n\n// ── describe() group registry ────────────────────────────────────────────\n// Same Symbol.for globalThis pattern as the check registry so registrations\n// survive module re-imports. `currentGroupId` is the slot describe() pushes\n// while its callback runs; defineCheck reads it to stamp member checks.\nconst GROUP_REGISTRY_KEY = Symbol.for(\"@apo-ai/sdk/agent-task/group-registry\");\nconst groupRegistry = (registryStore[GROUP_REGISTRY_KEY] ??= []) as CheckGroup[];\nlet currentGroupId: string | null = null;\nlet currentGroupName: string | null = null;\n\n/** Register a check. The `fn` receives the assertion surface `t` and the output.\n *\n * Framework-agnostic callers can pass a deliverables type explicitly:\n * ```ts\n * type Deliverables = { result: ReviewResult; stats: Stats };\n * defineCheck<Deliverables>(\"id\", (t, { deliverables }) => { ... });\n * ```\n */\nexport function defineCheck<TDeliverables>(\n id: string,\n fn: CheckFn<TDeliverables>,\n): void;\nexport function defineCheck(id: string, fn: CheckFn): void;\nexport function defineCheck(id: string, fn: CheckFn): void {\n if (registry.some((c) => c.id === id)) {\n throw new Error(`Duplicate check id '${id}'`);\n }\n registry.push({\n id,\n fn,\n ...(currentGroupId ? { group_id: currentGroupId } : {}),\n ...(currentGroupName ? { group_name: currentGroupName } : {}),\n });\n}\n\nexport function resetFlowChecks(): void {\n registry.length = 0;\n groupRegistry.length = 0;\n currentGroupId = null;\n currentGroupName = null;\n}\n\n/**\n * Register a single-level group of checks. Runs `fn` synchronously;\n * any `test()`/`defineCheck()` call inside it is stamped with the group's id\n * and display name, so the dashboard can nest those checks under a collapsible\n * header with a roll-up verdict.\n *\n * Groups are **organizational only** — they do not change execution order,\n * concurrency, or the task verdict. Nesting is prohibited: calling `describe`\n * inside a `describe` callback throws. Use sibling groups under one task\n * instead.\n *\n * The `id` is stable (survives display-name edits); `name` is the human label\n * shown in the dashboard and defaults to `id` when omitted.\n *\n * ```ts\n * const { test, describe } = task(\"bind\", { adapter, deliverables });\n * describe(\"rules\", \"Rules — each comment becomes a rule\", () => {\n * RULE_GOLD.forEach((g) => test(`R-${g.id} — …`, async (t, { deliverables }) => { … }));\n * });\n * ```\n */\nexport function describe(id: string, fn: () => void): void;\nexport function describe(id: string, name: string, fn: () => void): void;\nexport function describe(\n id: string,\n nameOrFn: string | (() => void),\n fn?: () => void,\n): void {\n const name = typeof nameOrFn === \"string\" ? nameOrFn : id;\n const body = typeof nameOrFn === \"string\" ? fn! : nameOrFn;\n if (currentGroupId !== null) {\n throw new Error(\n `describe(\"${id}\") cannot nest inside describe(\"${currentGroupId}\"); groups are single-level only.`,\n );\n }\n if (groupRegistry.some((g) => g.id === id)) {\n throw new Error(`Duplicate describe id '${id}'`);\n }\n groupRegistry.push({ id, name });\n currentGroupId = id;\n currentGroupName = name;\n try {\n body();\n } finally {\n currentGroupId = null;\n currentGroupName = null;\n }\n}\n\n/**\n * Projection-first check runner. Runs registered checks\n * against a {@link TraceView} built from a {@link TraceProjectionSnapshot}.\n *\n * Trace-dependent assertions that need unavailable evidence (e.g. timing,\n * errors) record ``outcome=\"unsupported\"`` (pass=false) instead of vacuously\n * passing. Value assertions (``t.check``) and LLM assertions (``t.judge``)\n * are unaffected by capabilities.\n */\nexport async function runTraceChecks(args: {\n snapshot: TraceProjectionSnapshot;\n deliverables: Record<string, unknown>;\n files?: unknown;\n task?: unknown;\n judgeConfig?: JudgeConfig;\n moduleUrl?: string;\n displayFile?: string;\n}): Promise<EvaluationItemResult[]> {\n const view = new TraceView(args.snapshot);\n\n const locate: LocateFn | undefined =\n args.moduleUrl && args.displayFile\n ? (stack) => parseCheckLocation(stack, args.moduleUrl!, args.displayFile!)\n : undefined;\n\n const results = await Promise.all(\n registry.map(async (check) => {\n const rec = new Recorder(locate);\n const t = createTraceTestContext(view, rec, args.judgeConfig);\n let thrownLocation: CheckLocation | undefined;\n try {\n await check.fn(t, {\n deliverables: args.deliverables,\n files: args.files,\n task: args.task,\n });\n } catch (error) {\n thrownLocation = locate\n ? locate(error instanceof Error ? error.stack ?? \"\" : \"\")\n : undefined;\n rec.record(\"check-error\", false, error instanceof Error ? error.message : String(error), {\n location: thrownLocation,\n });\n }\n\n const failed = rec.all.filter((r) => !r.pass);\n const pass = failed.length === 0;\n const reasoning =\n failed.length > 0\n ? failed.map((r) => r.reasoning || r.id).join(\"; \")\n : rec.all.length > 0\n ? \"passed\"\n : \"no assertions recorded\";\n const location = failed.find((r) => r.location)?.location;\n const judge = rec.all.find((r) => r.judge)?.judge;\n\n return {\n id: check.id,\n pass,\n reasoning,\n evaluator_type: \"code\" as const,\n ...(judge ? { judge } : {}),\n ...(location ? { location } : {}),\n ...(args.displayFile ? { source_file: args.displayFile } : {}),\n ...(rec.all.length > 0\n ? { assertions: rec.all.map((a) => ({ ...a })) }\n : {}),\n ...(check.group_id ? { group_id: check.group_id } : {}),\n ...(check.group_name ? { group_name: check.group_name } : {}),\n // stamp the snapshot source so consumers can detect\n // the deprecated legacy-flow compatibility path (source=\"legacy-flow\").\n ...(args.snapshot.source !== \"canonical\"\n ? { source: args.snapshot.source }\n : {}),\n };\n }),\n );\n\n return results;\n}\n\n/**\n * Loads a user's `checks.ts` (which registers checks via `test(...)`),\n * then runs them against the projection snapshot + deliverables. Mirrors the\n * legacy loader: copy to a temp module path, import, delete.\n */\nexport async function loadAndRunFlowChecks(\n checksPath: string | null,\n args: {\n snapshot: TraceProjectionSnapshot;\n deliverables: Record<string, unknown>;\n files?: unknown;\n task?: unknown;\n judgeConfig?: JudgeConfig;\n },\n brokenDeliverables: Record<string, string> = {},\n): Promise<EvaluationItemResult[]> {\n if (!checksPath) return [];\n\n resetFlowChecks();\n const moduleUrl = await loadChecksModule(checksPath);\n if (moduleUrl === null || registry.length === 0) return [];\n\n return runTraceChecks({\n snapshot: args.snapshot,\n deliverables: proxyBrokenDeliverables(args.deliverables, brokenDeliverables),\n files: args.files,\n task: args.task,\n judgeConfig: args.judgeConfig,\n moduleUrl,\n displayFile: basename(checksPath),\n });\n}\n\nexport async function loadChecksModule(checksPath: string): Promise<string | null> {\n const tempModulePath = `${checksPath}.${Date.now()}-${Math.random()\n .toString(36)\n .slice(2)}.ts`;\n try {\n copyFileSync(checksPath, tempModulePath);\n const moduleUrl = pathToFileURL(tempModulePath).href;\n // eslint-disable-next-line react-doctor/no-dynamic-import-path -- runtime loading of user task checks\n await import(moduleUrl);\n // If the module didn't register any checks, signal that to the caller.\n if (registry.length === 0) return null;\n return moduleUrl;\n } finally {\n if (existsSync(tempModulePath)) unlinkSync(tempModulePath);\n }\n}\n\nexport function proxyBrokenDeliverables(\n deliverables: Record<string, unknown>,\n brokenDeliverables: Record<string, string>,\n): Record<string, unknown> {\n if (Object.keys(brokenDeliverables).length === 0) return deliverables;\n return new Proxy(deliverables, {\n get(target, property, receiver) {\n if (typeof property === \"string\" && property in brokenDeliverables) {\n throw new Error(brokenDeliverables[property]);\n }\n return Reflect.get(target, property, receiver);\n },\n });\n}\n","import type {\n AdapterDefinition,\n CollectedDeliverables,\n DeliverableDefinition,\n TypedAdapterDefinition,\n} from \"../adapter/types.ts\";\nimport {\n defineCheck,\n describe,\n type DescribeRegistration,\n type TestRegistration,\n} from \"../checks/flow-runner.ts\";\nimport type { TaskConfig, TaskDefinition } from \"./types.ts\";\n\nconst TASK_ADAPTER_SYMBOL = Symbol.for(\"agent-task.adapter-definition\");\n\n// ── Task registry (same Symbol.for pattern as the check registry) ─────────\nconst TASK_REGISTRY_KEY = Symbol.for(\"@apo-ai/sdk/agent-task/task-registry\");\nconst taskRegistryStore = globalThis as typeof globalThis & {\n [key: symbol]: unknown;\n};\nconst taskRegistry = (taskRegistryStore[TASK_REGISTRY_KEY] ??= []) as TaskDefinition[];\n\nexport function resetTaskRegistry(): void {\n taskRegistry.length = 0;\n}\n\nexport function getRegisteredTask(): TaskDefinition | undefined {\n return taskRegistry[0];\n}\n\n// ── Backward compat ────────────────────────────────────────────────────────\nexport type DefinedTask<\n TName extends string,\n TDeliverableDefs extends Record<string, DeliverableDefinition>,\n> = TaskDefinition<TName, keyof TDeliverableDefs & string> & {\n readonly [TASK_ADAPTER_SYMBOL]: TypedAdapterDefinition<\n TName,\n TDeliverableDefs\n >;\n};\n\n/** Legacy two-file task definition. New tasks should use {@link task}. */\nexport function defineTask<\n const TName extends string,\n const TDeliverableDefs extends Record<string, DeliverableDefinition>,\n>(\n adapter: TypedAdapterDefinition<TName, TDeliverableDefs>,\n config: TaskConfig<keyof TDeliverableDefs & string>,\n): DefinedTask<TName, TDeliverableDefs> {\n const definedTask = {\n ...config,\n adapter: adapter.name,\n } as DefinedTask<TName, TDeliverableDefs>;\n\n attachAdapter(definedTask, adapter);\n return definedTask;\n}\n\nexport type TaskScope<TDeliverables> = {\n test: TestRegistration<TDeliverables>;\n /**\n * Register a single-level group of checks. See\n * {@link describe} in `checks/flow-runner.ts`. Returned from `task()` so the\n * `test` inside the callback stays task-scoped (typed deliverables).\n */\n describe: DescribeRegistration;\n};\n\n/**\n * Register a task + its checks in ONE file. The `name` is the task id;\n * `config` includes the adapter, deliverables, and other metadata. Checks\n * are registered through the returned, adapter-typed `test` function.\n *\n * ```ts\n * const { test } = task(\"code-review\", {\n * adapter: realAgentAdapter,\n * deliverables: [\"result\", \"tool_log\", \"stats\"],\n * maxTurns: 2,\n * });\n *\n * test(\"reviewed-methodically\", (t, { deliverables }) => {\n * t.check(deliverables.result, includes(\"finding\"));\n * });\n *\n * // A task that needs dev-machine resources (cloud creds, VPC, stage) can\n * // declare execution: \"local\" so `apo task run` runs it on the caller's\n * // machine while still recording a backend run row.\n * task(\"bind-e2e\", {\n * adapter: bindAdapter,\n * deliverables: [\"summary\"],\n * execution: \"local\",\n * });\n * ```\n */\nexport function task<\n const TTaskId extends string,\n const TAdapterName extends string,\n const TDeliverableDefs extends Record<string, DeliverableDefinition>,\n TCollected extends CollectedDeliverables,\n const TSelected extends readonly (\n DeliverableKey<TCollected> & keyof TDeliverableDefs\n )[],\n>(\n name: TTaskId,\n config: Omit<\n TaskConfig<TSelected[number] & string>,\n \"id\" | \"checks\" | \"deliverables\"\n > & {\n adapter: TypedAdapterDefinition<\n TAdapterName,\n TDeliverableDefs,\n TCollected\n >;\n deliverables: TSelected;\n },\n): TaskScope<SelectedDeliverables<TCollected, TSelected>> {\n const adapter = config.adapter;\n const {\n adapter: _adapter,\n deliverables,\n ...rest\n } = config;\n const definedTask = {\n ...rest,\n id: name,\n adapter: adapter.name,\n deliverables: [...deliverables],\n } satisfies TaskDefinition;\n\n attachAdapter(definedTask, adapter);\n\n taskRegistry.push(definedTask);\n return {\n test: defineCheck as TestRegistration<\n SelectedDeliverables<TCollected, TSelected>\n >,\n describe: describe as DescribeRegistration,\n };\n}\n\nexport function getTaskAdapterDefinition(\n task: object,\n): AdapterDefinition | null {\n return (task as { [TASK_ADAPTER_SYMBOL]?: AdapterDefinition })[\n TASK_ADAPTER_SYMBOL\n ] ?? null;\n}\n\nfunction attachAdapter(taskDefinition: object, adapter: AdapterDefinition): void {\n Object.defineProperty(taskDefinition, TASK_ADAPTER_SYMBOL, {\n value: adapter,\n enumerable: false,\n configurable: false,\n writable: false,\n });\n}\n\ntype DeliverableKey<TCollected> = TCollected extends unknown\n ? keyof TCollected & string\n : never;\n\ntype DeliverableValue<\n TCollected,\n TKey extends PropertyKey,\n> = TCollected extends unknown\n ? TKey extends keyof TCollected\n ? TCollected[TKey]\n : never\n : never;\n\ntype SelectedDeliverables<\n TCollected,\n TSelected extends readonly PropertyKey[],\n> = {\n [TKey in TSelected[number]]-?: Exclude<\n DeliverableValue<TCollected, TKey>,\n null | undefined\n >;\n};\n","import { copyFileSync, readdirSync, statSync, existsSync, unlinkSync } from \"fs\";\nimport { join, resolve, basename } from \"path\";\nimport { pathToFileURL } from \"url\";\nimport type { AdapterDefinition } from \"../adapter/types.ts\";\nimport { getTaskAdapterDefinition, getRegisteredTask, resetTaskRegistry } from \"./defineTask.ts\";\nimport { resetFlowChecks } from \"../checks/flow-runner.ts\";\nimport { resetTaskTurn } from \"../turn.ts\";\nimport type { TaskDefinition, FileEntry } from \"./types.ts\";\n\nexport type LoadedTask = {\n task: TaskDefinition;\n adapter: AdapterDefinition;\n taskDir: string;\n files: FileEntry[];\n /** Legacy external checks module, absent for single-file tasks. */\n checksPath: string | null;\n /** True when task(), test(), and turn() were registered by the eval file. */\n inlineChecks: boolean;\n /** The temp-module URL the task was imported from (used for location pinning). */\n moduleUrl: string;\n /** The original eval filename (e.g. \"code-review.eval.ts\") — used as source_file on check results. */\n evalFileName: string;\n};\n\nexport async function loadTask(taskDir: string): Promise<LoadedTask> {\n const absoluteDir = resolve(taskDir);\n const taskFilePath = findEvalFile(absoluteDir);\n\n if (!taskFilePath) {\n throw new Error(`No .eval.ts file found in: ${absoluteDir}`);\n }\n\n const { task, adapter, inlineChecks, moduleUrl } =\n await loadTaskDefinition(taskFilePath);\n validateTaskDefinition(task, absoluteDir);\n\n const files = loadFilesDirectory(absoluteDir);\n const checksPath = resolveChecksPath(task, absoluteDir);\n\n return {\n task,\n adapter,\n taskDir: absoluteDir,\n files,\n checksPath,\n inlineChecks,\n moduleUrl,\n evalFileName: basename(taskFilePath),\n };\n}\n\n/**\n * Import the task file as a temp module. The side-effect of importing\n * registers the task (via `task()`), all checks (via `check()`/`test()`),\n * and any turn override (via `turn()`) — all from ONE file.\n */\nasync function loadTaskDefinition(\n taskFilePath: string,\n): Promise<{\n task: TaskDefinition;\n adapter: AdapterDefinition;\n inlineChecks: boolean;\n moduleUrl: string;\n}> {\n const tempModulePath = `${taskFilePath}.${Date.now()}-${Math.random()\n .toString(36)\n .slice(2)}.ts`;\n\n try {\n copyFileSync(taskFilePath, tempModulePath);\n const moduleUrl = pathToFileURL(tempModulePath).href;\n\n // Clear all registries so this import starts clean.\n resetTaskRegistry();\n resetFlowChecks();\n resetTaskTurn();\n\n // eslint-disable-next-line react-doctor/no-dynamic-import-path -- runtime loading of user task file\n const loaded = (await import(moduleUrl)) as { default?: TaskDefinition };\n\n const registeredTask = getRegisteredTask();\n const task = registeredTask ?? loaded.default;\n if (!task || typeof task !== \"object\") {\n throw new Error(\n \"No task definition found. The .eval.ts file must call task(name, { adapter, deliverables, ... }) at module top level. \" +\n \"If it does, the CLI and the .eval.ts may be loading different @apo-ai/sdk instances \" +\n \"(check for a stale packages/sdk/dist build or a version mismatch between the CLI and node_modules).\",\n );\n }\n const adapter = getTaskAdapterDefinition(task);\n if (!adapter) {\n throw new Error(\n registeredTask\n ? \"task() config must include an adapter\"\n : \"Task module must call task(name, { adapter, ... }) — the config is missing an adapter.\",\n );\n }\n return {\n task,\n adapter,\n inlineChecks: registeredTask !== undefined,\n moduleUrl,\n };\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n throw new Error(`Failed to load task definition: ${taskFilePath} (${message})`);\n } finally {\n if (existsSync(tempModulePath)) {\n unlinkSync(tempModulePath);\n }\n }\n}\n\nfunction validateTaskDefinition(\n task: TaskDefinition,\n taskDir: string,\n): void {\n if (!task.id || typeof task.id !== \"string\") {\n throw new Error(`Task must have a string 'id': ${taskDir}`);\n }\n\n if (!task.adapter || typeof task.adapter !== \"string\") {\n throw new Error(`Task must have a derived string 'adapter': ${taskDir}`);\n }\n\n if (!Array.isArray(task.deliverables)) {\n throw new Error(`Task must have a 'deliverables' array: ${taskDir}`);\n }\n}\n\nfunction loadFilesDirectory(taskDir: string): FileEntry[] {\n const filesDir = join(taskDir, \"files\");\n if (!existsSync(filesDir) || !statSync(filesDir).isDirectory()) {\n return [];\n }\n\n return walkDirectory(filesDir, filesDir);\n}\n\nfunction walkDirectory(dir: string, root: string): FileEntry[] {\n const entries: FileEntry[] = [];\n\n for (const name of readdirSync(dir)) {\n const fullPath = join(dir, name);\n const stat = statSync(fullPath);\n\n if (stat.isDirectory()) {\n entries.push(...walkDirectory(fullPath, root));\n } else {\n entries.push({\n relativePath: fullPath.slice(root.length + 1),\n absolutePath: fullPath,\n });\n }\n }\n\n return entries;\n}\n\nfunction resolveChecksPath(\n task: TaskDefinition,\n taskDir: string,\n): string | null {\n if (task.checks === false) {\n return null;\n }\n\n if (typeof task.checks === \"string\") {\n const customPath = resolve(taskDir, task.checks);\n if (!existsSync(customPath)) {\n throw new Error(`Custom checks file not found: ${customPath}`);\n }\n return customPath;\n }\n\n const conventionPath = join(taskDir, \"checks.ts\");\n return existsSync(conventionPath) ? conventionPath : null;\n}\n\n/** Find the first `*.eval.ts` file in a directory (the task definition). */\nfunction findEvalFile(dir: string): string | null {\n try {\n const files = readdirSync(dir);\n const evalFile = files.find((f) => f.endsWith(\".eval.ts\"));\n return evalFile ? join(dir, evalFile) : null;\n } catch {\n return null;\n }\n}\n","import type { TaskFiles } from \"./task/TaskFiles.ts\";\n\nexport type TurnRecord = {\n turnNumber: number;\n input: unknown;\n output: unknown;\n};\n\nexport type TurnContext = {\n files: TaskFiles;\n transcript: TurnRecord[];\n};\n\nexport type TurnFn<TUserTurn = unknown> = (\n ctx: TurnContext,\n) => Promise<TUserTurn | null> | TUserTurn | null;\n\nconst TURN_KEY = Symbol.for(\"@apo-ai/sdk/agent-task/task-turn\");\n\nexport function turn<TUserTurn>(fn: TurnFn<TUserTurn>): void {\n (globalThis as Record<symbol, unknown>)[TURN_KEY] = fn;\n}\n\nexport function getTaskTurn(): TurnFn | undefined {\n return (globalThis as Record<symbol, unknown>)[TURN_KEY] as TurnFn | undefined;\n}\n\nexport function resetTaskTurn(): void {\n delete (globalThis as Record<symbol, unknown>)[TURN_KEY];\n}\n\nexport function resolveTurn(\n adapterTurn: TurnFn | undefined,\n taskTurn: TurnFn | undefined,\n): TurnFn {\n const resolved = taskTurn ?? adapterTurn;\n if (!resolved) {\n throw new Error(\n \"No turn behavior defined. Add a turn() call to your task file or a turn field to your adapter.\",\n );\n }\n return resolved;\n}\n","import { readFile } from \"fs/promises\";\nimport type { FileEntry } from \"./types.ts\";\n\nexport class TaskFiles {\n private entries: FileEntry[];\n\n constructor(entries: FileEntry[]) {\n this.entries = entries;\n }\n\n async read(relativePath: string): Promise<string> {\n const entry = this.find(relativePath);\n if (!entry) {\n throw new Error(`File not found: ${relativePath}`);\n }\n return readFile(entry.absolutePath, \"utf-8\");\n }\n\n async readBuffer(relativePath: string): Promise<Buffer> {\n const entry = this.find(relativePath);\n if (!entry) {\n throw new Error(`File not found: ${relativePath}`);\n }\n return readFile(entry.absolutePath);\n }\n\n find(relativePath: string): FileEntry | undefined {\n return this.entries.find((entry) => entry.relativePath === relativePath);\n }\n\n list(): FileEntry[] {\n return [...this.entries];\n }\n\n has(relativePath: string): boolean {\n return this.entries.some((entry) => entry.relativePath === relativePath);\n }\n}\n","import type {\n CollectedDeliverables,\n DeliverableDefinition,\n TypedAdapterDefinition,\n} from \"./types.ts\";\n\nexport function defineAdapter<\n const TName extends string,\n const TDeliverables extends Record<string, DeliverableDefinition>,\n TCollected extends CollectedDeliverables,\n>(\n adapter: TypedAdapterDefinition<TName, TDeliverables, TCollected>,\n): TypedAdapterDefinition<TName, TDeliverables, TCollected> {\n return adapter;\n}\n","/**\n * file Artifact declaration helper.\n *\n * A ``FileArtifact`` is a path descriptor that identifies a regular local\n * file at persistence time. The SDK streams it to the backend (two-phase\n * upload) rather than buffering bytes in the result body.\n *\n * Rules:\n * - ``path`` must identify a regular local file at persistence time;\n * - directories, sockets, devices, and symbolic links are rejected;\n * - the default display filename is ``basename(path)``;\n * - the default media type is ``application/octet-stream``;\n * - ``t.judge(fileArtifact(...))`` is rejected: a path descriptor is not file\n * content. Authors must explicitly read/parse the content to judge it.\n */\n\nimport { basename } from \"node:path\";\nimport { lstatSync, statSync } from \"node:fs\";\n\nexport interface FileArtifact {\n readonly kind: \"apo.file-artifact\";\n readonly path: string;\n readonly mediaType: string;\n readonly displayFilename: string;\n}\n\nexport interface FileArtifactOptions {\n readonly mediaType?: string;\n readonly displayFilename?: string;\n}\n\nconst DEFAULT_MEDIA_TYPE = \"application/octet-stream\";\n\n/**\n * Declare a file Deliverable from a local file path.\n *\n * Validates eagerly that ``path`` points to an existing regular file (not a\n * directory, symlink, socket, or device) so authors get an actionable error\n * before the backend creates an upload intent.\n */\nexport function fileArtifact(\n path: string,\n options: FileArtifactOptions = {},\n): FileArtifact {\n if (!path) {\n throw new Error(\"fileArtifact: path must not be empty\");\n }\n // lstat does not follow symlinks; a symlink must be rejected even when its\n // target is a regular file.\n let stat;\n try {\n const lstat = lstatSync(path);\n if (lstat.isSymbolicLink()) {\n throw new Error(\"fileArtifact: path is a symbolic link, not a regular file\");\n }\n stat = statSync(path);\n } catch (error) {\n if (error instanceof Error && error.message.startsWith(\"fileArtifact:\")) throw error;\n throw new Error(\"fileArtifact: path is not a regular file or is inaccessible\");\n }\n if (!stat.isFile()) {\n throw new Error(\"fileArtifact: path is not a regular file\");\n }\n\n const displayFilename = options.displayFilename ?? basename(path);\n if (!displayFilename) {\n throw new Error(\"fileArtifact: displayFilename must not be empty\");\n }\n\n return Object.freeze({\n kind: \"apo.file-artifact\",\n path,\n mediaType: options.mediaType ?? DEFAULT_MEDIA_TYPE,\n displayFilename,\n });\n}\n\nexport function isFileArtifact(value: unknown): value is FileArtifact {\n return (\n typeof value === \"object\" &&\n value !== null &&\n (value as { kind?: unknown }).kind === \"apo.file-artifact\" &&\n typeof (value as { path?: unknown }).path === \"string\"\n );\n}\n\n// ENOENT shows up as a thrown error; narrow it without depending on the node\n// error code constant at module scope.\nfunction existsLike(error: unknown): boolean {\n if (!(error instanceof Error)) return false;\n const code = (error as NodeJS.ErrnoException).code;\n return code === \"ENOENT\";\n}\n","/**\n * file Artifact uploader.\n *\n * After checks run against the original in-memory Deliverables, this module\n * partitions JSON values from file Artifacts, streams each file to the\n * backend's two-phase upload endpoint, and returns only JSON Deliverables for\n * the final result body. File bytes never travel through the result request\n * or subprocess stdout.\n *\n * Storage failure does not flip a failed test into a pass: it raises, so the\n * caller records the run as errored.\n */\n\nimport { createHash } from \"node:crypto\";\nimport { createReadStream } from \"node:fs\";\nimport { Readable } from \"node:stream\";\n\nimport { isFileArtifact, type FileArtifact } from \"./artifact.ts\";\n\nexport interface DeliverableSummary {\n id: string;\n name: string;\n kind: \"json\" | \"artifact\";\n status: \"pending\" | \"ready\" | \"failed\";\n media_type: string;\n display_filename: string | null;\n size_bytes: number;\n sha256: string;\n download_url: string | null;\n}\n\nexport interface ArtifactUploadIntent {\n id: string;\n upload_url: string;\n}\n\nexport interface ArtifactUploadConfig {\n /** The Task Run id owning these Deliverables. */\n taskRunId: string;\n /** Bearer token (service token or API key) authorizing the upload. */\n authToken: string;\n /** Backend base URL, e.g. ``http://127.0.0.1:8000``. */\n baseUrl: string;\n /** Injectable fetch (tests pass a stub); defaults to global fetch. */\n fetch?: typeof fetch;\n}\n\nexport interface PreparedTaskResult {\n /** JSON-only deliverables safe to send in the final result body. */\n jsonDeliverables: Record<string, unknown>;\n /** Successfully uploaded file Artifacts (summaries only, no bodies). */\n artifactUploads: DeliverableSummary[];\n}\n\nconst DEFAULT_FETCH: typeof fetch | undefined =\n typeof fetch === \"function\" ? fetch : undefined;\n\n/**\n * Partition and persist Deliverables after checks complete.\n *\n * - file Artifacts are streamed to the backend (hash, create intent, PUT);\n * - JSON values are returned untouched for the result body;\n * - the local path of any Artifact is never embedded in the result.\n */\nexport async function persistFileArtifacts(\n deliverables: Record<string, unknown>,\n config: ArtifactUploadConfig,\n): Promise<PreparedTaskResult> {\n const jsonDeliverables: Record<string, unknown> = {};\n const artifactUploads: DeliverableSummary[] = [];\n\n // Validate upload context only when at least one FileArtifact exists.\n // JSON-only recorded runs perform no Artifact HTTP request.\n const artifactNames = Object.entries(deliverables)\n .filter(([, v]) => isFileArtifact(v))\n .map(([name]) => name);\n if (artifactNames.length > 0) {\n validateUploadConfig(config, artifactNames[0]);\n }\n\n for (const [name, value] of Object.entries(deliverables)) {\n if (isFileArtifact(value)) {\n const summary = await uploadOne(name, value, config);\n artifactUploads.push(summary);\n } else {\n jsonDeliverables[name] = value;\n }\n }\n\n return { jsonDeliverables, artifactUploads };\n}\n\n/**\n * Fail early with a safe, path-free message before any file hashing or HTTP\n * request. The error names the first Artifact Deliverable so the author knows\n * which one is affected, but never includes the executor-local file path.\n */\nfunction validateUploadConfig(config: ArtifactUploadConfig, firstName: string): void {\n if (!config.taskRunId) {\n throw new Error(\n `Artifact '${firstName}' cannot be uploaded: missing task run ID`,\n );\n }\n if (!config.authToken) {\n throw new Error(\n `Artifact '${firstName}' cannot be uploaded: missing auth token`,\n );\n }\n if (!config.baseUrl) {\n throw new Error(\n `Artifact '${firstName}' cannot be uploaded: missing backend base URL`,\n );\n }\n}\n\nasync function uploadOne(\n name: string,\n artifact: FileArtifact,\n config: ArtifactUploadConfig,\n): Promise<DeliverableSummary> {\n try {\n const { size, sha256 } = await hashFile(artifact.path);\n const intent = await createIntent(name, artifact, size, sha256, config);\n\n const body = Readable.toWeb(createReadStream(artifact.path)) as ReadableStream<Uint8Array>;\n const summary = await putBytes(intent.upload_url, body, size, config);\n return summary;\n } catch (err) {\n // Sanitize file I/O errors (ENOENT, EACCES, etc.) which embed the full\n // local path in their message. HTTP errors carry server responses, not\n // paths, and propagate unchanged.\n if (err instanceof Error && (err as NodeJS.ErrnoException).code) {\n const code = (err as NodeJS.ErrnoException).code ?? \"UNKNOWN\";\n throw new Error(`Artifact '${name}' file read failed: ${code}`);\n }\n throw err;\n }\n}\n\nasync function hashFile(\n path: string,\n): Promise<{ size: number; sha256: string }> {\n return new Promise((resolve, reject) => {\n const hash = createHash(\"sha256\");\n let size = 0;\n const stream = createReadStream(path);\n stream.on(\"data\", (chunk: string | Buffer) => {\n hash.update(chunk);\n size += chunk.length;\n });\n stream.on(\"error\", reject);\n stream.on(\"end\", () => resolve({ size, sha256: hash.digest(\"hex\") }));\n });\n}\n\nasync function createIntent(\n name: string,\n artifact: FileArtifact,\n sizeBytes: number,\n sha256: string,\n config: ArtifactUploadConfig,\n): Promise<ArtifactUploadIntent> {\n const url = `${config.baseUrl}/v1/agent-task-runs/${config.taskRunId}/artifact-uploads`;\n const response = await doFetch(config, url, {\n method: \"POST\",\n headers: {\n Authorization: `Bearer ${config.authToken}`,\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify({\n name,\n display_filename: artifact.displayFilename,\n media_type: artifact.mediaType,\n size_bytes: sizeBytes,\n sha256,\n }),\n });\n if (response.status === 201) {\n const body = (await response.json()) as ArtifactUploadIntent;\n return body;\n }\n const detail = await safeDetail(response);\n throw new Error(\n `artifact upload intent for '${name}' failed (${response.status}): ${detail}`,\n );\n}\n\nasync function putBytes(\n uploadUrl: string,\n body: ReadableStream<Uint8Array>,\n sizeBytes: number,\n config: ArtifactUploadConfig,\n): Promise<DeliverableSummary> {\n const url = uploadUrl.startsWith(\"http\")\n ? uploadUrl\n : `${config.baseUrl}${uploadUrl}`;\n const response = await doFetch(config, url, {\n method: \"PUT\",\n headers: {\n Authorization: `Bearer ${config.authToken}`,\n \"Content-Type\": \"application/octet-stream\",\n \"Content-Length\": String(sizeBytes),\n },\n body,\n duplex: \"half\",\n } as RequestInit);\n if (response.status === 200) {\n return (await response.json()) as DeliverableSummary;\n }\n const detail = await safeDetail(response);\n throw new Error(\n `artifact upload of ${sizeBytes} bytes failed (${response.status}): ${detail}`,\n );\n}\n\nasync function doFetch(\n config: ArtifactUploadConfig,\n input: string,\n init: RequestInit,\n): Promise<Response> {\n const fetchImpl = config.fetch ?? DEFAULT_FETCH;\n if (!fetchImpl) {\n throw new Error(\"persistFileArtifacts: fetch is not available in this environment\");\n }\n return fetchImpl(input, init);\n}\n\nasync function safeDetail(response: Response): Promise<string> {\n try {\n const text = await response.text();\n return text.slice(0, 500);\n } catch {\n return \"<no body>\";\n }\n}\n","/**\n * FlowView — typed, derived access over a {@link Flow}. This is the read model\n * the assertion surface (`t`) queries. It hides all the filtering/derivation\n * so assertions stay one-liners.\n */\n\nimport type { Flow, FlowEvent } from \"./types.ts\";\n\ntype ToolCall = Extract<FlowEvent, { kind: \"tool_call\" }>;\ntype SkillLoad = Extract<FlowEvent, { kind: \"skill_load\" }>;\ntype SubagentCall = Extract<FlowEvent, { kind: \"subagent_call\" }>;\ntype Message = Extract<FlowEvent, { kind: \"message\" }>;\n\nexport class FlowView {\n readonly events: readonly FlowEvent[];\n readonly startedAt?: number;\n readonly endedAt?: number;\n\n constructor(flow: Flow) {\n this.events = flow.events;\n this.startedAt = flow.startedAt;\n this.endedAt = flow.endedAt;\n }\n\n get messages(): Message[] {\n return this.events.filter((e): e is Message => e.kind === \"message\");\n }\n\n get toolCalls(): ToolCall[] {\n return this.events.filter((e): e is ToolCall => e.kind === \"tool_call\");\n }\n\n get skillLoads(): SkillLoad[] {\n return this.events.filter((e): e is SkillLoad => e.kind === \"skill_load\");\n }\n\n get subagentCalls(): SubagentCall[] {\n return this.events.filter(\n (e): e is SubagentCall => e.kind === \"subagent_call\",\n );\n }\n\n get toolNamesInOrder(): string[] {\n return this.toolCalls.map((c) => c.name);\n }\n\n /** Last assistant message text — the agent's \"reply\". */\n get reply(): string {\n for (let i = this.messages.length - 1; i >= 0; i--) {\n if (this.messages[i]!.role === \"assistant\") return this.messages[i]!.text;\n }\n return \"\";\n }\n\n /** Number of completed assistant turns. */\n get turnCount(): number {\n return this.messages.filter((m) => m.role === \"assistant\").length;\n }\n\n /** Tool or subagent calls that reported an error. */\n get failedActions(): number {\n return this.events.filter(\n (e) =>\n (e.kind === \"tool_call\" || e.kind === \"subagent_call\") &&\n e.status === \"error\",\n ).length;\n }\n\n get durationMs(): number {\n if (this.startedAt != null && this.endedAt != null) {\n return Math.max(0, this.endedAt - this.startedAt);\n }\n // Fallback: sum recorded latencies when no wall-clock span is available.\n return this.events.reduce((sum, e) => {\n if (\"latencyMs\" in e && typeof e.latencyMs === \"number\") {\n return sum + e.latencyMs;\n }\n return sum;\n }, 0);\n }\n}\n","/**\n * Cross-framework Flow normalizers — the \"plugs\" that let agents NOT built on\n * apo's adapter produce a {@link Flow} from their own output, so the same\n * `t.*` checks work for everyone.\n *\n * Each normalizer is `(source) => Flow`. Add new ones by following the shape.\n *\n * @deprecated These are **compatibility recording adapters**,\n * not the primary testing architecture. The canonical path is now the Trace\n * Projection snapshot (`TraceProjectionSnapshot` → `TraceView` →\n * `runTraceChecks`). These normalizers remain available during the\n * deprecation period; `snapshotFromFlow` bridges their output into the\n * projection contract. New integrations should emit standard OTel spans\n * instead of producing a Flow.\n */\n\nimport type { Flow, FlowEvent } from \"./types.ts\";\n\nfunction safeParse(raw: unknown): unknown {\n if (typeof raw !== \"string\") return raw;\n try {\n return JSON.parse(raw);\n } catch {\n return raw;\n }\n}\n\n// ── OpenAI (chat completions message log) ────────────────────────────────\n\nexport interface OpenAIMessage {\n role?: string;\n content?: string | null;\n tool_calls?: Array<{\n id?: string;\n function?: { name?: string; arguments?: string };\n }>;\n tool_call_id?: string;\n}\n\nexport function fromOpenAIMessages(messages: OpenAIMessage[]): Flow {\n const events: FlowEvent[] = [];\n // First pass: tool results keyed by tool_call_id.\n const results = new Map<string, unknown>();\n for (const m of messages) {\n if (m.role === \"tool\" && m.tool_call_id) {\n results.set(m.tool_call_id, m.content);\n }\n }\n for (const m of messages) {\n if (m.role === \"user\") {\n events.push({ kind: \"message\", role: \"user\", text: m.content ?? \"\" });\n } else if (m.role === \"assistant\") {\n events.push({ kind: \"message\", role: \"assistant\", text: m.content ?? \"\" });\n for (const tc of m.tool_calls ?? []) {\n events.push({\n kind: \"tool_call\",\n name: tc.function?.name ?? \"unknown\",\n input: safeParse(tc.function?.arguments),\n output: tc.id ? results.get(tc.id) : undefined,\n });\n }\n }\n }\n return { events };\n}\n\n// ── Anthropic (messages API content blocks) ──────────────────────────────\n\nexport interface AnthropicMessage {\n role?: string;\n content?: Array<\n | { type: \"text\"; text: string }\n | { type: \"tool_use\"; id: string; name: string; input?: unknown }\n | { type: \"tool_result\"; tool_use_id: string; content?: unknown }\n >;\n}\n\nexport function fromAnthropicMessages(messages: AnthropicMessage[]): Flow {\n const events: FlowEvent[] = [];\n const results = new Map<string, unknown>();\n for (const m of messages) {\n for (const block of m.content ?? []) {\n if (block.type === \"tool_result\") {\n results.set(block.tool_use_id, block.content);\n }\n }\n }\n for (const m of messages) {\n const role = m.role === \"user\" ? \"user\" : \"assistant\";\n for (const block of m.content ?? []) {\n if (block.type === \"text\") {\n events.push({ kind: \"message\", role, text: block.text });\n } else if (block.type === \"tool_use\") {\n events.push({\n kind: \"tool_call\",\n name: block.name,\n input: block.input,\n output: results.get(block.id),\n });\n }\n }\n }\n return { events };\n}\n\n// ── Vercel AI SDK (generateText / streamText result) ─────────────────────\n\nexport interface AISDKResult {\n steps?: Array<{\n text?: string;\n toolCalls?: Array<{ toolName: string; input?: unknown }>;\n toolResults?: Array<{ toolName: string; output?: unknown }>;\n }>;\n}\n\nexport function fromAISDK(result: AISDKResult): Flow {\n const events: FlowEvent[] = [];\n for (const step of result.steps ?? []) {\n if (step.text) {\n events.push({ kind: \"message\", role: \"assistant\", text: step.text });\n }\n const outputs = step.toolResults ?? [];\n const toolCalls = step.toolCalls ?? [];\n toolCalls.forEach((tc, i) => {\n events.push({\n kind: \"tool_call\",\n name: tc.toolName,\n input: tc.input,\n output: outputs[i]?.output,\n });\n });\n }\n return { events };\n}\n","import type { AgentTaskRunConfiguration } from \"../adapter/types.ts\";\n\n/**\n * validate and normalize an adapter-reported Run Configuration.\n *\n * Mirrors the backend validation contract so the SDK and the shared backend\n * finalizer enforce identical rules. Returns `undefined` when no configuration\n * was reported. An invalid configuration (blank model, oversized value, or a\n * NUL/control character) throws — it is an adapter contract error that must\n * fail the Task Run before the first Task Turn.\n *\n * Rules:\n * - trim leading/trailing whitespace from `model` and `effort`;\n * - `model` is required (1–255 UTF-8 bytes);\n * - `effort` is optional; when present it is 1–64 UTF-8 bytes (an\n * empty/whitespace effort normalizes to `undefined` = not reported);\n * - reject NUL and ASCII control characters (checked before trimming, since\n * some runtimes strip C0 controls as whitespace);\n * - preserve casing and punctuation.\n *\n * Error messages name the field only — never echo secret-bearing source values.\n */\nexport function normalizeRunConfiguration(\n raw: AgentTaskRunConfiguration | undefined,\n): AgentTaskRunConfiguration | undefined {\n if (!raw) return undefined;\n const model = normalizeScalar(raw.model, \"run_configuration.model\", MAX_MODEL_BYTES, true);\n const effort = normalizeScalar(\n raw.effort,\n \"run_configuration.effort\",\n MAX_EFFORT_BYTES,\n false,\n );\n return effort === undefined ? { model } : { model, effort };\n}\n\nconst MAX_MODEL_BYTES = 255;\nconst MAX_EFFORT_BYTES = 64;\n// NUL and ASCII control characters (C0 controls plus DEL).\n// oxlint-disable-next-line no-control-regex -- intentional: these are the characters we reject.\nconst CONTROL_CHARS = /[\\x00-\\x1f\\x7f]/;\n\nconst utf8Encoder = new TextEncoder();\n\nfunction utf8ByteLength(value: string): number {\n return utf8Encoder.encode(value).length;\n}\n\nfunction normalizeScalar(\n value: string | undefined,\n field: string,\n maxBytes: number,\n required: true,\n): string;\nfunction normalizeScalar(\n value: string | undefined,\n field: string,\n maxBytes: number,\n required: false,\n): string | undefined;\nfunction normalizeScalar(\n value: string | undefined,\n field: string,\n maxBytes: number,\n required: boolean,\n): string | undefined {\n if (value === undefined) {\n if (required) throw new Error(`${field} is required`);\n return undefined;\n }\n if (CONTROL_CHARS.test(value)) {\n throw new Error(`${field} must not contain control characters`);\n }\n const trimmed = value.trim();\n if (trimmed === \"\") {\n if (required) throw new Error(`${field} is required and must be non-empty`);\n return undefined;\n }\n if (utf8ByteLength(trimmed) > maxBytes) {\n throw new Error(`${field} must be at most ${maxBytes} UTF-8 bytes`);\n }\n return trimmed;\n}\n","import type {\n CollectedDeliverables,\n DeliverableDefinition,\n ValidatableSchemaLike,\n} from \"../adapter/types.ts\";\nimport type { TaskDefinition } from \"../task/types.ts\";\nimport type { DeliverableValidationResult } from \"./types.ts\";\n\nfunction isZodSchema(value: unknown): value is ValidatableSchemaLike {\n return (\n typeof value === \"object\" &&\n value !== null &&\n \"safeParse\" in value &&\n typeof (value as Record<string, unknown>).safeParse === \"function\"\n );\n}\n\nexport function validateDeliverables(\n task: TaskDefinition,\n collected: CollectedDeliverables,\n deliverableDefs?: Record<string, DeliverableDefinition>,\n): DeliverableValidationResult {\n const results: DeliverableValidationResult[\"results\"] = [];\n const brokenDeliverables: Record<string, string> = {};\n\n for (const deliverableName of task.deliverables) {\n const value = collected[deliverableName];\n\n if (value === undefined || value === null) {\n const reason = `Deliverable '${deliverableName}' is missing`;\n results.push({\n id: `deliverable:${deliverableName}`,\n pass: false,\n reasoning: reason,\n });\n brokenDeliverables[deliverableName] = reason;\n continue;\n }\n\n const schema = resolveDeliverableSchema(\n deliverableDefs?.[deliverableName],\n );\n if (schema && isZodSchema(schema)) {\n const result = schema.safeParse(value);\n if (!result.success) {\n const reason = `Deliverable '${deliverableName}' failed schema validation: ${result.error?.message ?? \"Unknown error\"}`;\n results.push({\n id: `deliverable:${deliverableName}`,\n pass: false,\n reasoning: reason,\n });\n brokenDeliverables[deliverableName] = reason;\n }\n }\n }\n\n return { results, brokenDeliverables };\n}\n\nfunction resolveDeliverableSchema(\n definition: DeliverableDefinition | undefined,\n): ValidatableSchemaLike | undefined {\n if (!definition) {\n return undefined;\n }\n\n if (isZodSchema(definition)) {\n return definition;\n }\n\n if (\n typeof definition === \"object\" &&\n definition !== null &&\n \"schema\" in definition &&\n isZodSchema(definition.schema)\n ) {\n return definition.schema;\n }\n\n return undefined;\n}\n","/**\n * Projection tee — wraps a real {@link AgentTaskTraceContext} and records the\n * span lifecycle into a {@link TraceProjectionSnapshot}.\n *\n * This is the FlowTee replacement. FlowTee recorded legacy `FlowEvent`s which\n * `snapshotFromFlow` converted to a snapshot. This tee records\n * `TraceProjectionObservation`s directly — same source-of-truth, no Flow\n * intermediate. It delegates every call to the wrapped context (the real OTel\n * client), so real OTel spans still export via OTLP. The snapshot is only the\n * local, in-process assertion surface.\n *\n * The recording logic mirrors `local-recorder.ts` but as a delegating wrapper\n * rather than a standalone context.\n */\n\nimport type { AgentTaskTraceContext } from \"../tracing.ts\";\nimport type {\n CreateSpanParams,\n EndSpanParams,\n TraceEventOptions,\n CreateScoreParams,\n} from \"../../types.ts\";\nimport type {\n ObservationStatus,\n TraceProjectionCapabilities,\n TraceProjectionObservation,\n TraceProjectionSnapshot,\n} from \"./types.ts\";\n\nfunction monotonicNowMs(): number {\n if (typeof performance !== \"undefined\" && typeof performance.now === \"function\") {\n return performance.now();\n }\n return Date.now();\n}\n\nfunction round3(n: number): number {\n return Math.round(n * 1000) / 1000;\n}\n\nfunction observationTypeFor(\n t: CreateSpanParams[\"observation_type\"],\n): TraceProjectionObservation[\"type\"] {\n switch (t) {\n case \"GENERATION\": return \"GENERATION\";\n case \"TOOL\": return \"TOOL\";\n case \"AGENT\": return \"AGENT\";\n case \"CHAIN\": return \"CHAIN\";\n case \"RETRIEVER\": return \"RETRIEVER\";\n case \"EMBEDDING\": return \"EMBEDDING\";\n case \"GUARDRAIL\": return \"GUARDRAIL\";\n default: return \"SPAN\";\n }\n}\n\ninterface PendingObservation {\n spanId: string;\n parentSpanId?: string;\n type: TraceProjectionObservation[\"type\"];\n name: string;\n startedAtIso: string;\n startedAtMs: number;\n model?: string;\n input?: unknown;\n}\n\nfunction extractText(output: unknown): string {\n if (typeof output === \"string\") return output;\n if (output != null && typeof output === \"object\" && \"text\" in output) {\n const text = (output as { text: unknown }).text;\n if (typeof text === \"string\") return text;\n }\n return \"\";\n}\n\nfunction deriveCapabilities(\n observations: readonly TraceProjectionObservation[],\n): TraceProjectionCapabilities {\n const hasType = (t: TraceProjectionObservation[\"type\"]) =>\n observations.some((o) => o.type === t);\n const hasMessages = observations.some(\n (o) => o.type === \"GENERATION\" && o.messages && o.messages.length > 0,\n );\n return {\n messages: hasMessages ? \"available\" : \"unavailable\",\n tools: hasType(\"TOOL\") ? \"available\" : \"unavailable\",\n // Local capture records every span's status, so error evidence is always\n // available — the absence of error observations IS proof of no errors.\n errors: \"available\",\n timing: \"available\",\n skills: hasType(\"SKILL\") ? \"available\" : \"unavailable\",\n subagents: hasType(\"AGENT\") ? \"available\" : \"unavailable\",\n };\n}\n\nexport interface ProjectionTee {\n /** The wrapped trace context — delegate all span calls to this. */\n trace: AgentTaskTraceContext;\n /** Freeze the current observations into an immutable snapshot. */\n getSnapshot(): TraceProjectionSnapshot;\n}\n\n/**\n * Wrap a real {@link AgentTaskTraceContext} so every span/step call is\n * delegated to it (real OTel export) while also recording observations for a\n * local projection snapshot. This replaces FlowTee + snapshotFromFlow.\n */\nexport function createProjectionTee(\n real: AgentTaskTraceContext,\n): ProjectionTee {\n const observations: TraceProjectionObservation[] = [];\n const pending = new Map<string, PendingObservation>();\n // Map tee-issued span ids to the real context's span ids so endSpan can\n // resolve the real span it must close. Without this, createSpan discards\n // real.createSpan's return value and endSpan can never find the real span —\n // the span is never ended, never exported, and its usage is lost.\n const realIdByTeeId = new Map<string, string>();\n let spanCounter = 0;\n\n // Trace-level timing — captured at tee creation (root span start) and read\n // at snapshot time (root span end). Mirrors local-recorder.ts so that\n // TraceView.durationMs has the startedAt/endedAt pair it needs. Without\n // this, deriveCapabilities hard-codes timing:\"available\" but the trace\n // object carries no timestamps, so t.maxDurationMs sees undefined and\n // reports \"timing evidence unavailable\" despite every observation being\n // individually timestamped.\n const rootStartMs = monotonicNowMs();\n const rootStartIso = new Date(rootStartMs).toISOString();\n\n function complete(spanId: string, params: Omit<EndSpanParams, \"id\"> | undefined): void {\n const p = pending.get(spanId);\n if (!p) return;\n pending.delete(spanId);\n const endedAtMs = monotonicNowMs();\n const isError = params?.level === \"ERROR\";\n const status: ObservationStatus = isError ? \"error\" : \"ok\";\n\n const obs: TraceProjectionObservation = {\n spanId: p.spanId,\n type: p.type,\n name: p.name,\n startedAt: p.startedAtIso,\n endedAt: new Date(endedAtMs).toISOString(),\n durationMs: round3(endedAtMs - p.startedAtMs),\n status,\n };\n if (p.parentSpanId) obs.parentSpanId = p.parentSpanId;\n if (p.model) obs.model = p.model;\n if (isError && params?.status_message) obs.errorMessage = params.status_message;\n\n const meta = params?.metadata as Record<string, unknown> | undefined;\n if (p.type === \"TOOL\") {\n obs.toolName = (meta?.tool_name as string | undefined) ?? p.name;\n if (meta?.tool_parameters !== undefined) obs.toolParameters = meta.tool_parameters;\n else if (p.input !== undefined) obs.toolParameters = p.input;\n if (meta?.tool_result !== undefined) obs.toolResult = meta.tool_result;\n else if (params?.output !== undefined) obs.output = params.output;\n } else if (params?.output !== undefined) {\n obs.output = params.output;\n }\n\n if (p.type === \"GENERATION\" && params?.output != null) {\n const text = extractText(params.output);\n if (text !== \"\") {\n obs.messages = [{ role: \"assistant\", content: text }];\n }\n }\n\n observations.push(obs);\n }\n\n function recordStart(opts: {\n step_name?: string | null;\n observation_type?: CreateSpanParams[\"observation_type\"];\n parent_call_id?: string | null;\n model?: string | null;\n input?: unknown;\n }): string {\n spanCounter += 1;\n const spanId = `${real.rootSpanId}-${String(spanCounter).padStart(6, \"0\")}`;\n pending.set(spanId, {\n spanId,\n parentSpanId: opts.parent_call_id ?? real.rootSpanId,\n type: observationTypeFor(opts.observation_type),\n name: opts.step_name ?? \"step\",\n startedAtIso: new Date(monotonicNowMs()).toISOString(),\n startedAtMs: monotonicNowMs(),\n model: opts.model ?? undefined,\n input: opts.input,\n });\n return spanId;\n }\n\n // Delegate every method to `real`, recording observations alongside.\n const trace: AgentTaskTraceContext = {\n runId: real.runId,\n rootSpanId: real.rootSpanId,\n\n async step(opts, fn) {\n // Delegate to the real context so the OTel span is created. Record one\n // observation around the whole step.\n const obsSpanId = recordStart(opts);\n const start = monotonicNowMs();\n try {\n const result = await real.step(opts, fn);\n complete(obsSpanId, {\n latency_ms: round3(monotonicNowMs() - start),\n output: opts.summarize?.(result),\n metadata: opts.metadata,\n });\n return result;\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n complete(obsSpanId, {\n latency_ms: round3(monotonicNowMs() - start),\n status_message: message,\n level: \"ERROR\",\n metadata: { ...opts.metadata, failed: true },\n });\n throw error;\n }\n },\n\n recordEvent(evOptions: TraceEventOptions): string {\n const spanId = recordStart(evOptions);\n complete(spanId, {\n latency_ms: evOptions.latency_ms,\n output: evOptions.output,\n metadata: evOptions.metadata,\n });\n try { real.recordEvent(evOptions); } catch { /* best-effort */ }\n return spanId;\n },\n\n endRoot(endParams) {\n try { real.endRoot(endParams); } catch { /* best-effort */ }\n },\n\n createSpan(spanOptions): string {\n // Generate our OWN unique span id for recording (the wrapped context\n // may return a constant in noop mode). Delegate to real for the OTel\n // export, but return our id so endSpan finds the pending observation.\n const spanId = recordStart(spanOptions);\n\n // Spans originating from the ApoSpanProcessor (which intercepts the AI\n // SDK's own OTel spans) must NOT be re-exported via real.createSpan —\n // the original span is already being exported by the OTLP exporter, so\n // creating a second one here would produce duplicate LoggedCallDB rows.\n const isFromOtelProcessor =\n (spanOptions.metadata as Record<string, unknown> | undefined)?.source === \"otel-processor\";\n\n if (!isFromOtelProcessor) {\n try {\n const realId = real.createSpan(spanOptions);\n // Remember the real id so endSpan can close the real span. Falls back\n // to the tee id when the real context returns nothing (noop mode).\n realIdByTeeId.set(spanId, realId);\n } catch { /* best-effort */ }\n }\n return spanId;\n },\n\n endSpan(spanId, endParams) {\n complete(spanId, endParams);\n const realId = realIdByTeeId.get(spanId) ?? spanId;\n realIdByTeeId.delete(spanId);\n try { real.endSpan(realId, endParams); } catch { /* best-effort */ }\n },\n\n async traceTool(name, params, fn) {\n return real.traceTool(name, params, fn);\n },\n async traceRetriever(query, fn) {\n return real.traceRetriever(query, fn);\n },\n async traceChain(name, fn) {\n return real.traceChain(name, fn);\n },\n async traceAgent(name, fn) {\n return real.traceAgent(name, fn);\n },\n async traceGuardrail(name, fn) {\n return real.traceGuardrail(name, fn);\n },\n async traceEmbedding(model, input, fn) {\n return real.traceEmbedding(model, input, fn);\n },\n async score(params: CreateScoreParams) {\n return real.score(params);\n },\n };\n\n return {\n trace,\n getSnapshot(): TraceProjectionSnapshot {\n const endMs = monotonicNowMs();\n return {\n schemaVersion: 1,\n projectionVersion: 1,\n source: \"local\",\n trace: {\n traceId: real.runId,\n startedAt: rootStartIso,\n endedAt: new Date(endMs).toISOString(),\n durationMs: round3(endMs - rootStartMs),\n complete: true,\n },\n capabilities: deriveCapabilities(observations),\n observations: [...observations],\n };\n },\n };\n}\n","/**\n * Remote trace projection reader.\n *\n * Polls the Task-Run-scoped projection endpoint\n * (`GET /v1/agent-task-runs/{task_run_id}/trace-projection`) with bounded\n * exponential backoff until the projection is ready, then returns the immutable\n * snapshot Phase 2 evaluation reads.\n *\n * This is the canonical capture path for backend-launched required-persistence\n * runs: after the OTel exporter force-flushes, the runner polls its own\n * projection endpoint to read back the durable, projected trace — the same one\n * the dashboard shows.\n */\n\nimport type { TraceProjectionSnapshot } from \"./types.ts\";\n\n/** Configuration for the projection read retry loop. */\nexport interface ProjectionReadOptions {\n /** The backend base URL, e.g. ``\"http://localhost:8000\"``. */\n endpoint: string;\n /** The service token (Authorization: Bearer …). */\n authToken: string;\n /** The task run ID whose projection to read. */\n taskRunId: string;\n /** Maximum total wait time in milliseconds (default: 30000). */\n deadlineMs?: number;\n /** Initial retry interval in milliseconds (default: 500). */\n initialIntervalMs?: number;\n /** Maximum retry interval after backoff (default: 5000). */\n maxIntervalMs?: number;\n}\n\n/** Error thrown when the projection is not ready within the deadline. */\nexport class ProjectionTimeoutError extends Error {\n constructor(taskRunId: string, deadlineMs: number) {\n super(\n `Trace projection for task run ${taskRunId} was not ready within ${deadlineMs}ms`,\n );\n this.name = \"ProjectionTimeoutError\";\n }\n}\n\n/**\n * Read the projection snapshot for a task run, retrying with bounded\n * exponential backoff until it's ready (200) or the deadline expires.\n *\n * Throws {@link ProjectionTimeoutError} on timeout. Throws on 403/404/409\n * (the endpoint's permanent-error responses).\n */\nexport async function readTaskRunProjection(\n options: ProjectionReadOptions,\n): Promise<TraceProjectionSnapshot> {\n const deadlineMs = options.deadlineMs ?? 30_000;\n const initialIntervalMs = options.initialIntervalMs ?? 500;\n const maxIntervalMs = options.maxIntervalMs ?? 5_000;\n\n const url = `${options.endpoint.replace(/\\/$/, \"\")}/v1/agent-task-runs/${encodeURIComponent(options.taskRunId)}/trace-projection`;\n const start = Date.now();\n let interval = initialIntervalMs;\n\n // eslint-disable-next-line no-constant-condition\n while (true) {\n if (Date.now() - start > deadlineMs) {\n throw new ProjectionTimeoutError(options.taskRunId, deadlineMs);\n }\n\n const response = await fetch(url, {\n headers: { Authorization: `Bearer ${options.authToken}` },\n });\n\n if (response.status === 200) {\n return (await response.json()) as TraceProjectionSnapshot;\n }\n\n if (response.status === 202) {\n // Not ready yet — back off and retry.\n await sleep(interval);\n interval = Math.min(interval * 1.5, maxIntervalMs);\n continue;\n }\n\n // 403/404/409 — permanent errors, surface immediately.\n const detail = await response.json().catch(() => ({ detail: response.statusText }));\n throw new Error(\n `Projection read failed (${response.status}): ${(detail as { detail?: string }).detail ?? response.statusText}`,\n );\n }\n}\n\nfunction sleep(ms: number): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, ms));\n}\n","/**\n * apo semantic conventions — the stable attribute layer on top of OTLP.\n *\n * apo uses standard OpenTelemetry as the transport (OTLP/JSON spans) and\n * standard GenAI semantic conventions (`gen_ai.*`) where they're useful.\n * But `gen_ai.*` is still experimental as of 2026, and some apo concepts\n * (scores, run metadata, observation typing) have no OTel equivalent at all.\n *\n * This module defines the `apo.*` attribute namespace — a stable semantic\n * layer (like Phoenix's OpenInference) that:\n * 1. Encodes apo-specific concepts that OTel doesn't model (scores, runs).\n * 2. Provides a stable contract independent of `gen_ai.*` churn.\n * 3. Is the single source of truth for both the TS SDK and the Python path.\n *\n * The backend's OTLP mapper (`backend/apo/services/otel_mapper.py`) strips the\n * `apo.` prefix and routes these into the internal field names.\n *\n * @module\n */\n\n// ── Observation type ──────────────────────────────────────────────────────\n//\n// Overrides the mapper's automatic type detection. Set this on any span to\n// force its observation_type (GENERATION, TOOL, CHAIN, etc.).\n\nexport const APO_OBSERVATION_TYPE = \"apo.observation.type\" as const;\n\n// ── Run identity ──────────────────────────────────────────────────────────\n//\n// Carried on the root span of a trace. The backend's OTLP route synthesizes a\n// run-create from the first-seen traceId; these attributes populate the run's\n// task_id, flow_name, version, and tags.\n\nexport const APO_RUN_ID = \"apo.run.id\" as const;\nexport const APO_RUN_FLOW_NAME = \"apo.run.flow_name\" as const;\nexport const APO_RUN_TASK_ID = \"apo.run.task_id\" as const;\nexport const APO_RUN_VERSION = \"apo.run.version\" as const;\nexport const APO_RUN_TAGS = \"apo.run.tags\" as const; // JSON array string\n\n// ── Task-run ownership ──────────────────────────────────────\n//\n// Carried on the root span of a task-run Trace. The backend projector reads\n// `apo.task.run.id` and atomically claims `AgentTaskRunDB.trace_run_id`,\n// enforcing the one-trace-per-task-run invariant. Without these\n// attributes the claim path never fires for agent-task runs.\n\nexport const APO_TASK_ID = \"apo.task.id\" as const;\nexport const APO_TASK_RUN_ID = \"apo.task.run.id\" as const;\n\n// Scores are domain records via the HTTP score API, not sentinel spans.\n// See `score()` in `@apo-ai/sdk/otel` — it calls POST /api/v1/traces/{id}/scores.\n\n// ── Cost ──────────────────────────────────────────────────────────────────\n//\n// Optional client-computed cost for a GENERATION span. The backend also\n// computes `calculated_cost` server-side from token counts + model pricing;\n// this attribute carries the client-side estimate if the client has it.\n\nexport const APO_COST = \"apo.cost\" as const;\n\n// ── Enumeration values ────────────────────────────────────────────────────\n\nexport const OBSERVATION_TYPES = [\n \"GENERATION\",\n \"SPAN\",\n \"TOOL\",\n \"CHAIN\",\n \"RETRIEVER\",\n \"EVALUATOR\",\n \"EMBEDDING\",\n \"GUARDRAIL\",\n \"AGENT\",\n] as const;\n\nexport const SCORE_DATA_TYPES = [\"NUMERIC\", \"CATEGORICAL\", \"BOOLEAN\"] as const;\n\nexport const SCORE_SOURCES = [\"API\", \"EVAL\", \"ANNOTATION\"] as const;\n","import type { EvaluationItemResult, TaskEvaluationResult } from \"./types.ts\";\n\n/**\n * Issue #8: shown when a run ends with zero registered checks. A bare\n * `FAIL <task>` with no Checks section looked like a real failure but was\n * almost always a silent registration bug (e.g. a double-import that wiped\n * the check registry). Naming `test()` matches the documented registration\n * function — `apps/docs` reference/task.md.\n *\n * Lives next to {@link aggregateResult} because the empty-checks verdict is\n * the single source of truth for \"why did this run fail with no checks?\".\n * The CLI and the standalone e2e runner both import this so the wording\n * stays in one place.\n */\nexport const NO_CHECKS_REGISTERED_MESSAGE =\n \"No tests were registered by the eval module — a task must define at least one test().\";\n\nexport function aggregateResult(\n checksResults: EvaluationItemResult[],\n): TaskEvaluationResult {\n if (checksResults.length === 0) {\n return { checks: checksResults, pass: false };\n }\n const pass = checksResults.every((r) => r.pass);\n return { checks: checksResults, pass };\n}\n","import type {\n TraceRunContext,\n TraceRunOptions,\n CreateScoreParams,\n CreateSpanParams,\n EndSpanParams,\n} from \"../types.ts\";\nimport type { TraceEventOptions, TraceStepOptions } from \"../types.ts\";\n\nexport type AgentTaskTraceContext = TraceRunContext & {\n createSpan: (\n options: Omit<CreateSpanParams, \"project\" | \"run_id\">,\n ) => string;\n endSpan: (spanId: string, params?: Omit<EndSpanParams, \"id\">) => void;\n};\n\nexport type AgentTaskTraceOptions = {\n client: {\n traceRun<T>(\n params: TraceRunOptions,\n fn: (trace: AgentTaskTraceContext) => Promise<T>,\n ): Promise<T>;\n };\n project?: string;\n flowName?: string;\n version?: string;\n environment?: string;\n tags?: string[];\n runMetadata?: Record<string, unknown>;\n /**\n * The Task Run ID this trace should claim. Emitted as the\n * `apo.task.run.id` root-span attribute so the backend projector can\n * atomically link this trace to the task run. Omit for local/programmatic\n * runs that don't have a backend task run.\n */\n taskRunId?: string;\n};\n\nexport function createNoopAgentTaskTraceContext(): AgentTaskTraceContext {\n const noopFn = async <T>(fn: () => Promise<T>) => fn();\n return {\n runId: \"agent-task-untraced\",\n rootSpanId: \"agent-task-untraced-root\",\n async step<T>(options: TraceStepOptions, fn: (spanId: string) => Promise<T>) {\n return fn(options.id ?? \"agent-task-untraced-step\");\n },\n recordEvent(options: TraceEventOptions) {\n return options.id ?? \"agent-task-untraced-event\";\n },\n endRoot() {},\n traceTool<T>(_name: string, _params: Record<string, unknown>, fn: () => Promise<T>) {\n return noopFn(fn);\n },\n traceRetriever<T>(_query: string, fn: () => Promise<T>) {\n return noopFn(fn);\n },\n traceChain<T>(_name: string, fn: () => Promise<T>) {\n return noopFn(fn);\n },\n traceAgent<T>(_name: string, fn: () => Promise<T>) {\n return noopFn(fn);\n },\n traceGuardrail<T>(_name: string, fn: () => Promise<T>) {\n return noopFn(fn);\n },\n traceEmbedding<T>(_model: string, _input: unknown, fn: () => Promise<T>) {\n return noopFn(fn);\n },\n async score(_params: CreateScoreParams): Promise<void> {},\n createSpan(_options) {\n return \"agent-task-untraced-span\";\n },\n endSpan(_spanId, _params) {},\n };\n}\n","import type {\n TaskRunResult,\n EvaluationItemResult,\n TaskTranscriptTurn,\n} from \"./types.ts\";\nimport type { AgentTaskRunConfiguration, AdapterRuntimeState, AdapterSession } from \"../adapter/types.ts\";\nimport { normalizeRunConfiguration } from \"./run-configuration.ts\";\nimport { loadTask } from \"../task/loadTask.ts\";\nimport {\n getTaskTurn,\n resetTaskTurn,\n resolveTurn,\n type TurnRecord,\n} from \"../turn.ts\";\nimport { TaskFiles } from \"../task/TaskFiles.ts\";\nimport { validateDeliverables } from \"../deliverables/validate.ts\";\nimport {\n loadAndRunFlowChecks,\n loadChecksModule,\n proxyBrokenDeliverables,\n resetFlowChecks,\n runTraceChecks,\n} from \"../checks/flow-runner.ts\";\nimport { createProjectionTee } from \"../trace-projection/projection-tee.ts\";\nimport { readTaskRunProjection } from \"../trace-projection/remote-capture.ts\";\nimport type { JudgeConfig } from \"../checks/t.ts\";\nimport { APO_TASK_ID, APO_TASK_RUN_ID } from \"../../semconv.ts\";\nimport { aggregateResult } from \"./aggregate.ts\";\nimport type { AgentTaskTraceContext, AgentTaskTraceOptions } from \"../tracing.ts\";\nimport { createNoopAgentTaskTraceContext } from \"../tracing.ts\";\nimport type { LoadedTask } from \"../task/loadTask.ts\";\nimport { withApoRun } from \"../integrations/run-context.ts\";\n\n/**\n * Error thrown when a Task Run fails after the adapter's Run Configuration\n * has been resolved. Carries the resolved {@link AgentTaskRunConfiguration} so\n * callers (e.g. the CLI error-report path) can forward model/effort to the\n * backend even when the run never produced a summary (issue #40).\n *\n * The original failure is preserved on `cause`. Only errors thrown after\n * `startSession` reported a *valid* configuration are wrapped — a\n * configuration-validation failure propagates unwrapped (there is nothing to\n * attach).\n */\nexport class AgentTaskRunError extends Error {\n readonly runConfiguration?: AgentTaskRunConfiguration;\n /** The original error that caused the run to fail (preserved for diagnostics). */\n readonly cause?: unknown;\n constructor(\n message: string,\n options: { runConfiguration?: AgentTaskRunConfiguration; cause?: unknown },\n ) {\n super(message);\n this.name = \"AgentTaskRunError\";\n this.runConfiguration = options.runConfiguration;\n this.cause = options.cause;\n }\n}\n\n/**\n * Wrap an error with the resolved Run Configuration so it survives the throw\n * out of the run. Returns the original error unchanged when there is no\n * configuration to attach (old adapter) or when it is already branded.\n */\nfunction withRunConfiguration(\n error: unknown,\n runConfiguration: AgentTaskRunConfiguration | undefined,\n): unknown {\n if (!runConfiguration) return error;\n if (error instanceof AgentTaskRunError) return error;\n const message = error instanceof Error ? error.message : String(error);\n return new AgentTaskRunError(message, { runConfiguration, cause: error });\n}\n\nexport type RunTaskOptions = {\n maxTurnsOverride?: number;\n tracing?: AgentTaskTraceOptions;\n /** LLM judge model config for `t.judge(...)` calls in the task checks. */\n judge?: JudgeConfig;\n onTurn?: (\n turnNumber: number,\n userAction: TaskTranscriptTurn[\"userAction\"],\n agentResponse: unknown,\n ) => void;\n /**\n * Skip the internal `loadTask(taskDir)` call and reuse an already-loaded\n * task definition.\n *\n * The eval module's top level runs once per `loadTask` (it is copied to a\n * temp file and imported with all registries reset), so loading twice per\n * run breaks evals whose load-time behavior is not idempotent across module\n * systems (e.g. a helper that re-exports CJS `require()`-cached registrations\n * — the second import hits the cache and registers zero checks). Callers\n * that already need a `LoadedTask` for their own purposes (`runTaskDir`,\n * `runner-entry.ts`) should always pass it through here to keep the eval\n * import count at exactly one per run.\n *\n * When omitted, `runTask` calls `loadTask(taskDir)` itself. The `taskDir`\n * argument is still required for that fallback and is otherwise unused.\n */\n loaded?: LoadedTask;\n};\n\nexport async function runTask(\n taskDir: string,\n options?: RunTaskOptions,\n): Promise<TaskRunResult> {\n // Reuse an already-loaded task when provided — see `RunTaskOptions.loaded`.\n // Otherwise load it here (the eval module is imported exactly once either way).\n const loaded = options?.loaded ?? (await loadTask(taskDir));\n const trace = options?.tracing;\n\n if (!trace) {\n // No tracing — run everything in one pass (no two-phase split needed;\n // there's no trace to contaminate).\n return executeLoadedTask(\n loaded,\n options,\n createNoopAgentTaskTraceContext(),\n undefined,\n );\n }\n\n // Phase 1 (capture) runs inside the traceRun\n // callback; Phase 2 (evaluate) runs AFTER the root span ends and the trace\n // flushes, so checks/deliverable-validation cannot contaminate the trace.\n const phase1 = await trace.client.traceRun(\n buildTraceRunOptions(loaded, trace),\n async (traceContext) => captureExecution(loaded, options, traceContext),\n );\n\n // when this run is backend-launched (has a taskRunId),\n // read the canonical projection snapshot back from the backend instead of\n // the local tee. The backend's projection is the single source of truth —\n // it includes spans the subprocess exported natively over OTLP (which the\n // in-process tee can never see, since they're created in another process).\n // Falls back to the local snapshot on any failure (offline runs, unreachable\n // backend, projection timeout) so evaluation still runs.\n const canonical = await readCanonicalSnapshot(trace);\n if (canonical) phase1.snapshot = canonical;\n\n // Phase 2: evaluate against the frozen snapshot. The trace is now closed.\n return evaluate(loaded, options, phase1);\n}\n\n/**\n * Read the canonical projection snapshot from the backend (Track C).\n *\n * Returns `null` when there's nothing to read (no taskRunId = offline/local\n * run) or when the read fails for any reason — the caller falls back to the\n * local tee snapshot in that case. Errors are logged but never thrown: a\n * projection read problem must not fail the task run.\n */\nasync function readCanonicalSnapshot(\n trace: AgentTaskTraceOptions,\n): Promise<CapturedExecution[\"snapshot\"] | null> {\n if (!trace.taskRunId) return null; // offline/local run — no backend read\n const endpoint = process.env.AGENT_TASK_TRACE_ENDPOINT;\n const authToken = process.env.APO_AUTH_TOKEN;\n if (!endpoint || !authToken) return null;\n try {\n return await readTaskRunProjection({\n endpoint,\n authToken,\n taskRunId: trace.taskRunId,\n });\n } catch (error) {\n console.error(\n \"[AgentTask] Backend projection read failed, using local snapshot:\",\n error instanceof Error ? error.message : String(error),\n );\n return null;\n }\n}\n\n/** Phase 1 result: what capture produced, passed to Phase 2 evaluation. */\ninterface CapturedExecution {\n traceRunId: string | undefined;\n collected: Record<string, unknown>;\n transcriptTurns: TaskTranscriptTurn[];\n /** The adapter-reported run configuration, captured right after session open. */\n runConfiguration: AgentTaskRunConfiguration | undefined;\n /** The frozen projection snapshot Phase 2 evaluates against. */\n snapshot: import(\"../trace-projection/types.ts\").TraceProjectionSnapshot;\n}\n\nasync function executeLoadedTask(\n loaded: LoadedTask,\n options: RunTaskOptions | undefined,\n rawTrace: AgentTaskTraceContext,\n traceRunId: string | undefined,\n): Promise<TaskRunResult> {\n const {\n task,\n adapter,\n taskDir: absoluteDir,\n files,\n checksPath,\n inlineChecks,\n moduleUrl,\n evalFileName,\n } = loaded;\n const taskFiles = new TaskFiles(files);\n // Tee the trace so the run's tool/agent/message spans also build the\n // projection snapshot that checks read. `trace` below is the wrapped context.\n const tee = createProjectionTee(rawTrace);\n const { trace, getSnapshot } = { trace: tee.trace, getSnapshot: () => tee.getSnapshot() };\n\n // Establish the run on AsyncLocalStorage so the OTel SpanProcessor\n // (if registered) can route GenAI spans to this run's trace context.\n return withApoRun(\n { trace, parentSpanId: rawTrace.rootSpanId, taskId: task.id },\n async () => {\n // All the local state that the previous body used, now inside the ALS scope\n return executeRunBody();\n },\n );\n\n async function executeRunBody(): Promise<TaskRunResult> {\n let state: AdapterRuntimeState | undefined;\n let session: AdapterSession | undefined;\n const transcriptTurns: TaskTranscriptTurn[] = [];\n\n try {\n await trace.step(\n {\n step_name: \"task.load\",\n input: { taskId: task.id, taskDir: absoluteDir },\n metadata: {\n taskId: task.id,\n taskDir: absoluteDir,\n fileCount: files.length,\n hasChecks: inlineChecks || checksPath !== null,\n },\n summarize: () => ({\n taskId: task.id,\n adapterName: adapter.name,\n }),\n },\n async () => loaded,\n );\n\n if (adapter.initialize) {\n const initState = await trace.step(\n {\n step_name: \"adapter.initialize\",\n input: { adapterName: adapter.name },\n metadata: { adapterName: adapter.name },\n summarize: (result) => ({\n initialized: true,\n stateKeys:\n result && typeof result === \"object\"\n ? Object.keys(result as Record<string, unknown>)\n : [],\n }),\n },\n async () =>\n adapter.initialize?.({\n task,\n taskDir: absoluteDir,\n files,\n trace,\n }),\n );\n state = initState ?? undefined;\n }\n\n session = await trace.step(\n {\n step_name: \"adapter.open-session\",\n input: { adapterName: adapter.name, hasState: state !== undefined },\n metadata: { adapterName: adapter.name },\n summarize: () => ({ sessionOpened: true }),\n },\n async () =>\n adapter.startSession({\n task,\n taskDir: absoluteDir,\n files,\n state,\n trace,\n }),\n );\n\n // capture the adapter's resolved model/effort immediately after\n // the session opens and validate it before the first Task Turn. An invalid\n // reported configuration is an adapter contract error and fails the run.\n const runConfiguration = normalizeRunConfiguration(session.runConfiguration);\n\n // Issue #40: anything that throws past this point (a Task Turn, deliverable\n // collection, checks) must carry the resolved configuration out so callers\n // can still report model/effort on an errored run.\n try {\n // Legacy two-file tasks register turn() from checks.ts. Single-file tasks\n // already registered it while loadTask imported the .eval.ts file.\n if (!inlineChecks && checksPath) {\n resetTaskTurn();\n resetFlowChecks();\n await loadChecksModule(checksPath);\n }\n\n const taskTurn = getTaskTurn();\n resetTaskTurn();\n const turnFn = resolveTurn(adapter.turn, taskTurn);\n\n if (turnFn) {\n const turnTranscript: TurnRecord[] = [];\n let lastTurnResponse: unknown;\n // Precedence: explicit run override → task config → default 10.\n const maxTurns = options?.maxTurnsOverride ?? task.maxTurns ?? 10;\n\n for (let turnNum = 1; turnNum <= maxTurns; turnNum++) {\n const userTurn = await turnFn({ files: taskFiles, transcript: turnTranscript });\n if (userTurn === null || userTurn === undefined) break;\n\n const result = await trace.step(\n {\n step_name: \"task.turn\",\n metadata: { turnNumber: turnNum },\n summarize: (r) => ({ response: (r as { response: unknown }).response }),\n },\n async (spanId) => {\n if (!session) throw new Error(\"Session not created\");\n return session.sendUserTurn(userTurn, {\n trace,\n turnNumber: turnNum,\n parentSpanId: spanId,\n });\n },\n );\n\n turnTranscript.push({\n turnNumber: turnNum,\n input: userTurn,\n output: result.response,\n });\n transcriptTurns.push({\n turnNumber: turnNum,\n userAction: userTurn,\n agentResponse: result.response,\n });\n options?.onTurn?.(turnNum, userTurn, result.response);\n lastTurnResponse = result.response;\n }\n // Issue #45: roll the final turn's response up to the run root so the\n // trace header / run list shows what the agent answered at a glance.\n if (lastTurnResponse !== undefined) {\n rawTrace.endRoot({ output: { response: lastTurnResponse } });\n }\n }\n\n const collected = await trace.step(\n {\n step_name: \"adapter.collect-deliverables\",\n input: { adapterName: adapter.name, expectedDeliverables: task.deliverables },\n metadata: { adapterName: adapter.name },\n summarize: (result) => {\n const keys =\n result && typeof result === \"object\"\n ? Object.keys(result as Record<string, unknown>)\n : [];\n return { deliverableCount: keys.length, deliverableNames: keys };\n },\n },\n async () => {\n if (!session) {\n throw new Error(\"Adapter session was not created\");\n }\n\n return adapter.collectDeliverables({\n task,\n taskDir: absoluteDir,\n files,\n state,\n session,\n trace,\n });\n },\n );\n\n const validationResults = await trace.step(\n {\n step_name: \"deliverables.validate\",\n input: { deliverableNames: task.deliverables },\n summarize: (result) => {\n const r = result as ReturnType<typeof validateDeliverables>;\n const passCount = r.results.filter((x) => x.pass).length;\n const broken = Object.keys(r.brokenDeliverables);\n return {\n total: r.results.length,\n passCount,\n failCount: r.results.length - passCount,\n brokenDeliverableCount: broken.length,\n brokenDeliverables: broken,\n };\n },\n },\n async () => validateDeliverables(task, collected, adapter.deliverables),\n );\n\n const checksResults = await trace.step(\n {\n step_name: \"checks.run\",\n input: { sourceFile: inlineChecks ? evalFileName : checksPath },\n metadata: { sourceFile: inlineChecks ? evalFileName : checksPath },\n summarize: (result) =>\n summarizeEvaluationResults(result as EvaluationItemResult[]),\n },\n async () => {\n if (!inlineChecks) {\n return loadAndRunFlowChecks(\n checksPath,\n {\n snapshot: getSnapshot(),\n deliverables: collected,\n files,\n task,\n judgeConfig: options?.judge,\n },\n validationResults.brokenDeliverables,\n );\n }\n return runTraceChecks({\n snapshot: getSnapshot(),\n deliverables: proxyBrokenDeliverables(\n collected,\n validationResults.brokenDeliverables,\n ),\n files,\n task,\n judgeConfig: options?.judge,\n moduleUrl,\n displayFile: evalFileName,\n });\n },\n );\n\n const result = aggregateResult(checksResults);\n\n return {\n task,\n taskDir: absoluteDir,\n files,\n traceRunId,\n result,\n deliverables: collected,\n transcript: { turns: transcriptTurns },\n runConfiguration,\n };\n } catch (error) {\n throw withRunConfiguration(error, runConfiguration);\n }\n } finally {\n if (adapter.cleanup) {\n try {\n await trace.step(\n {\n step_name: \"adapter.cleanup\",\n input: { adapterName: adapter.name },\n metadata: { adapterName: adapter.name },\n summarize: () => ({ cleaned: true }),\n },\n async () =>\n adapter.cleanup?.({\n task,\n taskDir: absoluteDir,\n files,\n state,\n session,\n trace,\n }),\n );\n } catch (error) {\n console.error(\n \"[AgentTask] Cleanup failed:\",\n error instanceof Error ? error.message : String(error),\n );\n }\n }\n\n if (session?.close) {\n try {\n await session.close();\n } catch {\n // ignore close errors\n }\n }\n }\n } // end executeRunBody\n}\n\n/**\n * Phase 1: capture the execution inside the trace.\n * Runs adapter init → session → turns → deliverable collection → cleanup.\n * Excludes deliverable validation and checks — those run in Phase 2, after the\n * root span ends and the trace flushes, so they cannot contaminate the trace.\n */\nasync function captureExecution(\n loaded: LoadedTask,\n options: RunTaskOptions | undefined,\n rawTrace: AgentTaskTraceContext,\n): Promise<CapturedExecution> {\n const {\n task,\n adapter,\n taskDir: absoluteDir,\n files,\n checksPath,\n inlineChecks,\n } = loaded;\n const taskFiles = new TaskFiles(files);\n const tee = createProjectionTee(rawTrace);\n const trace = tee.trace;\n\n return withApoRun(\n { trace, parentSpanId: rawTrace.rootSpanId, taskId: task.id },\n async () => {\n let state: AdapterRuntimeState | undefined;\n let session: AdapterSession | undefined;\n const transcriptTurns: TaskTranscriptTurn[] = [];\n\n try {\n await trace.step(\n { step_name: \"task.load\", input: { taskId: task.id, taskDir: absoluteDir }, metadata: { taskId: task.id, taskDir: absoluteDir, fileCount: files.length, hasChecks: inlineChecks || checksPath !== null }, summarize: () => ({ taskId: task.id, adapterName: adapter.name }) },\n async () => loaded,\n );\n\n if (adapter.initialize) {\n const initState = await trace.step(\n { step_name: \"adapter.initialize\", input: { adapterName: adapter.name }, metadata: { adapterName: adapter.name }, summarize: (result) => ({ initialized: true, stateKeys: result && typeof result === \"object\" ? Object.keys(result as Record<string, unknown>) : [] }) },\n async () => adapter.initialize?.({ task, taskDir: absoluteDir, files, trace }),\n );\n state = initState ?? undefined;\n }\n\n session = await trace.step(\n { step_name: \"adapter.open-session\", input: { adapterName: adapter.name, hasState: state !== undefined }, metadata: { adapterName: adapter.name }, summarize: () => ({ sessionOpened: true }) },\n async () => adapter.startSession({ task, taskDir: absoluteDir, files, state, trace }),\n );\n\n // validate the adapter-reported configuration before the first\n // Task Turn. An invalid configuration fails the run inside the trace body.\n const runConfiguration = normalizeRunConfiguration(session.runConfiguration);\n\n // Issue #40: carry the resolved configuration out on any downstream\n // failure so the errored run keeps its model/effort label.\n try {\n if (!inlineChecks && checksPath) {\n resetTaskTurn();\n resetFlowChecks();\n await loadChecksModule(checksPath);\n }\n\n const taskTurn = getTaskTurn();\n resetTaskTurn();\n const turnFn = resolveTurn(adapter.turn, taskTurn);\n\n if (turnFn) {\n const turnTranscript: TurnRecord[] = [];\n let lastTurnResponse: unknown;\n const maxTurns = options?.maxTurnsOverride ?? task.maxTurns ?? 10;\n for (let turnNum = 1; turnNum <= maxTurns; turnNum++) {\n const userTurn = await turnFn({ files: taskFiles, transcript: turnTranscript });\n if (userTurn === null || userTurn === undefined) break;\n const result = await trace.step(\n { step_name: \"task.turn\", metadata: { turnNumber: turnNum }, summarize: (r) => ({ response: (r as { response: unknown }).response }) },\n async (spanId) => {\n if (!session) throw new Error(\"Session not created\");\n return session.sendUserTurn(userTurn, { trace, turnNumber: turnNum, parentSpanId: spanId });\n },\n );\n turnTranscript.push({ turnNumber: turnNum, input: userTurn, output: result.response });\n transcriptTurns.push({ turnNumber: turnNum, userAction: userTurn, agentResponse: result.response });\n options?.onTurn?.(turnNum, userTurn, result.response);\n lastTurnResponse = result.response;\n }\n // Issue #45: roll the final turn's response up to the run root.\n if (lastTurnResponse !== undefined) {\n rawTrace.endRoot({ output: { response: lastTurnResponse } });\n }\n }\n\n const collected = await trace.step(\n { step_name: \"adapter.collect-deliverables\", input: { adapterName: adapter.name, expectedDeliverables: task.deliverables }, metadata: { adapterName: adapter.name }, summarize: (result) => { const keys = result && typeof result === \"object\" ? Object.keys(result as Record<string, unknown>) : []; return { deliverableCount: keys.length, deliverableNames: keys }; } },\n async () => {\n if (!session) throw new Error(\"Adapter session was not created\");\n return adapter.collectDeliverables({ task, taskDir: absoluteDir, files, state, session, trace });\n },\n );\n\n // Freeze the snapshot from the projection tee. The root span will end\n // and flush after this callback returns — Phase 2 reads this snapshot.\n const snapshot = tee.getSnapshot();\n\n return {\n traceRunId: rawTrace.runId,\n collected: collected as Record<string, unknown>,\n transcriptTurns,\n runConfiguration,\n snapshot,\n };\n } catch (error) {\n throw withRunConfiguration(error, runConfiguration);\n }\n } finally {\n if (adapter.cleanup) {\n try {\n await trace.step(\n { step_name: \"adapter.cleanup\", input: { adapterName: adapter.name }, metadata: { adapterName: adapter.name }, summarize: () => ({ cleaned: true }) },\n async () => adapter.cleanup?.({ task, taskDir: absoluteDir, files, state, session, trace }),\n );\n } catch (error) {\n console.error(\"[AgentTask] Cleanup failed:\", error instanceof Error ? error.message : String(error));\n }\n }\n if (session?.close) {\n try { await session.close(); } catch { /* ignore */ }\n }\n }\n },\n );\n}\n\n/**\n * Phase 2: evaluate deliverables and run checks\n * AFTER the trace has closed and flushed. The snapshot is the frozen Phase-1\n * trace — checks cannot contaminate it because they run outside the trace body.\n */\nasync function evaluate(\n loaded: LoadedTask,\n options: RunTaskOptions | undefined,\n phase1: CapturedExecution,\n): Promise<TaskRunResult> {\n const {\n task,\n adapter,\n taskDir: absoluteDir,\n files,\n checksPath,\n inlineChecks,\n moduleUrl,\n evalFileName,\n } = loaded;\n\n // Validate deliverables (no longer a trace span — runs outside the trace).\n const validationResults = validateDeliverables(task, phase1.collected, adapter.deliverables);\n\n const deliverables = proxyBrokenDeliverables(\n phase1.collected,\n validationResults.brokenDeliverables,\n );\n\n const checksResults = await (inlineChecks\n ? runTraceChecks({\n snapshot: phase1.snapshot,\n deliverables,\n files,\n task,\n judgeConfig: options?.judge,\n moduleUrl,\n displayFile: evalFileName,\n })\n : loadAndRunFlowChecks(\n checksPath,\n {\n snapshot: phase1.snapshot,\n deliverables,\n files,\n task,\n judgeConfig: options?.judge,\n },\n validationResults.brokenDeliverables,\n ));\n\n const result = aggregateResult(checksResults);\n\n return {\n task,\n taskDir: absoluteDir,\n files,\n traceRunId: phase1.traceRunId,\n result,\n deliverables: phase1.collected,\n transcript: { turns: phase1.transcriptTurns },\n runConfiguration: phase1.runConfiguration,\n };\n}\n\n/** Compact summary of check evaluation results for span output.\n *\n * Keeps the full reasoning text (not just pass/fail) so the trace view\n * is useful for debugging. Also carries evaluator_type and judge model\n * when available, so the trace shows which checks were LLM-judged.\n */\nfunction summarizeEvaluationResults(results: EvaluationItemResult[]) {\n const passCount = results.filter((r) => r.pass).length;\n return {\n total: results.length,\n passCount,\n failCount: results.length - passCount,\n results: results.map((r) => ({\n id: r.id,\n pass: r.pass,\n reasoning: r.reasoning,\n evaluator_type: r.evaluator_type,\n judge_model: r.judge?.model,\n })),\n };\n}\n\nfunction buildTraceRunOptions(\n loaded: LoadedTask,\n tracing: AgentTaskTraceOptions,\n) { const tags = Array.from(new Set([\"agent-task\", \"e2e\", ...(tracing.tags ?? [])]));\n\n // Carry the task-run claim attributes on the root span. The\n // backend projector reads `apo.task.run.id` to atomically link this trace to\n // the task run. These land in rootSpan.metadata today (legacy ingestion);\n // once the runner migrates to OTLP export (Track C) they become real OTel\n // attributes that the projector's claim path reads directly.\n const rootMetadata: Record<string, unknown> = {\n taskId: loaded.task.id,\n taskDir: loaded.taskDir,\n adapterName: loaded.adapter.name,\n };\n if (tracing.taskRunId) {\n rootMetadata[APO_TASK_ID] = loaded.task.id;\n rootMetadata[APO_TASK_RUN_ID] = tracing.taskRunId;\n }\n\n return {\n project: tracing.project,\n task_id: loaded.task.id,\n flow_name: tracing.flowName ?? `agent-task.${loaded.task.id}`,\n version: tracing.version,\n environment: tracing.environment,\n tags,\n run_metadata: {\n taskDir: loaded.taskDir,\n adapterName: loaded.adapter.name,\n source: \"agent-task-e2e\",\n ...tracing.runMetadata,\n },\n rootSpan: {\n task_id: loaded.task.id,\n step_name: \"agent-task.run\",\n observation_type: \"CHAIN\" as const,\n model: \"agent-task\",\n metadata: rootMetadata,\n },\n };\n}\n","import { relative, resolve } from \"path\";\nimport { discoverAgentTaskDirs } from \"./discovery.ts\";\nimport { runTaskDir, type AgentTaskRunSummary } from \"./task-runtime.ts\";\nimport { NO_CHECKS_REGISTERED_MESSAGE } from \"./run/aggregate.ts\";\n\nexport type AgentTaskCliOptions = {\n task?: string;\n dir?: string;\n grep?: string;\n help?: boolean;\n};\n\nexport function parseAgentTaskCliArgs(argv: string[]): AgentTaskCliOptions {\n const options: AgentTaskCliOptions = {};\n\n for (let index = 0; index < argv.length; index += 1) {\n const arg = argv[index];\n\n if (arg === \"--help\" || arg === \"-h\") {\n options.help = true;\n continue;\n }\n\n if (arg === \"--task\") {\n options.task = requireNextValue(argv, index, \"--task\");\n index += 1;\n continue;\n }\n\n if (arg === \"--dir\") {\n options.dir = requireNextValue(argv, index, \"--dir\");\n index += 1;\n continue;\n }\n\n if (arg === \"--grep\") {\n options.grep = requireNextValue(argv, index, \"--grep\");\n index += 1;\n continue;\n }\n\n throw new Error(`Unknown argument: ${arg}`);\n }\n\n if (options.task && options.dir) {\n throw new Error(\"Use either --task or --dir, not both\");\n }\n\n return options;\n}\n\nexport async function runAgentTaskCli(\n argv: string[],\n cwd = process.cwd(),\n): Promise<number> {\n const normalizedArgv = argv[0] === \"--\" ? argv.slice(1) : argv;\n const options = parseAgentTaskCliArgs(normalizedArgv);\n\n if (options.help) {\n printHelp();\n return 0;\n }\n\n const selectedTaskDirs = resolveSelectedTaskDirs(options, cwd);\n if (selectedTaskDirs.length === 0) {\n throw new Error(\"No task folders found for the selected input\");\n }\n\n let hasFailures = false;\n let hasErrors = false;\n\n const results = await Promise.allSettled(\n selectedTaskDirs.map((taskDir) => runTaskDir(taskDir))\n );\n\n const summaries: AgentTaskRunSummary[] = [];\n for (let i = 0; i < results.length; i++) {\n const result = results[i];\n const taskDir = selectedTaskDirs[i];\n if (result.status === \"fulfilled\") {\n summaries.push(result.value);\n printTaskSummary(result.value, cwd);\n hasFailures ||= !result.value.pass;\n } else {\n hasErrors = true;\n printTaskError(taskDir, cwd, result.reason);\n }\n }\n\n printOverallSummary(summaries, hasErrors);\n\n if (hasErrors) {\n return 2;\n }\n\n return hasFailures ? 1 : 0;\n}\n\nfunction resolveSelectedTaskDirs(\n options: AgentTaskCliOptions,\n cwd: string,\n): string[] {\n if (options.task) {\n return [resolve(cwd, options.task)];\n }\n\n const rootDir = resolve(cwd, options.dir ?? \"e2e\");\n const discovered = discoverAgentTaskDirs(rootDir);\n\n if (!options.grep) {\n return discovered;\n }\n\n return discovered.filter((taskDir) =>\n // String.prototype.includes (not Array.includes) — false positive\n // react-doctor-disable-next-line react-doctor/js-set-map-lookups\n relative(cwd, taskDir).includes(options.grep as string),\n );\n}\n\nfunction requireNextValue(argv: string[], index: number, flag: string): string {\n const value = argv[index + 1];\n if (!value || value.startsWith(\"--\")) {\n throw new Error(`Missing value for ${flag}`);\n }\n return value;\n}\n\nfunction printHelp(): void {\n console.log(\"Usage: agent-task-e2e [--task <task-folder> | --dir <tasks-root>] [--grep <substring>]\");\n console.log(\"\");\n console.log(\"Options\");\n console.log(\"- --task <path> Run one task folder\");\n console.log(\"- --dir <path> Run all task folders under a root directory\");\n console.log(\"- --grep <text> Filter discovered task paths by substring\");\n console.log(\"- --help Show this help\");\n}\n\nfunction printTaskSummary(summary: AgentTaskRunSummary, cwd: string): void {\n const relativeTaskDir = relative(cwd, summary.taskDir);\n console.log(\"\");\n console.log(`${summary.pass ? \"PASS\" : \"FAIL\"} ${summary.taskId}`);\n console.log(`Path: ${relativeTaskDir}`);\n\n printResultGroup(\"Checks\", summary.checks);\n\n // Issue #8: a failed run with zero checks is almost always a silent\n // registration bug (e.g. a double-import that wiped the check registry).\n // Don't print a bare FAIL — say what went wrong.\n if (summary.checks.length === 0 && !summary.pass) {\n console.log(NO_CHECKS_REGISTERED_MESSAGE);\n }\n}\n\nfunction printResultGroup(\n label: string,\n results: AgentTaskRunSummary[\"checks\"],\n): void {\n if (results.length === 0) {\n return;\n }\n\n console.log(label);\n for (const result of results) {\n console.log(`- ${result.id}: ${result.pass ? \"PASS\" : \"FAIL\"}`);\n if (result.reasoning) {\n console.log(` ${result.reasoning}`);\n }\n }\n}\n\nfunction printTaskError(taskDir: string, cwd: string, error: unknown): void {\n const message = error instanceof Error ? error.message : String(error);\n console.log(\"\");\n console.log(`ERROR ${relative(cwd, taskDir)}`);\n console.log(message);\n}\n\nfunction printOverallSummary(\n summaries: AgentTaskRunSummary[],\n hasErrors: boolean,\n): void {\n const passed = summaries.filter((summary) => summary.pass).length;\n const failed = summaries.length - passed;\n\n console.log(\"\");\n console.log(\"Summary\");\n console.log(`- total: ${summaries.length}`);\n console.log(`- passed: ${passed}`);\n console.log(`- failed: ${failed}`);\n console.log(`- errors: ${hasErrors ? \"yes\" : \"no\"}`);\n}\n","import { existsSync, readdirSync, statSync } from \"fs\";\nimport { join, resolve } from \"path\";\n\nexport function discoverAgentTaskDirs(rootDir: string): string[] {\n const absoluteRoot = resolve(rootDir);\n\n if (!existsSync(absoluteRoot) || !statSync(absoluteRoot).isDirectory()) {\n throw new Error(`Task directory not found: ${absoluteRoot}`);\n }\n\n const discovered: string[] = [];\n walkForTaskDirs(absoluteRoot, discovered);\n return discovered.sort();\n}\n\nfunction walkForTaskDirs(currentDir: string, discovered: string[]): void {\n if (readdirSync(currentDir).some((f) => f.endsWith(\".eval.ts\"))) {\n discovered.push(currentDir);\n return;\n }\n\n for (const entry of readdirSync(currentDir)) {\n const absolutePath = join(currentDir, entry);\n if (!statSync(absolutePath).isDirectory()) {\n continue;\n }\n\n walkForTaskDirs(absolutePath, discovered);\n }\n}\n","/**\n * OTel-backed agent-task trace client.\n *\n * Replaces the deprecated ``TraceTracker``-backed ``createAgentTaskTraceClient``\n * with one that uses standard OpenTelemetry spans exported via the canonical\n * OTLP receiver. The ``AgentTaskTraceContext`` interface is identical —\n * ``runTask.ts``, ``FlowTee``, integrations, and task-authoring code work\n * unchanged.\n *\n * Key differences from the TraceTracker path:\n * - Spans are real OTel spans (``tracer.startSpan`` / ``span.end()``)\n * - Scores are domain records via the score API (not sentinel ingestion events)\n * - Run completion happens when the root span ends (OTel native)\n * - Export goes through ``configureApoTelemetry``'s OTLP exporter\n *\n * * 1. The runner starts an active root span named ``apo.task.run`` and adds\n * ``apo.task.id`` and ``apo.task.run.id``.\n * 2. Child framework spans inherit context normally.\n * 3. Completion happens when the root span ends.\n */\n\nimport { trace, context, type Span, type Tracer } from \"@opentelemetry/api\";\nimport { configureApoTelemetry, type ApoTelemetryHandle } from \"../otel/index.ts\";\nimport type {\n CreateSpanParams,\n EndSpanParams,\n TraceRunContext,\n TraceRunOptions,\n TraceStepOptions,\n TraceEventOptions,\n CreateScoreParams,\n} from \"../types.ts\";\n\nfunction monotonicNowMs(): number {\n if (typeof performance !== \"undefined\" && typeof performance.now === \"function\") {\n return performance.now();\n }\n return Date.now();\n}\n\nfunction round3(n: number): number {\n return Math.round(n * 1000) / 1000;\n}\n\nexport type AgentTaskTraceClientConfig = {\n endpoint: string;\n project: string;\n authToken?: string;\n requirePersistence?: boolean;\n /** Auth headers for the OTLP exporter (Authorization: Basic/Bearer). */\n headers?: Record<string, string>;\n};\n\ninterface ActiveSpan {\n span: Span;\n startedAt: number;\n model: string;\n}\n\n/**\n * Create an OTel-native agent-task trace client.\n *\n * Drop-in replacement for ``createAgentTaskTraceClient`` that uses\n * ``configureApoTelemetry`` instead of ``TraceTracker``.\n */\nexport function createOtelAgentTaskTraceClient(\n config: AgentTaskTraceClientConfig,\n): {\n traceRun<T>(\n params: TraceRunOptions,\n fn: (trace: TraceRunContext) => Promise<T>,\n ): Promise<T>;\n} {\n // Cache the provider across all client instances — OTel only allows one\n // global provider per process. Subsequent calls reuse the existing handle.\n let myHandle: ApoTelemetryHandle | null = null;\n\n async function ensureProvider(): Promise<Tracer> {\n if (!myHandle) {\n const headers = config.headers\n ?? (config.authToken ? { Authorization: `Bearer ${config.authToken}` } : {});\n myHandle = await configureApoTelemetry({\n takeOwnership: true,\n endpoint: `${config.endpoint.replace(/\\/$/, \"\")}/api/public/otel/v1/traces`,\n serviceName: \"apo-agent-task\",\n project: config.project,\n headers,\n processor: \"simple\",\n registerGlobal: true,\n });\n }\n return myHandle.tracer;\n }\n\n const activeSpans = new Map<string, ActiveSpan>();\n let activeTracer: Tracer | null = null;\n\n function createSpan(params: CreateSpanParams): string {\n if (!activeTracer) throw new Error(\"traceRun not started\");\n const spanName = params.step_name || params.observation_type || \"span\";\n // Use startSpan which inherits the active context. The root span is\n // activated in traceRun via context.with(). Child spans created here\n // inherit whatever span is currently active — correct nesting.\n const span = activeTracer.startSpan(spanName);\n\n // Set attributes using GenAI semantic conventions so the backend\n // normalizer can extract input/output/tokens into structured fields.\n if (params.observation_type) {\n span.setAttribute(\"apo.observation.type\", params.observation_type);\n }\n if (params.model) {\n span.setAttribute(\"gen_ai.request.model\", params.model);\n }\n if (params.input) {\n // Use gen_ai.input.messages so the normalizer routes it to the call's\n // structured input field (rendered as chat bubbles in the dashboard).\n if (params.input.messages) {\n span.setAttribute(\"gen_ai.input.messages\", JSON.stringify(params.input.messages));\n } else {\n span.setAttribute(\"gen_ai.input.messages\", JSON.stringify([{\n role: \"system\",\n parts: [{ type: \"text\", content: JSON.stringify(params.input) }],\n }]));\n }\n }\n if (params.metadata) {\n span.setAttribute(\"apo.metadata\", JSON.stringify(params.metadata));\n }\n\n const spanId = span.spanContext().spanId;\n activeSpans.set(spanId, {\n span,\n startedAt: monotonicNowMs(),\n model: params.model || \"unknown\",\n });\n return spanId;\n }\n\n function endSpan(params: EndSpanParams): void {\n const active = activeSpans.get(params.id);\n if (!active) {\n return;\n }\n\n const latency = params.latency_ms ?? round3(monotonicNowMs() - active.startedAt);\n active.span.setAttribute(\"latency_ms\", latency);\n\n if (params.output !== undefined) {\n // Use gen_ai.output.messages so the normalizer routes it to the call's\n // structured output field (rendered as chat bubbles + \"Correct\" button).\n if (params.output.text) {\n active.span.setAttribute(\"gen_ai.output.messages\", JSON.stringify([{\n role: \"assistant\",\n parts: [{ type: \"text\", content: String(params.output.text) }],\n }]));\n } else if (params.output.messages) {\n active.span.setAttribute(\"gen_ai.output.messages\", JSON.stringify(params.output.messages));\n } else if (params.output.error) {\n active.span.setAttribute(\"gen_ai.output.messages\", JSON.stringify([{\n role: \"assistant\",\n parts: [{ type: \"text\", content: String(params.output.error) }],\n }]));\n } else {\n active.span.setAttribute(\"gen_ai.output.messages\", JSON.stringify([{\n role: \"assistant\",\n parts: [{ type: \"text\", content: JSON.stringify(params.output) }],\n }]));\n }\n }\n if (params.prompt_tokens !== undefined) {\n active.span.setAttribute(\"gen_ai.usage.input_tokens\", params.prompt_tokens);\n }\n if (params.completion_tokens !== undefined) {\n active.span.setAttribute(\"gen_ai.usage.output_tokens\", params.completion_tokens);\n }\n if (params.status_message) {\n active.span.setAttribute(\"apo.status_message\", params.status_message);\n }\n if (params.level === \"ERROR\") {\n active.span.setStatus({ code: 2, message: params.status_message || \"error\" });\n }\n if (params.metadata) {\n active.span.setAttribute(\"apo.metadata\", JSON.stringify(params.metadata));\n }\n\n active.span.end();\n activeSpans.delete(params.id);\n }\n\n return {\n async traceRun<T>(\n params: TraceRunOptions,\n fn: (trace: TraceRunContext) => Promise<T>,\n ): Promise<T> {\n const tracer = await ensureProvider();\n activeTracer = tracer;\n\n const project = params.project ?? config.project;\n const taskId = params.task_id ?? params.flow_name ?? \"task\";\n const flowName = params.flow_name ?? taskId;\n\n // Create the root span with apo.task attributes\n const rootSpan = tracer.startSpan(\"apo.task.run\");\n rootSpan.setAttribute(\"apo.observation.type\", \"AGENT\");\n rootSpan.setAttribute(\"apo.run.flow_name\", flowName);\n rootSpan.setAttribute(\"apo.run.task_id\", taskId);\n if (params.version) {\n rootSpan.setAttribute(\"apo.run.version\", params.version);\n }\n if (params.run_metadata) {\n rootSpan.setAttribute(\"apo.run.metadata\", JSON.stringify(params.run_metadata));\n }\n if (params.tags?.length) {\n rootSpan.setAttribute(\"apo.run.tags\", JSON.stringify(params.tags));\n }\n\n // The task-run claim attributes. The backend projector\n // reads `apo.task.run.id` from the root span and atomically links this\n // trace to AgentTaskRunDB.trace_run_id. The task run id arrives from any\n // of three sources (first wins): an explicit taskRunId on params, the\n // rootSpan.metadata claim key (set by buildTraceRunOptions), or\n // run_metadata.agent_task_run_id (set by the backend at launch time).\n const rootMeta = params.rootSpan?.metadata as Record<string, unknown> | undefined;\n const taskRunId =\n ((params as { taskRunId?: string }).taskRunId) ??\n (rootMeta?.[\"apo.task.run.id\"] as string | undefined) ??\n (params.run_metadata?.[\"agent_task_run_id\"] as string | undefined);\n if (taskRunId) {\n rootSpan.setAttribute(\"apo.task.id\", taskId);\n rootSpan.setAttribute(\"apo.task.run.id\", taskRunId);\n }\n\n const runId = rootSpan.spanContext().traceId;\n const rootSpanId = rootSpan.spanContext().spanId;\n activeSpans.set(rootSpanId, {\n span: rootSpan,\n startedAt: monotonicNowMs(),\n model: \"trace\",\n });\n\n let callCount = 1;\n let rootEnded = false;\n\n const traceContext: TraceRunContext = {\n runId,\n rootSpanId,\n async step<TStep>(\n options: TraceStepOptions,\n stepFn: (spanId: string) => Promise<TStep>,\n ): Promise<TStep> {\n const spanId = createSpan({\n ...options,\n project,\n task_id: options.task_id ?? taskId,\n run_id: runId,\n parent_call_id: options.parent_call_id ?? rootSpanId,\n flow_name: options.flow_name ?? flowName,\n });\n const startedAt = monotonicNowMs();\n const activeSpan = activeSpans.get(spanId);\n\n // Activate this span in context so nested step()/traceTool() calls\n // inside stepFn see it as their parent (correct nesting hierarchy).\n const ctxWithSpan = activeSpan\n ? trace.setSpan(context.active(), activeSpan.span)\n : context.active();\n\n try {\n const result = await context.with(ctxWithSpan, () => stepFn(spanId));\n endSpan({\n id: spanId,\n latency_ms: round3(monotonicNowMs() - startedAt),\n output: options.summarize?.(result),\n metadata: options.metadata,\n });\n callCount += 1;\n return result;\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n endSpan({\n id: spanId,\n latency_ms: round3(monotonicNowMs() - startedAt),\n output: { error: message },\n status_message: message,\n level: \"ERROR\",\n metadata: { ...options.metadata, failed: true },\n });\n throw error;\n }\n },\n recordEvent(options: TraceEventOptions): string {\n const spanId = createSpan({\n ...options,\n project,\n task_id: options.task_id ?? taskId,\n run_id: runId,\n parent_call_id: options.parent_call_id ?? rootSpanId,\n flow_name: options.flow_name ?? flowName,\n });\n endSpan({\n id: spanId,\n latency_ms: options.latency_ms,\n output: options.output,\n metadata: options.metadata,\n });\n callCount += 1;\n return spanId;\n },\n endRoot(endParams?: Omit<EndSpanParams, \"id\">): void {\n if (rootEnded) return;\n endSpan({ id: rootSpanId, ...endParams });\n rootEnded = true;\n },\n // Non-LLM tracing helpers — these create spans through the same tracer\n async traceTool<TN>(name: string, params: Record<string, unknown>, fn: () => Promise<TN>): Promise<TN> {\n const spanId = createSpan({\n project, task_id: taskId, run_id: runId, parent_call_id: rootSpanId,\n flow_name: flowName, step_name: `tool ${name}`,\n observation_type: \"TOOL\", model: \"unknown\",\n input: params,\n });\n try {\n const result = await fn();\n endSpan({ id: spanId, output: result as Record<string, unknown> });\n callCount += 1;\n return result;\n } catch (error) {\n const msg = error instanceof Error ? error.message : String(error);\n endSpan({ id: spanId, output: { error: msg }, status_message: msg, level: \"ERROR\" });\n throw error;\n }\n },\n async traceRetriever<TN>(query: string, fn: () => Promise<TN>): Promise<TN> {\n const spanId = createSpan({\n project, task_id: taskId, run_id: runId, parent_call_id: rootSpanId,\n flow_name: flowName, step_name: \"retrieve\", observation_type: \"RETRIEVER\",\n model: \"unknown\", input: { query },\n });\n try { const r = await fn(); endSpan({ id: spanId, output: r as Record<string, unknown> }); callCount += 1; return r; }\n catch (e) { const m = e instanceof Error ? e.message : String(e); endSpan({ id: spanId, output: { error: m }, level: \"ERROR\" }); throw e; }\n },\n async traceChain<TN>(name: string, fn: () => Promise<TN>): Promise<TN> {\n const spanId = createSpan({\n project, task_id: taskId, run_id: runId, parent_call_id: rootSpanId,\n flow_name: flowName, step_name: name, observation_type: \"CHAIN\", model: \"unknown\",\n });\n try { const r = await fn(); endSpan({ id: spanId, output: r as Record<string, unknown> }); callCount += 1; return r; }\n catch (e) { const m = e instanceof Error ? e.message : String(e); endSpan({ id: spanId, output: { error: m }, level: \"ERROR\" }); throw e; }\n },\n async traceAgent<TN>(name: string, fn: () => Promise<TN>): Promise<TN> {\n const spanId = createSpan({\n project, task_id: taskId, run_id: runId, parent_call_id: rootSpanId,\n flow_name: flowName, step_name: name, observation_type: \"AGENT\", model: \"unknown\",\n });\n try { const r = await fn(); endSpan({ id: spanId, output: r as Record<string, unknown> }); callCount += 1; return r; }\n catch (e) { const m = e instanceof Error ? e.message : String(e); endSpan({ id: spanId, output: { error: m }, level: \"ERROR\" }); throw e; }\n },\n async traceGuardrail<TN>(name: string, fn: () => Promise<TN>): Promise<TN> {\n const spanId = createSpan({\n project, task_id: taskId, run_id: runId, parent_call_id: rootSpanId,\n flow_name: flowName, step_name: name, observation_type: \"GUARDRAIL\", model: \"unknown\",\n });\n try { const r = await fn(); endSpan({ id: spanId, output: r as Record<string, unknown> }); callCount += 1; return r; }\n catch (e) { const m = e instanceof Error ? e.message : String(e); endSpan({ id: spanId, output: { error: m }, level: \"ERROR\" }); throw e; }\n },\n async traceEmbedding<TN>(model: string, input: unknown, fn: () => Promise<TN>): Promise<TN> {\n const spanId = createSpan({\n project, task_id: taskId, run_id: runId, parent_call_id: rootSpanId,\n flow_name: flowName, step_name: \"embedding\", observation_type: \"EMBEDDING\", model,\n input: { value: input },\n });\n try { const r = await fn(); endSpan({ id: spanId, output: r as Record<string, unknown> }); callCount += 1; return r; }\n catch (e) { const m = e instanceof Error ? e.message : String(e); endSpan({ id: spanId, output: { error: m }, level: \"ERROR\" }); throw e; }\n },\n async score(scoreParams: CreateScoreParams): Promise<void> {\n // Scores are domain records via the score API\n const { score: scoreFn } = await import(\"../otel/index.ts\");\n const scoreHeaders = config.headers\n ?? (config.authToken ? { Authorization: `Bearer ${config.authToken}` } : {});\n await scoreFn(\n { traceId: runId, ...scoreParams },\n { endpoint: config.endpoint, headers: scoreHeaders },\n );\n },\n };\n\n // Add createSpan/endSpan for the AgentTaskTraceContext interface\n const agentTaskContext = {\n ...traceContext,\n createSpan(options: Omit<CreateSpanParams, \"project\" | \"run_id\">): string {\n const spanId = createSpan({\n ...options,\n project,\n run_id: runId,\n task_id: options.task_id ?? taskId,\n flow_name: options.flow_name ?? flowName,\n });\n callCount += 1;\n return spanId;\n },\n endSpan(spanId: string, endParams?: Omit<EndSpanParams, \"id\">): void {\n endSpan({ id: spanId, ...endParams });\n },\n };\n\n // Activate the root span in the OTel context so child spans created via\n // createSpan() (which calls tracer.startSpan) automatically inherit it\n // as their parent. This is standard OTel context propagation — no manual\n // parent_span_id passing needed.\n return context.with(trace.setSpan(context.active(), rootSpan), async () => {\n let result: T | undefined;\n let runError: unknown;\n try {\n result = await fn(agentTaskContext);\n agentTaskContext.endRoot();\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n agentTaskContext.endRoot({\n output: { error: message },\n status_message: message,\n level: \"ERROR\",\n metadata: { failed: true },\n });\n runError = error;\n }\n\n let flushError: unknown;\n if (myHandle) {\n try {\n await myHandle.forceFlush();\n } catch (error) {\n flushError = error;\n }\n await myHandle.shutdown();\n myHandle = null;\n }\n if (runError !== undefined) throw runError;\n if (flushError !== undefined && config.requirePersistence) {\n const detail = flushError instanceof Error\n ? flushError.message\n : String(flushError);\n throw new Error(`OTLP trace persistence failed: ${detail}`);\n }\n return result as T;\n });\n },\n };\n}\n","import { runTask } from \"./run/runTask.ts\";\nimport type { EvaluationItemResult } from \"./run/types.ts\";\nimport type { AgentTaskRunConfiguration } from \"./adapter/types.ts\";\nimport { loadTask } from \"./task/loadTask.ts\";\nimport type { JudgeConfig } from \"./checks/t.ts\";\nimport { createOtelAgentTaskTraceClient } from \"./otel-trace-client.ts\";\nimport type { AgentTaskTraceOptions } from \"./tracing.ts\";\n\nexport type AgentTaskRuntime = {\n judge?: JudgeConfig;\n};\n\nexport type AgentTaskRunSummary = {\n taskDir: string;\n taskId: string;\n pass: boolean;\n checks: EvaluationItemResult[];\n /** Adapter that ran the task. Forwarded to the backend when recording locally. */\n adapterName?: string;\n /** Trace id this run claimed (when tracing was enabled). */\n traceRunId?: string;\n /** Deliverables the adapter produced. */\n deliverables?: Record<string, unknown>;\n /** Per-turn transcript of the run. */\n transcript?: Record<string, unknown>;\n /** adapter-reported model/effort, forwarded when recording locally. */\n runConfiguration?: AgentTaskRunConfiguration;\n};\n\nexport async function loadTaskRuntime(\n _taskDir: string,\n): Promise<AgentTaskRuntime> {\n return {\n judge: resolveJudgeFromEnv(),\n };\n}\n\nfunction resolveJudgeFromEnv(): JudgeConfig | undefined {\n const openRouterModel = process.env.OPENROUTER_MODEL;\n const model = openRouterModel ?? process.env.OPENAI_MODEL;\n if (!model) return undefined;\n\n return {\n model,\n baseURL: openRouterModel\n ? process.env.OPENROUTER_BASE_URL\n : process.env.OPENAI_BASE_URL ?? \"https://api.openai.com/v1\",\n apiKey: openRouterModel\n ? process.env.OPENROUTER_API_KEY\n : process.env.OPENAI_API_KEY,\n };\n}\n\nexport async function runTaskDir(\n taskDir: string,\n): Promise<AgentTaskRunSummary> {\n const [loaded, runtime] = await Promise.all([\n loadTask(taskDir),\n loadTaskRuntime(taskDir),\n ]);\n\n // Set up OTel tracing for CLI-driven task runs.\n // The backend subprocess (runner-entry.ts) does its own setup;\n // this covers the CLI path (runAgentTaskCli → runTaskDir).\n // Falls back to noop tracing when no endpoint is configured (e.g. tests).\n const endpoint = process.env.AGENT_TASK_TRACE_ENDPOINT;\n const hasTracing = endpoint && process.env.AGENT_TASK_PROJECT;\n // When the backend pre-created the task run (external execution mode,\n // Issue #4), stamping apo.task.run.id on the root span lets the existing\n // claim machinery atomically link this trace to the run row. Mirrors\n // runner-entry.ts — never trust telemetry alone for ownership.\n const taskRunId = process.env.AGENT_TASK_RUN_ID;\n\n const tracing = hasTracing\n ? {\n client: createOtelAgentTaskTraceClient({\n endpoint,\n project: process.env.AGENT_TASK_PROJECT!,\n headers: _buildAuthHeaders(),\n }),\n project: process.env.AGENT_TASK_PROJECT!,\n environment: process.env.AGENT_TASK_ENVIRONMENT ?? \"default\",\n ...(taskRunId ? { taskRunId } : {}),\n } as AgentTaskTraceOptions\n : undefined;\n\n // Thread the already-loaded task through so runTask does not re-import the\n // eval module (Issue #7). loadTask above copied the eval to a temp file and\n // imported it once with all registries reset; a second loadTask would run\n // the eval's top level again and silently break evals whose load-time\n // behavior is not idempotent across module systems.\n const result = await runTask(taskDir, { ...runtime, tracing, loaded });\n\n return {\n taskDir: loaded.taskDir,\n taskId: loaded.task.id,\n pass: result.result.pass,\n checks: result.result.checks,\n adapterName: loaded.adapter.name,\n traceRunId: result.traceRunId,\n deliverables: result.deliverables,\n transcript: result.transcript as unknown as Record<string, unknown>,\n runConfiguration: result.runConfiguration,\n };\n}\n\nfunction _buildAuthHeaders(): Record<string, string> | undefined {\n const pk = process.env.APO_PUBLIC_KEY;\n const sk = process.env.APO_SECRET_KEY;\n if (pk && sk) {\n const creds = typeof btoa === \"function\"\n ? btoa(`${pk}:${sk}`)\n : Buffer.from(`${pk}:${sk}`).toString(\"base64\");\n return { Authorization: `Basic ${creds}` };\n }\n const token = process.env.APO_AUTH_TOKEN;\n if (token) {\n return { Authorization: `Bearer ${token}` };\n }\n return undefined;\n}\n","/**\n * canonical Task Revision manifest.\n *\n * Pure, dependency-free canonicalizer. Both this module and its Python twin\n * (`backend/apo/execution/task_revision_manifest.py`) MUST produce\n * byte-identical canonical JSON and digests for every fixture under\n * `specs/contracts/task-revision/v1/cases/`.\n *\n * Canonicalization rules:\n * - `/` path separators (caller `\\` normalized to `/`);\n * - Unicode NFC normalization of the path;\n * - bytewise lexical ordering of normalized UTF-8 paths (NOT UTF-16 —\n * diverges for codepoints > U+007F);\n * - exact file-byte SHA-256 (lowercase hex);\n * - mode reduced to `regular` | `executable`;\n * - ownership, timestamps, inode metadata, and absolute paths excluded.\n *\n * `contentSha256` is the SHA-256 of the compact canonical JSON built from\n * `schemaVersion` and the sorted `files` array. The `summary` block is NOT\n * part of source identity.\n */\n\nimport { createHash } from \"node:crypto\";\n\nexport type ModeClass = \"regular\" | \"executable\";\n\nexport interface ManifestFile {\n path: string;\n sizeBytes: number;\n sha256: string;\n modeClass: ModeClass;\n}\n\nexport interface TaskRevisionManifestV1 {\n schemaVersion: 1;\n files: ManifestFile[];\n summary: {\n fileCount: number;\n uncompressedSizeBytes: number;\n excludedFileCount: number;\n excludedDirectoryCount: number;\n };\n}\n\n/** Caller-reported file, before canonicalization. `content` is the exact bytes. */\nexport interface ManifestFileInput {\n path: string;\n modeClass: ModeClass;\n content: Uint8Array;\n}\n\n/**\n * Normalize a caller-reported path to canonical POSIX + NFC form.\n * Validation (no leading slash, no `.`/`..` segments) is the filesystem\n * walker's responsibility; this function only makes representation canonical.\n */\nexport function normalizeManifestPath(path: string): string {\n return path.split(\"\\\\\").join(\"/\").normalize(\"NFC\");\n}\n\n/** SHA-256 of exact bytes, lowercase hex. */\nexport function sha256Hex(bytes: Uint8Array): string {\n return createHash(\"sha256\").update(bytes).digest(\"hex\");\n}\n\n/** Compare two UTF-8 strings by their raw byte ordering (not UTF-16 code units). */\nfunction compareBytewiseUtf8(a: string, b: string): number {\n const ba = Buffer.from(a, \"utf8\");\n const bb = Buffer.from(b, \"utf8\");\n for (let i = 0; i < Math.min(ba.length, bb.length); i++) {\n if (ba[i]! !== bb[i]!) return ba[i]! < bb[i]! ? -1 : 1;\n }\n return ba.length - bb.length;\n}\n\n/**\n * Build the canonical V1 manifest from already-included files. Exclusion\n * counts default to zero; the filesystem walker supplies real counts when it\n * wraps this via `withExclusionCounts`.\n */\nexport function buildManifest(\n files: ManifestFileInput[],\n summary?: { excludedFileCount: number; excludedDirectoryCount: number },\n): TaskRevisionManifestV1 {\n const entries = files.map((f) => {\n const path = normalizeManifestPath(f.path);\n return {\n path,\n sizeBytes: f.content.byteLength,\n sha256: sha256Hex(f.content),\n modeClass: f.modeClass,\n } satisfies ManifestFile;\n });\n\n entries.sort((a, b) => compareBytewiseUtf8(a.path, b.path));\n\n return {\n schemaVersion: 1,\n files: entries,\n summary: {\n fileCount: entries.length,\n uncompressedSizeBytes: entries.reduce((n, f) => n + f.sizeBytes, 0),\n excludedFileCount: summary?.excludedFileCount ?? 0,\n excludedDirectoryCount: summary?.excludedDirectoryCount ?? 0,\n },\n };\n}\n\n/**\n * Compact canonical JSON over `schemaVersion` + the sorted `files` array only.\n * Object keys are alphabetical at every level; no whitespace; non-ASCII\n * emitted as UTF-8 (matches Python `json.dumps(sort_keys=True,\n * ensure_ascii=False, separators=(\",\", \":\"))`). The `summary` block is\n * intentionally excluded from source identity.\n */\nexport function canonicalManifestJson(manifest: TaskRevisionManifestV1): string {\n const filesPayload = manifest.files.map((f) => ({\n modeClass: f.modeClass,\n path: f.path,\n sha256: f.sha256,\n sizeBytes: f.sizeBytes,\n }));\n return JSON.stringify({ files: filesPayload, schemaVersion: manifest.schemaVersion });\n}\n\n/** SHA-256 (lowercase hex) of the canonical manifest JSON's UTF-8 bytes. */\nexport function contentSha256(manifest: TaskRevisionManifestV1): string {\n return sha256Hex(Buffer.from(canonicalManifestJson(manifest), \"utf8\"));\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;AA0DA,SAAS,mBAAmB,KAA2D;AACrF,QAAM,QAAQ,IAAI,aAAa,OAAO,IAAI;AAC1C,SAAO,CAAC,OAAO,IAAI,aAAa,IAAI,IAAI,MAAM;AAChD;AAEO,IAAM,YAAN,MAAgB;AAAA,EAGrB,YAAY,UAAmC;AAC7C,SAAK,WAAW;AAAA,EAClB;AAAA;AAAA,EAGA,kBACE,YACsB;AACtB,WAAO,KAAK,SAAS,aAAa,UAAU;AAAA,EAC9C;AAAA;AAAA,EAGQ,YAAY,YAAwD;AAC1E,WAAO,KAAK,SAAS,aAAa,UAAU,MAAM;AAAA,EACpD;AAAA;AAAA,EAGA,IAAI,WAA8C;AAChD,UAAM,MAAgC,CAAC;AACvC,eAAW,OAAO,KAAK,oBAAoB;AACzC,UAAI,IAAI,SAAU,KAAI,KAAK,GAAG,IAAI,QAAQ;AAAA,IAC5C;AACA,WAAO;AAAA,EACT;AAAA;AAAA,EAGA,IAAI,YAAsC;AACxC,WAAO,KAAK,mBACT,OAAO,CAAC,MAA0D,EAAE,SAAS,MAAM,EACnF,IAAI,CAAC,OAAO;AAAA,MACX,QAAQ,EAAE;AAAA,MACV,MAAM,EAAE,YAAY,EAAE;AAAA,MACtB,OAAO,EAAE,kBAAkB,EAAE;AAAA,MAC7B,QAAQ,EAAE,cAAc,EAAE;AAAA,MAC1B,QAAQ,EAAE;AAAA,MACV,WAAW,EAAE;AAAA,IACf,EAAE;AAAA,EACN;AAAA;AAAA,EAGA,IAAI,mBAAsC;AACxC,WAAO,KAAK,UAAU,IAAI,CAAC,MAAM,EAAE,IAAI;AAAA,EACzC;AAAA;AAAA,EAGA,IAAI,aAAwC;AAC1C,WAAO,KAAK,mBACT,OAAO,CAAC,MAA2D,EAAE,SAAS,OAAO,EACr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A,IAC7D;AAAA,EACF;AACF;AASO,SAAS,sBAAsB,UAA0C;AAC9E,QAAM,eAAe,SAAS,MAAM,IAAI,CAAC,OAAO;AAAA,IAC9C,WAAW,EAAE;AAAA,IACb,MAAM,EAAE;AAAA,IACR,QAAQ,EAAE;AAAA,IACV,WAAW,EAAE;AAAA,EACf,EAAE;AACF,SAAO,KAAK,UAAU,EAAE,OAAO,cAAc,eAAe,SAAS,cAAc,CAAC;AACtF;AAGO,SAAS,cAAc,UAA0C;AACtE,SAAO,UAAU,OAAO,KAAK,sBAAsB,QAAQ,GAAG,MAAM,CAAC;AACvE;","names":["task","task","copyFileSync","existsSync","unlinkSync","basename","pathToFileURL","task","basename","copyFileSync","pathToFileURL","existsSync","unlinkSync","basename","statSync","resolve","task","trace","resolve","trace","task","result","resolve","existsSync","readdirSync","statSync","join","resolve","monotonicNowMs","round3","params","fn","resolve","createHash"]}
|
|
1
|
+
{"version":3,"sources":["../../src/agent-task/trace-projection/view.ts","../../src/agent-task/checks/matchers.ts","../../src/agent-task/checks/judge.ts","../../src/agent-task/checks/t.ts","../../src/agent-task/checks/recorder.ts","../../src/agent-task/checks/location.ts","../../src/agent-task/checks/flow-runner.ts","../../src/agent-task/task/defineTask.ts","../../src/agent-task/task/loadTask.ts","../../src/agent-task/turn.ts","../../src/agent-task/task/TaskFiles.ts","../../src/agent-task/adapter/defineAdapter.ts","../../src/agent-task/deliverables/artifact.ts","../../src/agent-task/deliverables/upload.ts","../../src/agent-task/flow/view.ts","../../src/agent-task/flow/sources.ts","../../src/agent-task/run/run-configuration.ts","../../src/agent-task/deliverables/validate.ts","../../src/agent-task/trace-projection/projection-tee.ts","../../src/agent-task/trace-projection/remote-capture.ts","../../src/semconv.ts","../../src/agent-task/run/aggregate.ts","../../src/agent-task/tracing.ts","../../src/agent-task/run/runTask.ts","../../src/agent-task/run/rejudge.ts","../../src/agent-task/cli.ts","../../src/agent-task/discovery.ts","../../src/agent-task/otel-trace-client.ts","../../src/agent-task/task-runtime.ts","../../src/agent-task/task-revision-manifest.ts"],"sourcesContent":["/**\n * TraceView — typed, capability-gated, derived access over a\n * {@link TraceProjectionSnapshot}. This is the read model the projection-first\n * assertion surface queries. It is the projection analogue of `FlowView`.\n *\n * The defining difference from `FlowView` is **capability honesty**: when the\n * snapshot declares a category of evidence `unavailable`, the derived numeric\n * facts (`durationMs`, `failedActions`, `turnCount`) return `undefined` rather\n * than zero — so an assertion like `t.maxDurationMs` can record an explicit\n * `unsupported` outcome instead of vacuously passing against a fabricated 0ms.\n *\n * `toolNamesInOrder` sorts by observation invocation time (`startedAt`) with a\n * deterministic span-ID tie-breaker — NOT array/completion order. This fixes\n * the drift where concurrent tools appeared in completion order.\n */\n\nimport type {\n EvidenceAvailability,\n ObservationStatus,\n TraceProjectionCapabilities,\n TraceProjectionMessage,\n TraceProjectionObservation,\n TraceProjectionSnapshot,\n} from \"./types.ts\";\n\n/** A tool call derived from a `TOOL` observation. */\nexport interface TraceToolCall {\n spanId: string;\n name: string;\n input?: unknown;\n output?: unknown;\n status: ObservationStatus;\n startedAt?: string;\n}\n\n/** A skill load derived from a `SKILL` observation. */\nexport interface TraceSkillLoad {\n spanId: string;\n skill: string;\n startedAt?: string;\n}\n\n/** A subagent delegation derived from an `AGENT` observation. */\nexport interface TraceSubagentCall {\n spanId: string;\n agent: string;\n output?: unknown;\n status: ObservationStatus;\n startedAt?: string;\n}\n\n/** Sentinel that sorts before every real timestamp in string comparison. */\nconst TIMESTAMPED_MIN = \"\";\n\n/**\n * Comparison key for deterministic ordering by invocation time then span ID.\n * Missing `startedAt` sorts AFTER every timestamped observation.\n */\nfunction invocationOrderKey(obs: TraceProjectionObservation): [number, string, string] {\n const hasTs = obs.startedAt != null ? 0 : 1;\n return [hasTs, obs.startedAt ?? \"\", obs.spanId];\n}\n\nexport class TraceView {\n readonly snapshot: TraceProjectionSnapshot;\n\n constructor(snapshot: TraceProjectionSnapshot) {\n this.snapshot = snapshot;\n }\n\n /** Evidence availability for a capability. */\n requireCapability(\n capability: keyof TraceProjectionCapabilities,\n ): EvidenceAvailability {\n return this.snapshot.capabilities[capability];\n }\n\n /** Whether a capability is reported as available (not partial/unavailable). */\n private isAvailable(capability: keyof TraceProjectionCapabilities): boolean {\n return this.snapshot.capabilities[capability] === \"available\";\n }\n\n /** All chat messages flattened across generation observations, in order. */\n get messages(): readonly TraceProjectionMessage[] {\n const out: TraceProjectionMessage[] = [];\n for (const obs of this.sortedObservations) {\n if (obs.messages) out.push(...obs.messages);\n }\n return out;\n }\n\n /** Tool calls derived from `TOOL` observations, in invocation order. */\n get toolCalls(): readonly TraceToolCall[] {\n return this.sortedObservations\n .filter((o): o is TraceProjectionObservation & { type: \"TOOL\" } => o.type === \"TOOL\")\n .map((o) => ({\n spanId: o.spanId,\n name: o.toolName ?? o.name,\n input: o.toolParameters ?? o.input,\n output: o.toolResult ?? o.output,\n status: o.status,\n startedAt: o.startedAt,\n }));\n }\n\n /** Tool names in invocation order with deterministic span-ID tie-breaking. */\n get toolNamesInOrder(): readonly string[] {\n return this.toolCalls.map((c) => c.name);\n }\n\n /** Skill loads derived from `SKILL` observations, in invocation order. */\n get skillLoads(): readonly TraceSkillLoad[] {\n return this.sortedObservations\n .filter((o): o is TraceProjectionObservation & { type: \"SKILL\" } => o.type === \"SKILL\")\n .map((o) => ({ spanId: o.spanId, skill: o.name, startedAt: o.startedAt }));\n }\n\n /** Subagent delegations derived from `AGENT` observations, in invocation order. */\n get subagentCalls(): readonly TraceSubagentCall[] {\n return this.sortedObservations\n .filter((o): o is TraceProjectionObservation & { type: \"AGENT\" } => o.type === \"AGENT\")\n .map((o) => ({\n spanId: o.spanId,\n agent: o.name,\n output: o.output,\n status: o.status,\n startedAt: o.startedAt,\n }));\n }\n\n /** Last assistant message content — the agent's \"reply\". Empty if none. */\n get reply(): string {\n const msgs = this.messages;\n for (let i = msgs.length - 1; i >= 0; i--) {\n if (msgs[i]!.role === \"assistant\") return msgs[i]!.content;\n }\n return \"\";\n }\n\n /**\n * Number of completed assistant turns, or `undefined` when message evidence\n * is unavailable (capability honesty).\n */\n get turnCount(): number | undefined {\n if (!this.isAvailable(\"messages\")) return undefined;\n return this.messages.filter((m) => m.role === \"assistant\").length;\n }\n\n /**\n * Number of tool/subagent observations that reported an error, or `undefined`\n * when error evidence is unavailable (capability honesty).\n */\n get failedActions(): number | undefined {\n if (!this.isAvailable(\"errors\")) return undefined;\n return this.sortedObservations.filter(\n (o) => (o.type === \"TOOL\" || o.type === \"AGENT\") && o.status === \"error\",\n ).length;\n }\n\n /**\n * Total execution duration in milliseconds, or `undefined` when timing\n * evidence is unavailable (capability honesty). Uses trace-level\n * startedAt/endedAt when present.\n */\n get durationMs(): number | undefined {\n if (!this.isAvailable(\"timing\")) return undefined;\n const { startedAt, endedAt } = this.snapshot.trace;\n if (startedAt != null && endedAt != null) {\n const ms = Date.parse(endedAt) - Date.parse(startedAt);\n return Number.isNaN(ms) ? undefined : Math.max(0, ms);\n }\n return undefined;\n }\n\n /**\n * Observations sorted deterministically by invocation time then span ID.\n * Memoized per TraceView instance since the snapshot is immutable.\n */\n private get sortedObservations(): readonly TraceProjectionObservation[] {\n if (this._sorted !== undefined) return this._sorted;\n // Copy to a mutable array, then sort by invocation key: missing timestamps\n // (key prefix 1) sort after timestamped ones (prefix 0), then by span ID\n // for determinism.\n const sorted = [...this.snapshot.observations].sort((a, b) => {\n const ka = invocationOrderKey(a);\n const kb = invocationOrderKey(b);\n return (\n ka[0] - kb[0] ||\n ka[1].localeCompare(kb[1]) ||\n ka[2].localeCompare(kb[2])\n );\n });\n this._sorted = sorted;\n return sorted;\n }\n private _sorted: readonly TraceProjectionObservation[] | undefined;\n}\n\n// Keep the timestamp sentinel referenced for clarity — documents that empty\n// string is the \"earliest\" timestamp in lexicographic ordering.\nvoid TIMESTAMPED_MIN;\n","/**\n * Value matchers for `t.check(value, matcher)`. Small, composable, and the\n * single way to assert on deliverables/values (replaces the old `expect`).\n *\n * A matcher is just `{ label, test }` — easy to build custom ones inline with\n * `satisfies(fn, label)`.\n */\n\nexport type Matcher<T> = { label: string; test: (value: T) => boolean };\n\nfunction asString(value: unknown): string {\n if (typeof value === \"string\") return value;\n if (value === undefined) return \"undefined\";\n if (value === null) return \"null\";\n try {\n return JSON.stringify(value);\n } catch {\n return String(value);\n }\n}\n\n/** Serialize any value for compact \"Received:\" display. */\nexport function describeValue(value: unknown): string {\n return asString(value);\n}\n\nfunction escapeRegExp(s: string): string {\n return s.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\");\n}\n\nfunction deepEqual(a: unknown, b: unknown): boolean {\n if (a === b) return true;\n if (a === null || b === null || typeof a !== \"object\" || typeof b !== \"object\") {\n return false;\n }\n if (Array.isArray(a) !== Array.isArray(b)) return false;\n if (Array.isArray(a) && Array.isArray(b)) {\n if (a.length !== b.length) return false;\n return a.every((v, i) => deepEqual(v, b[i]));\n }\n const ao = a as Record<string, unknown>;\n const bo = b as Record<string, unknown>;\n const ak = Object.keys(ao);\n const bk = Object.keys(bo);\n if (ak.length !== bk.length) return false;\n return ak.every(\n (k) => Object.prototype.hasOwnProperty.call(bo, k) && deepEqual(ao[k], bo[k]),\n );\n}\n\n/** Coerces the value to a string and checks it contains a substring or RegExp. Gate. */\nexport function includes(needle: string | RegExp): Matcher<unknown> {\n const re = typeof needle === \"string\" ? new RegExp(escapeRegExp(needle)) : needle;\n return {\n label: `includes ${needle instanceof RegExp ? needle.source : needle}`,\n test: (v) => re.test(asString(v)),\n };\n}\n\n/** Deep structural equality. Gate. */\nexport function equals<T>(expected: T): Matcher<T> {\n return {\n label: `equals ${asString(expected)}`,\n test: (v) => deepEqual(v, expected),\n };\n}\n\n/**\n * Validates against a Standard-Schema-shaped validator (Zod, Valibot, …) —\n * anything exposing `safeParse`. Gate.\n */\nexport function matches<T = unknown>(\n schema: {\n safeParse: (value: unknown) => { success: boolean };\n },\n): Matcher<T> {\n return {\n label: \"matches schema\",\n test: (v) => schema.safeParse(v).success === true,\n };\n}\n\n/** Custom boolean predicate. Gate. */\nexport function satisfies<T>(\n predicate: (value: T) => boolean,\n label: string,\n): Matcher<T> {\n return { label, test: predicate };\n}\n\n// ── Value matching (for tool-call input/output fields) ───────────────────\n// A value can be matched by a literal (partial-deep for objects), a RegExp\n// (string-coerced), or a predicate function. Used by calledTool/notCalledTool\n// to match a tool call's input/output/status.\n\nexport type ValueMatcher<T> = T | RegExp | ((value: T) => boolean);\n\nexport function matchValue<T>(actual: T, matcher: ValueMatcher<T>): boolean {\n if (matcher instanceof RegExp) return matcher.test(asString(actual));\n if (typeof matcher === \"function\") {\n return (matcher as (value: T) => boolean)(actual);\n }\n if (matcher !== null && typeof matcher === \"object\") {\n // Partial-deep match: every key on the matcher must be present and match.\n if (actual === null || typeof actual !== \"object\") return false;\n const a = actual as Record<string, unknown>;\n const m = matcher as Record<string, unknown>;\n return Object.keys(m).every(\n (k) =>\n Object.prototype.hasOwnProperty.call(a, k) && matchValue(a[k], m[k]),\n );\n }\n return deepEqual(actual, matcher);\n}\n\n// ── Fuzzy similarity ─────────────────────────────────────────────────────\n\n/** Normalized Levenshtein similarity. Pass when score ≥ threshold (default 0.8). */\nexport function similarity(expected: string, threshold = 0.8): Matcher<unknown> {\n return {\n label: `similar to \"${expected}\" (≥ ${threshold})`,\n test: (v) => normalizedSimilarity(asString(v), expected) >= threshold,\n };\n}\n\nfunction normalizedSimilarity(a: string, b: string): number {\n const maxLen = Math.max(a.length, b.length);\n if (maxLen === 0) return 1;\n return 1 - levenshtein(a, b) / maxLen;\n}\n\nfunction levenshtein(a: string, b: string): number {\n const m = a.length;\n const n = b.length;\n if (m === 0) return n;\n if (n === 0) return m;\n let prev = Array.from({ length: n + 1 }, () => 0);\n let curr = Array.from({ length: n + 1 }, () => 0);\n for (let j = 0; j <= n; j++) prev[j] = j;\n for (let i = 1; i <= m; i++) {\n curr[0] = i;\n for (let j = 1; j <= n; j++) {\n const cost = a[i - 1] === b[j - 1] ? 0 : 1;\n curr[j] = Math.min(prev[j] + 1, curr[j - 1] + 1, prev[j - 1] + cost);\n }\n [prev, curr] = [curr, prev];\n }\n return prev[n];\n}\n","/**\n * LLM-as-judge call. Used by `t.judge(values, instruction)` to evaluate\n * deliverables against a natural-language rubric. Calls an OpenAI-compatible\n * endpoint (OpenRouter, OpenAI, etc.) via fetch and parses the verdict.\n */\n\nimport type { JudgeMetadata } from \"../run/types.ts\";\n\nexport type JudgeCallResult = {\n pass: boolean;\n reasoning: string;\n judge: JudgeMetadata;\n};\n\nconst JUDGE_SYSTEM_PROMPT =\n \"You are an evaluation judge. Evaluate the given value(s) against the \" +\n 'instruction. Respond with ONLY a JSON object: {\"pass\": true/false, \"reasoning\": \"your reasoning\"}';\n\nfunction formatValue(value: unknown, depth = 0): string {\n const indent = \" \".repeat(depth);\n if (value === null || value === undefined) return String(value);\n if (typeof value === \"string\") return value;\n if (typeof value === \"number\" || typeof value === \"boolean\") return String(value);\n if (Array.isArray(value)) {\n return value\n .map((item) => `${indent}${formatValue(item, depth + 1)}`)\n .join(\"\\n\");\n }\n if (typeof value === \"object\") {\n return Object.entries(value as Record<string, unknown>)\n .map(([key, val]) => {\n if (val && typeof val === \"object\") {\n return `${indent}${key}:\\n${formatValue(val, depth + 1)}`;\n }\n return `${indent}${key}: ${formatValue(val, depth + 1)}`;\n })\n .join(\"\\n\");\n }\n return String(value);\n}\n\nfunction formatJudgeValues(values: unknown[]): string {\n if (values.length === 1) return formatValue(values[0]);\n return values\n .map((v, i) => `--- Value ${i + 1} ---\\n${formatValue(v)}`)\n .join(\"\\n\\n\");\n}\n\n/**\n * Tolerantly parse the judge model's response into `{pass, reasoning}`.\n *\n * Despite `response_format: json_object`, models sometimes wrap output in\n * markdown code fences (```` ```json … ``` ````) or add surrounding prose.\n * Falling back to a raw `\"invalid JSON\"` string on the first parse failure\n * buries the verdict and reasoning the user actually needs. Instead: try the\n * raw text, strip fences, then extract the first balanced `{...}` block.\n */\n\n// Provider token usage for a judge call. Cached-prefix accounting arrives in\n// two shapes depending on the route: direct Anthropic exposes\n// cache_creation_input_tokens / cache_read_input_tokens, while OpenRouter\n// (and OpenAI) normalize them into prompt_tokens_details.cache_write_tokens /\n// prompt_tokens_details.cached_tokens. Their presence proves the cached\n// deliverable prefix was written once and read on subsequent criteria (#21).\ntype JudgeUsage = {\n prompt_tokens?: number;\n completion_tokens?: number;\n cache_creation_input_tokens?: number;\n cache_read_input_tokens?: number;\n prompt_tokens_details?: {\n cached_tokens?: number;\n cache_write_tokens?: number;\n };\n};\n\ntype JudgeTokens = {\n input: number;\n output: number;\n cache_creation?: number;\n cache_read?: number;\n};\n\nfunction parseJudgeUsage(usage: JudgeUsage | undefined): JudgeTokens | undefined {\n if (!usage) return undefined;\n const cacheCreation =\n usage.cache_creation_input_tokens ?? usage.prompt_tokens_details?.cache_write_tokens;\n const cacheRead =\n usage.cache_read_input_tokens ?? usage.prompt_tokens_details?.cached_tokens;\n const tokens: JudgeTokens = {\n input: usage.prompt_tokens ?? 0,\n output: usage.completion_tokens ?? 0,\n };\n if (typeof cacheCreation === \"number\") tokens.cache_creation = cacheCreation;\n if (typeof cacheRead === \"number\") tokens.cache_read = cacheRead;\n return tokens;\n}\n\nfunction parseJudgeJson(raw: string): { pass?: boolean; reasoning?: string } {\n // 1. Direct parse (the common, well-behaved case).\n try {\n return JSON.parse(raw);\n } catch {\n // fall through to tolerant strategies\n }\n // 2. Strip a single markdown code fence: ```json\\n{...}\\n``` -> {...}.\n const fenced = raw.match(/```(?:json)?\\s*([\\s\\S]*?)```/);\n if (fenced) {\n try {\n return JSON.parse(fenced[1].trim());\n } catch {\n // fall through\n }\n }\n // 3. Pull the first balanced {...} block out of surrounding prose.\n const block = raw.match(/\\{[\\s\\S]*\\}/);\n if (block) {\n try {\n return JSON.parse(block[0]);\n } catch {\n // fall through\n }\n }\n // 4. Unparseable. The verdict is genuinely unknown, so we treat it as a\n // failure (can't confirm pass) and explain what happened in plain language.\n // Dumping the raw response as \"reasoning\" is unhelpful — it's usually a\n // truncated or malformed blob the model emitted, and presenting it as an\n // explanation misleads. The raw response stays available on the judge\n // metadata for anyone who needs to debug the model output itself.\n return {\n pass: false,\n reasoning:\n \"Judge response could not be parsed as JSON — the verdict is unknown, \" +\n \"so this check is treated as a failure. The model's raw response is \" +\n \"available in the judge metadata.\",\n };\n}\n\n/**\n * Per-prefix serialization. Checks run concurrently (flow-runner uses\n * Promise.all), so without coordination N criteria judging the same\n * deliverable would all dispatch against a cold cache and mostly miss. This\n * chains calls that share a cached prefix: the first warms the provider's\n * prompt cache and the rest dispatch only after it resolves (and hit it).\n * Calls with different prefixes are independent and stay concurrent.\n */\nconst prefixQueues = new Map<string, Promise<unknown>>();\n\nfunction runWithSharedPrefix<T>(key: string, task: () => Promise<T>): Promise<T> {\n const prev = prefixQueues.get(key) ?? Promise.resolve();\n // Run `task` once the previous same-prefix call settles, regardless of\n // whether it succeeded — a failed warmer must not block its siblings.\n const next = prev.then(task, task);\n // Keep the chain alive through errors so one rejection can't poison the queue.\n prefixQueues.set(\n key,\n next.then(\n () => undefined,\n () => undefined,\n ),\n );\n return next;\n}\n\nexport async function callJudge(args: {\n values: unknown[];\n instruction: string;\n model: string;\n baseURL?: string;\n apiKey?: string;\n}): Promise<JudgeCallResult> {\n const baseURL = args.baseURL ?? process.env.OPENROUTER_BASE_URL ?? \"https://openrouter.ai/api/v1\";\n const apiKey = args.apiKey ?? process.env.OPENROUTER_API_KEY ?? process.env.OPENAI_API_KEY;\n\n // Structure the request so the (often huge) deliverable is a cacheable\n // prefix and only the small per-criterion instruction varies. Many criteria\n // judge the same deliverable; without a cache breakpoint the deliverable is\n // re-billed in full on every call. cache_control is an Anthropic/Gemini\n // extension that OpenRouter passes through, and is ignored harmlessly by\n // providers without prompt caching. See issue #21.\n const deliverableText = `Values to evaluate:\\n${formatJudgeValues(args.values)}`;\n const instructionText = `Instruction:\\n${args.instruction}`;\n const systemPromptText = `${JUDGE_SYSTEM_PROMPT}\\n\\n${deliverableText}`;\n\n // The cached prefix is model + system blocks; the varying instruction lives\n // in the user message, so it's excluded from the key.\n const cacheKey = `${args.model}\\u0000${deliverableText}`;\n\n return runWithSharedPrefix(cacheKey, async () => {\n const startedAt = Date.now();\n\n const response = await fetch(`${baseURL}/chat/completions`, {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n ...(apiKey ? { Authorization: `Bearer ${apiKey}` } : {}),\n },\n body: JSON.stringify({\n model: args.model,\n messages: [\n {\n role: \"system\",\n content: [\n { type: \"text\", text: JUDGE_SYSTEM_PROMPT },\n {\n type: \"text\",\n text: deliverableText,\n cache_control: { type: \"ephemeral\" },\n },\n ],\n },\n { role: \"user\", content: instructionText },\n ],\n temperature: 0,\n response_format: { type: \"json_object\" },\n }),\n });\n\n if (!response.ok) {\n const body = await response.text().catch(() => \"\");\n throw new Error(`Judge API ${response.status}: ${body.slice(0, 200)}`);\n }\n\n const data = (await response.json()) as {\n choices?: Array<{ message?: { content?: string } }>;\n usage?: JudgeUsage;\n };\n\n const text = data.choices?.[0]?.message?.content ?? \"\";\n const outputTokens = data.usage?.completion_tokens;\n\n // Guard: a response that is empty, OR that the provider reports as having\n // generated zero output tokens, is a transient/provider failure — not a\n // model verdict. This happens when a provider cuts a stream mid-generation\n // and returns a stub like \"[\" with completion_tokens: 0. Treat it as a\n // failure with a clear explanation rather than feeding garbage to the\n // parser. (Only guard on tokens when the provider actually reported usage;\n // absent usage means \"unknown\", not \"zero\".)\n const isEmpty = !text.trim();\n const reportedZeroTokens = data.usage !== undefined && outputTokens === 0;\n if (isEmpty || reportedZeroTokens) {\n return {\n pass: false,\n reasoning:\n \"Judge returned an empty or truncated response — likely a transient \" +\n \"provider failure. The verdict is unknown, so this check is treated \" +\n \"as a failure.\",\n judge: {\n model: args.model,\n prompt: { system: systemPromptText, user: instructionText },\n response: text,\n tokens: parseJudgeUsage(data.usage),\n latency_ms: Date.now() - startedAt,\n },\n };\n }\n\n // Models routinely wrap their JSON in markdown fences (```json … ```) or\n // add prose around it despite the json_object response_format. Parse\n // tolerantly so the verdict + reasoning aren't lost to a parse error:\n // try the raw text, then strip fences, then extract the first {...}.\n const parsed = parseJudgeJson(text);\n\n return {\n pass: parsed.pass === true,\n reasoning: typeof parsed.reasoning === \"string\" ? parsed.reasoning : \"\",\n judge: {\n model: args.model,\n prompt: { system: systemPromptText, user: instructionText },\n response: text,\n tokens: parseJudgeUsage(data.usage),\n latency_ms: Date.now() - startedAt,\n },\n };\n });\n}\n","/**\n * The assertion surface — `t`. Flat and eve-style: reads the trace (via\n * {@link TraceView}) for behavioural checks and grades explicit values via\n * `t.check`. Everything records (never throws), so a check reports all of its\n * failures, not just the first.\n *\n * Every assertion records structured ``expected`` / ``received`` values so\n * the dashboard can render testing-framework-style failures (Expected /\n * Received) instead of only a prose message.\n */\n\nimport { TraceView } from \"../trace-projection/view.ts\";\nimport type { TraceProjectionCapabilities } from \"../trace-projection/types.ts\";\nimport type { AssertionOutcome } from \"../run/types.ts\";\nimport type { Recorder } from \"./recorder.ts\";\nimport type { Matcher, ValueMatcher } from \"./matchers.ts\";\nimport { describeValue, matchValue } from \"./matchers.ts\";\nimport { callJudge } from \"./judge.ts\";\n\n/** A tool/agent name matcher: literal (exact), RegExp, or predicate. */\nexport type NameMatcher = string | RegExp | ((name: string) => boolean);\n\n/** Options for matching tool calls by count and recorded fields. */\nexport type ToolCallOptions = {\n count?: number;\n input?: ValueMatcher<unknown>;\n output?: ValueMatcher<unknown>;\n status?: \"ok\" | \"error\";\n};\n\n/**\n * LLM judge model config for `t.judge(...)` calls in checks.ts. Threaded\n * through `runTask({ judge })` from the caller — the runner has no opinion\n * about which model grades a deliverable.\n */\nexport type JudgeConfig = {\n /** Model id, e.g. ``\"google/gemini-2.5-flash-lite\"``. */\n model: string;\n /** Override the OpenRouter/OpenAI-compatible base URL. */\n baseURL?: string;\n /** Override the API key (defaults to env). */\n apiKey?: string;\n};\n\n/**\n * Resolves the judge config for a single ``t.judge`` call: merges a per-call\n * ``opts.judge`` override onto the run-level ``judgeConfig``, field-by-field.\n * Returns ``undefined`` when the result has no model — callers should treat\n * that as \"no judge configured\" and record the env-setup guidance. (The model\n * is the only required field, so it's the one worth gating on.)\n */\nfunction resolveJudgeConfig(\n judgeConfig: JudgeConfig | undefined,\n override: Partial<JudgeConfig> | undefined,\n): JudgeConfig | undefined {\n const model = override?.model ?? judgeConfig?.model;\n if (!model) return undefined;\n return {\n model,\n baseURL: override?.baseURL ?? judgeConfig?.baseURL,\n apiKey: override?.apiKey ?? judgeConfig?.apiKey,\n };\n}\n\nexport interface TestContext {\n // ── trace / \"did it run well\" ──────────────────────────────────────────\n /** Asserts a matching tool was called. Pass `{ count }` for an exact count. */\n calledTool(name: NameMatcher, opts?: ToolCallOptions): void;\n /** Asserts no tool call matches the supplied name and field constraints. */\n notCalledTool(name: NameMatcher, opts?: Omit<ToolCallOptions, \"count\">): void;\n /** Asserts the named tools appear, in this order (as a subsequence). */\n toolOrder(names: string[]): void;\n /** Asserts no tool calls happened at all. */\n usedNoTools(): void;\n /** Asserts at most `n` tool calls — anti-flail. */\n maxToolCalls(n: number): void;\n /** Asserts no tool/subagent call reported an error — anti-flail. */\n noFailedActions(): void;\n /** Asserts a skill was loaded. */\n loadedSkill(skill: string): void;\n /** Asserts a subagent delegation happened. */\n calledSubagent(agent: string): void;\n /** Asserts the agent's reply contains a substring or RegExp. */\n messageIncludes(token: string | RegExp): void;\n /** Asserts the run took at most `n` turns — anti-flail. */\n maxTurns(n: number): void;\n /** Asserts the run took at most `n` milliseconds — anti-flail. */\n maxDurationMs(n: number): void;\n /** Escape hatch for a named predicate over the complete normalized run. */\n assert(label: string, predicate: (flow: TraceView) => boolean): void;\n\n // ── values / deliverables ──────────────────────────────────────────────\n /** Grades any value (a deliverable, parsed JSON, anything) with a matcher. */\n check<T>(value: T, matcher: Matcher<T>, label?: string): void;\n /**\n * LLM-as-judge: asks the configured judge model to grade ``value`` against\n * ``instruction`` (a natural-language rubric). Async — the check function\n * must `await` it. Records a single assertion tagged\n * ``evaluator_type: \"llm\"`` with judge metadata (model, prompt, response,\n * tokens, latency) attached.\n *\n * ``opts.judge`` overrides the run's judge config **for this call only**,\n * merging field-by-field onto the config threaded in via ``runTask({ judge })``\n * — set ``{ model }`` to escalate a finicky criterion to a stronger model\n * without switching the whole run. Absent fields inherit from the base config.\n */\n judge(\n values: unknown | unknown[],\n instruction: string,\n opts?: { label?: string; judge?: Partial<JudgeConfig> },\n ): Promise<void>;\n}\n\n/**\n * Canonical names of every assertion method on {@link TestContext}.\n *\n * Single source of truth for \"what is a ``t.<method>`` call?\" — consumers that\n * highlight, lint, or otherwise detect `t.*` usage in check source read this\n * array instead of keeping their own copy (which historically drifted out of\n * sync with the interface, leaving methods like ``t.maxTurns`` unstyled).\n *\n * The literal below is compile-time-checked against ``keyof TestContext``:\n * adding a method to the interface without registering it here is a type\n * error, and vice versa. See ``tests/test-context-methods.test.ts``.\n */\nexport const TEST_METHOD_NAMES = [\n \"calledTool\",\n \"notCalledTool\",\n \"toolOrder\",\n \"usedNoTools\",\n \"maxToolCalls\",\n \"noFailedActions\",\n \"loadedSkill\",\n \"calledSubagent\",\n \"messageIncludes\",\n \"maxTurns\",\n \"maxDurationMs\",\n \"assert\",\n \"check\",\n \"judge\",\n] as const satisfies readonly (keyof TestContext)[];\n\n/**\n * Compile-time exhaustiveness guard: errors if any {@link TestContext} method\n * is missing from {@link TEST_METHOD_NAMES}. A method on the interface with no\n * matching array entry makes the conditional type resolve to the offending\n * key instead of ``never``, which fails to assign to ``TEST_METHOD_NAMES``.\n * Kept out of the public type surface (no export) — it's a build-time check.\n */\ntype _TestMethodNamesComplete<T = keyof TestContext> =\n Exclude<T, (typeof TEST_METHOD_NAMES)[number]> extends never ? true : never;\n// If this line errors, a TestContext method is not listed in TEST_METHOD_NAMES.\nconst _testMethodNamesComplete: _TestMethodNamesComplete = true;\n\nfunction describeName(m: NameMatcher): string {\n if (typeof m === \"string\") return `\"${m}\"`;\n if (m instanceof RegExp) return m.source;\n return \"<predicate>\";\n}\n\nfunction matchName(name: string, m: NameMatcher): boolean {\n if (typeof m === \"string\") return name === m;\n if (m instanceof RegExp) return m.test(name);\n return m(name);\n}\n\nexport function createTestContext(\n view: TraceView,\n rec: Recorder,\n judgeConfig?: JudgeConfig,\n): TestContext {\n return {\n calledTool(name, opts) {\n const count = view.toolCalls.filter((call) =>\n matchesToolCall(call, name, opts),\n ).length;\n const want = opts?.count;\n const pass = want === undefined ? count > 0 : count === want;\n rec.record(\n `calledTool(${describeName(name)})`,\n pass,\n pass\n ? \"\"\n : want === undefined\n ? `expected at least one ${describeName(name)} call, got ${count}`\n : `expected exactly ${want} ${describeName(name)} calls, got ${count}`,\n {\n expected:\n want === undefined\n ? `≥1 ${describeName(name)} call`\n : `exactly ${want} ${describeName(name)} calls`,\n received: `${count}`,\n },\n );\n },\n\n notCalledTool(name, opts) {\n const count = view.toolCalls.filter((call) =>\n matchesToolCall(call, name, opts),\n ).length;\n rec.record(\n `notCalledTool(${describeName(name)})`,\n count === 0,\n count === 0 ? \"\" : `expected no ${describeName(name)} calls, got ${count}`,\n { expected: `0 ${describeName(name)} calls`, received: `${count}` },\n );\n },\n\n toolOrder(names) {\n const order = view.toolNamesInOrder;\n let cursor = 0;\n let missingIdx = -1;\n for (let i = 0; i < names.length; i++) {\n const found = order.indexOf(names[i], cursor);\n if (found === -1) {\n missingIdx = i;\n break;\n }\n cursor = found + 1;\n }\n const ok = missingIdx === -1;\n // Arrow separators read better than commas, and \"expected X after Y\"\n // pinpoints WHICH tool broke the order — clearer than dumping both lists\n // and asking the reader to do the visual diff.\n const expectedStr = names.join(\" → \");\n const actualStr = order.length > 0 ? order.join(\" → \") : \"(no tools)\";\n const message = ok\n ? \"\"\n : missingIdx === 0\n ? `expected \"${names[0]}\" first; actual order ${actualStr}`\n : `expected \"${names[missingIdx]}\" after \"${names[missingIdx - 1]}\"; actual order ${actualStr}`;\n rec.record(`toolOrder(${expectedStr})`, ok, message, {\n expected: expectedStr,\n received: actualStr,\n });\n },\n\n usedNoTools() {\n const count = view.toolCalls.length;\n rec.record(\"usedNoTools\", count === 0, count === 0 ? \"\" : `expected no tool calls, got ${count}`, {\n expected: \"0 tool calls\",\n received: `${count}`,\n });\n },\n\n maxToolCalls(n) {\n const count = view.toolCalls.length;\n rec.record(`maxToolCalls(${n})`, count <= n, count <= n ? \"\" : `expected ≤ ${n} tool calls, got ${count}`, {\n expected: `≤ ${n} tool calls`,\n received: `${count}`,\n });\n },\n\n noFailedActions() {\n const failed = view.failedActions;\n rec.record(\"noFailedActions\", failed === 0, failed === 0 ? \"\" : `${failed} failed action(s)`, {\n expected: \"0 failed actions\",\n received: `${failed}`,\n });\n },\n\n loadedSkill(skill) {\n const ok = view.skillLoads.some((s) => s.skill === skill);\n rec.record(`loadedSkill(\"${skill}\")`, ok, ok ? \"\" : `skill \"${skill}\" was not loaded`, {\n expected: `skill \"${skill}\" loaded`,\n received: view.skillLoads.map((s) => s.skill).join(\", \") || \"none\",\n });\n },\n\n calledSubagent(agent) {\n const ok = view.subagentCalls.some((s) => s.agent === agent);\n rec.record(`calledSubagent(\"${agent}\")`, ok, ok ? \"\" : `subagent \"${agent}\" was not called`, {\n expected: `subagent \"${agent}\" called`,\n received: view.subagentCalls.map((s) => s.agent).join(\", \") || \"none\",\n });\n },\n\n messageIncludes(token) {\n const re = typeof token === \"string\" ? new RegExp(token) : token;\n const ok = re.test(view.reply);\n rec.record(`messageIncludes(${token instanceof RegExp ? token.source : token})`, ok, ok ? \"\" : `reply did not include ${token}`, {\n expected: `reply includes ${token instanceof RegExp ? token.source : token}`,\n received: describeValue(view.reply).slice(0, 200),\n });\n },\n\n maxTurns(n) {\n const turns = view.turnCount;\n const pass = turns !== undefined && turns <= n;\n rec.record(`maxTurns(${n})`, pass, pass ? \"\" : `expected ≤ ${n} turns, got ${turns}`, {\n expected: `≤ ${n} turns`,\n received: `${turns}`,\n });\n },\n\n maxDurationMs(n) {\n const ms = view.durationMs;\n const pass = ms !== undefined && ms <= n;\n rec.record(`maxDurationMs(${n})`, pass, pass ? \"\" : `expected ≤ ${n}ms, took ${ms}ms`, {\n expected: `≤ ${n}ms`,\n received: `${ms}ms`,\n });\n },\n\n check(value, matcher, label) {\n const pass = matcher.test(value);\n rec.record(\n label ?? \"check\",\n pass,\n pass ? \"\" : `expected ${label ?? \"value\"} ${matcher.label}`,\n // Expected = the matcher's own description; received = the actual value.\n { expected: matcher.label, received: describeValue(value) },\n );\n },\n\n assert(label, predicate) {\n const pass = predicate(view);\n rec.record(label, pass, pass ? \"\" : `assertion \"${label}\" failed`, {\n expected: label,\n received: pass ? \"true\" : \"false\",\n });\n },\n\n async judge(values, instruction, opts) {\n const label = opts?.label ?? \"judge\";\n // Capture the call site BEFORE any await. After `await callJudge` resumes,\n // V8 reports this caller's frame at an unreliable line (often the\n // statement's closing `});`), which placed the failure marker on the\n // wrong line. Pinning it here lands the marker on `await t.judge(`.\n const location = rec.captureLocation();\n const valueArray = Array.isArray(values) ? values : [values];\n const effective = resolveJudgeConfig(judgeConfig, opts?.judge);\n if (!effective) {\n rec.record(\n label,\n false,\n \"No judge model configured. Set one of:\\n\" +\n \"• OPENROUTER_MODEL + OPENROUTER_API_KEY (OpenRouter — works with 200+ models, one account)\\n\" +\n \"• OPENAI_MODEL + OPENAI_API_KEY (OpenAI direct)\\n\" +\n \"Or pass { judge } to runTask() programmatically.\",\n { evaluator_type: \"llm\", location },\n );\n return;\n }\n try {\n const { pass, reasoning, judge } = await callJudge({\n values: valueArray,\n instruction,\n model: effective.model,\n baseURL: effective.baseURL,\n apiKey: effective.apiKey,\n });\n rec.record(label, pass, reasoning, {\n evaluator_type: \"llm\",\n judge,\n expected: instruction,\n // Store the raw evaluated value (not a truncated string) so the\n // dashboard can render it with the right viewer — Markdown for\n // prose, a JSON tree for structured objects.\n received: valueArray.length === 1 ? valueArray[0] : valueArray,\n location,\n });\n } catch (error) {\n rec.record(\n label,\n false,\n `judge failed: ${error instanceof Error ? error.message : String(error)}`,\n {\n evaluator_type: \"llm\",\n expected: instruction,\n received: valueArray.length === 1 ? valueArray[0] : valueArray,\n location,\n },\n );\n }\n },\n };\n}\n\n/**\n * Capability key → human description, for unsupported-outcome reasoning.\n */\nconst CAPABILITY_LABELS: Record<keyof TraceProjectionCapabilities, string> = {\n messages: \"message\",\n tools: \"tool\",\n errors: \"error\",\n timing: \"timing\",\n skills: \"skill\",\n subagents: \"subagent\",\n} as const;\n\n/**\n * Create a projection-first test context from a {@link TraceView}. Mirrors {@link createTestContext} but gates trace-dependent\n * assertions on capabilities: when the projection declares a capability\n * ``unavailable``, the assertion records ``outcome=\"unsupported\"`` (pass=false)\n * instead of vacuously passing against fabricated zero/empty evidence.\n *\n * Value assertions (``t.check``) and LLM assertions (``t.judge``) do not\n * consult capabilities and retain their existing behavior.\n */\nexport function createTraceTestContext(\n view: TraceView,\n rec: Recorder,\n judgeConfig?: JudgeConfig,\n): TestContext {\n const unsupported = (\n id: string,\n capability: keyof TraceProjectionCapabilities,\n ): void => {\n const label = CAPABILITY_LABELS[capability];\n rec.record(id, false, `${label} evidence is unavailable in this trace projection`, {\n outcome: \"unsupported\" as AssertionOutcome,\n expected: `${label} evidence available`,\n received: view.requireCapability(capability),\n });\n };\n\n const isAvailable = (c: keyof TraceProjectionCapabilities): boolean =>\n view.requireCapability(c) === \"available\";\n\n return {\n calledTool(name, opts) {\n if (!isAvailable(\"tools\")) {\n unsupported(`calledTool(${describeName(name)})`, \"tools\");\n return;\n }\n // Matching by { status } additionally requires errors evidence.\n if (opts?.status !== undefined && !isAvailable(\"errors\")) {\n unsupported(`calledTool(${describeName(name)}, { status })`, \"errors\");\n return;\n }\n const count = view.toolCalls.filter((call) =>\n matchesTraceToolCall(call, name, opts),\n ).length;\n const want = opts?.count;\n const pass = want === undefined ? count > 0 : count === want;\n rec.record(\n `calledTool(${describeName(name)})`,\n pass,\n pass\n ? \"\"\n : want === undefined\n ? `expected at least one ${describeName(name)} call, got ${count}`\n : `expected exactly ${want} ${describeName(name)} calls, got ${count}`,\n {\n expected:\n want === undefined\n ? `≥1 ${describeName(name)} call`\n : `exactly ${want} ${describeName(name)} calls`,\n received: `${count}`,\n },\n );\n },\n\n notCalledTool(name, opts) {\n if (!isAvailable(\"tools\")) {\n unsupported(`notCalledTool(${describeName(name)})`, \"tools\");\n return;\n }\n const count = view.toolCalls.filter((call) =>\n matchesTraceToolCall(call, name, opts),\n ).length;\n rec.record(\n `notCalledTool(${describeName(name)})`,\n count === 0,\n count === 0 ? \"\" : `expected no ${describeName(name)} calls, got ${count}`,\n { expected: `0 ${describeName(name)} calls`, received: `${count}` },\n );\n },\n\n toolOrder(names) {\n if (!isAvailable(\"tools\")) {\n unsupported(`toolOrder(${names.join(\" → \")})`, \"tools\");\n return;\n }\n const order = view.toolNamesInOrder;\n let cursor = 0;\n let missingIdx = -1;\n for (let i = 0; i < names.length; i++) {\n const found = order.indexOf(names[i], cursor);\n if (found === -1) {\n missingIdx = i;\n break;\n }\n cursor = found + 1;\n }\n const ok = missingIdx === -1;\n const expectedStr = names.join(\" → \");\n const actualStr = order.length > 0 ? order.join(\" → \") : \"(no tools)\";\n const message = ok\n ? \"\"\n : missingIdx === 0\n ? `expected \"${names[0]}\" first; actual order ${actualStr}`\n : `expected \"${names[missingIdx]}\" after \"${names[missingIdx - 1]}\"; actual order ${actualStr}`;\n rec.record(`toolOrder(${expectedStr})`, ok, message, {\n expected: expectedStr,\n received: actualStr,\n });\n },\n\n usedNoTools() {\n if (!isAvailable(\"tools\")) {\n unsupported(\"usedNoTools\", \"tools\");\n return;\n }\n const count = view.toolCalls.length;\n rec.record(\"usedNoTools\", count === 0, count === 0 ? \"\" : `expected no tool calls, got ${count}`, {\n expected: \"0 tool calls\",\n received: `${count}`,\n });\n },\n\n maxToolCalls(n) {\n if (!isAvailable(\"tools\")) {\n unsupported(`maxToolCalls(${n})`, \"tools\");\n return;\n }\n const count = view.toolCalls.length;\n rec.record(`maxToolCalls(${n})`, count <= n, count <= n ? \"\" : `expected ≤ ${n} tool calls, got ${count}`, {\n expected: `≤ ${n} tool calls`,\n received: `${count}`,\n });\n },\n\n noFailedActions() {\n if (!isAvailable(\"errors\")) {\n unsupported(\"noFailedActions\", \"errors\");\n return;\n }\n const failed = view.failedActions ?? 0;\n rec.record(\"noFailedActions\", failed === 0, failed === 0 ? \"\" : `${failed} failed action(s)`, {\n expected: \"0 failed actions\",\n received: `${failed}`,\n });\n },\n\n loadedSkill(skill) {\n if (!isAvailable(\"skills\")) {\n unsupported(`loadedSkill(\"${skill}\")`, \"skills\");\n return;\n }\n const ok = view.skillLoads.some((s) => s.skill === skill);\n rec.record(`loadedSkill(\"${skill}\")`, ok, ok ? \"\" : `skill \"${skill}\" was not loaded`, {\n expected: `skill \"${skill}\" loaded`,\n received: view.skillLoads.map((s) => s.skill).join(\", \") || \"none\",\n });\n },\n\n calledSubagent(agent) {\n if (!isAvailable(\"subagents\")) {\n unsupported(`calledSubagent(\"${agent}\")`, \"subagents\");\n return;\n }\n const ok = view.subagentCalls.some((s) => s.agent === agent);\n rec.record(`calledSubagent(\"${agent}\")`, ok, ok ? \"\" : `subagent \"${agent}\" was not called`, {\n expected: `subagent \"${agent}\" called`,\n received: view.subagentCalls.map((s) => s.agent).join(\", \") || \"none\",\n });\n },\n\n messageIncludes(token) {\n if (!isAvailable(\"messages\")) {\n unsupported(`messageIncludes(${token instanceof RegExp ? token.source : token})`, \"messages\");\n return;\n }\n const re = typeof token === \"string\" ? new RegExp(token) : token;\n const ok = re.test(view.reply);\n rec.record(`messageIncludes(${token instanceof RegExp ? token.source : token})`, ok, ok ? \"\" : `reply did not include ${token}`, {\n expected: `reply includes ${token instanceof RegExp ? token.source : token}`,\n received: describeValue(view.reply).slice(0, 200),\n });\n },\n\n maxTurns(n) {\n if (!isAvailable(\"messages\")) {\n unsupported(`maxTurns(${n})`, \"messages\");\n return;\n }\n const turns = view.turnCount ?? 0;\n rec.record(`maxTurns(${n})`, turns <= n, turns <= n ? \"\" : `expected ≤ ${n} turns, got ${turns}`, {\n expected: `≤ ${n} turns`,\n received: `${turns}`,\n });\n },\n\n maxDurationMs(n) {\n if (!isAvailable(\"timing\")) {\n unsupported(`maxDurationMs(${n})`, \"timing\");\n return;\n }\n const ms = view.durationMs;\n if (ms === undefined) {\n unsupported(`maxDurationMs(${n})`, \"timing\");\n return;\n }\n rec.record(`maxDurationMs(${n})`, ms <= n, ms <= n ? \"\" : `expected ≤ ${n}ms, took ${ms}ms`, {\n expected: `≤ ${n}ms`,\n received: `${ms}ms`,\n });\n },\n\n assert(label, predicate) {\n // The author is responsible for checking capabilities inside the predicate.\n const pass = predicate(view as unknown as TraceView);\n rec.record(label, pass, pass ? \"\" : `assertion \"${label}\" failed`, {\n expected: label,\n received: pass ? \"true\" : \"false\",\n });\n },\n\n check(value, matcher, label) {\n const pass = matcher.test(value);\n rec.record(\n label ?? \"check\",\n pass,\n pass ? \"\" : `expected ${label ?? \"value\"} ${matcher.label}`,\n { expected: matcher.label, received: describeValue(value) },\n );\n },\n\n async judge(values, instruction, opts) {\n // judge does not consult trace capabilities.\n const label = opts?.label ?? \"judge\";\n const location = rec.captureLocation();\n const valueArray = Array.isArray(values) ? values : [values];\n const effective = resolveJudgeConfig(judgeConfig, opts?.judge);\n if (!effective) {\n rec.record(\n label,\n false,\n \"No judge model configured. Set one of:\\n\" +\n \"• OPENROUTER_MODEL + OPENROUTER_API_KEY (OpenRouter — works with 200+ models, one account)\\n\" +\n \"• OPENAI_MODEL + OPENAI_API_KEY (OpenAI direct)\\n\" +\n \"Or pass { judge } to runTask() programmatically.\",\n { evaluator_type: \"llm\", location },\n );\n return;\n }\n try {\n const { pass, reasoning, judge } = await callJudge({\n values: valueArray,\n instruction,\n model: effective.model,\n baseURL: effective.baseURL,\n apiKey: effective.apiKey,\n });\n rec.record(label, pass, reasoning, {\n evaluator_type: \"llm\",\n judge,\n expected: instruction,\n received: valueArray.length === 1 ? valueArray[0] : valueArray,\n location,\n });\n } catch (error) {\n rec.record(\n label,\n false,\n `judge failed: ${error instanceof Error ? error.message : String(error)}`,\n {\n evaluator_type: \"llm\",\n expected: instruction,\n received: valueArray.length === 1 ? valueArray[0] : valueArray,\n location,\n },\n );\n }\n },\n };\n}\n\nfunction matchesTraceToolCall(\n call: { name: string; input?: unknown; output?: unknown; status?: string },\n name: NameMatcher,\n opts?: Omit<ToolCallOptions, \"count\">,\n): boolean {\n if (!matchName(call.name, name)) return false;\n if (opts?.input !== undefined && !matchValue(call.input, opts.input)) {\n return false;\n }\n if (opts?.output !== undefined && !matchValue(call.output, opts.output)) {\n return false;\n }\n if (opts?.status !== undefined && call.status !== opts.status) {\n return false;\n }\n return true;\n}\n\nfunction matchesToolCall(\n call: TraceView[\"toolCalls\"][number],\n name: NameMatcher,\n opts?: Omit<ToolCallOptions, \"count\">,\n): boolean {\n if (!matchName(call.name, name)) return false;\n if (opts?.input !== undefined && !matchValue(call.input, opts.input)) {\n return false;\n }\n if (opts?.output !== undefined && !matchValue(call.output, opts.output)) {\n return false;\n }\n if (opts?.status !== undefined && call.status !== opts.status) {\n return false;\n }\n return true;\n}\n","/**\n * Recorder — collects assertion outcomes within a single check so every\n * failure is reported (nothing throws/dies on the first miss). Aggregated\n * per-check by the runner into one evaluation result.\n */\n\nimport type { AssertionResult, CheckLocation } from \"../run/types.ts\";\n\n/** Back-compat alias; {@link AssertionResult} is the canonical type. */\nexport type AssertionRecord = AssertionResult;\n\n/**\n * Optional hook the runner installs when it knows how to map a stack to the\n * task/check module. The Recorder captures ``new Error().stack`` at the\n * assertion call site and hands it to ``locate``.\n */\nexport type LocateFn = (stack: string) => CheckLocation | undefined;\n\nexport class Recorder {\n private records: AssertionResult[] = [];\n private readonly locate?: LocateFn;\n\n constructor(locate?: LocateFn) {\n this.locate = locate;\n }\n\n /**\n * Record an assertion.\n *\n * - ``extra.location`` overrides auto-capture (used by the runner for thrown\n * errors, whose relevant stack is the error's own, not the call site).\n * - ``extra.expected`` / ``extra.received`` carry the structured values for\n * testing-framework-style display.\n */\n /**\n * Capture the call site location synchronously. Use this when a record will\n * happen AFTER an `await` (e.g. `t.judge`): once an async function resumes,\n * `new Error().stack` reports the caller's frame at an unreliable line\n * (often the statement's closing brace). Capturing here, before the await,\n * pins the location to the actual call line; pass it to ``record`` via\n * ``extra.location``.\n */\n captureLocation(): CheckLocation | undefined {\n return this.locate ? this.locate(new Error().stack ?? \"\") : undefined;\n }\n\n record(\n id: string,\n pass: boolean,\n reasoning: string,\n extra?: {\n location?: CheckLocation;\n expected?: string;\n received?: unknown;\n evaluator_type?: \"llm\" | \"code\";\n judge?: import(\"../run/types.ts\").JudgeMetadata;\n outcome?: import(\"../run/types.ts\").AssertionOutcome;\n },\n ): void {\n const location =\n extra?.location\n ?? (this.locate ? this.locate(new Error().stack ?? \"\") : undefined);\n this.records.push({\n id,\n pass,\n reasoning,\n location,\n expected: extra?.expected,\n received: extra?.received,\n evaluator_type: extra?.evaluator_type,\n judge: extra?.judge,\n outcome: extra?.outcome,\n });\n }\n\n get all(): readonly AssertionResult[] {\n return this.records;\n }\n}\n","/**\n * Parses a failure's stack trace into a {@link CheckLocation} anchored inside\n * the user's task/check module.\n *\n * Task modules and legacy checks modules load from verbatim temporary copies,\n * so frame line/column values map 1:1 to the original source. The display\n * ``file`` is the original filename, allowing the dashboard to fetch it.\n */\n\nimport type { CheckLocation } from \"../run/types.ts\";\n\nconst FRAME_TAIL = /:(\\d+):(\\d+)\\)?\\s*$/;\n\nexport function parseCheckLocation(\n stack: string | undefined,\n moduleUrl: string,\n displayFile: string,\n): CheckLocation | undefined {\n if (!stack || !moduleUrl) return undefined;\n // Match either the full module URL (native Node stacks) or its de-schemed\n // path (source-mapped / transformed stacks, e.g. under test runners), so\n // the locator is robust to how the frame URL is rendered.\n const needle = moduleUrl.replace(/^file:\\/\\//, \"\");\n for (const line of stack.split(\"\\n\")) {\n if (!line.includes(moduleUrl) && !line.includes(needle)) continue;\n const m = line.match(FRAME_TAIL);\n if (m) {\n return { file: displayFile, line: Number(m[1]), column: Number(m[2]) };\n }\n }\n return undefined;\n}\n","/**\n * Check runner — builds a {@link TestContext} (`t`) per registered check from\n * a {@link TraceProjectionSnapshot}, runs it, and aggregates every recorded\n * assertion into one evaluation result per check.\n */\n\nimport { TraceView } from \"../trace-projection/view.ts\";\nimport type { TraceProjectionSnapshot } from \"../trace-projection/types.ts\";\nimport type { CheckLocation, EvaluationItemResult } from \"../run/types.ts\";\nimport { createTraceTestContext, type TestContext, type JudgeConfig } from \"./t.ts\";\nimport { Recorder, type LocateFn } from \"./recorder.ts\";\nimport { parseCheckLocation } from \"./location.ts\";\nimport { copyFileSync, existsSync, unlinkSync } from \"fs\";\nimport { basename } from \"path\";\nimport { pathToFileURL } from \"url\";\n\n/**\n * The check context — deliberately framework-agnostic. `deliverables` is the\n * output; `files`/`task` are optional and untyped here so the core never\n * depends on any agent-framework's types. apo passes its own typed values;\n * other frameworks pass whatever they have (or omit).\n *\n * A task-scoped ``test`` gets typed deliverables from the adapter automatically:\n *\n * ```ts\n * const { test } = task(\"review\", {\n * adapter: reviewAdapter,\n * deliverables: [\"result\"],\n * });\n * test(\"id\", (t, { deliverables }) => {\n * deliverables.result // typed as ReviewResult\n * });\n * ```\n *\n * The generic overload of {@link defineCheck} remains available for\n * framework-agnostic checks that have no task scope.\n */\nexport type CheckContext<TDeliverables = Record<string, unknown>> = {\n deliverables: TDeliverables;\n files?: unknown;\n task?: unknown;\n};\n\nexport function filePaths(files: unknown): string[] {\n if (!Array.isArray(files)) return [];\n return (files as Array<{ relativePath: string }>).map((f) => f.relativePath);\n}\n\nexport type CheckFn<TDeliverables = Record<string, unknown>> = (\n t: TestContext,\n ctx: CheckContext<TDeliverables>,\n) => Promise<void> | void;\n\nexport type TestRegistration<TDeliverables = Record<string, unknown>> = (\n id: string,\n fn: CheckFn<TDeliverables>,\n) => void;\n\n/**\n * A registered `describe()` group — single-level, organizational only. See\n * {@link describe}.\n */\nexport type CheckGroup = {\n /** Stable, unique group id (kebab-case). Grouping key + React key. */\n id: string;\n /** Human-readable label shown in the dashboard. Defaults to the id. */\n name: string;\n};\n\n/** Signature of the `describe` registration primitive. */\nexport type DescribeRegistration = {\n (id: string, fn: () => void): void;\n (id: string, name: string, fn: () => void): void;\n};\n\ntype RegisteredCheck = { id: string; fn: CheckFn; group_id?: string; group_name?: string };\n\nconst REGISTRY_KEY = Symbol.for(\"@apo-ai/sdk/agent-task/check-registry\");\nconst registryStore = globalThis as typeof globalThis & {\n [key: symbol]: unknown;\n};\nconst registry = (registryStore[REGISTRY_KEY] ??= []) as RegisteredCheck[];\n\n// ── describe() group registry ────────────────────────────────────────────\n// Same Symbol.for globalThis pattern as the check registry so registrations\n// survive module re-imports. `currentGroupId` is the slot describe() pushes\n// while its callback runs; defineCheck reads it to stamp member checks.\nconst GROUP_REGISTRY_KEY = Symbol.for(\"@apo-ai/sdk/agent-task/group-registry\");\nconst groupRegistry = (registryStore[GROUP_REGISTRY_KEY] ??= []) as CheckGroup[];\nlet currentGroupId: string | null = null;\nlet currentGroupName: string | null = null;\n\n/** Register a check. The `fn` receives the assertion surface `t` and the output.\n *\n * Framework-agnostic callers can pass a deliverables type explicitly:\n * ```ts\n * type Deliverables = { result: ReviewResult; stats: Stats };\n * defineCheck<Deliverables>(\"id\", (t, { deliverables }) => { ... });\n * ```\n */\nexport function defineCheck<TDeliverables>(\n id: string,\n fn: CheckFn<TDeliverables>,\n): void;\nexport function defineCheck(id: string, fn: CheckFn): void;\nexport function defineCheck(id: string, fn: CheckFn): void {\n if (registry.some((c) => c.id === id)) {\n throw new Error(`Duplicate check id '${id}'`);\n }\n registry.push({\n id,\n fn,\n ...(currentGroupId ? { group_id: currentGroupId } : {}),\n ...(currentGroupName ? { group_name: currentGroupName } : {}),\n });\n}\n\nexport function resetFlowChecks(): void {\n registry.length = 0;\n groupRegistry.length = 0;\n currentGroupId = null;\n currentGroupName = null;\n}\n\n/**\n * Register a single-level group of checks. Runs `fn` synchronously;\n * any `test()`/`defineCheck()` call inside it is stamped with the group's id\n * and display name, so the dashboard can nest those checks under a collapsible\n * header with a roll-up verdict.\n *\n * Groups are **organizational only** — they do not change execution order,\n * concurrency, or the task verdict. Nesting is prohibited: calling `describe`\n * inside a `describe` callback throws. Use sibling groups under one task\n * instead.\n *\n * The `id` is stable (survives display-name edits); `name` is the human label\n * shown in the dashboard and defaults to `id` when omitted.\n *\n * ```ts\n * const { test, describe } = task(\"bind\", { adapter, deliverables });\n * describe(\"rules\", \"Rules — each comment becomes a rule\", () => {\n * RULE_GOLD.forEach((g) => test(`R-${g.id} — …`, async (t, { deliverables }) => { … }));\n * });\n * ```\n */\nexport function describe(id: string, fn: () => void): void;\nexport function describe(id: string, name: string, fn: () => void): void;\nexport function describe(\n id: string,\n nameOrFn: string | (() => void),\n fn?: () => void,\n): void {\n const name = typeof nameOrFn === \"string\" ? nameOrFn : id;\n const body = typeof nameOrFn === \"string\" ? fn! : nameOrFn;\n if (currentGroupId !== null) {\n throw new Error(\n `describe(\"${id}\") cannot nest inside describe(\"${currentGroupId}\"); groups are single-level only.`,\n );\n }\n if (groupRegistry.some((g) => g.id === id)) {\n throw new Error(`Duplicate describe id '${id}'`);\n }\n groupRegistry.push({ id, name });\n currentGroupId = id;\n currentGroupName = name;\n try {\n body();\n } finally {\n currentGroupId = null;\n currentGroupName = null;\n }\n}\n\n/**\n * Projection-first check runner. Runs registered checks\n * against a {@link TraceView} built from a {@link TraceProjectionSnapshot}.\n *\n * Trace-dependent assertions that need unavailable evidence (e.g. timing,\n * errors) record ``outcome=\"unsupported\"`` (pass=false) instead of vacuously\n * passing. Value assertions (``t.check``) and LLM assertions (``t.judge``)\n * are unaffected by capabilities.\n */\nexport async function runTraceChecks(args: {\n snapshot: TraceProjectionSnapshot;\n deliverables: Record<string, unknown>;\n files?: unknown;\n task?: unknown;\n judgeConfig?: JudgeConfig;\n moduleUrl?: string;\n displayFile?: string;\n}): Promise<EvaluationItemResult[]> {\n const view = new TraceView(args.snapshot);\n\n const locate: LocateFn | undefined =\n args.moduleUrl && args.displayFile\n ? (stack) => parseCheckLocation(stack, args.moduleUrl!, args.displayFile!)\n : undefined;\n\n const results = await Promise.all(\n registry.map(async (check) => {\n const rec = new Recorder(locate);\n const t = createTraceTestContext(view, rec, args.judgeConfig);\n let thrownLocation: CheckLocation | undefined;\n try {\n await check.fn(t, {\n deliverables: args.deliverables,\n files: args.files,\n task: args.task,\n });\n } catch (error) {\n thrownLocation = locate\n ? locate(error instanceof Error ? error.stack ?? \"\" : \"\")\n : undefined;\n rec.record(\"check-error\", false, error instanceof Error ? error.message : String(error), {\n location: thrownLocation,\n });\n }\n\n const failed = rec.all.filter((r) => !r.pass);\n const pass = failed.length === 0;\n const reasoning =\n failed.length > 0\n ? failed.map((r) => r.reasoning || r.id).join(\"; \")\n : rec.all.length > 0\n ? \"passed\"\n : \"no assertions recorded\";\n const location = failed.find((r) => r.location)?.location;\n const judge = rec.all.find((r) => r.judge)?.judge;\n\n return {\n id: check.id,\n pass,\n reasoning,\n evaluator_type: \"code\" as const,\n ...(judge ? { judge } : {}),\n ...(location ? { location } : {}),\n ...(args.displayFile ? { source_file: args.displayFile } : {}),\n ...(rec.all.length > 0\n ? { assertions: rec.all.map((a) => ({ ...a })) }\n : {}),\n ...(check.group_id ? { group_id: check.group_id } : {}),\n ...(check.group_name ? { group_name: check.group_name } : {}),\n // stamp the snapshot source so consumers can detect\n // the deprecated legacy-flow compatibility path (source=\"legacy-flow\").\n ...(args.snapshot.source !== \"canonical\"\n ? { source: args.snapshot.source }\n : {}),\n };\n }),\n );\n\n return results;\n}\n\n/**\n * Loads a user's `checks.ts` (which registers checks via `test(...)`),\n * then runs them against the projection snapshot + deliverables. Mirrors the\n * legacy loader: copy to a temp module path, import, delete.\n */\nexport async function loadAndRunFlowChecks(\n checksPath: string | null,\n args: {\n snapshot: TraceProjectionSnapshot;\n deliverables: Record<string, unknown>;\n files?: unknown;\n task?: unknown;\n judgeConfig?: JudgeConfig;\n },\n brokenDeliverables: Record<string, string> = {},\n): Promise<EvaluationItemResult[]> {\n if (!checksPath) return [];\n\n resetFlowChecks();\n const moduleUrl = await loadChecksModule(checksPath);\n if (moduleUrl === null || registry.length === 0) return [];\n\n return runTraceChecks({\n snapshot: args.snapshot,\n deliverables: proxyBrokenDeliverables(args.deliverables, brokenDeliverables),\n files: args.files,\n task: args.task,\n judgeConfig: args.judgeConfig,\n moduleUrl,\n displayFile: basename(checksPath),\n });\n}\n\nexport async function loadChecksModule(checksPath: string): Promise<string | null> {\n const tempModulePath = `${checksPath}.${Date.now()}-${Math.random()\n .toString(36)\n .slice(2)}.ts`;\n try {\n copyFileSync(checksPath, tempModulePath);\n const moduleUrl = pathToFileURL(tempModulePath).href;\n // eslint-disable-next-line react-doctor/no-dynamic-import-path -- runtime loading of user task checks\n await import(moduleUrl);\n // If the module didn't register any checks, signal that to the caller.\n if (registry.length === 0) return null;\n return moduleUrl;\n } finally {\n if (existsSync(tempModulePath)) unlinkSync(tempModulePath);\n }\n}\n\nexport function proxyBrokenDeliverables(\n deliverables: Record<string, unknown>,\n brokenDeliverables: Record<string, string>,\n): Record<string, unknown> {\n if (Object.keys(brokenDeliverables).length === 0) return deliverables;\n return new Proxy(deliverables, {\n get(target, property, receiver) {\n if (typeof property === \"string\" && property in brokenDeliverables) {\n throw new Error(brokenDeliverables[property]);\n }\n return Reflect.get(target, property, receiver);\n },\n });\n}\n","import type {\n AdapterDefinition,\n CollectedDeliverables,\n DeliverableDefinition,\n TypedAdapterDefinition,\n} from \"../adapter/types.ts\";\nimport {\n defineCheck,\n describe,\n type DescribeRegistration,\n type TestRegistration,\n} from \"../checks/flow-runner.ts\";\nimport type { TaskConfig, TaskDefinition } from \"./types.ts\";\n\nconst TASK_ADAPTER_SYMBOL = Symbol.for(\"agent-task.adapter-definition\");\n\n// ── Task registry (same Symbol.for pattern as the check registry) ─────────\nconst TASK_REGISTRY_KEY = Symbol.for(\"@apo-ai/sdk/agent-task/task-registry\");\nconst taskRegistryStore = globalThis as typeof globalThis & {\n [key: symbol]: unknown;\n};\nconst taskRegistry = (taskRegistryStore[TASK_REGISTRY_KEY] ??= []) as TaskDefinition[];\n\nexport function resetTaskRegistry(): void {\n taskRegistry.length = 0;\n}\n\nexport function getRegisteredTask(): TaskDefinition | undefined {\n return taskRegistry[0];\n}\n\n// ── Backward compat ────────────────────────────────────────────────────────\nexport type DefinedTask<\n TName extends string,\n TDeliverableDefs extends Record<string, DeliverableDefinition>,\n> = TaskDefinition<TName, keyof TDeliverableDefs & string> & {\n readonly [TASK_ADAPTER_SYMBOL]: TypedAdapterDefinition<\n TName,\n TDeliverableDefs\n >;\n};\n\n/** Legacy two-file task definition. New tasks should use {@link task}. */\nexport function defineTask<\n const TName extends string,\n const TDeliverableDefs extends Record<string, DeliverableDefinition>,\n>(\n adapter: TypedAdapterDefinition<TName, TDeliverableDefs>,\n config: TaskConfig<keyof TDeliverableDefs & string>,\n): DefinedTask<TName, TDeliverableDefs> {\n const definedTask = {\n ...config,\n adapter: adapter.name,\n } as DefinedTask<TName, TDeliverableDefs>;\n\n attachAdapter(definedTask, adapter);\n return definedTask;\n}\n\nexport type TaskScope<TDeliverables> = {\n test: TestRegistration<TDeliverables>;\n /**\n * Register a single-level group of checks. See\n * {@link describe} in `checks/flow-runner.ts`. Returned from `task()` so the\n * `test` inside the callback stays task-scoped (typed deliverables).\n */\n describe: DescribeRegistration;\n};\n\n/**\n * Register a task + its checks in ONE file. The `name` is the task id;\n * `config` includes the adapter, deliverables, and other metadata. Checks\n * are registered through the returned, adapter-typed `test` function.\n *\n * ```ts\n * const { test } = task(\"code-review\", {\n * adapter: realAgentAdapter,\n * deliverables: [\"result\", \"tool_log\", \"stats\"],\n * maxTurns: 2,\n * });\n *\n * test(\"reviewed-methodically\", (t, { deliverables }) => {\n * t.check(deliverables.result, includes(\"finding\"));\n * });\n *\n * // A task that needs dev-machine resources (cloud creds, VPC, stage) can\n * // declare execution: \"local\" so `apo task run` runs it on the caller's\n * // machine while still recording a backend run row.\n * task(\"bind-e2e\", {\n * adapter: bindAdapter,\n * deliverables: [\"summary\"],\n * execution: \"local\",\n * });\n * ```\n */\nexport function task<\n const TTaskId extends string,\n const TAdapterName extends string,\n const TDeliverableDefs extends Record<string, DeliverableDefinition>,\n TCollected extends CollectedDeliverables,\n const TSelected extends readonly (\n DeliverableKey<TCollected> & keyof TDeliverableDefs\n )[],\n>(\n name: TTaskId,\n config: Omit<\n TaskConfig<TSelected[number] & string>,\n \"id\" | \"checks\" | \"deliverables\"\n > & {\n adapter: TypedAdapterDefinition<\n TAdapterName,\n TDeliverableDefs,\n TCollected\n >;\n deliverables: TSelected;\n },\n): TaskScope<SelectedDeliverables<TCollected, TSelected>> {\n const adapter = config.adapter;\n const {\n adapter: _adapter,\n deliverables,\n ...rest\n } = config;\n const definedTask = {\n ...rest,\n id: name,\n adapter: adapter.name,\n deliverables: [...deliverables],\n } satisfies TaskDefinition;\n\n attachAdapter(definedTask, adapter);\n\n taskRegistry.push(definedTask);\n return {\n test: defineCheck as TestRegistration<\n SelectedDeliverables<TCollected, TSelected>\n >,\n describe: describe as DescribeRegistration,\n };\n}\n\nexport function getTaskAdapterDefinition(\n task: object,\n): AdapterDefinition | null {\n return (task as { [TASK_ADAPTER_SYMBOL]?: AdapterDefinition })[\n TASK_ADAPTER_SYMBOL\n ] ?? null;\n}\n\nfunction attachAdapter(taskDefinition: object, adapter: AdapterDefinition): void {\n Object.defineProperty(taskDefinition, TASK_ADAPTER_SYMBOL, {\n value: adapter,\n enumerable: false,\n configurable: false,\n writable: false,\n });\n}\n\ntype DeliverableKey<TCollected> = TCollected extends unknown\n ? keyof TCollected & string\n : never;\n\ntype DeliverableValue<\n TCollected,\n TKey extends PropertyKey,\n> = TCollected extends unknown\n ? TKey extends keyof TCollected\n ? TCollected[TKey]\n : never\n : never;\n\ntype SelectedDeliverables<\n TCollected,\n TSelected extends readonly PropertyKey[],\n> = {\n [TKey in TSelected[number]]-?: Exclude<\n DeliverableValue<TCollected, TKey>,\n null | undefined\n >;\n};\n","import { copyFileSync, readdirSync, statSync, existsSync, unlinkSync, writeFileSync } from \"fs\";\nimport { join, resolve, basename } from \"path\";\nimport { pathToFileURL } from \"url\";\nimport type { AdapterDefinition } from \"../adapter/types.ts\";\nimport { getTaskAdapterDefinition, getRegisteredTask, resetTaskRegistry } from \"./defineTask.ts\";\nimport { resetFlowChecks } from \"../checks/flow-runner.ts\";\nimport { resetTaskTurn } from \"../turn.ts\";\nimport type { TaskDefinition, FileEntry } from \"./types.ts\";\n\nexport type LoadedTask = {\n task: TaskDefinition;\n adapter: AdapterDefinition;\n taskDir: string;\n files: FileEntry[];\n /** Legacy external checks module, absent for single-file tasks. */\n checksPath: string | null;\n /** True when task(), test(), and turn() were registered by the eval file. */\n inlineChecks: boolean;\n /** The temp-module URL the task was imported from (used for location pinning). */\n moduleUrl: string;\n /** The original eval filename (e.g. \"code-review.eval.ts\") — used as source_file on check results. */\n evalFileName: string;\n};\n\nexport async function loadTask(taskDir: string): Promise<LoadedTask> {\n const absoluteDir = resolve(taskDir);\n const taskFilePath = findEvalFile(absoluteDir);\n\n if (!taskFilePath) {\n throw new Error(`No .eval.ts file found in: ${absoluteDir}`);\n }\n\n const { task, adapter, inlineChecks, moduleUrl } =\n await loadTaskDefinition(taskFilePath);\n validateTaskDefinition(task, absoluteDir);\n\n const files = loadFilesDirectory(absoluteDir);\n const checksPath = resolveChecksPath(task, absoluteDir);\n\n return {\n task,\n adapter,\n taskDir: absoluteDir,\n files,\n checksPath,\n inlineChecks,\n moduleUrl,\n evalFileName: basename(taskFilePath),\n };\n}\n\n/**\n * Materialize and load an eval from stored source text (issue #159 rejudge).\n *\n * Writes `content` as a temp sibling inside `siblingDir` (a real task\n * directory, so relative imports and `files/` fixtures resolve like a live\n * run) or inside `isolatedDir` (self-contained evals only — a scaffold next\n * to the SDK so package imports resolve). The stored revision pins only the\n * eval file itself; when a sibling dir is unavailable, evals that import\n * sibling modules cannot replay and fail with a guided error.\n */\nexport async function loadEvalSource(\n fileName: string,\n content: string,\n opts: { siblingDir?: string | null; isolatedDir?: string | null } = {},\n): Promise<LoadedTask> {\n const dir = opts.siblingDir ?? opts.isolatedDir;\n if (!dir) {\n throw new Error(\"loadEvalSource requires a siblingDir or isolatedDir to materialize next to\");\n }\n const tempPath = join(\n dir,\n `${fileName}.rejudge-${Date.now()}-${Math.random().toString(36).slice(2)}.ts`,\n );\n writeFileSync(tempPath, content);\n try {\n const { task, adapter, inlineChecks, moduleUrl } = await loadTaskDefinition(tempPath);\n validateTaskDefinition(task, dir);\n if (!inlineChecks && !existsSync(join(dir, \"checks.ts\"))) {\n throw new Error(\n `The pinned eval did not register checks: legacy two-file tasks need their checks module, ` +\n `which the stored definition revision does not include`,\n );\n }\n return {\n task,\n adapter,\n taskDir: dir,\n files: loadFilesDirectory(dir),\n checksPath: resolveChecksPath(task, dir),\n inlineChecks,\n moduleUrl,\n evalFileName: fileName,\n };\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n if (!opts.siblingDir && /Failed to load task definition/.test(message)) {\n throw new Error(\n `Replay needs the task directory: the pinned eval imports sibling files that are not ` +\n `part of the stored definition revision. Point the command at a checkout of the task ` +\n `(--task-dir) and retry. Underlying error: ${message}`,\n );\n }\n throw error;\n } finally {\n if (existsSync(tempPath)) {\n unlinkSync(tempPath);\n }\n }\n}\n\n/**\n * Import the task file as a temp module. The side-effect of importing\n * registers the task (via `task()`), all checks (via `check()`/`test()`),\n * and any turn override (via `turn()`) — all from ONE file.\n */\nasync function loadTaskDefinition(\n taskFilePath: string,\n): Promise<{\n task: TaskDefinition;\n adapter: AdapterDefinition;\n inlineChecks: boolean;\n moduleUrl: string;\n}> {\n const tempModulePath = `${taskFilePath}.${Date.now()}-${Math.random()\n .toString(36)\n .slice(2)}.ts`;\n\n try {\n copyFileSync(taskFilePath, tempModulePath);\n const moduleUrl = pathToFileURL(tempModulePath).href;\n\n // Clear all registries so this import starts clean.\n resetTaskRegistry();\n resetFlowChecks();\n resetTaskTurn();\n\n // eslint-disable-next-line react-doctor/no-dynamic-import-path -- runtime loading of user task file\n const loaded = (await import(moduleUrl)) as { default?: TaskDefinition };\n\n const registeredTask = getRegisteredTask();\n const task = registeredTask ?? loaded.default;\n if (!task || typeof task !== \"object\") {\n throw new Error(\n \"No task definition found. The .eval.ts file must call task(name, { adapter, deliverables, ... }) at module top level. \" +\n \"If it does, the CLI and the .eval.ts may be loading different @apo-ai/sdk instances \" +\n \"(check for a stale packages/sdk/dist build or a version mismatch between the CLI and node_modules).\",\n );\n }\n const adapter = getTaskAdapterDefinition(task);\n if (!adapter) {\n throw new Error(\n registeredTask\n ? \"task() config must include an adapter\"\n : \"Task module must call task(name, { adapter, ... }) — the config is missing an adapter.\",\n );\n }\n return {\n task,\n adapter,\n inlineChecks: registeredTask !== undefined,\n moduleUrl,\n };\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n throw new Error(`Failed to load task definition: ${taskFilePath} (${message})`);\n } finally {\n if (existsSync(tempModulePath)) {\n unlinkSync(tempModulePath);\n }\n }\n}\n\nfunction validateTaskDefinition(\n task: TaskDefinition,\n taskDir: string,\n): void {\n if (!task.id || typeof task.id !== \"string\") {\n throw new Error(`Task must have a string 'id': ${taskDir}`);\n }\n\n if (!task.adapter || typeof task.adapter !== \"string\") {\n throw new Error(`Task must have a derived string 'adapter': ${taskDir}`);\n }\n\n if (!Array.isArray(task.deliverables)) {\n throw new Error(`Task must have a 'deliverables' array: ${taskDir}`);\n }\n}\n\nfunction loadFilesDirectory(taskDir: string): FileEntry[] {\n const filesDir = join(taskDir, \"files\");\n if (!existsSync(filesDir) || !statSync(filesDir).isDirectory()) {\n return [];\n }\n\n return walkDirectory(filesDir, filesDir);\n}\n\nfunction walkDirectory(dir: string, root: string): FileEntry[] {\n const entries: FileEntry[] = [];\n\n for (const name of readdirSync(dir)) {\n const fullPath = join(dir, name);\n const stat = statSync(fullPath);\n\n if (stat.isDirectory()) {\n entries.push(...walkDirectory(fullPath, root));\n } else {\n entries.push({\n relativePath: fullPath.slice(root.length + 1),\n absolutePath: fullPath,\n });\n }\n }\n\n return entries;\n}\n\nfunction resolveChecksPath(\n task: TaskDefinition,\n taskDir: string,\n): string | null {\n if (task.checks === false) {\n return null;\n }\n\n if (typeof task.checks === \"string\") {\n const customPath = resolve(taskDir, task.checks);\n if (!existsSync(customPath)) {\n throw new Error(`Custom checks file not found: ${customPath}`);\n }\n return customPath;\n }\n\n const conventionPath = join(taskDir, \"checks.ts\");\n return existsSync(conventionPath) ? conventionPath : null;\n}\n\n/** Find the first `*.eval.ts` file in a directory (the task definition). */\nfunction findEvalFile(dir: string): string | null {\n try {\n const files = readdirSync(dir);\n const evalFile = files.find((f) => f.endsWith(\".eval.ts\"));\n return evalFile ? join(dir, evalFile) : null;\n } catch {\n return null;\n }\n}\n","import type { TaskFiles } from \"./task/TaskFiles.ts\";\n\nexport type TurnRecord = {\n turnNumber: number;\n input: unknown;\n output: unknown;\n};\n\nexport type TurnContext = {\n files: TaskFiles;\n transcript: TurnRecord[];\n};\n\nexport type TurnFn<TUserTurn = unknown> = (\n ctx: TurnContext,\n) => Promise<TUserTurn | null> | TUserTurn | null;\n\nconst TURN_KEY = Symbol.for(\"@apo-ai/sdk/agent-task/task-turn\");\n\nexport function turn<TUserTurn>(fn: TurnFn<TUserTurn>): void {\n (globalThis as Record<symbol, unknown>)[TURN_KEY] = fn;\n}\n\nexport function getTaskTurn(): TurnFn | undefined {\n return (globalThis as Record<symbol, unknown>)[TURN_KEY] as TurnFn | undefined;\n}\n\nexport function resetTaskTurn(): void {\n delete (globalThis as Record<symbol, unknown>)[TURN_KEY];\n}\n\nexport function resolveTurn(\n adapterTurn: TurnFn | undefined,\n taskTurn: TurnFn | undefined,\n): TurnFn {\n const resolved = taskTurn ?? adapterTurn;\n if (!resolved) {\n throw new Error(\n \"No turn behavior defined. Add a turn() call to your task file or a turn field to your adapter.\",\n );\n }\n return resolved;\n}\n","import { readFile } from \"fs/promises\";\nimport type { FileEntry } from \"./types.ts\";\n\nexport class TaskFiles {\n private entries: FileEntry[];\n\n constructor(entries: FileEntry[]) {\n this.entries = entries;\n }\n\n async read(relativePath: string): Promise<string> {\n const entry = this.find(relativePath);\n if (!entry) {\n throw new Error(`File not found: ${relativePath}`);\n }\n return readFile(entry.absolutePath, \"utf-8\");\n }\n\n async readBuffer(relativePath: string): Promise<Buffer> {\n const entry = this.find(relativePath);\n if (!entry) {\n throw new Error(`File not found: ${relativePath}`);\n }\n return readFile(entry.absolutePath);\n }\n\n find(relativePath: string): FileEntry | undefined {\n return this.entries.find((entry) => entry.relativePath === relativePath);\n }\n\n list(): FileEntry[] {\n return [...this.entries];\n }\n\n has(relativePath: string): boolean {\n return this.entries.some((entry) => entry.relativePath === relativePath);\n }\n}\n","import type {\n CollectedDeliverables,\n DeliverableDefinition,\n TypedAdapterDefinition,\n} from \"./types.ts\";\n\nexport function defineAdapter<\n const TName extends string,\n const TDeliverables extends Record<string, DeliverableDefinition>,\n TCollected extends CollectedDeliverables,\n>(\n adapter: TypedAdapterDefinition<TName, TDeliverables, TCollected>,\n): TypedAdapterDefinition<TName, TDeliverables, TCollected> {\n return adapter;\n}\n","/**\n * file Artifact declaration helper.\n *\n * A ``FileArtifact`` is a path descriptor that identifies a regular local\n * file at persistence time. The SDK streams it to the backend (two-phase\n * upload) rather than buffering bytes in the result body.\n *\n * Rules:\n * - ``path`` must identify a regular local file at persistence time;\n * - directories, sockets, devices, and symbolic links are rejected;\n * - the default display filename is ``basename(path)``;\n * - the default media type is ``application/octet-stream``;\n * - ``t.judge(fileArtifact(...))`` is rejected: a path descriptor is not file\n * content. Authors must explicitly read/parse the content to judge it.\n */\n\nimport { basename } from \"node:path\";\nimport { lstatSync, statSync } from \"node:fs\";\n\nexport interface FileArtifact {\n readonly kind: \"apo.file-artifact\";\n readonly path: string;\n readonly mediaType: string;\n readonly displayFilename: string;\n}\n\nexport interface FileArtifactOptions {\n readonly mediaType?: string;\n readonly displayFilename?: string;\n}\n\nconst DEFAULT_MEDIA_TYPE = \"application/octet-stream\";\n\n/**\n * Declare a file Deliverable from a local file path.\n *\n * Validates eagerly that ``path`` points to an existing regular file (not a\n * directory, symlink, socket, or device) so authors get an actionable error\n * before the backend creates an upload intent.\n */\nexport function fileArtifact(\n path: string,\n options: FileArtifactOptions = {},\n): FileArtifact {\n if (!path) {\n throw new Error(\"fileArtifact: path must not be empty\");\n }\n // lstat does not follow symlinks; a symlink must be rejected even when its\n // target is a regular file.\n let stat;\n try {\n const lstat = lstatSync(path);\n if (lstat.isSymbolicLink()) {\n throw new Error(\"fileArtifact: path is a symbolic link, not a regular file\");\n }\n stat = statSync(path);\n } catch (error) {\n if (error instanceof Error && error.message.startsWith(\"fileArtifact:\")) throw error;\n throw new Error(\"fileArtifact: path is not a regular file or is inaccessible\");\n }\n if (!stat.isFile()) {\n throw new Error(\"fileArtifact: path is not a regular file\");\n }\n\n const displayFilename = options.displayFilename ?? basename(path);\n if (!displayFilename) {\n throw new Error(\"fileArtifact: displayFilename must not be empty\");\n }\n\n return Object.freeze({\n kind: \"apo.file-artifact\",\n path,\n mediaType: options.mediaType ?? DEFAULT_MEDIA_TYPE,\n displayFilename,\n });\n}\n\nexport function isFileArtifact(value: unknown): value is FileArtifact {\n return (\n typeof value === \"object\" &&\n value !== null &&\n (value as { kind?: unknown }).kind === \"apo.file-artifact\" &&\n typeof (value as { path?: unknown }).path === \"string\"\n );\n}\n\n// ENOENT shows up as a thrown error; narrow it without depending on the node\n// error code constant at module scope.\nfunction existsLike(error: unknown): boolean {\n if (!(error instanceof Error)) return false;\n const code = (error as NodeJS.ErrnoException).code;\n return code === \"ENOENT\";\n}\n","/**\n * file Artifact uploader.\n *\n * After checks run against the original in-memory Deliverables, this module\n * partitions JSON values from file Artifacts, streams each file to the\n * backend's two-phase upload endpoint, and returns only JSON Deliverables for\n * the final result body. File bytes never travel through the result request\n * or subprocess stdout.\n *\n * Storage failure does not flip a failed test into a pass: it raises, so the\n * caller records the run as errored.\n */\n\nimport { createHash } from \"node:crypto\";\nimport { createReadStream } from \"node:fs\";\nimport { Readable } from \"node:stream\";\n\nimport { isFileArtifact, type FileArtifact } from \"./artifact.ts\";\n\nexport interface DeliverableSummary {\n id: string;\n name: string;\n kind: \"json\" | \"artifact\";\n status: \"pending\" | \"ready\" | \"failed\";\n media_type: string;\n display_filename: string | null;\n size_bytes: number;\n sha256: string;\n download_url: string | null;\n}\n\nexport interface ArtifactUploadIntent {\n id: string;\n upload_url: string;\n}\n\nexport interface ArtifactUploadConfig {\n /** The Task Run id owning these Deliverables. */\n taskRunId: string;\n /** Bearer token (service token or API key) authorizing the upload. */\n authToken: string;\n /** Backend base URL, e.g. ``http://127.0.0.1:8000``. */\n baseUrl: string;\n /** Injectable fetch (tests pass a stub); defaults to global fetch. */\n fetch?: typeof fetch;\n}\n\nexport interface PreparedTaskResult {\n /** JSON-only deliverables safe to send in the final result body. */\n jsonDeliverables: Record<string, unknown>;\n /** Successfully uploaded file Artifacts (summaries only, no bodies). */\n artifactUploads: DeliverableSummary[];\n}\n\nconst DEFAULT_FETCH: typeof fetch | undefined =\n typeof fetch === \"function\" ? fetch : undefined;\n\n/**\n * Partition and persist Deliverables after checks complete.\n *\n * - file Artifacts are streamed to the backend (hash, create intent, PUT);\n * - JSON values are returned untouched for the result body;\n * - the local path of any Artifact is never embedded in the result.\n */\nexport async function persistFileArtifacts(\n deliverables: Record<string, unknown>,\n config: ArtifactUploadConfig,\n): Promise<PreparedTaskResult> {\n const jsonDeliverables: Record<string, unknown> = {};\n const artifactUploads: DeliverableSummary[] = [];\n\n // Validate upload context only when at least one FileArtifact exists.\n // JSON-only recorded runs perform no Artifact HTTP request.\n const artifactNames = Object.entries(deliverables)\n .filter(([, v]) => isFileArtifact(v))\n .map(([name]) => name);\n if (artifactNames.length > 0) {\n validateUploadConfig(config, artifactNames[0]);\n }\n\n for (const [name, value] of Object.entries(deliverables)) {\n if (isFileArtifact(value)) {\n const summary = await uploadOne(name, value, config);\n artifactUploads.push(summary);\n } else {\n jsonDeliverables[name] = value;\n }\n }\n\n return { jsonDeliverables, artifactUploads };\n}\n\n/**\n * Fail early with a safe, path-free message before any file hashing or HTTP\n * request. The error names the first Artifact Deliverable so the author knows\n * which one is affected, but never includes the executor-local file path.\n */\nfunction validateUploadConfig(config: ArtifactUploadConfig, firstName: string): void {\n if (!config.taskRunId) {\n throw new Error(\n `Artifact '${firstName}' cannot be uploaded: missing task run ID`,\n );\n }\n if (!config.authToken) {\n throw new Error(\n `Artifact '${firstName}' cannot be uploaded: missing auth token`,\n );\n }\n if (!config.baseUrl) {\n throw new Error(\n `Artifact '${firstName}' cannot be uploaded: missing backend base URL`,\n );\n }\n}\n\nasync function uploadOne(\n name: string,\n artifact: FileArtifact,\n config: ArtifactUploadConfig,\n): Promise<DeliverableSummary> {\n try {\n const { size, sha256 } = await hashFile(artifact.path);\n const intent = await createIntent(name, artifact, size, sha256, config);\n\n const body = Readable.toWeb(createReadStream(artifact.path)) as ReadableStream<Uint8Array>;\n const summary = await putBytes(intent.upload_url, body, size, config);\n return summary;\n } catch (err) {\n // Sanitize file I/O errors (ENOENT, EACCES, etc.) which embed the full\n // local path in their message. HTTP errors carry server responses, not\n // paths, and propagate unchanged.\n if (err instanceof Error && (err as NodeJS.ErrnoException).code) {\n const code = (err as NodeJS.ErrnoException).code ?? \"UNKNOWN\";\n throw new Error(`Artifact '${name}' file read failed: ${code}`);\n }\n throw err;\n }\n}\n\nasync function hashFile(\n path: string,\n): Promise<{ size: number; sha256: string }> {\n return new Promise((resolve, reject) => {\n const hash = createHash(\"sha256\");\n let size = 0;\n const stream = createReadStream(path);\n stream.on(\"data\", (chunk: string | Buffer) => {\n hash.update(chunk);\n size += chunk.length;\n });\n stream.on(\"error\", reject);\n stream.on(\"end\", () => resolve({ size, sha256: hash.digest(\"hex\") }));\n });\n}\n\nasync function createIntent(\n name: string,\n artifact: FileArtifact,\n sizeBytes: number,\n sha256: string,\n config: ArtifactUploadConfig,\n): Promise<ArtifactUploadIntent> {\n const url = `${config.baseUrl}/v1/agent-task-runs/${config.taskRunId}/artifact-uploads`;\n const response = await doFetch(config, url, {\n method: \"POST\",\n headers: {\n Authorization: `Bearer ${config.authToken}`,\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify({\n name,\n display_filename: artifact.displayFilename,\n media_type: artifact.mediaType,\n size_bytes: sizeBytes,\n sha256,\n }),\n });\n if (response.status === 201) {\n const body = (await response.json()) as ArtifactUploadIntent;\n return body;\n }\n const detail = await safeDetail(response);\n throw new Error(\n `artifact upload intent for '${name}' failed (${response.status}): ${detail}`,\n );\n}\n\nasync function putBytes(\n uploadUrl: string,\n body: ReadableStream<Uint8Array>,\n sizeBytes: number,\n config: ArtifactUploadConfig,\n): Promise<DeliverableSummary> {\n const url = uploadUrl.startsWith(\"http\")\n ? uploadUrl\n : `${config.baseUrl}${uploadUrl}`;\n const response = await doFetch(config, url, {\n method: \"PUT\",\n headers: {\n Authorization: `Bearer ${config.authToken}`,\n \"Content-Type\": \"application/octet-stream\",\n \"Content-Length\": String(sizeBytes),\n },\n body,\n duplex: \"half\",\n } as RequestInit);\n if (response.status === 200) {\n return (await response.json()) as DeliverableSummary;\n }\n const detail = await safeDetail(response);\n throw new Error(\n `artifact upload of ${sizeBytes} bytes failed (${response.status}): ${detail}`,\n );\n}\n\nasync function doFetch(\n config: ArtifactUploadConfig,\n input: string,\n init: RequestInit,\n): Promise<Response> {\n const fetchImpl = config.fetch ?? DEFAULT_FETCH;\n if (!fetchImpl) {\n throw new Error(\"persistFileArtifacts: fetch is not available in this environment\");\n }\n return fetchImpl(input, init);\n}\n\nasync function safeDetail(response: Response): Promise<string> {\n try {\n const text = await response.text();\n return text.slice(0, 500);\n } catch {\n return \"<no body>\";\n }\n}\n","/**\n * FlowView — typed, derived access over a {@link Flow}. This is the read model\n * the assertion surface (`t`) queries. It hides all the filtering/derivation\n * so assertions stay one-liners.\n */\n\nimport type { Flow, FlowEvent } from \"./types.ts\";\n\ntype ToolCall = Extract<FlowEvent, { kind: \"tool_call\" }>;\ntype SkillLoad = Extract<FlowEvent, { kind: \"skill_load\" }>;\ntype SubagentCall = Extract<FlowEvent, { kind: \"subagent_call\" }>;\ntype Message = Extract<FlowEvent, { kind: \"message\" }>;\n\nexport class FlowView {\n readonly events: readonly FlowEvent[];\n readonly startedAt?: number;\n readonly endedAt?: number;\n\n constructor(flow: Flow) {\n this.events = flow.events;\n this.startedAt = flow.startedAt;\n this.endedAt = flow.endedAt;\n }\n\n get messages(): Message[] {\n return this.events.filter((e): e is Message => e.kind === \"message\");\n }\n\n get toolCalls(): ToolCall[] {\n return this.events.filter((e): e is ToolCall => e.kind === \"tool_call\");\n }\n\n get skillLoads(): SkillLoad[] {\n return this.events.filter((e): e is SkillLoad => e.kind === \"skill_load\");\n }\n\n get subagentCalls(): SubagentCall[] {\n return this.events.filter(\n (e): e is SubagentCall => e.kind === \"subagent_call\",\n );\n }\n\n get toolNamesInOrder(): string[] {\n return this.toolCalls.map((c) => c.name);\n }\n\n /** Last assistant message text — the agent's \"reply\". */\n get reply(): string {\n for (let i = this.messages.length - 1; i >= 0; i--) {\n if (this.messages[i]!.role === \"assistant\") return this.messages[i]!.text;\n }\n return \"\";\n }\n\n /** Number of completed assistant turns. */\n get turnCount(): number {\n return this.messages.filter((m) => m.role === \"assistant\").length;\n }\n\n /** Tool or subagent calls that reported an error. */\n get failedActions(): number {\n return this.events.filter(\n (e) =>\n (e.kind === \"tool_call\" || e.kind === \"subagent_call\") &&\n e.status === \"error\",\n ).length;\n }\n\n get durationMs(): number {\n if (this.startedAt != null && this.endedAt != null) {\n return Math.max(0, this.endedAt - this.startedAt);\n }\n // Fallback: sum recorded latencies when no wall-clock span is available.\n return this.events.reduce((sum, e) => {\n if (\"latencyMs\" in e && typeof e.latencyMs === \"number\") {\n return sum + e.latencyMs;\n }\n return sum;\n }, 0);\n }\n}\n","/**\n * Cross-framework Flow normalizers — the \"plugs\" that let agents NOT built on\n * apo's adapter produce a {@link Flow} from their own output, so the same\n * `t.*` checks work for everyone.\n *\n * Each normalizer is `(source) => Flow`. Add new ones by following the shape.\n *\n * @deprecated These are **compatibility recording adapters**,\n * not the primary testing architecture. The canonical path is now the Trace\n * Projection snapshot (`TraceProjectionSnapshot` → `TraceView` →\n * `runTraceChecks`). These normalizers remain available during the\n * deprecation period; `snapshotFromFlow` bridges their output into the\n * projection contract. New integrations should emit standard OTel spans\n * instead of producing a Flow.\n */\n\nimport type { Flow, FlowEvent } from \"./types.ts\";\n\nfunction safeParse(raw: unknown): unknown {\n if (typeof raw !== \"string\") return raw;\n try {\n return JSON.parse(raw);\n } catch {\n return raw;\n }\n}\n\n// ── OpenAI (chat completions message log) ────────────────────────────────\n\nexport interface OpenAIMessage {\n role?: string;\n content?: string | null;\n tool_calls?: Array<{\n id?: string;\n function?: { name?: string; arguments?: string };\n }>;\n tool_call_id?: string;\n}\n\nexport function fromOpenAIMessages(messages: OpenAIMessage[]): Flow {\n const events: FlowEvent[] = [];\n // First pass: tool results keyed by tool_call_id.\n const results = new Map<string, unknown>();\n for (const m of messages) {\n if (m.role === \"tool\" && m.tool_call_id) {\n results.set(m.tool_call_id, m.content);\n }\n }\n for (const m of messages) {\n if (m.role === \"user\") {\n events.push({ kind: \"message\", role: \"user\", text: m.content ?? \"\" });\n } else if (m.role === \"assistant\") {\n events.push({ kind: \"message\", role: \"assistant\", text: m.content ?? \"\" });\n for (const tc of m.tool_calls ?? []) {\n events.push({\n kind: \"tool_call\",\n name: tc.function?.name ?? \"unknown\",\n input: safeParse(tc.function?.arguments),\n output: tc.id ? results.get(tc.id) : undefined,\n });\n }\n }\n }\n return { events };\n}\n\n// ── Anthropic (messages API content blocks) ──────────────────────────────\n\nexport interface AnthropicMessage {\n role?: string;\n content?: Array<\n | { type: \"text\"; text: string }\n | { type: \"tool_use\"; id: string; name: string; input?: unknown }\n | { type: \"tool_result\"; tool_use_id: string; content?: unknown }\n >;\n}\n\nexport function fromAnthropicMessages(messages: AnthropicMessage[]): Flow {\n const events: FlowEvent[] = [];\n const results = new Map<string, unknown>();\n for (const m of messages) {\n for (const block of m.content ?? []) {\n if (block.type === \"tool_result\") {\n results.set(block.tool_use_id, block.content);\n }\n }\n }\n for (const m of messages) {\n const role = m.role === \"user\" ? \"user\" : \"assistant\";\n for (const block of m.content ?? []) {\n if (block.type === \"text\") {\n events.push({ kind: \"message\", role, text: block.text });\n } else if (block.type === \"tool_use\") {\n events.push({\n kind: \"tool_call\",\n name: block.name,\n input: block.input,\n output: results.get(block.id),\n });\n }\n }\n }\n return { events };\n}\n\n// ── Vercel AI SDK (generateText / streamText result) ─────────────────────\n\nexport interface AISDKResult {\n steps?: Array<{\n text?: string;\n toolCalls?: Array<{ toolName: string; input?: unknown }>;\n toolResults?: Array<{ toolName: string; output?: unknown }>;\n }>;\n}\n\nexport function fromAISDK(result: AISDKResult): Flow {\n const events: FlowEvent[] = [];\n for (const step of result.steps ?? []) {\n if (step.text) {\n events.push({ kind: \"message\", role: \"assistant\", text: step.text });\n }\n const outputs = step.toolResults ?? [];\n const toolCalls = step.toolCalls ?? [];\n toolCalls.forEach((tc, i) => {\n events.push({\n kind: \"tool_call\",\n name: tc.toolName,\n input: tc.input,\n output: outputs[i]?.output,\n });\n });\n }\n return { events };\n}\n","import type { AgentTaskRunConfiguration } from \"../adapter/types.ts\";\n\n/**\n * validate and normalize an adapter-reported Run Configuration.\n *\n * Mirrors the backend validation contract so the SDK and the shared backend\n * finalizer enforce identical rules. Returns `undefined` when no configuration\n * was reported. An invalid configuration (blank model, oversized value, or a\n * NUL/control character) throws — it is an adapter contract error that must\n * fail the Task Run before the first Task Turn.\n *\n * Rules:\n * - trim leading/trailing whitespace from `model` and `effort`;\n * - `model` is required (1–255 UTF-8 bytes);\n * - `effort` is optional; when present it is 1–64 UTF-8 bytes (an\n * empty/whitespace effort normalizes to `undefined` = not reported);\n * - reject NUL and ASCII control characters (checked before trimming, since\n * some runtimes strip C0 controls as whitespace);\n * - preserve casing and punctuation.\n *\n * Error messages name the field only — never echo secret-bearing source values.\n */\nexport function normalizeRunConfiguration(\n raw: AgentTaskRunConfiguration | undefined,\n): AgentTaskRunConfiguration | undefined {\n if (!raw) return undefined;\n const model = normalizeScalar(raw.model, \"run_configuration.model\", MAX_MODEL_BYTES, true);\n const effort = normalizeScalar(\n raw.effort,\n \"run_configuration.effort\",\n MAX_EFFORT_BYTES,\n false,\n );\n return effort === undefined ? { model } : { model, effort };\n}\n\nconst MAX_MODEL_BYTES = 255;\nconst MAX_EFFORT_BYTES = 64;\n// NUL and ASCII control characters (C0 controls plus DEL).\n// oxlint-disable-next-line no-control-regex -- intentional: these are the characters we reject.\nconst CONTROL_CHARS = /[\\x00-\\x1f\\x7f]/;\n\nconst utf8Encoder = new TextEncoder();\n\nfunction utf8ByteLength(value: string): number {\n return utf8Encoder.encode(value).length;\n}\n\nfunction normalizeScalar(\n value: string | undefined,\n field: string,\n maxBytes: number,\n required: true,\n): string;\nfunction normalizeScalar(\n value: string | undefined,\n field: string,\n maxBytes: number,\n required: false,\n): string | undefined;\nfunction normalizeScalar(\n value: string | undefined,\n field: string,\n maxBytes: number,\n required: boolean,\n): string | undefined {\n if (value === undefined) {\n if (required) throw new Error(`${field} is required`);\n return undefined;\n }\n if (CONTROL_CHARS.test(value)) {\n throw new Error(`${field} must not contain control characters`);\n }\n const trimmed = value.trim();\n if (trimmed === \"\") {\n if (required) throw new Error(`${field} is required and must be non-empty`);\n return undefined;\n }\n if (utf8ByteLength(trimmed) > maxBytes) {\n throw new Error(`${field} must be at most ${maxBytes} UTF-8 bytes`);\n }\n return trimmed;\n}\n","import type {\n CollectedDeliverables,\n DeliverableDefinition,\n ValidatableSchemaLike,\n} from \"../adapter/types.ts\";\nimport type { TaskDefinition } from \"../task/types.ts\";\nimport type { DeliverableValidationResult } from \"./types.ts\";\n\nfunction isZodSchema(value: unknown): value is ValidatableSchemaLike {\n return (\n typeof value === \"object\" &&\n value !== null &&\n \"safeParse\" in value &&\n typeof (value as Record<string, unknown>).safeParse === \"function\"\n );\n}\n\nexport function validateDeliverables(\n task: TaskDefinition,\n collected: CollectedDeliverables,\n deliverableDefs?: Record<string, DeliverableDefinition>,\n): DeliverableValidationResult {\n const results: DeliverableValidationResult[\"results\"] = [];\n const brokenDeliverables: Record<string, string> = {};\n\n for (const deliverableName of task.deliverables) {\n const value = collected[deliverableName];\n\n if (value === undefined || value === null) {\n const reason = `Deliverable '${deliverableName}' is missing`;\n results.push({\n id: `deliverable:${deliverableName}`,\n pass: false,\n reasoning: reason,\n });\n brokenDeliverables[deliverableName] = reason;\n continue;\n }\n\n const schema = resolveDeliverableSchema(\n deliverableDefs?.[deliverableName],\n );\n if (schema && isZodSchema(schema)) {\n const result = schema.safeParse(value);\n if (!result.success) {\n const reason = `Deliverable '${deliverableName}' failed schema validation: ${result.error?.message ?? \"Unknown error\"}`;\n results.push({\n id: `deliverable:${deliverableName}`,\n pass: false,\n reasoning: reason,\n });\n brokenDeliverables[deliverableName] = reason;\n }\n }\n }\n\n return { results, brokenDeliverables };\n}\n\nfunction resolveDeliverableSchema(\n definition: DeliverableDefinition | undefined,\n): ValidatableSchemaLike | undefined {\n if (!definition) {\n return undefined;\n }\n\n if (isZodSchema(definition)) {\n return definition;\n }\n\n if (\n typeof definition === \"object\" &&\n definition !== null &&\n \"schema\" in definition &&\n isZodSchema(definition.schema)\n ) {\n return definition.schema;\n }\n\n return undefined;\n}\n","/**\n * Projection tee — wraps a real {@link AgentTaskTraceContext} and records the\n * span lifecycle into a {@link TraceProjectionSnapshot}.\n *\n * This is the FlowTee replacement. FlowTee recorded legacy `FlowEvent`s which\n * `snapshotFromFlow` converted to a snapshot. This tee records\n * `TraceProjectionObservation`s directly — same source-of-truth, no Flow\n * intermediate. It delegates every call to the wrapped context (the real OTel\n * client), so real OTel spans still export via OTLP. The snapshot is only the\n * local, in-process assertion surface.\n *\n * The recording logic mirrors `local-recorder.ts` but as a delegating wrapper\n * rather than a standalone context.\n */\n\nimport type { AgentTaskTraceContext } from \"../tracing.ts\";\nimport type {\n CreateSpanParams,\n EndSpanParams,\n TraceEventOptions,\n CreateScoreParams,\n} from \"../../types.ts\";\nimport type {\n ObservationStatus,\n TraceProjectionCapabilities,\n TraceProjectionObservation,\n TraceProjectionSnapshot,\n} from \"./types.ts\";\n\nfunction monotonicNowMs(): number {\n if (typeof performance !== \"undefined\" && typeof performance.now === \"function\") {\n return performance.now();\n }\n return Date.now();\n}\n\nfunction round3(n: number): number {\n return Math.round(n * 1000) / 1000;\n}\n\nfunction observationTypeFor(\n t: CreateSpanParams[\"observation_type\"],\n): TraceProjectionObservation[\"type\"] {\n switch (t) {\n case \"GENERATION\": return \"GENERATION\";\n case \"TOOL\": return \"TOOL\";\n case \"AGENT\": return \"AGENT\";\n case \"CHAIN\": return \"CHAIN\";\n case \"RETRIEVER\": return \"RETRIEVER\";\n case \"EMBEDDING\": return \"EMBEDDING\";\n case \"GUARDRAIL\": return \"GUARDRAIL\";\n default: return \"SPAN\";\n }\n}\n\ninterface PendingObservation {\n spanId: string;\n parentSpanId?: string;\n type: TraceProjectionObservation[\"type\"];\n name: string;\n startedAtIso: string;\n startedAtMs: number;\n model?: string;\n input?: unknown;\n}\n\nfunction extractText(output: unknown): string {\n if (typeof output === \"string\") return output;\n if (output != null && typeof output === \"object\" && \"text\" in output) {\n const text = (output as { text: unknown }).text;\n if (typeof text === \"string\") return text;\n }\n return \"\";\n}\n\nfunction deriveCapabilities(\n observations: readonly TraceProjectionObservation[],\n): TraceProjectionCapabilities {\n const hasType = (t: TraceProjectionObservation[\"type\"]) =>\n observations.some((o) => o.type === t);\n const hasMessages = observations.some(\n (o) => o.type === \"GENERATION\" && o.messages && o.messages.length > 0,\n );\n return {\n messages: hasMessages ? \"available\" : \"unavailable\",\n tools: hasType(\"TOOL\") ? \"available\" : \"unavailable\",\n // Local capture records every span's status, so error evidence is always\n // available — the absence of error observations IS proof of no errors.\n errors: \"available\",\n timing: \"available\",\n skills: hasType(\"SKILL\") ? \"available\" : \"unavailable\",\n subagents: hasType(\"AGENT\") ? \"available\" : \"unavailable\",\n };\n}\n\nexport interface ProjectionTee {\n /** The wrapped trace context — delegate all span calls to this. */\n trace: AgentTaskTraceContext;\n /** Freeze the current observations into an immutable snapshot. */\n getSnapshot(): TraceProjectionSnapshot;\n}\n\n/**\n * Wrap a real {@link AgentTaskTraceContext} so every span/step call is\n * delegated to it (real OTel export) while also recording observations for a\n * local projection snapshot. This replaces FlowTee + snapshotFromFlow.\n */\nexport function createProjectionTee(\n real: AgentTaskTraceContext,\n): ProjectionTee {\n const observations: TraceProjectionObservation[] = [];\n const pending = new Map<string, PendingObservation>();\n // Map tee-issued span ids to the real context's span ids so endSpan can\n // resolve the real span it must close. Without this, createSpan discards\n // real.createSpan's return value and endSpan can never find the real span —\n // the span is never ended, never exported, and its usage is lost.\n const realIdByTeeId = new Map<string, string>();\n let spanCounter = 0;\n\n // Trace-level timing — captured at tee creation (root span start) and read\n // at snapshot time (root span end). Mirrors local-recorder.ts so that\n // TraceView.durationMs has the startedAt/endedAt pair it needs. Without\n // this, deriveCapabilities hard-codes timing:\"available\" but the trace\n // object carries no timestamps, so t.maxDurationMs sees undefined and\n // reports \"timing evidence unavailable\" despite every observation being\n // individually timestamped.\n const rootStartMs = monotonicNowMs();\n const rootStartIso = new Date(rootStartMs).toISOString();\n\n function complete(spanId: string, params: Omit<EndSpanParams, \"id\"> | undefined): void {\n const p = pending.get(spanId);\n if (!p) return;\n pending.delete(spanId);\n const endedAtMs = monotonicNowMs();\n const isError = params?.level === \"ERROR\";\n const status: ObservationStatus = isError ? \"error\" : \"ok\";\n\n const obs: TraceProjectionObservation = {\n spanId: p.spanId,\n type: p.type,\n name: p.name,\n startedAt: p.startedAtIso,\n endedAt: new Date(endedAtMs).toISOString(),\n durationMs: round3(endedAtMs - p.startedAtMs),\n status,\n };\n if (p.parentSpanId) obs.parentSpanId = p.parentSpanId;\n if (p.model) obs.model = p.model;\n if (isError && params?.status_message) obs.errorMessage = params.status_message;\n\n const meta = params?.metadata as Record<string, unknown> | undefined;\n if (p.type === \"TOOL\") {\n obs.toolName = (meta?.tool_name as string | undefined) ?? p.name;\n if (meta?.tool_parameters !== undefined) obs.toolParameters = meta.tool_parameters;\n else if (p.input !== undefined) obs.toolParameters = p.input;\n if (meta?.tool_result !== undefined) obs.toolResult = meta.tool_result;\n else if (params?.output !== undefined) obs.output = params.output;\n } else if (params?.output !== undefined) {\n obs.output = params.output;\n }\n\n if (p.type === \"GENERATION\" && params?.output != null) {\n const text = extractText(params.output);\n if (text !== \"\") {\n obs.messages = [{ role: \"assistant\", content: text }];\n }\n }\n\n observations.push(obs);\n }\n\n function recordStart(opts: {\n step_name?: string | null;\n observation_type?: CreateSpanParams[\"observation_type\"];\n parent_call_id?: string | null;\n model?: string | null;\n input?: unknown;\n }): string {\n spanCounter += 1;\n const spanId = `${real.rootSpanId}-${String(spanCounter).padStart(6, \"0\")}`;\n pending.set(spanId, {\n spanId,\n parentSpanId: opts.parent_call_id ?? real.rootSpanId,\n type: observationTypeFor(opts.observation_type),\n name: opts.step_name ?? \"step\",\n startedAtIso: new Date(monotonicNowMs()).toISOString(),\n startedAtMs: monotonicNowMs(),\n model: opts.model ?? undefined,\n input: opts.input,\n });\n return spanId;\n }\n\n // Delegate every method to `real`, recording observations alongside.\n const trace: AgentTaskTraceContext = {\n runId: real.runId,\n rootSpanId: real.rootSpanId,\n\n async step(opts, fn) {\n // Delegate to the real context so the OTel span is created. Record one\n // observation around the whole step.\n const obsSpanId = recordStart(opts);\n const start = monotonicNowMs();\n try {\n const result = await real.step(opts, fn);\n complete(obsSpanId, {\n latency_ms: round3(monotonicNowMs() - start),\n output: opts.summarize?.(result),\n metadata: opts.metadata,\n });\n return result;\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n complete(obsSpanId, {\n latency_ms: round3(monotonicNowMs() - start),\n status_message: message,\n level: \"ERROR\",\n metadata: { ...opts.metadata, failed: true },\n });\n throw error;\n }\n },\n\n recordEvent(evOptions: TraceEventOptions): string {\n const spanId = recordStart(evOptions);\n complete(spanId, {\n latency_ms: evOptions.latency_ms,\n output: evOptions.output,\n metadata: evOptions.metadata,\n });\n try { real.recordEvent(evOptions); } catch { /* best-effort */ }\n return spanId;\n },\n\n endRoot(endParams) {\n try { real.endRoot(endParams); } catch { /* best-effort */ }\n },\n\n createSpan(spanOptions): string {\n // Generate our OWN unique span id for recording (the wrapped context\n // may return a constant in noop mode). Delegate to real for the OTel\n // export, but return our id so endSpan finds the pending observation.\n const spanId = recordStart(spanOptions);\n\n // Spans originating from the ApoSpanProcessor (which intercepts the AI\n // SDK's own OTel spans) must NOT be re-exported via real.createSpan —\n // the original span is already being exported by the OTLP exporter, so\n // creating a second one here would produce duplicate LoggedCallDB rows.\n const isFromOtelProcessor =\n (spanOptions.metadata as Record<string, unknown> | undefined)?.source === \"otel-processor\";\n\n if (!isFromOtelProcessor) {\n try {\n const realId = real.createSpan(spanOptions);\n // Remember the real id so endSpan can close the real span. Falls back\n // to the tee id when the real context returns nothing (noop mode).\n realIdByTeeId.set(spanId, realId);\n } catch { /* best-effort */ }\n }\n return spanId;\n },\n\n endSpan(spanId, endParams) {\n complete(spanId, endParams);\n const realId = realIdByTeeId.get(spanId) ?? spanId;\n realIdByTeeId.delete(spanId);\n try { real.endSpan(realId, endParams); } catch { /* best-effort */ }\n },\n\n async traceTool(name, params, fn) {\n return real.traceTool(name, params, fn);\n },\n async traceRetriever(query, fn) {\n return real.traceRetriever(query, fn);\n },\n async traceChain(name, fn) {\n return real.traceChain(name, fn);\n },\n async traceAgent(name, fn) {\n return real.traceAgent(name, fn);\n },\n async traceGuardrail(name, fn) {\n return real.traceGuardrail(name, fn);\n },\n async traceEmbedding(model, input, fn) {\n return real.traceEmbedding(model, input, fn);\n },\n async score(params: CreateScoreParams) {\n return real.score(params);\n },\n };\n\n return {\n trace,\n getSnapshot(): TraceProjectionSnapshot {\n const endMs = monotonicNowMs();\n return {\n schemaVersion: 1,\n projectionVersion: 1,\n source: \"local\",\n trace: {\n traceId: real.runId,\n startedAt: rootStartIso,\n endedAt: new Date(endMs).toISOString(),\n durationMs: round3(endMs - rootStartMs),\n complete: true,\n },\n capabilities: deriveCapabilities(observations),\n observations: [...observations],\n };\n },\n };\n}\n","/**\n * Remote trace projection reader.\n *\n * Polls the Task-Run-scoped projection endpoint\n * (`GET /v1/agent-task-runs/{task_run_id}/trace-projection`) with bounded\n * exponential backoff until the projection is ready, then returns the immutable\n * snapshot Phase 2 evaluation reads.\n *\n * This is the canonical capture path for backend-launched required-persistence\n * runs: after the OTel exporter force-flushes, the runner polls its own\n * projection endpoint to read back the durable, projected trace — the same one\n * the dashboard shows.\n */\n\nimport type { TraceProjectionSnapshot } from \"./types.ts\";\n\n/** Configuration for the projection read retry loop. */\nexport interface ProjectionReadOptions {\n /** The backend base URL, e.g. ``\"http://localhost:8000\"``. */\n endpoint: string;\n /** The service token (Authorization: Bearer …). */\n authToken: string;\n /** The task run ID whose projection to read. */\n taskRunId: string;\n /** Maximum total wait time in milliseconds (default: 30000). */\n deadlineMs?: number;\n /** Initial retry interval in milliseconds (default: 500). */\n initialIntervalMs?: number;\n /** Maximum retry interval after backoff (default: 5000). */\n maxIntervalMs?: number;\n}\n\n/** Error thrown when the projection is not ready within the deadline. */\nexport class ProjectionTimeoutError extends Error {\n constructor(taskRunId: string, deadlineMs: number) {\n super(\n `Trace projection for task run ${taskRunId} was not ready within ${deadlineMs}ms`,\n );\n this.name = \"ProjectionTimeoutError\";\n }\n}\n\n/**\n * Read the projection snapshot for a task run, retrying with bounded\n * exponential backoff until it's ready (200) or the deadline expires.\n *\n * Throws {@link ProjectionTimeoutError} on timeout. Throws on 403/404/409\n * (the endpoint's permanent-error responses).\n */\nexport async function readTaskRunProjection(\n options: ProjectionReadOptions,\n): Promise<TraceProjectionSnapshot> {\n const deadlineMs = options.deadlineMs ?? 30_000;\n const initialIntervalMs = options.initialIntervalMs ?? 500;\n const maxIntervalMs = options.maxIntervalMs ?? 5_000;\n\n const url = `${options.endpoint.replace(/\\/$/, \"\")}/v1/agent-task-runs/${encodeURIComponent(options.taskRunId)}/trace-projection`;\n const start = Date.now();\n let interval = initialIntervalMs;\n\n // eslint-disable-next-line no-constant-condition\n while (true) {\n if (Date.now() - start > deadlineMs) {\n throw new ProjectionTimeoutError(options.taskRunId, deadlineMs);\n }\n\n const response = await fetch(url, {\n headers: { Authorization: `Bearer ${options.authToken}` },\n });\n\n if (response.status === 200) {\n return (await response.json()) as TraceProjectionSnapshot;\n }\n\n if (response.status === 202) {\n // Not ready yet — back off and retry.\n await sleep(interval);\n interval = Math.min(interval * 1.5, maxIntervalMs);\n continue;\n }\n\n // 403/404/409 — permanent errors, surface immediately.\n const detail = await response.json().catch(() => ({ detail: response.statusText }));\n throw new Error(\n `Projection read failed (${response.status}): ${(detail as { detail?: string }).detail ?? response.statusText}`,\n );\n }\n}\n\nfunction sleep(ms: number): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, ms));\n}\n","/**\n * apo semantic conventions — the stable attribute layer on top of OTLP.\n *\n * apo uses standard OpenTelemetry as the transport (OTLP/JSON spans) and\n * standard GenAI semantic conventions (`gen_ai.*`) where they're useful.\n * But `gen_ai.*` is still experimental as of 2026, and some apo concepts\n * (scores, run metadata, observation typing) have no OTel equivalent at all.\n *\n * This module defines the `apo.*` attribute namespace — a stable semantic\n * layer (like Phoenix's OpenInference) that:\n * 1. Encodes apo-specific concepts that OTel doesn't model (scores, runs).\n * 2. Provides a stable contract independent of `gen_ai.*` churn.\n * 3. Is the single source of truth for both the TS SDK and the Python path.\n *\n * The backend's OTLP mapper (`backend/apo/services/otel_mapper.py`) strips the\n * `apo.` prefix and routes these into the internal field names.\n *\n * @module\n */\n\n// ── Observation type ──────────────────────────────────────────────────────\n//\n// Overrides the mapper's automatic type detection. Set this on any span to\n// force its observation_type (GENERATION, TOOL, CHAIN, etc.).\n\nexport const APO_OBSERVATION_TYPE = \"apo.observation.type\" as const;\n\n// ── Run identity ──────────────────────────────────────────────────────────\n//\n// Carried on the root span of a trace. The backend's OTLP route synthesizes a\n// run-create from the first-seen traceId; these attributes populate the run's\n// task_id, flow_name, version, and tags.\n\nexport const APO_RUN_ID = \"apo.run.id\" as const;\nexport const APO_RUN_FLOW_NAME = \"apo.run.flow_name\" as const;\nexport const APO_RUN_TASK_ID = \"apo.run.task_id\" as const;\nexport const APO_RUN_VERSION = \"apo.run.version\" as const;\nexport const APO_RUN_TAGS = \"apo.run.tags\" as const; // JSON array string\n\n// ── Task-run ownership ──────────────────────────────────────\n//\n// Carried on the root span of a task-run Trace. The backend projector reads\n// `apo.task.run.id` and atomically claims `AgentTaskRunDB.trace_run_id`,\n// enforcing the one-trace-per-task-run invariant. Without these\n// attributes the claim path never fires for agent-task runs.\n\nexport const APO_TASK_ID = \"apo.task.id\" as const;\nexport const APO_TASK_RUN_ID = \"apo.task.run.id\" as const;\n\n// Scores are domain records via the HTTP score API, not sentinel spans.\n// See `score()` in `@apo-ai/sdk/otel` — it calls POST /api/v1/traces/{id}/scores.\n\n// ── Cost ──────────────────────────────────────────────────────────────────\n//\n// Optional client-computed cost for a GENERATION span. The backend also\n// computes `calculated_cost` server-side from token counts + model pricing;\n// this attribute carries the client-side estimate if the client has it.\n\nexport const APO_COST = \"apo.cost\" as const;\n\n// ── Enumeration values ────────────────────────────────────────────────────\n\nexport const OBSERVATION_TYPES = [\n \"GENERATION\",\n \"SPAN\",\n \"TOOL\",\n \"CHAIN\",\n \"RETRIEVER\",\n \"EVALUATOR\",\n \"EMBEDDING\",\n \"GUARDRAIL\",\n \"AGENT\",\n] as const;\n\nexport const SCORE_DATA_TYPES = [\"NUMERIC\", \"CATEGORICAL\", \"BOOLEAN\"] as const;\n\nexport const SCORE_SOURCES = [\"API\", \"EVAL\", \"ANNOTATION\"] as const;\n","import type { EvaluationItemResult, TaskEvaluationResult } from \"./types.ts\";\n\n/**\n * Issue #8: shown when a run ends with zero registered checks. A bare\n * `FAIL <task>` with no Checks section looked like a real failure but was\n * almost always a silent registration bug (e.g. a double-import that wiped\n * the check registry). Naming `test()` matches the documented registration\n * function — `apps/docs` reference/task.md.\n *\n * Lives next to {@link aggregateResult} because the empty-checks verdict is\n * the single source of truth for \"why did this run fail with no checks?\".\n * The CLI and the standalone e2e runner both import this so the wording\n * stays in one place.\n */\nexport const NO_CHECKS_REGISTERED_MESSAGE =\n \"No tests were registered by the eval module — a task must define at least one test().\";\n\nexport function aggregateResult(\n checksResults: EvaluationItemResult[],\n): TaskEvaluationResult {\n if (checksResults.length === 0) {\n return { checks: checksResults, pass: false };\n }\n const pass = checksResults.every((r) => r.pass);\n return { checks: checksResults, pass };\n}\n","import type {\n TraceRunContext,\n TraceRunOptions,\n CreateScoreParams,\n CreateSpanParams,\n EndSpanParams,\n} from \"../types.ts\";\nimport type { TraceEventOptions, TraceStepOptions } from \"../types.ts\";\n\nexport type AgentTaskTraceContext = TraceRunContext & {\n createSpan: (\n options: Omit<CreateSpanParams, \"project\" | \"run_id\">,\n ) => string;\n endSpan: (spanId: string, params?: Omit<EndSpanParams, \"id\">) => void;\n};\n\nexport type AgentTaskTraceOptions = {\n client: {\n traceRun<T>(\n params: TraceRunOptions,\n fn: (trace: AgentTaskTraceContext) => Promise<T>,\n ): Promise<T>;\n };\n project?: string;\n flowName?: string;\n version?: string;\n environment?: string;\n tags?: string[];\n runMetadata?: Record<string, unknown>;\n /**\n * The Task Run ID this trace should claim. Emitted as the\n * `apo.task.run.id` root-span attribute so the backend projector can\n * atomically link this trace to the task run. Omit for local/programmatic\n * runs that don't have a backend task run.\n */\n taskRunId?: string;\n};\n\nexport function createNoopAgentTaskTraceContext(): AgentTaskTraceContext {\n const noopFn = async <T>(fn: () => Promise<T>) => fn();\n return {\n runId: \"agent-task-untraced\",\n rootSpanId: \"agent-task-untraced-root\",\n async step<T>(options: TraceStepOptions, fn: (spanId: string) => Promise<T>) {\n return fn(options.id ?? \"agent-task-untraced-step\");\n },\n recordEvent(options: TraceEventOptions) {\n return options.id ?? \"agent-task-untraced-event\";\n },\n endRoot() {},\n traceTool<T>(_name: string, _params: Record<string, unknown>, fn: () => Promise<T>) {\n return noopFn(fn);\n },\n traceRetriever<T>(_query: string, fn: () => Promise<T>) {\n return noopFn(fn);\n },\n traceChain<T>(_name: string, fn: () => Promise<T>) {\n return noopFn(fn);\n },\n traceAgent<T>(_name: string, fn: () => Promise<T>) {\n return noopFn(fn);\n },\n traceGuardrail<T>(_name: string, fn: () => Promise<T>) {\n return noopFn(fn);\n },\n traceEmbedding<T>(_model: string, _input: unknown, fn: () => Promise<T>) {\n return noopFn(fn);\n },\n async score(_params: CreateScoreParams): Promise<void> {},\n createSpan(_options) {\n return \"agent-task-untraced-span\";\n },\n endSpan(_spanId, _params) {},\n };\n}\n","import type {\n TaskRunResult,\n EvaluationItemResult,\n TaskTranscriptTurn,\n} from \"./types.ts\";\nimport type { AgentTaskRunConfiguration, AdapterRuntimeState, AdapterSession } from \"../adapter/types.ts\";\nimport { normalizeRunConfiguration } from \"./run-configuration.ts\";\nimport { loadTask } from \"../task/loadTask.ts\";\nimport {\n getTaskTurn,\n resetTaskTurn,\n resolveTurn,\n type TurnRecord,\n} from \"../turn.ts\";\nimport { TaskFiles } from \"../task/TaskFiles.ts\";\nimport { validateDeliverables } from \"../deliverables/validate.ts\";\nimport {\n loadAndRunFlowChecks,\n loadChecksModule,\n proxyBrokenDeliverables,\n resetFlowChecks,\n runTraceChecks,\n} from \"../checks/flow-runner.ts\";\nimport { createProjectionTee } from \"../trace-projection/projection-tee.ts\";\nimport { readTaskRunProjection } from \"../trace-projection/remote-capture.ts\";\nimport type { JudgeConfig } from \"../checks/t.ts\";\nimport { APO_TASK_ID, APO_TASK_RUN_ID } from \"../../semconv.ts\";\nimport { aggregateResult } from \"./aggregate.ts\";\nimport type { AgentTaskTraceContext, AgentTaskTraceOptions } from \"../tracing.ts\";\nimport { createNoopAgentTaskTraceContext } from \"../tracing.ts\";\nimport type { LoadedTask } from \"../task/loadTask.ts\";\nimport { withApoRun } from \"../integrations/run-context.ts\";\n\n/**\n * Error thrown when a Task Run fails after the adapter's Run Configuration\n * has been resolved. Carries the resolved {@link AgentTaskRunConfiguration} so\n * callers (e.g. the CLI error-report path) can forward model/effort to the\n * backend even when the run never produced a summary (issue #40).\n *\n * The original failure is preserved on `cause`. Only errors thrown after\n * `startSession` reported a *valid* configuration are wrapped — a\n * configuration-validation failure propagates unwrapped (there is nothing to\n * attach).\n */\nexport class AgentTaskRunError extends Error {\n readonly runConfiguration?: AgentTaskRunConfiguration;\n /** The original error that caused the run to fail (preserved for diagnostics). */\n readonly cause?: unknown;\n constructor(\n message: string,\n options: { runConfiguration?: AgentTaskRunConfiguration; cause?: unknown },\n ) {\n super(message);\n this.name = \"AgentTaskRunError\";\n this.runConfiguration = options.runConfiguration;\n this.cause = options.cause;\n }\n}\n\n/**\n * Wrap an error with the resolved Run Configuration so it survives the throw\n * out of the run. Returns the original error unchanged when there is no\n * configuration to attach (old adapter) or when it is already branded.\n */\nfunction withRunConfiguration(\n error: unknown,\n runConfiguration: AgentTaskRunConfiguration | undefined,\n): unknown {\n if (!runConfiguration) return error;\n if (error instanceof AgentTaskRunError) return error;\n const message = error instanceof Error ? error.message : String(error);\n return new AgentTaskRunError(message, { runConfiguration, cause: error });\n}\n\nexport type RunTaskOptions = {\n maxTurnsOverride?: number;\n tracing?: AgentTaskTraceOptions;\n /** LLM judge model config for `t.judge(...)` calls in the task checks. */\n judge?: JudgeConfig;\n onTurn?: (\n turnNumber: number,\n userAction: TaskTranscriptTurn[\"userAction\"],\n agentResponse: unknown,\n ) => void;\n /**\n * Skip the internal `loadTask(taskDir)` call and reuse an already-loaded\n * task definition.\n *\n * The eval module's top level runs once per `loadTask` (it is copied to a\n * temp file and imported with all registries reset), so loading twice per\n * run breaks evals whose load-time behavior is not idempotent across module\n * systems (e.g. a helper that re-exports CJS `require()`-cached registrations\n * — the second import hits the cache and registers zero checks). Callers\n * that already need a `LoadedTask` for their own purposes (`runTaskDir`,\n * `runner-entry.ts`) should always pass it through here to keep the eval\n * import count at exactly one per run.\n *\n * When omitted, `runTask` calls `loadTask(taskDir)` itself. The `taskDir`\n * argument is still required for that fallback and is otherwise unused.\n */\n loaded?: LoadedTask;\n};\n\nexport async function runTask(\n taskDir: string,\n options?: RunTaskOptions,\n): Promise<TaskRunResult> {\n // Reuse an already-loaded task when provided — see `RunTaskOptions.loaded`.\n // Otherwise load it here (the eval module is imported exactly once either way).\n const loaded = options?.loaded ?? (await loadTask(taskDir));\n const trace = options?.tracing;\n\n if (!trace) {\n // No tracing — run everything in one pass (no two-phase split needed;\n // there's no trace to contaminate).\n return executeLoadedTask(\n loaded,\n options,\n createNoopAgentTaskTraceContext(),\n undefined,\n );\n }\n\n // Phase 1 (capture) runs inside the traceRun\n // callback; Phase 2 (evaluate) runs AFTER the root span ends and the trace\n // flushes, so checks/deliverable-validation cannot contaminate the trace.\n const phase1 = await trace.client.traceRun(\n buildTraceRunOptions(loaded, trace),\n async (traceContext) => captureExecution(loaded, options, traceContext),\n );\n\n // when this run is backend-launched (has a taskRunId),\n // read the canonical projection snapshot back from the backend instead of\n // the local tee. The backend's projection is the single source of truth —\n // it includes spans the subprocess exported natively over OTLP (which the\n // in-process tee can never see, since they're created in another process).\n // Falls back to the local snapshot on any failure (offline runs, unreachable\n // backend, projection timeout) so evaluation still runs.\n const canonical = await readCanonicalSnapshot(trace);\n if (canonical) phase1.snapshot = canonical;\n\n // Phase 2: evaluate against the frozen snapshot. The trace is now closed.\n return evaluate(loaded, options, phase1);\n}\n\n/**\n * Read the canonical projection snapshot from the backend (Track C).\n *\n * Returns `null` when there's nothing to read (no taskRunId = offline/local\n * run) or when the read fails for any reason — the caller falls back to the\n * local tee snapshot in that case. Errors are logged but never thrown: a\n * projection read problem must not fail the task run.\n */\nasync function readCanonicalSnapshot(\n trace: AgentTaskTraceOptions,\n): Promise<CapturedExecution[\"snapshot\"] | null> {\n if (!trace.taskRunId) return null; // offline/local run — no backend read\n const endpoint = process.env.AGENT_TASK_TRACE_ENDPOINT;\n const authToken = process.env.APO_AUTH_TOKEN;\n if (!endpoint || !authToken) return null;\n try {\n return await readTaskRunProjection({\n endpoint,\n authToken,\n taskRunId: trace.taskRunId,\n });\n } catch (error) {\n console.error(\n \"[AgentTask] Backend projection read failed, using local snapshot:\",\n error instanceof Error ? error.message : String(error),\n );\n return null;\n }\n}\n\n/** Phase 1 result: what capture produced, passed to Phase 2 evaluation. */\ninterface CapturedExecution {\n traceRunId: string | undefined;\n collected: Record<string, unknown>;\n transcriptTurns: TaskTranscriptTurn[];\n /** The adapter-reported run configuration, captured right after session open. */\n runConfiguration: AgentTaskRunConfiguration | undefined;\n /** The frozen projection snapshot Phase 2 evaluates against. */\n snapshot: import(\"../trace-projection/types.ts\").TraceProjectionSnapshot;\n}\n\nasync function executeLoadedTask(\n loaded: LoadedTask,\n options: RunTaskOptions | undefined,\n rawTrace: AgentTaskTraceContext,\n traceRunId: string | undefined,\n): Promise<TaskRunResult> {\n const {\n task,\n adapter,\n taskDir: absoluteDir,\n files,\n checksPath,\n inlineChecks,\n moduleUrl,\n evalFileName,\n } = loaded;\n const taskFiles = new TaskFiles(files);\n // Tee the trace so the run's tool/agent/message spans also build the\n // projection snapshot that checks read. `trace` below is the wrapped context.\n const tee = createProjectionTee(rawTrace);\n const { trace, getSnapshot } = { trace: tee.trace, getSnapshot: () => tee.getSnapshot() };\n\n // Establish the run on AsyncLocalStorage so the OTel SpanProcessor\n // (if registered) can route GenAI spans to this run's trace context.\n return withApoRun(\n { trace, parentSpanId: rawTrace.rootSpanId, taskId: task.id },\n async () => {\n // All the local state that the previous body used, now inside the ALS scope\n return executeRunBody();\n },\n );\n\n async function executeRunBody(): Promise<TaskRunResult> {\n let state: AdapterRuntimeState | undefined;\n let session: AdapterSession | undefined;\n const transcriptTurns: TaskTranscriptTurn[] = [];\n\n try {\n await trace.step(\n {\n step_name: \"task.load\",\n input: { taskId: task.id, taskDir: absoluteDir },\n metadata: {\n taskId: task.id,\n taskDir: absoluteDir,\n fileCount: files.length,\n hasChecks: inlineChecks || checksPath !== null,\n },\n summarize: () => ({\n taskId: task.id,\n adapterName: adapter.name,\n }),\n },\n async () => loaded,\n );\n\n if (adapter.initialize) {\n const initState = await trace.step(\n {\n step_name: \"adapter.initialize\",\n input: { adapterName: adapter.name },\n metadata: { adapterName: adapter.name },\n summarize: (result) => ({\n initialized: true,\n stateKeys:\n result && typeof result === \"object\"\n ? Object.keys(result as Record<string, unknown>)\n : [],\n }),\n },\n async () =>\n adapter.initialize?.({\n task,\n taskDir: absoluteDir,\n files,\n trace,\n }),\n );\n state = initState ?? undefined;\n }\n\n session = await trace.step(\n {\n step_name: \"adapter.open-session\",\n input: { adapterName: adapter.name, hasState: state !== undefined },\n metadata: { adapterName: adapter.name },\n summarize: () => ({ sessionOpened: true }),\n },\n async () =>\n adapter.startSession({\n task,\n taskDir: absoluteDir,\n files,\n state,\n trace,\n }),\n );\n\n // capture the adapter's resolved model/effort immediately after\n // the session opens and validate it before the first Task Turn. An invalid\n // reported configuration is an adapter contract error and fails the run.\n const runConfiguration = normalizeRunConfiguration(session.runConfiguration);\n\n // Issue #40: anything that throws past this point (a Task Turn, deliverable\n // collection, checks) must carry the resolved configuration out so callers\n // can still report model/effort on an errored run.\n try {\n // Legacy two-file tasks register turn() from checks.ts. Single-file tasks\n // already registered it while loadTask imported the .eval.ts file.\n if (!inlineChecks && checksPath) {\n resetTaskTurn();\n resetFlowChecks();\n await loadChecksModule(checksPath);\n }\n\n const taskTurn = getTaskTurn();\n resetTaskTurn();\n const turnFn = resolveTurn(adapter.turn, taskTurn);\n\n if (turnFn) {\n const turnTranscript: TurnRecord[] = [];\n let lastTurnResponse: unknown;\n // Precedence: explicit run override → task config → default 10.\n const maxTurns = options?.maxTurnsOverride ?? task.maxTurns ?? 10;\n\n for (let turnNum = 1; turnNum <= maxTurns; turnNum++) {\n const userTurn = await turnFn({ files: taskFiles, transcript: turnTranscript });\n if (userTurn === null || userTurn === undefined) break;\n\n const result = await trace.step(\n {\n step_name: \"task.turn\",\n metadata: { turnNumber: turnNum },\n summarize: (r) => ({ response: (r as { response: unknown }).response }),\n },\n async (spanId) => {\n if (!session) throw new Error(\"Session not created\");\n return session.sendUserTurn(userTurn, {\n trace,\n turnNumber: turnNum,\n parentSpanId: spanId,\n });\n },\n );\n\n turnTranscript.push({\n turnNumber: turnNum,\n input: userTurn,\n output: result.response,\n });\n transcriptTurns.push({\n turnNumber: turnNum,\n userAction: userTurn,\n agentResponse: result.response,\n });\n options?.onTurn?.(turnNum, userTurn, result.response);\n lastTurnResponse = result.response;\n }\n // Issue #45: roll the final turn's response up to the run root so the\n // trace header / run list shows what the agent answered at a glance.\n if (lastTurnResponse !== undefined) {\n rawTrace.endRoot({ output: { response: lastTurnResponse } });\n }\n }\n\n const collected = await trace.step(\n {\n step_name: \"adapter.collect-deliverables\",\n input: { adapterName: adapter.name, expectedDeliverables: task.deliverables },\n metadata: { adapterName: adapter.name },\n summarize: (result) => {\n const keys =\n result && typeof result === \"object\"\n ? Object.keys(result as Record<string, unknown>)\n : [];\n return { deliverableCount: keys.length, deliverableNames: keys };\n },\n },\n async () => {\n if (!session) {\n throw new Error(\"Adapter session was not created\");\n }\n\n return adapter.collectDeliverables({\n task,\n taskDir: absoluteDir,\n files,\n state,\n session,\n trace,\n });\n },\n );\n\n const validationResults = await trace.step(\n {\n step_name: \"deliverables.validate\",\n input: { deliverableNames: task.deliverables },\n summarize: (result) => {\n const r = result as ReturnType<typeof validateDeliverables>;\n const passCount = r.results.filter((x) => x.pass).length;\n const broken = Object.keys(r.brokenDeliverables);\n return {\n total: r.results.length,\n passCount,\n failCount: r.results.length - passCount,\n brokenDeliverableCount: broken.length,\n brokenDeliverables: broken,\n };\n },\n },\n async () => validateDeliverables(task, collected, adapter.deliverables),\n );\n\n const checksResults = await trace.step(\n {\n step_name: \"checks.run\",\n input: { sourceFile: inlineChecks ? evalFileName : checksPath },\n metadata: { sourceFile: inlineChecks ? evalFileName : checksPath },\n summarize: (result) =>\n summarizeEvaluationResults(result as EvaluationItemResult[]),\n },\n async () => {\n if (!inlineChecks) {\n return loadAndRunFlowChecks(\n checksPath,\n {\n snapshot: getSnapshot(),\n deliverables: collected,\n files,\n task,\n judgeConfig: options?.judge,\n },\n validationResults.brokenDeliverables,\n );\n }\n return runTraceChecks({\n snapshot: getSnapshot(),\n deliverables: proxyBrokenDeliverables(\n collected,\n validationResults.brokenDeliverables,\n ),\n files,\n task,\n judgeConfig: options?.judge,\n moduleUrl,\n displayFile: evalFileName,\n });\n },\n );\n\n const result = aggregateResult(checksResults);\n\n return {\n task,\n taskDir: absoluteDir,\n files,\n traceRunId,\n result,\n deliverables: collected,\n transcript: { turns: transcriptTurns },\n runConfiguration,\n };\n } catch (error) {\n throw withRunConfiguration(error, runConfiguration);\n }\n } finally {\n if (adapter.cleanup) {\n try {\n await trace.step(\n {\n step_name: \"adapter.cleanup\",\n input: { adapterName: adapter.name },\n metadata: { adapterName: adapter.name },\n summarize: () => ({ cleaned: true }),\n },\n async () =>\n adapter.cleanup?.({\n task,\n taskDir: absoluteDir,\n files,\n state,\n session,\n trace,\n }),\n );\n } catch (error) {\n console.error(\n \"[AgentTask] Cleanup failed:\",\n error instanceof Error ? error.message : String(error),\n );\n }\n }\n\n if (session?.close) {\n try {\n await session.close();\n } catch {\n // ignore close errors\n }\n }\n }\n } // end executeRunBody\n}\n\n/**\n * Phase 1: capture the execution inside the trace.\n * Runs adapter init → session → turns → deliverable collection → cleanup.\n * Excludes deliverable validation and checks — those run in Phase 2, after the\n * root span ends and the trace flushes, so they cannot contaminate the trace.\n */\nasync function captureExecution(\n loaded: LoadedTask,\n options: RunTaskOptions | undefined,\n rawTrace: AgentTaskTraceContext,\n): Promise<CapturedExecution> {\n const {\n task,\n adapter,\n taskDir: absoluteDir,\n files,\n checksPath,\n inlineChecks,\n } = loaded;\n const taskFiles = new TaskFiles(files);\n const tee = createProjectionTee(rawTrace);\n const trace = tee.trace;\n\n return withApoRun(\n { trace, parentSpanId: rawTrace.rootSpanId, taskId: task.id },\n async () => {\n let state: AdapterRuntimeState | undefined;\n let session: AdapterSession | undefined;\n const transcriptTurns: TaskTranscriptTurn[] = [];\n\n try {\n await trace.step(\n { step_name: \"task.load\", input: { taskId: task.id, taskDir: absoluteDir }, metadata: { taskId: task.id, taskDir: absoluteDir, fileCount: files.length, hasChecks: inlineChecks || checksPath !== null }, summarize: () => ({ taskId: task.id, adapterName: adapter.name }) },\n async () => loaded,\n );\n\n if (adapter.initialize) {\n const initState = await trace.step(\n { step_name: \"adapter.initialize\", input: { adapterName: adapter.name }, metadata: { adapterName: adapter.name }, summarize: (result) => ({ initialized: true, stateKeys: result && typeof result === \"object\" ? Object.keys(result as Record<string, unknown>) : [] }) },\n async () => adapter.initialize?.({ task, taskDir: absoluteDir, files, trace }),\n );\n state = initState ?? undefined;\n }\n\n session = await trace.step(\n { step_name: \"adapter.open-session\", input: { adapterName: adapter.name, hasState: state !== undefined }, metadata: { adapterName: adapter.name }, summarize: () => ({ sessionOpened: true }) },\n async () => adapter.startSession({ task, taskDir: absoluteDir, files, state, trace }),\n );\n\n // validate the adapter-reported configuration before the first\n // Task Turn. An invalid configuration fails the run inside the trace body.\n const runConfiguration = normalizeRunConfiguration(session.runConfiguration);\n\n // Issue #40: carry the resolved configuration out on any downstream\n // failure so the errored run keeps its model/effort label.\n try {\n if (!inlineChecks && checksPath) {\n resetTaskTurn();\n resetFlowChecks();\n await loadChecksModule(checksPath);\n }\n\n const taskTurn = getTaskTurn();\n resetTaskTurn();\n const turnFn = resolveTurn(adapter.turn, taskTurn);\n\n if (turnFn) {\n const turnTranscript: TurnRecord[] = [];\n let lastTurnResponse: unknown;\n const maxTurns = options?.maxTurnsOverride ?? task.maxTurns ?? 10;\n for (let turnNum = 1; turnNum <= maxTurns; turnNum++) {\n const userTurn = await turnFn({ files: taskFiles, transcript: turnTranscript });\n if (userTurn === null || userTurn === undefined) break;\n const result = await trace.step(\n { step_name: \"task.turn\", metadata: { turnNumber: turnNum }, summarize: (r) => ({ response: (r as { response: unknown }).response }) },\n async (spanId) => {\n if (!session) throw new Error(\"Session not created\");\n return session.sendUserTurn(userTurn, { trace, turnNumber: turnNum, parentSpanId: spanId });\n },\n );\n turnTranscript.push({ turnNumber: turnNum, input: userTurn, output: result.response });\n transcriptTurns.push({ turnNumber: turnNum, userAction: userTurn, agentResponse: result.response });\n options?.onTurn?.(turnNum, userTurn, result.response);\n lastTurnResponse = result.response;\n }\n // Issue #45: roll the final turn's response up to the run root.\n if (lastTurnResponse !== undefined) {\n rawTrace.endRoot({ output: { response: lastTurnResponse } });\n }\n }\n\n const collected = await trace.step(\n { step_name: \"adapter.collect-deliverables\", input: { adapterName: adapter.name, expectedDeliverables: task.deliverables }, metadata: { adapterName: adapter.name }, summarize: (result) => { const keys = result && typeof result === \"object\" ? Object.keys(result as Record<string, unknown>) : []; return { deliverableCount: keys.length, deliverableNames: keys }; } },\n async () => {\n if (!session) throw new Error(\"Adapter session was not created\");\n return adapter.collectDeliverables({ task, taskDir: absoluteDir, files, state, session, trace });\n },\n );\n\n // Freeze the snapshot from the projection tee. The root span will end\n // and flush after this callback returns — Phase 2 reads this snapshot.\n const snapshot = tee.getSnapshot();\n\n return {\n traceRunId: rawTrace.runId,\n collected: collected as Record<string, unknown>,\n transcriptTurns,\n runConfiguration,\n snapshot,\n };\n } catch (error) {\n throw withRunConfiguration(error, runConfiguration);\n }\n } finally {\n if (adapter.cleanup) {\n try {\n await trace.step(\n { step_name: \"adapter.cleanup\", input: { adapterName: adapter.name }, metadata: { adapterName: adapter.name }, summarize: () => ({ cleaned: true }) },\n async () => adapter.cleanup?.({ task, taskDir: absoluteDir, files, state, session, trace }),\n );\n } catch (error) {\n console.error(\"[AgentTask] Cleanup failed:\", error instanceof Error ? error.message : String(error));\n }\n }\n if (session?.close) {\n try { await session.close(); } catch { /* ignore */ }\n }\n }\n },\n );\n}\n\n/**\n * Phase 2: evaluate deliverables and run checks\n * AFTER the trace has closed and flushed. The snapshot is the frozen Phase-1\n * trace — checks cannot contaminate it because they run outside the trace body.\n */\nasync function evaluate(\n loaded: LoadedTask,\n options: RunTaskOptions | undefined,\n phase1: CapturedExecution,\n): Promise<TaskRunResult> {\n const {\n task,\n adapter,\n taskDir: absoluteDir,\n files,\n checksPath,\n inlineChecks,\n moduleUrl,\n evalFileName,\n } = loaded;\n\n // Validate deliverables (no longer a trace span — runs outside the trace).\n const validationResults = validateDeliverables(task, phase1.collected, adapter.deliverables);\n\n const deliverables = proxyBrokenDeliverables(\n phase1.collected,\n validationResults.brokenDeliverables,\n );\n\n const checksResults = await (inlineChecks\n ? runTraceChecks({\n snapshot: phase1.snapshot,\n deliverables,\n files,\n task,\n judgeConfig: options?.judge,\n moduleUrl,\n displayFile: evalFileName,\n })\n : loadAndRunFlowChecks(\n checksPath,\n {\n snapshot: phase1.snapshot,\n deliverables,\n files,\n task,\n judgeConfig: options?.judge,\n },\n validationResults.brokenDeliverables,\n ));\n\n const result = aggregateResult(checksResults);\n\n return {\n task,\n taskDir: absoluteDir,\n files,\n traceRunId: phase1.traceRunId,\n result,\n deliverables: phase1.collected,\n transcript: { turns: phase1.transcriptTurns },\n runConfiguration: phase1.runConfiguration,\n };\n}\n\n/** Compact summary of check evaluation results for span output.\n *\n * Keeps the full reasoning text (not just pass/fail) so the trace view\n * is useful for debugging. Also carries evaluator_type and judge model\n * when available, so the trace shows which checks were LLM-judged.\n */\nfunction summarizeEvaluationResults(results: EvaluationItemResult[]) {\n const passCount = results.filter((r) => r.pass).length;\n return {\n total: results.length,\n passCount,\n failCount: results.length - passCount,\n results: results.map((r) => ({\n id: r.id,\n pass: r.pass,\n reasoning: r.reasoning,\n evaluator_type: r.evaluator_type,\n judge_model: r.judge?.model,\n })),\n };\n}\n\nfunction buildTraceRunOptions(\n loaded: LoadedTask,\n tracing: AgentTaskTraceOptions,\n) { const tags = Array.from(new Set([\"agent-task\", \"e2e\", ...(tracing.tags ?? [])]));\n\n // Carry the task-run claim attributes on the root span. The\n // backend projector reads `apo.task.run.id` to atomically link this trace to\n // the task run. These land in rootSpan.metadata today (legacy ingestion);\n // once the runner migrates to OTLP export (Track C) they become real OTel\n // attributes that the projector's claim path reads directly.\n const rootMetadata: Record<string, unknown> = {\n taskId: loaded.task.id,\n taskDir: loaded.taskDir,\n adapterName: loaded.adapter.name,\n };\n if (tracing.taskRunId) {\n rootMetadata[APO_TASK_ID] = loaded.task.id;\n rootMetadata[APO_TASK_RUN_ID] = tracing.taskRunId;\n }\n\n return {\n project: tracing.project,\n task_id: loaded.task.id,\n flow_name: tracing.flowName ?? `agent-task.${loaded.task.id}`,\n version: tracing.version,\n environment: tracing.environment,\n tags,\n run_metadata: {\n taskDir: loaded.taskDir,\n adapterName: loaded.adapter.name,\n source: \"agent-task-e2e\",\n ...tracing.runMetadata,\n },\n rootSpan: {\n task_id: loaded.task.id,\n step_name: \"agent-task.run\",\n observation_type: \"CHAIN\" as const,\n model: \"agent-task\",\n metadata: rootMetadata,\n },\n };\n}\n","/**\n * Issue #159: replay Phase 2 of a completed Run against its stored\n * Deliverables — without re-running the agent.\n *\n * The backend serves what replay reads (run detail, Deliverable bodies, the\n * pinned Task Definition source, the canonical trace projection) and stores\n * what replay produces (a judgment record — submitted by the CLI, not here).\n * The eval source itself is executed HERE, never in the backend: the\n * definition revision's contract is that the backend stores source as\n * private data and never executes it.\n *\n * Rules this module enforces on itself:\n * - whole-run replay: the full registered check set runs every sample;\n * - the Run must be terminal (passed/failed) and every Deliverable ready —\n * a missing Deliverable must surface as a refusal, not a low score;\n * - scoring defaults to the Run's pinned definition revision; an explicit\n * different revision is allowed but reported as unpinned so it can never\n * be misread as \"the same eval, better judge\".\n */\n\nimport { mkdtempSync, rmSync, writeFileSync } from \"node:fs\";\nimport { tmpdir } from \"node:os\";\nimport { basename, dirname, join } from \"node:path\";\nimport { fileURLToPath } from \"node:url\";\nimport type { JudgeConfig } from \"../checks/t.ts\";\nimport {\n loadAndRunFlowChecks,\n proxyBrokenDeliverables,\n runTraceChecks,\n} from \"../checks/flow-runner.ts\";\nimport { validateDeliverables } from \"../deliverables/validate.ts\";\nimport { loadEvalSource } from \"../task/loadTask.ts\";\nimport { readTaskRunProjection } from \"../trace-projection/remote-capture.ts\";\nimport type { TraceProjectionSnapshot } from \"../trace-projection/types.ts\";\nimport { aggregateResult } from \"./aggregate.ts\";\nimport type { EvaluationItemResult } from \"./types.ts\";\n\n/** Backend coordinates for every read replay performs. */\nexport interface RejudgeEndpoints {\n /** Backend base URL, e.g. ``\"http://localhost:8000\"``. */\n backendUrl: string;\n /** Project API key (Authorization: Bearer …). Never recorded on judgments. */\n authToken: string;\n}\n\nexport interface RejudgeOptions {\n /** Judge config for ``t.judge`` calls; the API key stays client-side. */\n judge?: JudgeConfig;\n /** Judge the same Deliverables N times for a per-criterion stability measure. */\n samples?: number;\n /** Score against this revision instead of the Run's pinned one. */\n definitionRevisionId?: string;\n /**\n * Local checkout of the task directory. The stored revision pins only the\n * eval file, so relative imports and `files/` fixtures resolve from here.\n */\n taskDir?: string;\n /** Max wait for the canonical trace projection (default 30s). */\n projectionDeadlineMs?: number;\n /** Progress sink for human-facing operators (CLI prints to stderr). */\n onProgress?: (message: string) => void;\n}\n\n/** Per-check pass counts across samples — \"fails 2 of 5\", not \"failed\". */\nexport interface RejudgeCheckStability {\n check_id: string;\n passes: number;\n samples: number;\n}\n\nexport interface RejudgeOutcome {\n runId: string;\n taskId: string;\n /** Revision the checks were actually scored against. */\n definitionRevisionId: string;\n /** False when an explicit --definition-revision moved the target. */\n definitionRevisionIsPinned: boolean;\n /** Resolved judge config actually used (model + base URL, never the key). */\n judge: { model: string; baseURL?: string } | null;\n samples: number;\n /** Full check results from the primary (first) sample. */\n checks: EvaluationItemResult[];\n pass: boolean;\n /** Only meaningful with samples > 1; ordered like the primary sample. */\n stability: RejudgeCheckStability[];\n /** False when the trace projection was unreadable — trajectory assertions were unsupported. */\n traceSnapshotAvailable: boolean;\n /** The local task dir replay ran against, or null for an isolated scaffold. */\n taskDirUsed: string | null;\n}\n\n/** A deliberate, operator-facing replay failure (refusals, bad state). */\nexport class RejudgeError extends Error {\n constructor(message: string) {\n super(message);\n this.name = \"RejudgeError\";\n }\n}\n\nconst TERMINAL_VERDICT_STATUSES = new Set([\"passed\", \"failed\"]);\nconst MAX_SAMPLES = 50;\n\ninterface RunDetailResponse {\n id: string;\n task_id: string;\n status: string;\n deliverables_json?: Record<string, unknown>;\n task_definition?: { id?: string } | null;\n}\n\ninterface DeliverablesManifestResponse {\n task_run_id: string;\n items: RunDeliverableItem[];\n}\n\ninterface RunDeliverableItem {\n id: string;\n name: string;\n kind: string;\n status: string;\n media_type?: string;\n display_filename?: string | null;\n}\n\ninterface DefinitionSourceResponse {\n task_definition_revision_id: string;\n task_id: string;\n files: Array<{ path: string; content: string }>;\n}\n\nexport async function rejudgeTaskRun(\n runId: string,\n endpoints: RejudgeEndpoints,\n options: RejudgeOptions = {},\n): Promise<RejudgeOutcome> {\n const api = createApiClient(endpoints);\n const progress = options.onProgress ?? (() => {});\n\n const detail = await api.get<RunDetailResponse>(`/v1/agent-task-runs/${runId}`);\n if (!TERMINAL_VERDICT_STATUSES.has(detail.status)) {\n throw new RejudgeError(\n `Run ${runId} is '${detail.status}', not a completed run with a verdict — ` +\n `there is nothing to replay against yet`,\n );\n }\n\n // The dedicated manifest endpoint (same one `apo runs deliverable` reads)\n // projects AgentTaskDeliverableDB rows and synthesizes legacy manifests —\n // the run-detail response does not carry it.\n const manifest = await api.get<DeliverablesManifestResponse>(\n `/v1/agent-task-runs/${runId}/deliverables`,\n );\n const items = manifest.items ?? [];\n const notReady = items.filter((item) => item.status !== \"ready\");\n if (notReady.length > 0) {\n const names = notReady.map((item) => `${item.name} (${item.status})`).join(\", \");\n throw new RejudgeError(\n `Refusing to replay run ${runId}: deliverables are not ready: ${names}. ` +\n `A missing deliverable must not render as a low score — re-run the agent instead.`,\n );\n }\n\n const requestedRevision =\n options.definitionRevisionId ?? detail.task_definition?.id ?? null;\n if (!requestedRevision) {\n throw new RejudgeError(\n `Run ${runId} has no pinned Task Definition Revision — its checks cannot be replayed`,\n );\n }\n const sourceQuery =\n options.definitionRevisionId && options.definitionRevisionId !== detail.task_definition?.id\n ? `?revision=${encodeURIComponent(options.definitionRevisionId)}`\n : \"\";\n progress(`fetching definition source (${requestedRevision})`);\n const source = await api.get<DefinitionSourceResponse>(\n `/v1/agent-task-runs/${runId}/definition-source${sourceQuery}`,\n );\n const revisionId = source.task_definition_revision_id;\n const revisionIsPinned = revisionId === (detail.task_definition?.id ?? null);\n const evalFile = source.files[0];\n if (!evalFile) {\n throw new RejudgeError(`Definition revision ${revisionId} carries no source files`);\n }\n\n progress(\"fetching stored deliverables\");\n const artifactDir = mkdtempSync(join(tmpdir(), \"apo-rejudge-artifacts-\"));\n let scaffoldDir: string | null = null;\n try {\n const taskDir = options.taskDir ?? null;\n scaffoldDir = taskDir ? null : isolatedScaffoldDir();\n const deliverables = await fetchDeliverables(api, runId, items, artifactDir);\n\n progress(\"reading canonical trace projection\");\n const snapshotResult = await readCanonicalSnapshot(\n endpoints,\n runId,\n options.projectionDeadlineMs,\n );\n if (!snapshotResult.available) {\n progress(\n \"trace projection unavailable — trajectory assertions (t.calledTool, …) will be \" +\n \"recorded as unsupported rather than replayed\",\n );\n }\n const snapshot = snapshotResult.snapshot;\n\n const loaded = await loadEvalSource(evalFile.path, evalFile.content, {\n siblingDir: taskDir,\n isolatedDir: scaffoldDir,\n });\n progress(`loaded eval ${evalFile.path} from revision ${revisionId}`);\n\n const missingDeliverables = loaded.task.deliverables.filter(\n (name) => !Object.prototype.hasOwnProperty.call(deliverables, name),\n );\n if (missingDeliverables.length > 0) {\n throw new RejudgeError(\n `Refusing to replay run ${runId}: stored deliverables are incomplete; ` +\n `missing ${missingDeliverables.join(\", \")}. Re-run the agent instead.`,\n );\n }\n\n const samples = Math.max(1, Math.min(options.samples ?? 1, MAX_SAMPLES));\n const validation = validateDeliverables(\n loaded.task,\n deliverables,\n loaded.adapter.deliverables,\n );\n const proxied = proxyBrokenDeliverables(deliverables, validation.brokenDeliverables);\n\n const passCounts = new Map<string, number>();\n let primary: EvaluationItemResult[] = [];\n for (let sample = 0; sample < samples; sample++) {\n if (samples > 1) progress(`judging sample ${sample + 1}/${samples}`);\n const results = await runChecksOnce(loaded, proxied, snapshot, options.judge);\n if (sample === 0) primary = results;\n for (const result of results) {\n passCounts.set(result.id, (passCounts.get(result.id) ?? 0) + (result.pass ? 1 : 0));\n }\n }\n\n const stability = primary.map((result) => ({\n check_id: result.id,\n passes: passCounts.get(result.id) ?? 0,\n samples,\n }));\n const aggregate = aggregateResult(primary);\n\n return {\n runId,\n taskId: detail.task_id,\n definitionRevisionId: revisionId,\n definitionRevisionIsPinned: revisionIsPinned,\n judge: options.judge\n ? {\n model: options.judge.model,\n baseURL: options.judge.baseURL ?? process.env.OPENROUTER_BASE_URL,\n }\n : null,\n samples,\n checks: aggregate.checks,\n pass: aggregate.pass,\n stability,\n traceSnapshotAvailable: snapshotResult.available,\n taskDirUsed: taskDir,\n };\n } finally {\n // Check evidence (judge responses, artifacts re-hydrated to disk) has\n // already been captured into the returned results by the time we get\n // here, so the scratch dirs can go.\n rmSync(artifactDir, { recursive: true, force: true });\n if (scaffoldDir) rmSync(scaffoldDir, { recursive: true, force: true });\n }\n}\n\nasync function runChecksOnce(\n loaded: Awaited<ReturnType<typeof loadEvalSource>>,\n deliverables: Record<string, unknown>,\n snapshot: TraceProjectionSnapshot,\n judgeConfig: JudgeConfig | undefined,\n): Promise<EvaluationItemResult[]> {\n if (loaded.inlineChecks) {\n return runTraceChecks({\n snapshot,\n deliverables,\n files: loaded.files,\n task: loaded.task,\n judgeConfig,\n moduleUrl: loaded.moduleUrl,\n displayFile: loaded.evalFileName,\n });\n }\n return loadAndRunFlowChecks(\n loaded.checksPath,\n {\n snapshot,\n deliverables,\n files: loaded.files,\n task: loaded.task,\n judgeConfig,\n },\n {},\n );\n}\n\nasync function fetchDeliverables(\n api: ReturnType<typeof createApiClient>,\n runId: string,\n items: RunDeliverableItem[],\n artifactDir: string,\n): Promise<Record<string, unknown>> {\n const deliverables: Record<string, unknown> = {};\n for (const [index, item] of items.entries()) {\n if (item.kind === \"artifact\") {\n const bytes = await api.getBytes(`/v1/agent-task-runs/${runId}/deliverables/${item.id}`);\n const displayFilename = item.display_filename || item.name;\n // display_filename is remote metadata, not a trusted local path. A\n // unique prefix also prevents two artifacts with the same display name\n // from overwriting each other during replay.\n const safeFilename = basename(displayFilename) || \"artifact\";\n const path = join(artifactDir, `artifact-${index}-${safeFilename}`);\n writeFileSync(path, bytes);\n deliverables[item.name] = Object.freeze({\n kind: \"apo.file-artifact\",\n path,\n mediaType: item.media_type ?? \"application/octet-stream\",\n displayFilename,\n });\n } else {\n deliverables[item.name] = await api.getJson(\n `/v1/agent-task-runs/${runId}/deliverables/${item.id}`,\n );\n }\n }\n return deliverables;\n}\n\ninterface SnapshotRead {\n available: boolean;\n snapshot: TraceProjectionSnapshot;\n}\n\nasync function readCanonicalSnapshot(\n endpoints: RejudgeEndpoints,\n runId: string,\n deadlineMs: number | undefined,\n): Promise<SnapshotRead> {\n try {\n const snapshot = await readTaskRunProjection({\n endpoint: endpoints.backendUrl,\n authToken: endpoints.authToken,\n taskRunId: runId,\n deadlineMs: deadlineMs ?? 15_000,\n });\n return { available: true, snapshot };\n } catch {\n // No claimed trace (409), unreadable projection, or timeout. Fall back\n // to a degenerate snapshot: every capability is honestly unavailable, so\n // trace assertions fail closed as \"unsupported\" instead of vacuously\n // passing or silently skipping.\n return { available: false, snapshot: degenerateSnapshot(runId) };\n }\n}\n\nfunction degenerateSnapshot(runId: string): TraceProjectionSnapshot {\n return {\n schemaVersion: 1,\n projectionVersion: 1,\n source: \"local\",\n trace: { traceId: `rejudge-${runId}`, complete: true },\n capabilities: {\n messages: \"unavailable\",\n tools: \"unavailable\",\n errors: \"unavailable\",\n timing: \"unavailable\",\n skills: \"unavailable\",\n subagents: \"unavailable\",\n },\n observations: [],\n };\n}\n\n/**\n * Scaffold next to this SDK module for evals without a local task dir.\n * Package imports (`@apo-ai/sdk/agent-task`) resolve from here because the\n * scaffold sits inside the package's module-resolution tree; a system\n * temp dir would have no node_modules above it.\n */\nfunction isolatedScaffoldDir(): string {\n const here = dirname(fileURLToPath(import.meta.url));\n return mkdtempSync(join(here, \".rejudge-scaffold-\"));\n}\n\nfunction createApiClient(endpoints: RejudgeEndpoints) {\n const base = endpoints.backendUrl.replace(/\\/$/, \"\");\n const headers = { Authorization: `Bearer ${endpoints.authToken}` };\n\n async function request(path: string): Promise<Response> {\n const response = await fetch(`${base}${path}`, { headers });\n if (!response.ok) {\n const body = await response.text().catch(() => \"\");\n throw new RejudgeError(\n `${path} failed (${response.status}): ${body.slice(0, 200) || response.statusText}`,\n );\n }\n return response;\n }\n\n return {\n async get<T>(path: string): Promise<T> {\n return (await request(path).then((r) => r.json())) as T;\n },\n async getJson(path: string): Promise<unknown> {\n return request(path).then((r) => r.json());\n },\n async getBytes(path: string): Promise<Buffer> {\n const buffer = await request(path).then((r) => r.arrayBuffer());\n return Buffer.from(new Uint8Array(buffer));\n },\n };\n}\n","import { relative, resolve } from \"path\";\nimport { discoverAgentTaskDirs } from \"./discovery.ts\";\nimport { runTaskDir, type AgentTaskRunSummary } from \"./task-runtime.ts\";\nimport { NO_CHECKS_REGISTERED_MESSAGE } from \"./run/aggregate.ts\";\n\nexport type AgentTaskCliOptions = {\n task?: string;\n dir?: string;\n grep?: string;\n help?: boolean;\n};\n\nexport function parseAgentTaskCliArgs(argv: string[]): AgentTaskCliOptions {\n const options: AgentTaskCliOptions = {};\n\n for (let index = 0; index < argv.length; index += 1) {\n const arg = argv[index];\n\n if (arg === \"--help\" || arg === \"-h\") {\n options.help = true;\n continue;\n }\n\n if (arg === \"--task\") {\n options.task = requireNextValue(argv, index, \"--task\");\n index += 1;\n continue;\n }\n\n if (arg === \"--dir\") {\n options.dir = requireNextValue(argv, index, \"--dir\");\n index += 1;\n continue;\n }\n\n if (arg === \"--grep\") {\n options.grep = requireNextValue(argv, index, \"--grep\");\n index += 1;\n continue;\n }\n\n throw new Error(`Unknown argument: ${arg}`);\n }\n\n if (options.task && options.dir) {\n throw new Error(\"Use either --task or --dir, not both\");\n }\n\n return options;\n}\n\nexport async function runAgentTaskCli(\n argv: string[],\n cwd = process.cwd(),\n): Promise<number> {\n const normalizedArgv = argv[0] === \"--\" ? argv.slice(1) : argv;\n const options = parseAgentTaskCliArgs(normalizedArgv);\n\n if (options.help) {\n printHelp();\n return 0;\n }\n\n const selectedTaskDirs = resolveSelectedTaskDirs(options, cwd);\n if (selectedTaskDirs.length === 0) {\n throw new Error(\"No task folders found for the selected input\");\n }\n\n let hasFailures = false;\n let hasErrors = false;\n\n const results = await Promise.allSettled(\n selectedTaskDirs.map((taskDir) => runTaskDir(taskDir))\n );\n\n const summaries: AgentTaskRunSummary[] = [];\n for (let i = 0; i < results.length; i++) {\n const result = results[i];\n const taskDir = selectedTaskDirs[i];\n if (result.status === \"fulfilled\") {\n summaries.push(result.value);\n printTaskSummary(result.value, cwd);\n hasFailures ||= !result.value.pass;\n } else {\n hasErrors = true;\n printTaskError(taskDir, cwd, result.reason);\n }\n }\n\n printOverallSummary(summaries, hasErrors);\n\n if (hasErrors) {\n return 2;\n }\n\n return hasFailures ? 1 : 0;\n}\n\nfunction resolveSelectedTaskDirs(\n options: AgentTaskCliOptions,\n cwd: string,\n): string[] {\n if (options.task) {\n return [resolve(cwd, options.task)];\n }\n\n const rootDir = resolve(cwd, options.dir ?? \"e2e\");\n const discovered = discoverAgentTaskDirs(rootDir);\n\n if (!options.grep) {\n return discovered;\n }\n\n return discovered.filter((taskDir) =>\n // String.prototype.includes (not Array.includes) — false positive\n // react-doctor-disable-next-line react-doctor/js-set-map-lookups\n relative(cwd, taskDir).includes(options.grep as string),\n );\n}\n\nfunction requireNextValue(argv: string[], index: number, flag: string): string {\n const value = argv[index + 1];\n if (!value || value.startsWith(\"--\")) {\n throw new Error(`Missing value for ${flag}`);\n }\n return value;\n}\n\nfunction printHelp(): void {\n console.log(\"Usage: agent-task-e2e [--task <task-folder> | --dir <tasks-root>] [--grep <substring>]\");\n console.log(\"\");\n console.log(\"Options\");\n console.log(\"- --task <path> Run one task folder\");\n console.log(\"- --dir <path> Run all task folders under a root directory\");\n console.log(\"- --grep <text> Filter discovered task paths by substring\");\n console.log(\"- --help Show this help\");\n}\n\nfunction printTaskSummary(summary: AgentTaskRunSummary, cwd: string): void {\n const relativeTaskDir = relative(cwd, summary.taskDir);\n console.log(\"\");\n console.log(`${summary.pass ? \"PASS\" : \"FAIL\"} ${summary.taskId}`);\n console.log(`Path: ${relativeTaskDir}`);\n\n printResultGroup(\"Checks\", summary.checks);\n\n // Issue #8: a failed run with zero checks is almost always a silent\n // registration bug (e.g. a double-import that wiped the check registry).\n // Don't print a bare FAIL — say what went wrong.\n if (summary.checks.length === 0 && !summary.pass) {\n console.log(NO_CHECKS_REGISTERED_MESSAGE);\n }\n}\n\nfunction printResultGroup(\n label: string,\n results: AgentTaskRunSummary[\"checks\"],\n): void {\n if (results.length === 0) {\n return;\n }\n\n console.log(label);\n for (const result of results) {\n console.log(`- ${result.id}: ${result.pass ? \"PASS\" : \"FAIL\"}`);\n if (result.reasoning) {\n console.log(` ${result.reasoning}`);\n }\n }\n}\n\nfunction printTaskError(taskDir: string, cwd: string, error: unknown): void {\n const message = error instanceof Error ? error.message : String(error);\n console.log(\"\");\n console.log(`ERROR ${relative(cwd, taskDir)}`);\n console.log(message);\n}\n\nfunction printOverallSummary(\n summaries: AgentTaskRunSummary[],\n hasErrors: boolean,\n): void {\n const passed = summaries.filter((summary) => summary.pass).length;\n const failed = summaries.length - passed;\n\n console.log(\"\");\n console.log(\"Summary\");\n console.log(`- total: ${summaries.length}`);\n console.log(`- passed: ${passed}`);\n console.log(`- failed: ${failed}`);\n console.log(`- errors: ${hasErrors ? \"yes\" : \"no\"}`);\n}\n","import { existsSync, readdirSync, statSync } from \"fs\";\nimport { join, resolve } from \"path\";\n\nexport function discoverAgentTaskDirs(rootDir: string): string[] {\n const absoluteRoot = resolve(rootDir);\n\n if (!existsSync(absoluteRoot) || !statSync(absoluteRoot).isDirectory()) {\n throw new Error(`Task directory not found: ${absoluteRoot}`);\n }\n\n const discovered: string[] = [];\n walkForTaskDirs(absoluteRoot, discovered);\n return discovered.sort();\n}\n\nfunction walkForTaskDirs(currentDir: string, discovered: string[]): void {\n if (readdirSync(currentDir).some((f) => f.endsWith(\".eval.ts\"))) {\n discovered.push(currentDir);\n return;\n }\n\n for (const entry of readdirSync(currentDir)) {\n const absolutePath = join(currentDir, entry);\n if (!statSync(absolutePath).isDirectory()) {\n continue;\n }\n\n walkForTaskDirs(absolutePath, discovered);\n }\n}\n","/**\n * OTel-backed agent-task trace client.\n *\n * Replaces the deprecated ``TraceTracker``-backed ``createAgentTaskTraceClient``\n * with one that uses standard OpenTelemetry spans exported via the canonical\n * OTLP receiver. The ``AgentTaskTraceContext`` interface is identical —\n * ``runTask.ts``, ``FlowTee``, integrations, and task-authoring code work\n * unchanged.\n *\n * Key differences from the TraceTracker path:\n * - Spans are real OTel spans (``tracer.startSpan`` / ``span.end()``)\n * - Scores are domain records via the score API (not sentinel ingestion events)\n * - Run completion happens when the root span ends (OTel native)\n * - Export goes through ``configureApoTelemetry``'s OTLP exporter\n *\n * * 1. The runner starts an active root span named ``apo.task.run`` and adds\n * ``apo.task.id`` and ``apo.task.run.id``.\n * 2. Child framework spans inherit context normally.\n * 3. Completion happens when the root span ends.\n */\n\nimport { trace, context, type Span, type Tracer } from \"@opentelemetry/api\";\nimport { configureApoTelemetry, type ApoTelemetryHandle } from \"../otel/index.ts\";\nimport type {\n CreateSpanParams,\n EndSpanParams,\n TraceRunContext,\n TraceRunOptions,\n TraceStepOptions,\n TraceEventOptions,\n CreateScoreParams,\n} from \"../types.ts\";\n\nfunction monotonicNowMs(): number {\n if (typeof performance !== \"undefined\" && typeof performance.now === \"function\") {\n return performance.now();\n }\n return Date.now();\n}\n\nfunction round3(n: number): number {\n return Math.round(n * 1000) / 1000;\n}\n\nexport type AgentTaskTraceClientConfig = {\n endpoint: string;\n project: string;\n authToken?: string;\n requirePersistence?: boolean;\n /** Auth headers for the OTLP exporter (Authorization: Basic/Bearer). */\n headers?: Record<string, string>;\n};\n\ninterface ActiveSpan {\n span: Span;\n startedAt: number;\n model: string;\n}\n\n/**\n * Create an OTel-native agent-task trace client.\n *\n * Drop-in replacement for ``createAgentTaskTraceClient`` that uses\n * ``configureApoTelemetry`` instead of ``TraceTracker``.\n */\nexport function createOtelAgentTaskTraceClient(\n config: AgentTaskTraceClientConfig,\n): {\n traceRun<T>(\n params: TraceRunOptions,\n fn: (trace: TraceRunContext) => Promise<T>,\n ): Promise<T>;\n} {\n // Cache the provider across all client instances — OTel only allows one\n // global provider per process. Subsequent calls reuse the existing handle.\n let myHandle: ApoTelemetryHandle | null = null;\n\n async function ensureProvider(): Promise<Tracer> {\n if (!myHandle) {\n const headers = config.headers\n ?? (config.authToken ? { Authorization: `Bearer ${config.authToken}` } : {});\n myHandle = await configureApoTelemetry({\n takeOwnership: true,\n endpoint: `${config.endpoint.replace(/\\/$/, \"\")}/api/public/otel/v1/traces`,\n serviceName: \"apo-agent-task\",\n project: config.project,\n headers,\n processor: \"simple\",\n registerGlobal: true,\n });\n }\n return myHandle.tracer;\n }\n\n const activeSpans = new Map<string, ActiveSpan>();\n let activeTracer: Tracer | null = null;\n\n function createSpan(params: CreateSpanParams): string {\n if (!activeTracer) throw new Error(\"traceRun not started\");\n const spanName = params.step_name || params.observation_type || \"span\";\n // Use startSpan which inherits the active context. The root span is\n // activated in traceRun via context.with(). Child spans created here\n // inherit whatever span is currently active — correct nesting.\n const span = activeTracer.startSpan(spanName);\n\n // Set attributes using GenAI semantic conventions so the backend\n // normalizer can extract input/output/tokens into structured fields.\n if (params.observation_type) {\n span.setAttribute(\"apo.observation.type\", params.observation_type);\n }\n if (params.model) {\n span.setAttribute(\"gen_ai.request.model\", params.model);\n }\n if (params.input) {\n // Use gen_ai.input.messages so the normalizer routes it to the call's\n // structured input field (rendered as chat bubbles in the dashboard).\n if (params.input.messages) {\n span.setAttribute(\"gen_ai.input.messages\", JSON.stringify(params.input.messages));\n } else {\n span.setAttribute(\"gen_ai.input.messages\", JSON.stringify([{\n role: \"system\",\n parts: [{ type: \"text\", content: JSON.stringify(params.input) }],\n }]));\n }\n }\n if (params.metadata) {\n span.setAttribute(\"apo.metadata\", JSON.stringify(params.metadata));\n }\n\n const spanId = span.spanContext().spanId;\n activeSpans.set(spanId, {\n span,\n startedAt: monotonicNowMs(),\n model: params.model || \"unknown\",\n });\n return spanId;\n }\n\n function endSpan(params: EndSpanParams): void {\n const active = activeSpans.get(params.id);\n if (!active) {\n return;\n }\n\n const latency = params.latency_ms ?? round3(monotonicNowMs() - active.startedAt);\n active.span.setAttribute(\"latency_ms\", latency);\n\n if (params.output !== undefined) {\n // Use gen_ai.output.messages so the normalizer routes it to the call's\n // structured output field (rendered as chat bubbles + \"Correct\" button).\n if (params.output.text) {\n active.span.setAttribute(\"gen_ai.output.messages\", JSON.stringify([{\n role: \"assistant\",\n parts: [{ type: \"text\", content: String(params.output.text) }],\n }]));\n } else if (params.output.messages) {\n active.span.setAttribute(\"gen_ai.output.messages\", JSON.stringify(params.output.messages));\n } else if (params.output.error) {\n active.span.setAttribute(\"gen_ai.output.messages\", JSON.stringify([{\n role: \"assistant\",\n parts: [{ type: \"text\", content: String(params.output.error) }],\n }]));\n } else {\n active.span.setAttribute(\"gen_ai.output.messages\", JSON.stringify([{\n role: \"assistant\",\n parts: [{ type: \"text\", content: JSON.stringify(params.output) }],\n }]));\n }\n }\n if (params.prompt_tokens !== undefined) {\n active.span.setAttribute(\"gen_ai.usage.input_tokens\", params.prompt_tokens);\n }\n if (params.completion_tokens !== undefined) {\n active.span.setAttribute(\"gen_ai.usage.output_tokens\", params.completion_tokens);\n }\n if (params.status_message) {\n active.span.setAttribute(\"apo.status_message\", params.status_message);\n }\n if (params.level === \"ERROR\") {\n active.span.setStatus({ code: 2, message: params.status_message || \"error\" });\n }\n if (params.metadata) {\n active.span.setAttribute(\"apo.metadata\", JSON.stringify(params.metadata));\n }\n\n active.span.end();\n activeSpans.delete(params.id);\n }\n\n return {\n async traceRun<T>(\n params: TraceRunOptions,\n fn: (trace: TraceRunContext) => Promise<T>,\n ): Promise<T> {\n const tracer = await ensureProvider();\n activeTracer = tracer;\n\n const project = params.project ?? config.project;\n const taskId = params.task_id ?? params.flow_name ?? \"task\";\n const flowName = params.flow_name ?? taskId;\n\n // Create the root span with apo.task attributes\n const rootSpan = tracer.startSpan(\"apo.task.run\");\n rootSpan.setAttribute(\"apo.observation.type\", \"AGENT\");\n rootSpan.setAttribute(\"apo.run.flow_name\", flowName);\n rootSpan.setAttribute(\"apo.run.task_id\", taskId);\n if (params.version) {\n rootSpan.setAttribute(\"apo.run.version\", params.version);\n }\n if (params.run_metadata) {\n rootSpan.setAttribute(\"apo.run.metadata\", JSON.stringify(params.run_metadata));\n }\n if (params.tags?.length) {\n rootSpan.setAttribute(\"apo.run.tags\", JSON.stringify(params.tags));\n }\n\n // The task-run claim attributes. The backend projector\n // reads `apo.task.run.id` from the root span and atomically links this\n // trace to AgentTaskRunDB.trace_run_id. The task run id arrives from any\n // of three sources (first wins): an explicit taskRunId on params, the\n // rootSpan.metadata claim key (set by buildTraceRunOptions), or\n // run_metadata.agent_task_run_id (set by the backend at launch time).\n const rootMeta = params.rootSpan?.metadata as Record<string, unknown> | undefined;\n const taskRunId =\n ((params as { taskRunId?: string }).taskRunId) ??\n (rootMeta?.[\"apo.task.run.id\"] as string | undefined) ??\n (params.run_metadata?.[\"agent_task_run_id\"] as string | undefined);\n if (taskRunId) {\n rootSpan.setAttribute(\"apo.task.id\", taskId);\n rootSpan.setAttribute(\"apo.task.run.id\", taskRunId);\n }\n\n const runId = rootSpan.spanContext().traceId;\n const rootSpanId = rootSpan.spanContext().spanId;\n activeSpans.set(rootSpanId, {\n span: rootSpan,\n startedAt: monotonicNowMs(),\n model: \"trace\",\n });\n\n let callCount = 1;\n let rootEnded = false;\n\n const traceContext: TraceRunContext = {\n runId,\n rootSpanId,\n async step<TStep>(\n options: TraceStepOptions,\n stepFn: (spanId: string) => Promise<TStep>,\n ): Promise<TStep> {\n const spanId = createSpan({\n ...options,\n project,\n task_id: options.task_id ?? taskId,\n run_id: runId,\n parent_call_id: options.parent_call_id ?? rootSpanId,\n flow_name: options.flow_name ?? flowName,\n });\n const startedAt = monotonicNowMs();\n const activeSpan = activeSpans.get(spanId);\n\n // Activate this span in context so nested step()/traceTool() calls\n // inside stepFn see it as their parent (correct nesting hierarchy).\n const ctxWithSpan = activeSpan\n ? trace.setSpan(context.active(), activeSpan.span)\n : context.active();\n\n try {\n const result = await context.with(ctxWithSpan, () => stepFn(spanId));\n endSpan({\n id: spanId,\n latency_ms: round3(monotonicNowMs() - startedAt),\n output: options.summarize?.(result),\n metadata: options.metadata,\n });\n callCount += 1;\n return result;\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n endSpan({\n id: spanId,\n latency_ms: round3(monotonicNowMs() - startedAt),\n output: { error: message },\n status_message: message,\n level: \"ERROR\",\n metadata: { ...options.metadata, failed: true },\n });\n throw error;\n }\n },\n recordEvent(options: TraceEventOptions): string {\n const spanId = createSpan({\n ...options,\n project,\n task_id: options.task_id ?? taskId,\n run_id: runId,\n parent_call_id: options.parent_call_id ?? rootSpanId,\n flow_name: options.flow_name ?? flowName,\n });\n endSpan({\n id: spanId,\n latency_ms: options.latency_ms,\n output: options.output,\n metadata: options.metadata,\n });\n callCount += 1;\n return spanId;\n },\n endRoot(endParams?: Omit<EndSpanParams, \"id\">): void {\n if (rootEnded) return;\n endSpan({ id: rootSpanId, ...endParams });\n rootEnded = true;\n },\n // Non-LLM tracing helpers — these create spans through the same tracer\n async traceTool<TN>(name: string, params: Record<string, unknown>, fn: () => Promise<TN>): Promise<TN> {\n const spanId = createSpan({\n project, task_id: taskId, run_id: runId, parent_call_id: rootSpanId,\n flow_name: flowName, step_name: `tool ${name}`,\n observation_type: \"TOOL\", model: \"unknown\",\n input: params,\n });\n try {\n const result = await fn();\n endSpan({ id: spanId, output: result as Record<string, unknown> });\n callCount += 1;\n return result;\n } catch (error) {\n const msg = error instanceof Error ? error.message : String(error);\n endSpan({ id: spanId, output: { error: msg }, status_message: msg, level: \"ERROR\" });\n throw error;\n }\n },\n async traceRetriever<TN>(query: string, fn: () => Promise<TN>): Promise<TN> {\n const spanId = createSpan({\n project, task_id: taskId, run_id: runId, parent_call_id: rootSpanId,\n flow_name: flowName, step_name: \"retrieve\", observation_type: \"RETRIEVER\",\n model: \"unknown\", input: { query },\n });\n try { const r = await fn(); endSpan({ id: spanId, output: r as Record<string, unknown> }); callCount += 1; return r; }\n catch (e) { const m = e instanceof Error ? e.message : String(e); endSpan({ id: spanId, output: { error: m }, level: \"ERROR\" }); throw e; }\n },\n async traceChain<TN>(name: string, fn: () => Promise<TN>): Promise<TN> {\n const spanId = createSpan({\n project, task_id: taskId, run_id: runId, parent_call_id: rootSpanId,\n flow_name: flowName, step_name: name, observation_type: \"CHAIN\", model: \"unknown\",\n });\n try { const r = await fn(); endSpan({ id: spanId, output: r as Record<string, unknown> }); callCount += 1; return r; }\n catch (e) { const m = e instanceof Error ? e.message : String(e); endSpan({ id: spanId, output: { error: m }, level: \"ERROR\" }); throw e; }\n },\n async traceAgent<TN>(name: string, fn: () => Promise<TN>): Promise<TN> {\n const spanId = createSpan({\n project, task_id: taskId, run_id: runId, parent_call_id: rootSpanId,\n flow_name: flowName, step_name: name, observation_type: \"AGENT\", model: \"unknown\",\n });\n try { const r = await fn(); endSpan({ id: spanId, output: r as Record<string, unknown> }); callCount += 1; return r; }\n catch (e) { const m = e instanceof Error ? e.message : String(e); endSpan({ id: spanId, output: { error: m }, level: \"ERROR\" }); throw e; }\n },\n async traceGuardrail<TN>(name: string, fn: () => Promise<TN>): Promise<TN> {\n const spanId = createSpan({\n project, task_id: taskId, run_id: runId, parent_call_id: rootSpanId,\n flow_name: flowName, step_name: name, observation_type: \"GUARDRAIL\", model: \"unknown\",\n });\n try { const r = await fn(); endSpan({ id: spanId, output: r as Record<string, unknown> }); callCount += 1; return r; }\n catch (e) { const m = e instanceof Error ? e.message : String(e); endSpan({ id: spanId, output: { error: m }, level: \"ERROR\" }); throw e; }\n },\n async traceEmbedding<TN>(model: string, input: unknown, fn: () => Promise<TN>): Promise<TN> {\n const spanId = createSpan({\n project, task_id: taskId, run_id: runId, parent_call_id: rootSpanId,\n flow_name: flowName, step_name: \"embedding\", observation_type: \"EMBEDDING\", model,\n input: { value: input },\n });\n try { const r = await fn(); endSpan({ id: spanId, output: r as Record<string, unknown> }); callCount += 1; return r; }\n catch (e) { const m = e instanceof Error ? e.message : String(e); endSpan({ id: spanId, output: { error: m }, level: \"ERROR\" }); throw e; }\n },\n async score(scoreParams: CreateScoreParams): Promise<void> {\n // Scores are domain records via the score API\n const { score: scoreFn } = await import(\"../otel/index.ts\");\n const scoreHeaders = config.headers\n ?? (config.authToken ? { Authorization: `Bearer ${config.authToken}` } : {});\n await scoreFn(\n { traceId: runId, ...scoreParams },\n { endpoint: config.endpoint, headers: scoreHeaders },\n );\n },\n };\n\n // Add createSpan/endSpan for the AgentTaskTraceContext interface\n const agentTaskContext = {\n ...traceContext,\n createSpan(options: Omit<CreateSpanParams, \"project\" | \"run_id\">): string {\n const spanId = createSpan({\n ...options,\n project,\n run_id: runId,\n task_id: options.task_id ?? taskId,\n flow_name: options.flow_name ?? flowName,\n });\n callCount += 1;\n return spanId;\n },\n endSpan(spanId: string, endParams?: Omit<EndSpanParams, \"id\">): void {\n endSpan({ id: spanId, ...endParams });\n },\n };\n\n // Activate the root span in the OTel context so child spans created via\n // createSpan() (which calls tracer.startSpan) automatically inherit it\n // as their parent. This is standard OTel context propagation — no manual\n // parent_span_id passing needed.\n return context.with(trace.setSpan(context.active(), rootSpan), async () => {\n let result: T | undefined;\n let runError: unknown;\n try {\n result = await fn(agentTaskContext);\n agentTaskContext.endRoot();\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n agentTaskContext.endRoot({\n output: { error: message },\n status_message: message,\n level: \"ERROR\",\n metadata: { failed: true },\n });\n runError = error;\n }\n\n let flushError: unknown;\n if (myHandle) {\n try {\n await myHandle.forceFlush();\n } catch (error) {\n flushError = error;\n }\n await myHandle.shutdown();\n myHandle = null;\n }\n if (runError !== undefined) throw runError;\n if (flushError !== undefined && config.requirePersistence) {\n const detail = flushError instanceof Error\n ? flushError.message\n : String(flushError);\n throw new Error(`OTLP trace persistence failed: ${detail}`);\n }\n return result as T;\n });\n },\n };\n}\n","import { runTask } from \"./run/runTask.ts\";\nimport type { EvaluationItemResult } from \"./run/types.ts\";\nimport type { AgentTaskRunConfiguration } from \"./adapter/types.ts\";\nimport { loadTask } from \"./task/loadTask.ts\";\nimport type { JudgeConfig } from \"./checks/t.ts\";\nimport { createOtelAgentTaskTraceClient } from \"./otel-trace-client.ts\";\nimport type { AgentTaskTraceOptions } from \"./tracing.ts\";\n\nexport type AgentTaskRuntime = {\n judge?: JudgeConfig;\n};\n\nexport type AgentTaskRunSummary = {\n taskDir: string;\n taskId: string;\n pass: boolean;\n checks: EvaluationItemResult[];\n /** Adapter that ran the task. Forwarded to the backend when recording locally. */\n adapterName?: string;\n /** Trace id this run claimed (when tracing was enabled). */\n traceRunId?: string;\n /** Deliverables the adapter produced. */\n deliverables?: Record<string, unknown>;\n /** Per-turn transcript of the run. */\n transcript?: Record<string, unknown>;\n /** adapter-reported model/effort, forwarded when recording locally. */\n runConfiguration?: AgentTaskRunConfiguration;\n};\n\nexport async function loadTaskRuntime(\n _taskDir: string,\n): Promise<AgentTaskRuntime> {\n return {\n judge: resolveJudgeFromEnv(),\n };\n}\n\nfunction resolveJudgeFromEnv(): JudgeConfig | undefined {\n const openRouterModel = process.env.OPENROUTER_MODEL;\n const model = openRouterModel ?? process.env.OPENAI_MODEL;\n if (!model) return undefined;\n\n return {\n model,\n baseURL: openRouterModel\n ? process.env.OPENROUTER_BASE_URL\n : process.env.OPENAI_BASE_URL ?? \"https://api.openai.com/v1\",\n apiKey: openRouterModel\n ? process.env.OPENROUTER_API_KEY\n : process.env.OPENAI_API_KEY,\n };\n}\n\nexport async function runTaskDir(\n taskDir: string,\n): Promise<AgentTaskRunSummary> {\n const [loaded, runtime] = await Promise.all([\n loadTask(taskDir),\n loadTaskRuntime(taskDir),\n ]);\n\n // Set up OTel tracing for CLI-driven task runs.\n // The backend subprocess (runner-entry.ts) does its own setup;\n // this covers the CLI path (runAgentTaskCli → runTaskDir).\n // Falls back to noop tracing when no endpoint is configured (e.g. tests).\n const endpoint = process.env.AGENT_TASK_TRACE_ENDPOINT;\n const hasTracing = endpoint && process.env.AGENT_TASK_PROJECT;\n // When the backend pre-created the task run (external execution mode,\n // Issue #4), stamping apo.task.run.id on the root span lets the existing\n // claim machinery atomically link this trace to the run row. Mirrors\n // runner-entry.ts — never trust telemetry alone for ownership.\n const taskRunId = process.env.AGENT_TASK_RUN_ID;\n\n const tracing = hasTracing\n ? {\n client: createOtelAgentTaskTraceClient({\n endpoint,\n project: process.env.AGENT_TASK_PROJECT!,\n headers: _buildAuthHeaders(),\n }),\n project: process.env.AGENT_TASK_PROJECT!,\n environment: process.env.AGENT_TASK_ENVIRONMENT ?? \"default\",\n ...(taskRunId ? { taskRunId } : {}),\n } as AgentTaskTraceOptions\n : undefined;\n\n // Thread the already-loaded task through so runTask does not re-import the\n // eval module (Issue #7). loadTask above copied the eval to a temp file and\n // imported it once with all registries reset; a second loadTask would run\n // the eval's top level again and silently break evals whose load-time\n // behavior is not idempotent across module systems.\n const result = await runTask(taskDir, { ...runtime, tracing, loaded });\n\n return {\n taskDir: loaded.taskDir,\n taskId: loaded.task.id,\n pass: result.result.pass,\n checks: result.result.checks,\n adapterName: loaded.adapter.name,\n traceRunId: result.traceRunId,\n deliverables: result.deliverables,\n transcript: result.transcript as unknown as Record<string, unknown>,\n runConfiguration: result.runConfiguration,\n };\n}\n\nfunction _buildAuthHeaders(): Record<string, string> | undefined {\n const pk = process.env.APO_PUBLIC_KEY;\n const sk = process.env.APO_SECRET_KEY;\n if (pk && sk) {\n const creds = typeof btoa === \"function\"\n ? btoa(`${pk}:${sk}`)\n : Buffer.from(`${pk}:${sk}`).toString(\"base64\");\n return { Authorization: `Basic ${creds}` };\n }\n const token = process.env.APO_AUTH_TOKEN;\n if (token) {\n return { Authorization: `Bearer ${token}` };\n }\n return undefined;\n}\n","/**\n * canonical Task Revision manifest.\n *\n * Pure, dependency-free canonicalizer. Both this module and its Python twin\n * (`backend/apo/execution/task_revision_manifest.py`) MUST produce\n * byte-identical canonical JSON and digests for every fixture under\n * `specs/contracts/task-revision/v1/cases/`.\n *\n * Canonicalization rules:\n * - `/` path separators (caller `\\` normalized to `/`);\n * - Unicode NFC normalization of the path;\n * - bytewise lexical ordering of normalized UTF-8 paths (NOT UTF-16 —\n * diverges for codepoints > U+007F);\n * - exact file-byte SHA-256 (lowercase hex);\n * - mode reduced to `regular` | `executable`;\n * - ownership, timestamps, inode metadata, and absolute paths excluded.\n *\n * `contentSha256` is the SHA-256 of the compact canonical JSON built from\n * `schemaVersion` and the sorted `files` array. The `summary` block is NOT\n * part of source identity.\n */\n\nimport { createHash } from \"node:crypto\";\n\nexport type ModeClass = \"regular\" | \"executable\";\n\nexport interface ManifestFile {\n path: string;\n sizeBytes: number;\n sha256: string;\n modeClass: ModeClass;\n}\n\nexport interface TaskRevisionManifestV1 {\n schemaVersion: 1;\n files: ManifestFile[];\n summary: {\n fileCount: number;\n uncompressedSizeBytes: number;\n excludedFileCount: number;\n excludedDirectoryCount: number;\n };\n}\n\n/** Caller-reported file, before canonicalization. `content` is the exact bytes. */\nexport interface ManifestFileInput {\n path: string;\n modeClass: ModeClass;\n content: Uint8Array;\n}\n\n/**\n * Normalize a caller-reported path to canonical POSIX + NFC form.\n * Validation (no leading slash, no `.`/`..` segments) is the filesystem\n * walker's responsibility; this function only makes representation canonical.\n */\nexport function normalizeManifestPath(path: string): string {\n return path.split(\"\\\\\").join(\"/\").normalize(\"NFC\");\n}\n\n/** SHA-256 of exact bytes, lowercase hex. */\nexport function sha256Hex(bytes: Uint8Array): string {\n return createHash(\"sha256\").update(bytes).digest(\"hex\");\n}\n\n/** Compare two UTF-8 strings by their raw byte ordering (not UTF-16 code units). */\nfunction compareBytewiseUtf8(a: string, b: string): number {\n const ba = Buffer.from(a, \"utf8\");\n const bb = Buffer.from(b, \"utf8\");\n for (let i = 0; i < Math.min(ba.length, bb.length); i++) {\n if (ba[i]! !== bb[i]!) return ba[i]! < bb[i]! ? -1 : 1;\n }\n return ba.length - bb.length;\n}\n\n/**\n * Build the canonical V1 manifest from already-included files. Exclusion\n * counts default to zero; the filesystem walker supplies real counts when it\n * wraps this via `withExclusionCounts`.\n */\nexport function buildManifest(\n files: ManifestFileInput[],\n summary?: { excludedFileCount: number; excludedDirectoryCount: number },\n): TaskRevisionManifestV1 {\n const entries = files.map((f) => {\n const path = normalizeManifestPath(f.path);\n return {\n path,\n sizeBytes: f.content.byteLength,\n sha256: sha256Hex(f.content),\n modeClass: f.modeClass,\n } satisfies ManifestFile;\n });\n\n entries.sort((a, b) => compareBytewiseUtf8(a.path, b.path));\n\n return {\n schemaVersion: 1,\n files: entries,\n summary: {\n fileCount: entries.length,\n uncompressedSizeBytes: entries.reduce((n, f) => n + f.sizeBytes, 0),\n excludedFileCount: summary?.excludedFileCount ?? 0,\n excludedDirectoryCount: summary?.excludedDirectoryCount ?? 0,\n },\n };\n}\n\n/**\n * Compact canonical JSON over `schemaVersion` + the sorted `files` array only.\n * Object keys are alphabetical at every level; no whitespace; non-ASCII\n * emitted as UTF-8 (matches Python `json.dumps(sort_keys=True,\n * ensure_ascii=False, separators=(\",\", \":\"))`). The `summary` block is\n * intentionally excluded from source identity.\n */\nexport function canonicalManifestJson(manifest: TaskRevisionManifestV1): string {\n const filesPayload = manifest.files.map((f) => ({\n modeClass: f.modeClass,\n path: f.path,\n sha256: f.sha256,\n sizeBytes: f.sizeBytes,\n }));\n return JSON.stringify({ files: filesPayload, schemaVersion: manifest.schemaVersion });\n}\n\n/** SHA-256 (lowercase hex) of the canonical manifest JSON's UTF-8 bytes. */\nexport function contentSha256(manifest: TaskRevisionManifestV1): string {\n return sha256Hex(Buffer.from(canonicalManifestJson(manifest), \"utf8\"));\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;AA0DA,SAAS,mBAAmB,KAA2D;AACrF,QAAM,QAAQ,IAAI,aAAa,OAAO,IAAI;AAC1C,SAAO,CAAC,OAAO,IAAI,aAAa,IAAI,IAAI,MAAM;AAChD;AAEO,IAAM,YAAN,MAAgB;AAAA,EAGrB,YAAY,UAAmC;AAC7C,SAAK,WAAW;AAAA,EAClB;AAAA;AAAA,EAGA,kBACE,YACsB;AACtB,WAAO,KAAK,SAAS,aAAa,UAAU;AAAA,EAC9C;AAAA;AAAA,EAGQ,YAAY,YAAwD;AAC1E,WAAO,KAAK,SAAS,aAAa,UAAU,MAAM;AAAA,EACpD;AAAA;AAAA,EAGA,IAAI,WAA8C;AAChD,UAAM,MAAgC,CAAC;AACvC,eAAW,OAAO,KAAK,oBAAoB;AACzC,UAAI,IAAI,SAAU,KAAI,KAAK,GAAG,IAAI,QAAQ;AAAA,IAC5C;AACA,WAAO;AAAA,EACT;AAAA;AAAA,EAGA,IAAI,YAAsC;AACxC,WAAO,KAAK,mBACT,OAAO,CAAC,MAA0D,EAAE,SAAS,MAAM,EACnF,IAAI,CAAC,OAAO;AAAA,MACX,QAAQ,EAAE;AAAA,MACV,MAAM,EAAE,YAAY,EAAE;AAAA,MACtB,OAAO,EAAE,kBAAkB,EAAE;AAAA,MAC7B,QAAQ,EAAE,cAAc,EAAE;AAAA,MAC1B,QAAQ,EAAE;AAAA,MACV,WAAW,EAAE;AAAA,IACf,EAAE;AAAA,EACN;AAAA;AAAA,EAGA,IAAI,mBAAsC;AACxC,WAAO,KAAK,UAAU,IAAI,CAAC,MAAM,EAAE,IAAI;AAAA,EACzC;AAAA;AAAA,EAGA,IAAI,aAAwC;AAC1C,WAAO,KAAK,mBACT,OAAO,CA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ACP,SAAS;AAAA,MACP,WAAW,QAAQ;AAAA,MACnB,uBAAuB,QAAQ,OAAO,CAAC,GAAG,MAAM,IAAI,EAAE,WAAW,CAAC;AAAA,MAClE,mBAAmB,SAAS,qBAAqB;AAAA,MACjD,wBAAwB,SAAS,0BAA0B;AAAA,IAC7D;AAAA,EACF;AACF;AASO,SAAS,sBAAsB,UAA0C;AAC9E,QAAM,eAAe,SAAS,MAAM,IAAI,CAAC,OAAO;AAAA,IAC9C,WAAW,EAAE;AAAA,IACb,MAAM,EAAE;AAAA,IACR,QAAQ,EAAE;AAAA,IACV,WAAW,EAAE;AAAA,EACf,EAAE;AACF,SAAO,KAAK,UAAU,EAAE,OAAO,cAAc,eAAe,SAAS,cAAc,CAAC;AACtF;AAGO,SAAS,cAAc,UAA0C;AACtE,SAAO,UAAU,OAAO,KAAK,sBAAsB,QAAQ,GAAG,MAAM,CAAC;AACvE;","names":["task","task","copyFileSync","existsSync","unlinkSync","basename","pathToFileURL","task","basename","existsSync","unlinkSync","copyFileSync","pathToFileURL","basename","statSync","resolve","task","trace","resolve","trace","task","result","writeFileSync","basename","join","join","readCanonicalSnapshot","basename","writeFileSync","resolve","existsSync","readdirSync","statSync","join","resolve","monotonicNowMs","round3","params","fn","resolve","createHash"]}
|