@tangle-network/agent-runtime 0.90.1 → 0.91.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/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/conversation/call-policy.ts","../src/conversation/headers.ts","../src/conversation/turn-id.ts","../src/conversation/run-conversation.ts","../src/conversation/conversation-backend.ts","../src/conversation/define-conversation.ts","../src/conversation/journal.ts","../src/conversation/journal-sql.ts","../src/conversation/run-persona.ts","../src/durable/chat-engine.ts","../src/durable/execution-handle.ts","../src/improvement/improve.ts","../src/improvement/improvement-driver.ts","../src/improvement/raw-trace-distiller.ts","../src/improvement/rollout-policy.ts","../src/improvement/reflective-generator.ts","../src/readiness.ts","../src/resolve-agent-backend.ts","../src/run.ts","../src/runtime-run.ts","../src/sanitize.ts","../src/sse.ts","../src/tool-loop.ts"],"sourcesContent":["/**\n *\n * Per-call resilience policy for participant backends: deadline, retry with\n * backoff, and a circuit breaker. Each policy is applied *around* a single\n * turn's backend invocation, not across the whole conversation — the\n * conversation-level credit cap and `maxTurns` bound the broader run.\n *\n * Deadlines abort the underlying backend stream via `AbortSignal` linkage so\n * the OpenAI/SDK clients tear down their HTTP request cleanly instead of\n * leaking sockets. Retries replay the same logical turn (same `turnId`) so\n * any caching gateway can dedupe. Circuit breakers are *per participant*: A's\n * failures don't open B's breaker.\n *\n * @stable\n */\n\n/** Pure judgment of whether an error is worth retrying. Defaults: TimeoutError, AbortError, fetch-level network errors. */\nexport type RetryableErrorPredicate = (err: unknown) => boolean\n\n/** Backoff between attempts. Constant ms, or `(attempt: 1-indexed) => ms`. */\nexport type RetryBackoff = number | ((attempt: number) => number)\n\n/** Circuit-breaker tuning. `failuresToOpen` consecutive failures opens it; closed only after `cooldownMs`. */\nexport interface CircuitBreakerConfig {\n failuresToOpen: number\n cooldownMs: number\n}\n\nexport interface BackendCallPolicy {\n /** Per-attempt wall clock limit. Exceeding fires an AbortSignal and is treated as a retryable failure. */\n perAttemptDeadlineMs?: number\n /** Number of retries after the first attempt; total attempts = 1 + maxRetries. Default 0. */\n maxRetries?: number\n /** Backoff between attempts. Default 250ms with jitter. */\n retryBackoffMs?: RetryBackoff\n /** Custom retry classifier. Defaults to {@link defaultIsRetryable}. */\n isRetryable?: RetryableErrorPredicate\n /** Circuit breaker that opens after N consecutive failures per participant. */\n circuitBreaker?: CircuitBreakerConfig\n}\n\n/** Thrown when the circuit breaker is open for a participant and no retry is allowed yet. */\nexport class CircuitOpenError extends Error {\n constructor(participant: string, retryAfterMs: number) {\n super(\n `circuit open for participant '${participant}'; ${retryAfterMs}ms remaining before retry allowed`,\n )\n this.name = 'CircuitOpenError'\n }\n}\n\n/** Thrown when a backend call exceeds its per-attempt deadline. */\nexport class DeadlineExceededError extends Error {\n constructor(deadlineMs: number) {\n super(`backend call exceeded per-attempt deadline of ${deadlineMs}ms`)\n this.name = 'DeadlineExceededError'\n }\n}\n\n/**\n * Default retryable classification — network/timeout class errors. Errors\n * a model deliberately throws (validation, refusal, 4xx) are not retried;\n * those represent real outcomes, not transient infrastructure faults.\n */\nexport const defaultIsRetryable: RetryableErrorPredicate = (err) => {\n if (err instanceof DeadlineExceededError) return true\n if (err instanceof Error) {\n const name = err.name\n const message = err.message.toLowerCase()\n if (name === 'AbortError' || name === 'TimeoutError') return true\n if (\n message.includes('econnreset') ||\n message.includes('etimedout') ||\n message.includes('econnrefused') ||\n message.includes('socket hang up') ||\n message.includes('network') ||\n message.includes('fetch failed')\n ) {\n return true\n }\n }\n return false\n}\n\n/** Live circuit-breaker state — one instance per (participant, conversation run). */\nexport class CircuitBreakerState {\n private consecutiveFailures = 0\n private openedAt: number | undefined\n\n constructor(private readonly config: CircuitBreakerConfig | undefined) {}\n\n /**\n * Check whether the next call is allowed. Throws `CircuitOpenError` when\n * the breaker is open and the cooldown hasn't elapsed.\n */\n preflight(participant: string, now: number = Date.now()): void {\n if (!this.config || this.openedAt === undefined) return\n const remaining = this.config.cooldownMs - (now - this.openedAt)\n if (remaining > 0) {\n throw new CircuitOpenError(participant, remaining)\n }\n this.openedAt = undefined\n this.consecutiveFailures = 0\n }\n\n recordSuccess(): void {\n this.consecutiveFailures = 0\n this.openedAt = undefined\n }\n\n recordFailure(now: number = Date.now()): void {\n if (!this.config) return\n this.consecutiveFailures += 1\n if (this.consecutiveFailures >= this.config.failuresToOpen) {\n this.openedAt = now\n }\n }\n}\n\n/**\n * Build a per-attempt AbortSignal linked to the parent signal AND fired when\n * the deadline elapses. The returned `dispose()` MUST be called in a\n * `finally` (clears the timer, detaches the listener) so we don't leak.\n *\n * When the deadline fires, the signal's `reason` is a `DeadlineExceededError`\n * — callers can detect timeout-vs-cancel by reading `signal.reason` after\n * the underlying operation throws.\n */\nexport function makePerAttemptSignal(\n parentSignal: AbortSignal | undefined,\n deadlineMs: number | undefined,\n): {\n signal: AbortSignal\n dispose: () => void\n getDeadlineError(): DeadlineExceededError | undefined\n} {\n const controller = new AbortController()\n let deadlineError: DeadlineExceededError | undefined\n const cleanups: Array<() => void> = []\n\n if (parentSignal) {\n if (parentSignal.aborted) controller.abort(parentSignal.reason)\n else {\n const onAbort = () => controller.abort(parentSignal.reason)\n parentSignal.addEventListener('abort', onAbort, { once: true })\n cleanups.push(() => parentSignal.removeEventListener('abort', onAbort))\n }\n }\n if (deadlineMs !== undefined) {\n const ms = deadlineMs\n const timer = setTimeout(() => {\n deadlineError = new DeadlineExceededError(ms)\n controller.abort(deadlineError)\n }, ms)\n cleanups.push(() => clearTimeout(timer))\n }\n return {\n signal: controller.signal,\n dispose() {\n for (const c of cleanups) c()\n },\n getDeadlineError() {\n return deadlineError\n },\n }\n}\n\n/** Compute the delay before the next attempt. Default: 250ms exponential with jitter. */\nexport function computeBackoff(spec: RetryBackoff | undefined, attempt: number): number {\n if (spec === undefined) {\n const base = 250\n const jitter = Math.floor(Math.random() * base)\n return base * 2 ** (attempt - 1) + jitter\n }\n if (typeof spec === 'function') return Math.max(0, spec(attempt))\n return Math.max(0, spec)\n}\n\n/** Resolve after `ms` milliseconds — used for retry backoff in conversation call policy. */\nexport function sleep(ms: number): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, ms))\n}\n","/**\n *\n * Cross-gateway forwarding headers — the wire-level contract that makes\n * agent-to-agent communication composable across organizational boundaries.\n * Every header here is read on inbound and re-emitted on outbound, so a chain\n * `caller → A's gateway → A's runtime → B's gateway → B's runtime` ends with\n * B billing the original user, the depth counter monotonically incremented,\n * and the run/turn correlation IDs preserved end-to-end.\n *\n * The actual depth refusal (HTTP 413 at MAX_DEPTH) is enforced by\n * `agent-gateway`'s middleware; this module owns the names + the propagation\n * rules so both sides agree.\n *\n * Full protocol: `docs/agent-bus-protocol.md`.\n *\n * @stable\n */\n\n/** Standard names — lowercased so Headers maps interop on every runtime. */\nexport const FORWARD_HEADERS = {\n /** Forwarded original-user identity (`Bearer sk-tan-<user>`); downstream gateways bill against this. */\n authorization: 'x-tangle-forwarded-authorization',\n /** Monotonically incremented on every gateway hop. Refused at MAX_DEPTH. */\n depth: 'x-tangle-forwarded-depth',\n /** Top-level conversation run identifier, propagated through every nested call. */\n runId: 'x-tangle-runid',\n /** This call's turn within the run; deterministic + stable across retries. */\n turnId: 'x-tangle-turnid',\n /** When the call is *inside* another turn (recursion), the parent turn's id. */\n parentTurnId: 'x-tangle-parent-turnid',\n /** Logical conversation peer label at the sending side, for trace stitching. */\n speaker: 'x-tangle-speaker',\n} as const\n\nexport type ForwardHeaderName = (typeof FORWARD_HEADERS)[keyof typeof FORWARD_HEADERS]\n\n/** Hard cap on chained gateway hops; refused beyond this. Default keeps recursion bounded. */\nexport const DEFAULT_MAX_DEPTH = 4\n\n/**\n * Lowercase a header lookup so we read the same key regardless of source\n * casing (Hono, fetch's `Headers`, raw Node IncomingMessage, …).\n */\nfunction lc(name: string): string {\n return name.toLowerCase()\n}\n\n/**\n * Read the depth counter off an inbound request. Missing → 0 (caller is the\n * origin). Non-integer → throws — silent coercion would let a bad caller\n * reset depth and bypass the limit.\n */\nexport function readDepth(\n headers: Readonly<Record<string, string | string[] | undefined>>,\n): number {\n const raw = pickHeader(headers, FORWARD_HEADERS.depth)\n if (raw === undefined || raw === '') return 0\n const n = Number(raw)\n if (!Number.isInteger(n) || n < 0) {\n throw new Error(\n `invalid ${FORWARD_HEADERS.depth} header value '${raw}' — must be a non-negative integer`,\n )\n }\n return n\n}\n\n/**\n * Refuse further forwarding when the inbound depth has reached the limit.\n * Callers (the gateway middleware) translate the boolean to an HTTP 413.\n */\nexport function isDepthExceeded(inboundDepth: number, max: number = DEFAULT_MAX_DEPTH): boolean {\n return inboundDepth >= max\n}\n\n/**\n * Build the headers to emit on an outbound participant call, given the\n * conversation's propagation context. Depth is incremented from the inbound\n * value; runId / turnId / speaker stamp the current hop; the user's\n * `Authorization` is preserved verbatim so the downstream gateway bills the\n * right wallet.\n */\nexport function buildForwardHeaders(input: {\n inboundDepth: number\n forwardedAuthorization?: string\n runId: string\n turnId: string\n parentTurnId?: string\n speaker: string\n}): Record<string, string> {\n const out: Record<string, string> = {\n [FORWARD_HEADERS.depth]: String(input.inboundDepth + 1),\n [FORWARD_HEADERS.runId]: input.runId,\n [FORWARD_HEADERS.turnId]: input.turnId,\n [FORWARD_HEADERS.speaker]: input.speaker,\n }\n if (input.forwardedAuthorization !== undefined) {\n out[FORWARD_HEADERS.authorization] = input.forwardedAuthorization\n }\n if (input.parentTurnId !== undefined) {\n out[FORWARD_HEADERS.parentTurnId] = input.parentTurnId\n }\n return out\n}\n\n/**\n * Header bag carried through `AgentBackendContext.propagatedHeaders` so\n * backends that opt in can merge them into their outbound HTTP requests.\n * Distinct from `buildForwardHeaders` so callers can attach extra\n * non-protocol headers (e.g. tracing) without colliding.\n */\nexport type PropagatedHeaders = Readonly<Record<string, string>>\n\nfunction pickHeader(\n headers: Readonly<Record<string, string | string[] | undefined>>,\n name: string,\n): string | undefined {\n const target = lc(name)\n for (const key of Object.keys(headers)) {\n if (lc(key) === target) {\n const value = headers[key]\n if (Array.isArray(value)) return value[0]\n return value\n }\n }\n return undefined\n}\n","/**\n *\n * Deterministic turn identifier. Stable across retries of the same logical\n * turn so backends (and any caching gateway in between) can dedupe on it.\n * A retry triggered by a network blip or deadline timeout MUST produce the\n * same `turn_id`; only the underlying attempt count differs.\n *\n * Shape: `${runId}.t${index}.${speakerSlug}` — readable in logs, sortable by\n * turn index, attributable to a speaker. Slugify keeps the speaker portion\n * URL-safe so it can ride in HTTP headers without escaping.\n *\n * @stable\n */\n\nexport function turnId(runId: string, index: number, speaker: string): string {\n return `${runId}.t${index}.${slugifySpeaker(speaker)}`\n}\n\n/**\n * Reduce a speaker name to ASCII alphanumerics + dashes. Preserves enough\n * substance to read in a log line; collisions between speakers within a\n * single Conversation are prevented by `defineConversation`'s\n * unique-name check, so the slug only needs to be deterministic, not unique.\n */\nexport function slugifySpeaker(speaker: string): string {\n const cleaned = speaker\n .normalize('NFKD')\n .replace(/[^\\w-]+/g, '-')\n .replace(/-+/g, '-')\n .replace(/^-|-$/g, '')\n .toLowerCase()\n return cleaned || 'anon'\n}\n","/**\n *\n * Conversation orchestrator. Drives N participants in turn through their own\n * `AgentExecutionBackend`s, aggregating per-turn text + usage, enforcing\n * `maxTurns` / `maxCreditsCents` / `haltOn`, and emitting per-event stream\n * markers so callers can plumb the run through SSE without buffering.\n *\n * `runConversation` returns the full result; `runConversationStream` returns\n * an `AsyncIterable<ConversationStreamEvent>` for callers that want to\n * forward events as they arrive. Both share one driving loop.\n *\n * Distributed-systems primitives layered on top of the loop:\n * - **Idempotent turn ids** — `turnId(runId, index, speaker)` stays stable\n * across retries so caching gateways can dedupe.\n * - **Durable journal** — optional `ConversationJournal` persists every\n * committed turn; reusing a runId against the same journal resumes\n * transparently from the last committed turn.\n * - **Per-turn call policy** — deadline, retry-with-backoff, and a\n * per-participant circuit breaker. Retries replay the same logical turn\n * (same `turnId`); the retry loop lives inside the outer generator so\n * deltas yield naturally without cross-coroutine buffering.\n * - **Header propagation** — run/turn/depth headers (+ forwarded user\n * authorization) stamped onto every outbound backend call so downstream\n * gateways can bill the right user and enforce `X-Tangle-Forwarded-Depth`.\n *\n * Credit cap is enforced *between turns*, not mid-stream: a turn that\n * overshoots the cap completes, the cap then halts the conversation before\n * the next turn.\n *\n * @stable\n */\n\nimport type { KnowledgeReadinessReport } from '@tangle-network/agent-eval'\n\nimport { BackendTransportError } from '../errors'\nimport { newRuntimeSession, nowIso, touchSession } from '../sessions'\nimport type {\n AgentBackendContext,\n AgentBackendInput,\n AgentTaskSpec,\n RuntimeSession,\n} from '../types'\nimport {\n type BackendCallPolicy,\n CircuitBreakerState,\n computeBackoff,\n defaultIsRetryable,\n makePerAttemptSignal,\n sleep,\n} from './call-policy'\nimport { buildForwardHeaders, FORWARD_HEADERS } from './headers'\nimport { turnId as deriveTurnId } from './turn-id'\nimport type {\n Conversation,\n ConversationParticipant,\n ConversationResult,\n ConversationStreamEvent,\n ConversationTurn,\n HaltContext,\n HaltReason,\n RunConversationOptions,\n TurnOrder,\n} from './types'\n\nexport async function runConversation(\n conversation: Conversation,\n options: RunConversationOptions,\n): Promise<ConversationResult> {\n let result: ConversationResult | undefined\n for await (const event of runConversationStream(conversation, options)) {\n if (options.onEvent) await options.onEvent(event)\n if (event.type === 'conversation_end') result = event.result\n }\n if (!result) {\n throw new BackendTransportError(\n 'conversation',\n 'conversation stream ended without a conversation_end event',\n )\n }\n return result\n}\n\n/** Streaming conversation orchestrator: drives N participants in turn through their own backends, enforcing `maxTurns` / `maxCreditsCents` / `haltOn`, yielding per-event stream markers. */\nexport async function* runConversationStream(\n conversation: Conversation,\n options: RunConversationOptions,\n): AsyncIterable<ConversationStreamEvent> {\n const runId = options.runId ?? `conv_${crypto.randomUUID()}`\n const inboundDepth = options.inboundDepth ?? 0\n const callerHeaders = options.propagatedHeaders ?? {}\n const forwardedAuthorization = callerHeaders[FORWARD_HEADERS.authorization]\n\n const breakers = new Map<string, CircuitBreakerState>()\n for (const participant of conversation.participants) {\n const cfg =\n participant.callPolicy?.circuitBreaker ??\n conversation.policy.defaultCallPolicy?.circuitBreaker\n breakers.set(participant.name, new CircuitBreakerState(cfg))\n }\n\n let transcript: ConversationTurn[] = []\n let spentCreditsCents = 0\n let startedAt = nowIso()\n let resumed = false\n\n if (options.journal) {\n const prior = await options.journal.loadRun(runId)\n if (prior) {\n if (prior.halted) {\n // Run already terminated — surface its final state without re-running.\n const replayResult: ConversationResult = {\n runId,\n transcript: prior.turns,\n turns: prior.turns.length,\n spentCreditsCents: prior.turns.reduce(\n (sum, t) => sum + centsFromUsd(t.usage?.costUsd ?? 0),\n 0,\n ),\n halted: prior.halted,\n durationMs: 0,\n startedAt: prior.startedAt,\n endedAt: prior.endedAt ?? prior.startedAt,\n }\n yield {\n type: 'conversation_resumed',\n runId,\n participants: conversation.participants.map((p) => p.name),\n transcript: prior.turns,\n timestamp: nowIso(),\n }\n yield { type: 'conversation_end', runId, result: replayResult, timestamp: nowIso() }\n return\n }\n transcript = [...prior.turns]\n spentCreditsCents = transcript.reduce(\n (sum, t) => sum + centsFromUsd(t.usage?.costUsd ?? 0),\n 0,\n )\n startedAt = prior.startedAt\n resumed = true\n } else {\n await options.journal.beginRun(runId, startedAt)\n }\n }\n const startedAtMs = Date.now()\n\n if (resumed) {\n yield {\n type: 'conversation_resumed',\n runId,\n participants: conversation.participants.map((p) => p.name),\n // Snapshot the resumed transcript — the live `transcript` array gets\n // pushed to as the run continues, so handing the bare reference to a\n // subscriber would leak future writes into a past event.\n transcript: [...transcript],\n timestamp: nowIso(),\n }\n } else {\n yield {\n type: 'conversation_start',\n runId,\n participants: conversation.participants.map((p) => p.name),\n seed: options.seed,\n timestamp: startedAt,\n }\n }\n\n // When resumed, the next user input is the last persisted turn's text;\n // for a fresh run, it's the caller's seed.\n let currentInput =\n transcript.length === 0\n ? options.seed\n : (transcript[transcript.length - 1]?.text ?? options.seed)\n let halt: HaltReason | undefined\n\n const initialOffset = transcript.length\n for (let turnIndex = initialOffset; turnIndex < conversation.policy.maxTurns; turnIndex++) {\n if (options.signal?.aborted) {\n halt = { kind: 'abort' }\n break\n }\n if (\n conversation.policy.maxCreditsCents !== undefined &&\n spentCreditsCents >= conversation.policy.maxCreditsCents\n ) {\n halt = {\n kind: 'max_credits',\n spentCents: spentCreditsCents,\n capCents: conversation.policy.maxCreditsCents,\n }\n break\n }\n\n const speakerIdx = selectSpeaker(\n conversation.policy.turnOrder,\n conversation.participants.length,\n { transcript, turnIndex, spentCreditsCents },\n )\n const speaker = conversation.participants[speakerIdx]\n if (!speaker) {\n throw new BackendTransportError(\n 'conversation',\n `turnOrder selector returned out-of-range index ${speakerIdx} for ${conversation.participants.length} participants`,\n )\n }\n\n const tid = deriveTurnId(runId, turnIndex, speaker.name)\n const callPolicy: BackendCallPolicy | undefined =\n speaker.callPolicy ?? conversation.policy.defaultCallPolicy\n const breaker = breakers.get(speaker.name)\n if (!breaker) {\n throw new BackendTransportError(\n 'conversation',\n `internal: no circuit-breaker state registered for participant '${speaker.name}'`,\n )\n }\n const isRetryable = callPolicy?.isRetryable ?? defaultIsRetryable\n const totalAttempts = 1 + (callPolicy?.maxRetries ?? 0)\n\n yield {\n type: 'turn_start',\n runId,\n index: turnIndex,\n speaker: speaker.name,\n turnId: tid,\n attempt: 1,\n timestamp: nowIso(),\n }\n\n let aggregator: TurnAggregator | undefined\n let attemptCount = 0\n let lastError: unknown\n let breakerOpenFailure: unknown\n\n for (let attempt = 1; attempt <= totalAttempts; attempt++) {\n attemptCount = attempt\n try {\n breaker.preflight(speaker.name)\n } catch (err) {\n // Breaker open — no point retrying; halt the conversation with this\n // participant's error rather than busy-looping until exhaustion.\n breakerOpenFailure = err\n break\n }\n\n if (attempt > 1) {\n yield {\n type: 'turn_retry',\n runId,\n index: turnIndex,\n speaker: speaker.name,\n turnId: tid,\n attempt,\n reason: lastError instanceof Error ? lastError.message : String(lastError),\n timestamp: nowIso(),\n }\n }\n\n const perAttempt = makePerAttemptSignal(options.signal, callPolicy?.perAttemptDeadlineMs)\n const localAgg = new TurnAggregator({\n index: turnIndex,\n speaker: speaker.name,\n startedAt: nowIso(),\n })\n\n try {\n for await (const delta of driveSingleAttempt({\n speaker,\n participants: conversation.participants,\n input: currentInput,\n turnIndex,\n runId,\n turnId: tid,\n transcript,\n signal: perAttempt.signal,\n aggregator: localAgg,\n propagatedHeaders: buildForwardHeaders({\n inboundDepth,\n // When the participant elects to pay for its own outbound calls,\n // drop the forwarded user identity so the downstream gateway\n // bills the participant's own credentials instead. The backend\n // brings its own `Authorization` header at construction time\n // (e.g. `createOpenAICompatibleBackend({ apiKey: sk-tan-AGENT })`);\n // omitting the forwarded header is what flips the billing target.\n forwardedAuthorization: resolveAuthForwarding(speaker, {\n transcript,\n turnIndex,\n spentCreditsCents,\n })\n ? forwardedAuthorization\n : undefined,\n runId,\n turnId: tid,\n parentTurnId: options.parentTurnId,\n speaker: speaker.name,\n }),\n })) {\n yield {\n type: 'turn_text_delta',\n runId,\n index: turnIndex,\n speaker: speaker.name,\n turnId: tid,\n text: delta.text,\n timestamp: delta.timestamp,\n }\n }\n perAttempt.dispose()\n breaker.recordSuccess()\n aggregator = localAgg\n break\n } catch (err) {\n perAttempt.dispose()\n breaker.recordFailure()\n // Surface the deadline error explicitly when timeout was the cause —\n // otherwise the upstream may throw a generic AbortError that loses\n // diagnostic info.\n lastError = perAttempt.getDeadlineError() ?? err\n if (attempt >= totalAttempts || !isRetryable(lastError)) {\n break\n }\n await sleep(computeBackoff(callPolicy?.retryBackoffMs, attempt))\n }\n }\n\n if (!aggregator) {\n const failure = breakerOpenFailure ?? lastError\n const message = failure instanceof Error ? failure.message : String(failure)\n halt = { kind: 'participant_error', participant: speaker.name, message }\n break\n }\n\n const turn = aggregator.toTurn({ turnId: tid, attempts: attemptCount })\n transcript.push(turn)\n spentCreditsCents += centsFromUsd(turn.usage?.costUsd ?? 0)\n if (options.journal) {\n await options.journal.appendTurn(runId, turn)\n }\n\n yield { type: 'turn_end', runId, turn, timestamp: nowIso() }\n\n if (conversation.policy.haltOn) {\n const haltCtx: HaltContext = {\n transcript,\n lastTurn: turn,\n turnIndex,\n spentCreditsCents,\n }\n const decision = await conversation.policy.haltOn(haltCtx)\n if (decision === true) {\n halt = { kind: 'predicate', reason: 'predicate_true' }\n break\n }\n if (typeof decision === 'object' && decision !== null && decision.halted) {\n halt = { kind: 'predicate', reason: decision.reason }\n break\n }\n }\n\n currentInput = turn.text\n }\n\n if (!halt) halt = { kind: 'max_turns', turns: transcript.length }\n\n const endedAt = nowIso()\n const result: ConversationResult = {\n runId,\n transcript,\n turns: transcript.length,\n spentCreditsCents,\n halted: halt,\n durationMs: Date.now() - startedAtMs,\n startedAt,\n endedAt,\n }\n if (options.journal) {\n await options.journal.recordHalt(runId, halt, endedAt)\n }\n\n yield { type: 'conversation_end', runId, result, timestamp: endedAt }\n}\n\n// ── Single attempt ───────────────────────────────────────────────────────\n\ninterface SingleAttemptArgs {\n speaker: ConversationParticipant\n participants: readonly ConversationParticipant[]\n input: string\n turnIndex: number\n runId: string\n turnId: string\n transcript: readonly ConversationTurn[]\n signal: AbortSignal\n aggregator: TurnAggregator\n propagatedHeaders: Record<string, string>\n}\n\nasync function* driveSingleAttempt(\n args: SingleAttemptArgs,\n): AsyncGenerator<{ text: string; timestamp?: string }> {\n const task: AgentTaskSpec = {\n id: args.turnId,\n intent: args.input,\n metadata: {\n runId: args.runId,\n turnId: args.turnId,\n turnIndex: args.turnIndex,\n speaker: args.speaker.name,\n participants: args.participants.map((p) => p.name),\n },\n }\n const knowledge = passingReadiness(task.id)\n const messages = buildMessagesFor(args.speaker.name, args.transcript, args.input)\n const backendInput: AgentBackendInput = { task, message: args.input, messages }\n\n const startCtx: Omit<AgentBackendContext, 'session'> & { requestedSessionId?: string } = {\n task,\n knowledge,\n signal: args.signal,\n runId: args.runId,\n turnId: args.turnId,\n propagatedHeaders: args.propagatedHeaders,\n }\n const session: RuntimeSession = args.speaker.backend.start\n ? touchSession(await args.speaker.backend.start(backendInput, startCtx))\n : newRuntimeSession(args.speaker.backend.kind, undefined, {\n runId: args.runId,\n turnIndex: args.turnIndex,\n turnId: args.turnId,\n speaker: args.speaker.name,\n })\n\n const streamCtx: AgentBackendContext = {\n task,\n knowledge,\n session,\n signal: args.signal,\n runId: args.runId,\n turnId: args.turnId,\n propagatedHeaders: args.propagatedHeaders,\n }\n\n for await (const event of args.speaker.backend.stream(backendInput, streamCtx)) {\n if (args.signal.aborted) {\n // Surface the abort so the outer retry/halt logic can react. The signal\n // either fires because of caller-cancel (propagate as-is) or because of\n // the per-attempt deadline timer (signal.reason is DeadlineExceededError).\n const reason = args.signal.reason\n throw reason instanceof Error ? reason : new Error('aborted')\n }\n if (event.type === 'text_delta') {\n args.aggregator.appendText(event.text)\n yield { text: event.text, timestamp: event.timestamp }\n } else if (event.type === 'llm_call') {\n args.aggregator.recordUsage(event)\n } else if (event.type === 'final') {\n args.aggregator.adoptFinalText(event.text)\n }\n }\n}\n\nclass TurnAggregator {\n private text = ''\n private adoptedFinal = false\n private usage:\n | {\n tokensIn?: number\n tokensOut?: number\n costUsd?: number\n latencyMs?: number\n model?: string\n }\n | undefined\n\n constructor(private readonly base: { index: number; speaker: string; startedAt: string }) {}\n\n appendText(text: string): void {\n if (this.adoptedFinal) return\n this.text += text\n }\n\n /**\n * Use the backend's `final.text` only when no streamed deltas were observed.\n * Some backends emit deltas AND a final summary; treating both as content\n * would double-count.\n */\n adoptFinalText(text: string | undefined): void {\n if (!text) return\n if (this.text.length > 0) return\n this.text = text\n this.adoptedFinal = true\n }\n\n recordUsage(event: {\n model?: string\n tokensIn?: number\n tokensOut?: number\n costUsd?: number\n latencyMs?: number\n }): void {\n const u = this.usage ?? {}\n if (event.tokensIn !== undefined) u.tokensIn = (u.tokensIn ?? 0) + event.tokensIn\n if (event.tokensOut !== undefined) u.tokensOut = (u.tokensOut ?? 0) + event.tokensOut\n if (event.costUsd !== undefined) u.costUsd = (u.costUsd ?? 0) + event.costUsd\n if (event.latencyMs !== undefined) u.latencyMs = event.latencyMs\n if (event.model !== undefined) u.model = event.model\n this.usage = u\n }\n\n toTurn(meta: { turnId: string; attempts: number }): ConversationTurn {\n return {\n index: this.base.index,\n speaker: this.base.speaker,\n turnId: meta.turnId,\n text: this.text.trim(),\n usage: this.usage,\n attempts: meta.attempts,\n startedAt: this.base.startedAt,\n endedAt: nowIso(),\n }\n }\n}\n\n/**\n * Build the participant's POV of the transcript so an OpenAI-compatible\n * backend sees its own turns as `assistant` and everyone else's as `user`,\n * with explicit speaker tags so 3+ party conversations stay disambiguated.\n * The seed / current input is appended as the trailing user message.\n */\nfunction buildMessagesFor(\n speakerName: string,\n transcript: readonly ConversationTurn[],\n currentInput: string,\n): Array<{ role: string; content: string }> {\n const messages: Array<{ role: string; content: string }> = []\n for (const turn of transcript) {\n if (turn.speaker === speakerName) {\n messages.push({ role: 'assistant', content: turn.text })\n } else {\n messages.push({ role: 'user', content: `[${turn.speaker}] ${turn.text}` })\n }\n }\n if (currentInput) messages.push({ role: 'user', content: currentInput })\n return messages\n}\n\n/**\n * True when this participant should forward the caller's\n * `X-Tangle-Forwarded-Authorization` on outbound calls (the \"pass-through\"\n * commercial mode). False when it elects to pay for its own outbound calls\n * (the \"reseller\" / \"bundle\" mode). See ConversationParticipant.authSource.\n */\nfunction resolveAuthForwarding(\n participant: ConversationParticipant,\n state: { transcript: readonly ConversationTurn[]; turnIndex: number; spentCreditsCents: number },\n): boolean {\n const decision =\n typeof participant.authSource === 'function'\n ? participant.authSource(state)\n : (participant.authSource ?? 'forward-user')\n return decision === 'forward-user'\n}\n\nfunction selectSpeaker(\n order: TurnOrder | undefined,\n participantCount: number,\n state: { transcript: readonly ConversationTurn[]; turnIndex: number; spentCreditsCents: number },\n): number {\n const resolved = order ?? (participantCount === 2 ? 'alternate' : 'round-robin')\n if (resolved === 'alternate' || resolved === 'round-robin') {\n return state.turnIndex % participantCount\n }\n if (typeof resolved === 'function') {\n const idx = resolved(state)\n if (!Number.isInteger(idx) || idx < 0 || idx >= participantCount) {\n throw new BackendTransportError(\n 'conversation',\n `turnOrder function returned invalid index ${String(idx)} for ${participantCount} participants`,\n )\n }\n return idx\n }\n throw new BackendTransportError('conversation', `unknown turnOrder: ${String(resolved)}`)\n}\n\nfunction centsFromUsd(usd: number): number {\n return Math.round(usd * 100)\n}\n\n/**\n * Synthesize a knowledge-readiness report that *passes* every gate, used to\n * satisfy `AgentBackendContext.knowledge` per turn. Conversations don't apply\n * task-level readiness gating per-turn — that's a `runAgentTask` concern.\n */\nfunction passingReadiness(taskId: string): KnowledgeReadinessReport {\n return {\n taskId,\n readinessScore: 1,\n blockingMissingRequirements: [],\n nonBlockingGaps: [],\n recommendedAction: 'run_agent',\n bundle: {\n taskId,\n requirements: [],\n evidenceIds: [],\n claimIds: [],\n wikiPageIds: [],\n userAnswers: {},\n missing: [],\n readinessScore: 1,\n },\n severity: 'info',\n reason: 'conversation-mode: readiness gating not applied per-turn',\n }\n}\n","/**\n *\n * Wrap a `Conversation` so it satisfies `AgentExecutionBackend`. The result is\n * an addressable \"single agent\" whose internal behavior is an N-party\n * orchestrated conversation — the recursion primitive that lets a swarm be a\n * participant inside another swarm, or be published behind a single\n * agent-gateway endpoint.\n *\n * Stream events from inner participants are NOT forwarded verbatim. Outer\n * callers see one `text_delta` per inner turn (the turn's full text), tagged\n * with `[speaker] ` prefix so the outer transcript stays attributable. The\n * conversation's `conversation_end` halt reason rides on a `final` event.\n *\n * @stable\n */\n\nimport { newRuntimeSession, nowIso } from '../sessions'\nimport type {\n AgentBackendContext,\n AgentBackendInput,\n AgentExecutionBackend,\n RuntimeSession,\n RuntimeStreamEvent,\n} from '../types'\nimport { FORWARD_HEADERS, readDepth } from './headers'\nimport { runConversationStream } from './run-conversation'\nimport type { Conversation, HaltReason } from './types'\n\nexport function createConversationBackend(options: {\n conversation: Conversation\n /** Optional backend kind label. Defaults to `'conversation'`. */\n kind?: string\n}): AgentExecutionBackend {\n const kind = options.kind ?? 'conversation'\n\n return {\n kind,\n start(_input, context): RuntimeSession {\n return newRuntimeSession(kind, context.requestedSessionId, {\n participants: options.conversation.participants.map((p) => p.name),\n })\n },\n async *stream(\n input: AgentBackendInput,\n context: AgentBackendContext,\n ): AsyncIterable<RuntimeStreamEvent> {\n const seed = input.message ?? input.messages?.at(-1)?.content ?? context.task.intent\n const task = context.task\n const session = context.session\n\n yield { type: 'backend_start', task, session, backend: kind, timestamp: nowIso() }\n\n let finalText = ''\n let totalCostUsd = 0\n let totalTokensIn = 0\n let totalTokensOut = 0\n\n // Recursion: forward this call's propagation context into the nested\n // conversation. The nested run INHERITS the parent's runId (protocol\n // invariant: runId is immutable across nesting), continues the depth\n // counter from the headers, and stamps the enclosing turn as the\n // parentTurnId so trace stitching reaches across nesting levels.\n const inboundDepth = parseInboundDepth(context.propagatedHeaders)\n for await (const event of runConversationStream(options.conversation, {\n seed,\n signal: context.signal,\n runId: context.runId,\n propagatedHeaders: context.propagatedHeaders,\n inboundDepth,\n parentTurnId: context.turnId,\n })) {\n if (event.type === 'turn_end') {\n const tagged = `[${event.turn.speaker}] ${event.turn.text}\\n`\n finalText += tagged\n yield { type: 'text_delta', task, session, text: tagged, timestamp: event.timestamp }\n if (event.turn.usage) {\n const u = event.turn.usage\n if (u.costUsd !== undefined) totalCostUsd += u.costUsd\n if (u.tokensIn !== undefined) totalTokensIn += u.tokensIn\n if (u.tokensOut !== undefined) totalTokensOut += u.tokensOut\n yield {\n type: 'llm_call',\n task,\n session,\n model: u.model ?? `${kind}/${event.turn.speaker}`,\n tokensIn: u.tokensIn,\n tokensOut: u.tokensOut,\n costUsd: u.costUsd,\n latencyMs: u.latencyMs,\n timestamp: event.timestamp,\n }\n }\n } else if (event.type === 'conversation_end') {\n const halt = event.result.halted\n yield {\n type: 'final',\n task,\n session,\n status: halt.kind === 'participant_error' ? 'failed' : 'completed',\n reason: describeHalt(halt),\n text: finalText.trim(),\n metadata: {\n conversationRunId: event.result.runId,\n turns: event.result.turns,\n spentCreditsCents: event.result.spentCreditsCents,\n halted: halt,\n durationMs: event.result.durationMs,\n tokensIn: totalTokensIn,\n tokensOut: totalTokensOut,\n costUsd: totalCostUsd,\n },\n timestamp: event.timestamp,\n }\n }\n }\n\n yield { type: 'backend_end', task, session, backend: kind, timestamp: nowIso() }\n },\n }\n}\n\nfunction parseInboundDepth(headers: Readonly<Record<string, string>> | undefined): number {\n if (!headers) return 0\n // Accept either the canonical header key OR a lookup via the keyed name.\n const raw = headers[FORWARD_HEADERS.depth]\n if (raw === undefined) return 0\n try {\n return readDepth({ [FORWARD_HEADERS.depth]: raw })\n } catch {\n return 0\n }\n}\n\nfunction describeHalt(halt: HaltReason): string {\n switch (halt.kind) {\n case 'max_turns':\n return `max_turns (${halt.turns})`\n case 'max_credits':\n return `max_credits (${halt.spentCents}/${halt.capCents}¢)`\n case 'predicate':\n return `predicate: ${halt.reason}`\n case 'abort':\n return 'abort'\n case 'participant_error':\n return `participant_error[${halt.participant}]: ${halt.message}`\n }\n}\n","/**\n *\n * Declarative constructor for a multi-agent `Conversation`. Validates inputs\n * fail-loud at definition time (duplicate participant names, alternate order\n * with ≠2 participants, non-positive `maxTurns`) so misconfiguration is caught\n * before `runConversation` is called and not buried inside a streaming run.\n *\n * @stable\n */\n\nimport { ValidationError } from '../errors'\nimport type { Conversation, ConversationParticipant, ConversationPolicy, TurnOrder } from './types'\n\nexport function defineConversation(input: {\n participants: ConversationParticipant[]\n policy: ConversationPolicy\n}): Conversation {\n if (input.participants.length < 2) {\n throw new ValidationError(\n `Conversation requires at least 2 participants; received ${input.participants.length}.`,\n )\n }\n\n const seen = new Set<string>()\n for (const p of input.participants) {\n if (!p.name || p.name.trim() === '') {\n throw new ValidationError('Conversation participant.name must be a non-empty string.')\n }\n if (seen.has(p.name)) {\n throw new ValidationError(\n `Conversation participant names must be unique within a Conversation; '${p.name}' appears more than once.`,\n )\n }\n seen.add(p.name)\n if (!p.backend || typeof p.backend.stream !== 'function') {\n throw new ValidationError(\n `Conversation participant '${p.name}' is missing a backend with a stream() method.`,\n )\n }\n }\n\n const policy = normalizePolicy(input.policy, input.participants.length)\n\n return {\n participants: input.participants,\n policy,\n }\n}\n\nfunction normalizePolicy(policy: ConversationPolicy, participantCount: number): ConversationPolicy {\n if (!Number.isInteger(policy.maxTurns) || policy.maxTurns < 1) {\n throw new ValidationError(\n `ConversationPolicy.maxTurns must be a positive integer; received ${String(policy.maxTurns)}.`,\n )\n }\n if (\n policy.maxCreditsCents !== undefined &&\n (!Number.isFinite(policy.maxCreditsCents) || policy.maxCreditsCents < 0)\n ) {\n throw new ValidationError(\n `ConversationPolicy.maxCreditsCents must be a non-negative finite number when set; received ${String(\n policy.maxCreditsCents,\n )}.`,\n )\n }\n const turnOrder = policy.turnOrder ?? (participantCount === 2 ? 'alternate' : 'round-robin')\n if (turnOrder === 'alternate' && participantCount !== 2) {\n throw new ValidationError(\n `ConversationPolicy.turnOrder 'alternate' requires exactly 2 participants; received ${participantCount}. Use 'round-robin' or a custom selector for N-party conversations.`,\n )\n }\n return { ...policy, turnOrder: turnOrder as TurnOrder }\n}\n","/**\n *\n * Durable conversation transcript — survives a driver process crash mid-run.\n * The runner journals every committed turn before yielding `turn_end`, so a\n * resumed run replays the same `runId` against the same journal and picks up\n * from the first un-recorded turn. Combined with the deterministic\n * `turnId(runId, index, speaker)`, a retried turn collides with the prior\n * attempt's id and any caching gateway can dedupe.\n *\n * The interface is small enough that a Cloudflare D1 / R2 / postgres adapter\n * is ~30 lines. The in-memory adapter is the default for tests and scratch.\n * The file adapter (JSONL on disk) is the default-durable choice when no\n * upstream store is wired.\n *\n * @stable\n */\n\nimport type { ConversationTurn, HaltReason } from './types'\n\nexport interface ConversationJournalEntry {\n runId: string\n startedAt: string\n /** Set when the run reaches a terminal state. */\n halted?: HaltReason\n endedAt?: string\n turns: ConversationTurn[]\n}\n\nexport interface ConversationJournal {\n /**\n * Load any prior state for `runId`. Returns `undefined` for a fresh run.\n * Implementations MUST NOT mutate the returned object — the runner clones\n * before continuing — but the runtime treats absence and emptiness\n * identically, so a journal with zero turns is equivalent to \"fresh.\"\n */\n loadRun(runId: string): Promise<ConversationJournalEntry | undefined>\n\n /**\n * Initialise journal state for a fresh run. Called once per run, before any\n * `appendTurn`. Idempotent: calling with an existing runId is a no-op if\n * the entry already exists with the same `startedAt`.\n */\n beginRun(runId: string, startedAt: string): Promise<void>\n\n /**\n * Append a committed turn. The runner only calls this AFTER the turn's\n * backend stream completed and the credit total has been updated, so an\n * appended turn is observed-committed and never speculative.\n */\n appendTurn(runId: string, turn: ConversationTurn): Promise<void>\n\n /**\n * Record the run's terminal halt reason + end time. Once called, the run\n * is observed-final; subsequent `loadRun` returns the same halt.\n */\n recordHalt(runId: string, halt: HaltReason, endedAt: string): Promise<void>\n}\n\n/** In-memory `ConversationJournal` — suitable for testing and single-process runs. */\nexport class InMemoryConversationJournal implements ConversationJournal {\n private readonly entries = new Map<string, ConversationJournalEntry>()\n\n async loadRun(runId: string): Promise<ConversationJournalEntry | undefined> {\n const entry = this.entries.get(runId)\n if (!entry) return undefined\n // Defensive copy — callers MUST NOT mutate journal-owned arrays.\n return {\n runId: entry.runId,\n startedAt: entry.startedAt,\n halted: entry.halted,\n endedAt: entry.endedAt,\n turns: [...entry.turns],\n }\n }\n\n async beginRun(runId: string, startedAt: string): Promise<void> {\n const existing = this.entries.get(runId)\n if (existing) {\n if (existing.startedAt !== startedAt) {\n throw new Error(\n `runId '${runId}' already exists with startedAt=${existing.startedAt}; refusing to overwrite with ${startedAt}`,\n )\n }\n return\n }\n this.entries.set(runId, { runId, startedAt, turns: [] })\n }\n\n async appendTurn(runId: string, turn: ConversationTurn): Promise<void> {\n const entry = this.entries.get(runId)\n if (!entry) {\n throw new Error(\n `appendTurn called for unknown runId '${runId}'; call beginRun first or use the runner which handles it`,\n )\n }\n if (entry.halted) {\n throw new Error(\n `cannot append turn to halted run '${runId}' (halt reason: ${JSON.stringify(entry.halted)})`,\n )\n }\n entry.turns.push(turn)\n }\n\n async recordHalt(runId: string, halt: HaltReason, endedAt: string): Promise<void> {\n const entry = this.entries.get(runId)\n if (!entry) {\n throw new Error(`recordHalt called for unknown runId '${runId}'`)\n }\n entry.halted = halt\n entry.endedAt = endedAt\n }\n}\n\n/**\n * JSONL on disk. One line per record; first line is the `begin`, subsequent\n * lines are `turn` records, terminal line is `halt`. Replays the whole file\n * on `loadRun` — cheap for the conversation sizes this is designed for\n * (thousands of turns, not millions). For huge runs, plug in a real DB\n * adapter; the interface is small.\n *\n * Each `appendTurn` / `recordHalt` calls `fsync` after the write so a\n * process crash between writes never loses an acknowledged turn.\n */\nexport class FileConversationJournal implements ConversationJournal {\n constructor(private readonly path: string) {}\n\n async loadRun(runId: string): Promise<ConversationJournalEntry | undefined> {\n const fs = await import('node:fs/promises')\n let text: string\n try {\n text = await fs.readFile(this.path, 'utf8')\n } catch (err) {\n if (isNoEntError(err)) return undefined\n throw err\n }\n const lines = text.split('\\n').filter((line) => line.length > 0)\n let entry: ConversationJournalEntry | undefined\n for (const line of lines) {\n const record = JSON.parse(line) as JournalRecord\n if (record.runId !== runId) continue\n if (record.kind === 'begin') {\n entry = { runId, startedAt: record.startedAt, turns: [] }\n } else if (record.kind === 'turn') {\n if (!entry) {\n throw new Error(\n `journal corrupted: turn record for runId '${runId}' precedes its begin record`,\n )\n }\n entry.turns.push(record.turn)\n } else if (record.kind === 'halt') {\n if (!entry) {\n throw new Error(\n `journal corrupted: halt record for runId '${runId}' precedes its begin record`,\n )\n }\n entry.halted = record.halted\n entry.endedAt = record.endedAt\n }\n }\n return entry\n }\n\n async beginRun(runId: string, startedAt: string): Promise<void> {\n const existing = await this.loadRun(runId)\n if (existing) {\n if (existing.startedAt !== startedAt) {\n throw new Error(\n `runId '${runId}' already exists in ${this.path} with startedAt=${existing.startedAt}; refusing to overwrite with ${startedAt}`,\n )\n }\n return\n }\n await this.appendRecord({ kind: 'begin', runId, startedAt })\n }\n\n async appendTurn(runId: string, turn: ConversationTurn): Promise<void> {\n await this.appendRecord({ kind: 'turn', runId, turn })\n }\n\n async recordHalt(runId: string, halt: HaltReason, endedAt: string): Promise<void> {\n await this.appendRecord({ kind: 'halt', runId, halted: halt, endedAt })\n }\n\n private async appendRecord(record: JournalRecord): Promise<void> {\n const fs = await import('node:fs/promises')\n const path = await import('node:path')\n await fs.mkdir(path.dirname(this.path), { recursive: true })\n const fh = await fs.open(this.path, 'a')\n try {\n await fh.write(`${JSON.stringify(record)}\\n`)\n await fh.sync()\n } finally {\n await fh.close()\n }\n }\n}\n\ntype JournalRecord =\n | { kind: 'begin'; runId: string; startedAt: string }\n | { kind: 'turn'; runId: string; turn: ConversationTurn }\n | { kind: 'halt'; runId: string; halted: HaltReason; endedAt: string }\n\nfunction isNoEntError(err: unknown): boolean {\n return (\n typeof err === 'object' &&\n err !== null &&\n 'code' in err &&\n (err as { code: unknown }).code === 'ENOENT'\n )\n}\n","/**\n *\n * Durable conversation journal backed by any SQL store. Adapter-agnostic by\n * design: callers wire a `SqlAdapter` against their driver of choice (D1,\n * postgres, sqlite, libSQL…) and the same journal implementation persists\n * conversation runs durably across process restarts. The schema is two\n * tables — runs (latest state) + events (append-only log) — so a partial\n * crash in the middle of a turn leaves an unambiguous \"last committed turn\"\n * to resume from.\n *\n * Why not bake in a specific driver? agent-runtime ships against multiple\n * runtimes (Cloudflare Workers, Node, Bun, Deno) and consumers' fleets have\n * already standardized on one of D1 / postgres / sqlite / libSQL. Adapter\n * indirection costs ~5 lines per driver in the consumer's code and keeps the\n * SDK free of native deps.\n *\n * @example D1 (Cloudflare Workers)\n * import { SqlConversationJournal, d1ToSqlAdapter } from '@tangle-network/agent-runtime'\n * const journal = new SqlConversationJournal(d1ToSqlAdapter(env.DB))\n * await journal.migrate() // once at deploy\n * await runConversation(conv, { seed, journal, runId: 'run_abc' })\n *\n * @example node-postgres\n * import { Pool } from 'pg'\n * const pool = new Pool({ connectionString: process.env.DATABASE_URL })\n * const pg: SqlAdapter = {\n * exec: async (sql, params = []) => {\n * const r = await pool.query(sql, params as never)\n * return { rowsAffected: r.rowCount ?? 0 }\n * },\n * query: async (sql, params = []) => (await pool.query(sql, params as never)).rows,\n * }\n * const journal = new SqlConversationJournal(pg)\n * await journal.migrate()\n *\n * @stable\n */\n\nimport type { ConversationJournal, ConversationJournalEntry } from './journal'\nimport type { ConversationTurn, HaltReason } from './types'\n\n/**\n * Minimal SQL driver shape. Implementations forward to whichever client the\n * deployment already uses; agent-runtime takes no opinion on which.\n *\n * Parameter placeholders MUST be `?` (positional). All adapters listed in the\n * file header accept this convention.\n */\nexport interface SqlAdapter {\n /** Execute a write statement (INSERT/UPDATE/DELETE/DDL). */\n exec(sql: string, params?: readonly unknown[]): Promise<{ rowsAffected: number }>\n /** Execute a read statement (SELECT). Returns rows as plain objects. */\n query<TRow = Record<string, unknown>>(sql: string, params?: readonly unknown[]): Promise<TRow[]>\n}\n\n/**\n * Adapt a Cloudflare D1 binding to the SqlAdapter shape. Lives here so D1\n * consumers don't have to write the wrapper themselves; the runtime never\n * imports `@cloudflare/workers-types` directly (peer-style typing).\n */\nexport function d1ToSqlAdapter(db: D1DatabaseLike): SqlAdapter {\n return {\n async exec(sql, params = []) {\n const stmt = db.prepare(sql)\n const bound = params.length > 0 ? stmt.bind(...params) : stmt\n const result = await bound.run()\n const meta = (result as { meta?: { rows_written?: number; changes?: number } }).meta\n return { rowsAffected: meta?.rows_written ?? meta?.changes ?? 0 }\n },\n async query<TRow>(sql: string, params: readonly unknown[] = []): Promise<TRow[]> {\n const stmt = db.prepare(sql)\n const bound = params.length > 0 ? stmt.bind(...params) : stmt\n const result = await bound.all<TRow>()\n return result.results ?? []\n },\n }\n}\n\n/**\n * Structural type matching the surface of `D1Database` we depend on, so the\n * SDK never imports `@cloudflare/workers-types`. Consumers pass their real\n * `D1Database` from `env.DB` and TS structural compatibility lines it up.\n */\nexport interface D1DatabaseLike {\n prepare(sql: string): D1StmtLike\n}\nexport interface D1StmtLike {\n bind(...params: unknown[]): D1StmtLike\n run(): Promise<unknown>\n all<TRow = unknown>(): Promise<{ results?: TRow[] }>\n}\n\nconst RUNS_TABLE_DDL = (table: string) => `\n CREATE TABLE IF NOT EXISTS ${table}_runs (\n run_id TEXT PRIMARY KEY,\n started_at TEXT NOT NULL,\n halted_kind TEXT,\n halted_payload TEXT,\n ended_at TEXT\n )\n`\nconst TURNS_TABLE_DDL = (table: string) => `\n CREATE TABLE IF NOT EXISTS ${table}_turns (\n run_id TEXT NOT NULL,\n turn_index INTEGER NOT NULL,\n payload TEXT NOT NULL,\n PRIMARY KEY (run_id, turn_index)\n )\n`\nconst TURNS_INDEX_DDL = (table: string) => `\n CREATE INDEX IF NOT EXISTS idx_${table}_turns_run ON ${table}_turns (run_id, turn_index)\n`\n\n/**\n * SQL-backed ConversationJournal. Two tables — runs (one row per runId, holds\n * start/halt timestamps + halt reason) and turns (one row per committed turn,\n * payload is the ConversationTurn JSON). Replays the turns table on\n * `loadRun` and writes append-only per `appendTurn`.\n */\nexport class SqlConversationJournal implements ConversationJournal {\n /**\n * @param db SQL adapter (D1, postgres, sqlite, libSQL — all work)\n * @param table Table-name prefix; the journal creates `${table}_runs` and\n * `${table}_turns`. Lets multiple journals share a database\n * without colliding (e.g. one per product surface).\n */\n constructor(\n private readonly db: SqlAdapter,\n private readonly table: string = 'agent_runtime_journal',\n ) {}\n\n /**\n * Create the journal's tables if absent. Idempotent. Call once at deploy\n * (or at app boot) — running on every request is harmless but adds latency.\n */\n async migrate(): Promise<void> {\n await this.db.exec(RUNS_TABLE_DDL(this.table))\n await this.db.exec(TURNS_TABLE_DDL(this.table))\n await this.db.exec(TURNS_INDEX_DDL(this.table))\n }\n\n async loadRun(runId: string): Promise<ConversationJournalEntry | undefined> {\n const runs = await this.db.query<{\n run_id: string\n started_at: string\n halted_kind: string | null\n halted_payload: string | null\n ended_at: string | null\n }>(\n `SELECT run_id, started_at, halted_kind, halted_payload, ended_at FROM ${this.table}_runs WHERE run_id = ?`,\n [runId],\n )\n const row = runs[0]\n if (!row) return undefined\n const turns = await this.db.query<{ payload: string; turn_index: number }>(\n `SELECT payload, turn_index FROM ${this.table}_turns WHERE run_id = ? ORDER BY turn_index ASC`,\n [runId],\n )\n return {\n runId: row.run_id,\n startedAt: row.started_at,\n halted: row.halted_payload ? (JSON.parse(row.halted_payload) as HaltReason) : undefined,\n endedAt: row.ended_at ?? undefined,\n turns: turns.map((t) => JSON.parse(t.payload) as ConversationTurn),\n }\n }\n\n async beginRun(runId: string, startedAt: string): Promise<void> {\n const existing = await this.db.query<{ started_at: string }>(\n `SELECT started_at FROM ${this.table}_runs WHERE run_id = ?`,\n [runId],\n )\n if (existing.length > 0) {\n if (existing[0]?.started_at !== startedAt) {\n throw new Error(\n `runId '${runId}' already exists with startedAt=${existing[0]?.started_at}; refusing to overwrite with ${startedAt}`,\n )\n }\n return\n }\n await this.db.exec(`INSERT INTO ${this.table}_runs (run_id, started_at) VALUES (?, ?)`, [\n runId,\n startedAt,\n ])\n }\n\n async appendTurn(runId: string, turn: ConversationTurn): Promise<void> {\n const halted = await this.db.query<{ halted_kind: string | null }>(\n `SELECT halted_kind FROM ${this.table}_runs WHERE run_id = ?`,\n [runId],\n )\n if (halted.length === 0) {\n throw new Error(\n `appendTurn called for unknown runId '${runId}'; call beginRun first or use the runner which handles it`,\n )\n }\n if (halted[0]?.halted_kind) {\n throw new Error(\n `cannot append turn to halted run '${runId}' (halt kind: ${halted[0]?.halted_kind})`,\n )\n }\n await this.db.exec(\n `INSERT INTO ${this.table}_turns (run_id, turn_index, payload) VALUES (?, ?, ?)`,\n [runId, turn.index, JSON.stringify(turn)],\n )\n }\n\n async recordHalt(runId: string, halt: HaltReason, endedAt: string): Promise<void> {\n const rs = await this.db.exec(\n `UPDATE ${this.table}_runs SET halted_kind = ?, halted_payload = ?, ended_at = ? WHERE run_id = ?`,\n [halt.kind, JSON.stringify(halt), endedAt, runId],\n )\n if (rs.rowsAffected === 0) {\n throw new Error(`recordHalt called for unknown runId '${runId}'`)\n }\n }\n}\n","/**\n * `runPersonaConversation` — the persona loop runner: run a WORKER `AgentProfile`\n * (the agent under test) as a multi-round conversation driven by a PERSONA (the\n * simulated user), over the persistent conversation transcript.\n *\n * It is profiles-vs-profiles: the persona is itself a driver `AgentProfile` (an\n * LLM role-playing the user from its facts) — `runConversation` runs the two\n * against each other. Scripted persona turns are kept as a deterministic\n * fast-path. Only the WORKER is metered (it is the side under test); the\n * persona-driver is the test harness, not billed against the agent.\n *\n * `runPersonaDispatch` wraps the runner as a `ProfileDispatchFn` so it drops\n * straight into `runProfileMatrix({ dispatch })` — the same loop serves a single\n * cell and the whole matrix, replacing the per-agent hand-rolled\n * `dispatchWithSurface` bridges.\n */\n\nimport type { AgentProfile } from '@tangle-network/agent-eval'\nimport type {\n DispatchContext,\n ProfileDispatchFn,\n Scenario,\n} from '@tangle-network/agent-eval/campaign'\nimport { createIterableBackend } from '../backends'\nimport type { AgentExecutionBackend, RuntimeStreamEvent } from '../types'\nimport { defineConversation } from './define-conversation'\nimport { runConversation } from './run-conversation'\nimport type { ConversationTurn, HaltPredicate, HaltReason } from './types'\n\n/** A persona that drives the conversation: either a full driver `AgentProfile`\n * (an LLM user-sim) or a deterministic script of user turns (the fast-path). */\nexport type PersonaDriver =\n | { kind: 'profile'; profile: AgentProfile }\n | { kind: 'scripted'; turns: string[] }\n\nexport interface RunPersonaConversationOptions {\n /** The agent under test. Metered; its rendered prompt leads its turns. */\n worker: AgentProfile\n /** The simulated user driving the dialogue. */\n persona: PersonaDriver\n /** Turn an `AgentProfile` into a runnable backend (router / sandbox / fake).\n * Applied to the worker and to a `profile`-kind persona. */\n backendFor: (profile: AgentProfile, role: 'worker' | 'persona') => AgentExecutionBackend\n /** Render a profile's system prompt — prepended to that profile's messages. */\n systemPromptOf: (profile: AgentProfile) => string\n /** Speaker-turn cap. Default for a scripted persona = `2 * turns.length`\n * (worker answers each user turn). REQUIRED for a `profile` persona. */\n maxTurns?: number\n /** Kickoff message routed to the first speaker (the persona). Default 'Begin.' */\n seed?: string\n /** Content-based \"until satisfied\" halt, called after every turn. `maxTurns` is the\n * hard ceiling; this is the early stop (the persona declares the goal met / unreachable). */\n haltOn?: HaltPredicate\n signal?: AbortSignal\n /** Worker participant / transcript speaker label. Default 'agent'. */\n workerName?: string\n}\n\nexport interface PersonaConversationResult {\n transcript: ConversationTurn[]\n turns: number\n halted: HaltReason\n /** Worker-only spend (the side under test). */\n costUsd: number\n tokensIn: number\n tokensOut: number\n}\n\ninterface UsageCounter {\n tokensIn: number\n tokensOut: number\n costUsd: number\n}\n\n/** Prefix a backend's requests with `systemPrompt`; when `counter` is given,\n * accumulate its `llm_call` token/cost usage (used for the metered worker). */\nfunction withProfilePrompt(\n inner: AgentExecutionBackend,\n systemPrompt: string,\n counter?: UsageCounter,\n): AgentExecutionBackend {\n return {\n kind: inner.kind,\n start: inner.start ? (input, ctx) => inner.start!(input, ctx) : undefined,\n resume: inner.resume ? (session, input, ctx) => inner.resume!(session, input, ctx) : undefined,\n stop: inner.stop ? (session, reason) => inner.stop!(session, reason) : undefined,\n async *stream(input, context) {\n const base =\n input.messages ?? (input.message ? [{ role: 'user', content: input.message }] : [])\n const messages =\n base[0]?.role === 'system' ? base : [{ role: 'system', content: systemPrompt }, ...base]\n for await (const event of inner.stream({ ...input, messages }, context)) {\n if (counter && event.type === 'llm_call') {\n counter.tokensIn += event.tokensIn ?? 0\n counter.tokensOut += event.tokensOut ?? 0\n counter.costUsd += event.costUsd ?? 0\n }\n yield event\n }\n },\n }\n}\n\n/** A persona participant that replays scripted user turns in order. */\nfunction scriptedPersonaBackend(turns: readonly string[]): AgentExecutionBackend {\n let idx = 0\n return createIterableBackend({\n kind: 'persona-user',\n async *stream(_input, context) {\n const text = turns[idx]\n if (text === undefined) {\n throw new Error(\n `persona-user: ran out of scripted turns at index ${idx} (had ${turns.length})`,\n )\n }\n idx += 1\n yield {\n type: 'text_delta',\n task: context.task,\n session: context.session,\n text,\n timestamp: new Date().toISOString(),\n } satisfies RuntimeStreamEvent\n },\n })\n}\n\n/**\n * Run one worker profile against one persona as a multi-round conversation.\n * The persona leads (participant 0): it speaks, the worker answers, repeat,\n * until `maxTurns`. Returns the persistent transcript + worker-only usage.\n */\nexport async function runPersonaConversation(\n opts: RunPersonaConversationOptions,\n): Promise<PersonaConversationResult> {\n const counter: UsageCounter = { tokensIn: 0, tokensOut: 0, costUsd: 0 }\n const workerName = opts.workerName ?? 'agent'\n const worker = withProfilePrompt(\n opts.backendFor(opts.worker, 'worker'),\n opts.systemPromptOf(opts.worker),\n counter,\n )\n\n let persona: AgentExecutionBackend\n let maxTurns: number\n if (opts.persona.kind === 'scripted') {\n if (opts.persona.turns.length === 0) {\n throw new Error('runPersonaConversation: scripted persona has no turns')\n }\n persona = scriptedPersonaBackend(opts.persona.turns)\n maxTurns = opts.maxTurns ?? 2 * opts.persona.turns.length\n } else {\n persona = withProfilePrompt(\n opts.backendFor(opts.persona.profile, 'persona'),\n opts.systemPromptOf(opts.persona.profile),\n )\n if (opts.maxTurns === undefined) {\n throw new Error('runPersonaConversation: maxTurns is required for a profile-driven persona')\n }\n maxTurns = opts.maxTurns\n }\n\n const conversation = defineConversation({\n // Persona leads (participant 0): the seed routes to it, it produces the\n // user turn, the worker answers, alternate.\n participants: [\n { name: 'user', backend: persona },\n { name: workerName, backend: worker },\n ],\n policy: { maxTurns, turnOrder: 'alternate', ...(opts.haltOn ? { haltOn: opts.haltOn } : {}) },\n })\n const result = await runConversation(conversation, {\n seed: opts.seed ?? 'Begin.',\n signal: opts.signal,\n })\n // Worker-only cost. Prefer the worker's own metered llm_call spend. Fall back\n // to the engine's aggregate spend ONLY for a scripted persona — there the\n // harness has no LLM cost so the aggregate IS the worker's. For a\n // profile-driven persona the aggregate also includes the persona-driver's\n // spend, so attributing it to the worker would over-count; report the\n // worker's metered spend (0 if its backend reported none) instead.\n const costUsd =\n counter.costUsd > 0\n ? counter.costUsd\n : opts.persona.kind === 'scripted'\n ? result.spentCreditsCents / 100\n : 0\n return {\n transcript: result.transcript,\n turns: result.turns,\n halted: result.halted,\n costUsd,\n tokensIn: counter.tokensIn,\n tokensOut: counter.tokensOut,\n }\n}\n\nexport interface RunPersonaConfig<TScenario extends Scenario, TArtifact> {\n /** Turn an `AgentProfile` into a runnable backend (router / sandbox / fake). */\n backendFor: (profile: AgentProfile, role: 'worker' | 'persona') => AgentExecutionBackend\n /** Render a profile's system prompt. */\n systemPromptOf: (profile: AgentProfile) => string\n /** The persona driving each scenario — a driver profile or scripted turns. */\n personaOf: (scenario: TScenario) => PersonaDriver\n /** Build the scored artifact from the finished transcript. */\n artifactOf: (transcript: ConversationTurn[], scenario: TScenario) => TArtifact\n /** Speaker-turn cap (required when a persona is profile-driven). */\n maxTurns?: (scenario: TScenario) => number\n seed?: (scenario: TScenario) => string\n workerName?: string\n}\n\n/**\n * Wrap {@link runPersonaConversation} as a `ProfileDispatchFn` for\n * `runProfileMatrix`: the profile axis is the worker-under-test, the scenario\n * axis is the persona, and the runner is the cell. Meters the worker through\n * `ctx.cost` so the matrix's backend-integrity guard sees real usage.\n */\nexport function runPersonaDispatch<TScenario extends Scenario, TArtifact>(\n config: RunPersonaConfig<TScenario, TArtifact>,\n): ProfileDispatchFn<TScenario, TArtifact> {\n return async (\n worker: AgentProfile,\n scenario: TScenario,\n ctx: DispatchContext,\n ): Promise<TArtifact> => {\n const result = await runPersonaConversation({\n worker,\n persona: config.personaOf(scenario),\n backendFor: config.backendFor,\n systemPromptOf: config.systemPromptOf,\n maxTurns: config.maxTurns?.(scenario),\n seed: config.seed?.(scenario),\n signal: ctx.signal,\n workerName: config.workerName,\n })\n ctx.cost.observe(result.costUsd, 'persona-conversation')\n ctx.cost.observeTokens({ input: result.tokensIn, output: result.tokensOut })\n return config.artifactOf(result.transcript, scenario)\n }\n}\n","/**\n * `handleChatTurn` — framework-neutral chat-turn HTTP orchestrator.\n * Owns the NDJSON `ChatStreamEvent` line protocol, the `session.run.*`\n * lifecycle vocabulary, and the persist / post-process / trace-flush\n * hook order. Returns a `ReadableStream` body the product hands to its\n * platform `Response`.\n *\n * Execution durability is the substrate's concern: `box.streamPrompt`\n * auto-reconnects in-call; cross-process reconnect via `X-Execution-ID`\n * is the product's job. The producer this engine wraps already speaks\n * that protocol — the engine just frames the events.\n *\n * Hooks (`ChatTurnHooks`):\n * - `produce` — build the backend event stream\n * - `persistAssistantMessage` — write the assistant turn to the product DB\n * - `onTurnComplete?` — post-process (proposals, citations, …)\n * - `onEvent?` — per-event side channel (e.g. DO broadcast)\n * - `transformFinalText?` — pre-persist transform (e.g. PII redact)\n * - `traceFlush?` — handed to waitUntil so OTLP export lands\n *\n * Framework neutrality: takes already-resolved values (`identity` tuple,\n * a `waitUntil`), never a `Request` or a `Context`. The product's thin\n * route adapter does auth + parse + access-control, then calls\n * `handleChatTurn(...)` and returns `result.body` as its platform `Response`.\n */\n\n/** The NDJSON line protocol every product chat client already speaks. */\nexport interface ChatStreamEvent {\n type: string\n data?: Record<string, unknown>\n}\n\n/** Identity of a chat turn. `tenantId` is the workspace id for workspace-\n * scoped products and the user id for session-scoped products. */\nexport interface ChatTurnIdentity {\n tenantId: string\n /** Thread / session id. */\n sessionId: string\n userId: string\n /** Monotonic 0-based turn index within the session. */\n turnIndex: number\n}\n\n/** The live side of a turn — what the product's `produce` hook returns. */\nexport interface ChatTurnProducer<TEvent extends ChatStreamEvent = ChatStreamEvent> {\n /** The turn's event stream. Forwarded verbatim to the caller. */\n stream: AsyncGenerator<TEvent, void, unknown>\n /** The turn's final assistant text. Read once, after `stream` drains. */\n finalText(): string\n}\n\nexport interface ChatTurnHooks {\n /** Build the backend stream. The engine forwards events verbatim and\n * reads `finalText()` once the stream drains. */\n produce(): ChatTurnProducer\n /** Persist the assistant message to the product's own store. Called\n * once, after drain, with the assembled (transform-applied) text. */\n persistAssistantMessage(input: { identity: ChatTurnIdentity; finalText: string }): Promise<void>\n /** Optional post-processing (proposals, citations, credit metering …).\n * Errors are swallowed + logged — post-process must never fail a turn\n * that already streamed successfully. */\n onTurnComplete?(input: { identity: ChatTurnIdentity; finalText: string }): Promise<void>\n /** Optional per-event side channel (e.g. DO broadcast). Runs for every\n * emitted event, lifecycle envelope included. Errors swallowed — a\n * broadcast failure must not break the chat stream. */\n onEvent?(event: ChatStreamEvent): void | Promise<void>\n /** Optional pre-persist transform of the final text (e.g. PII\n * redaction). Affects only what is persisted; the live stream is\n * never altered. */\n transformFinalText?(text: string): string | Promise<string>\n /** Optional trace flush — resolves when OTLP export completes. Handed\n * to `waitUntil` so the worker isolate stays alive for the POST. */\n traceFlush?(): Promise<void>\n}\n\nexport interface RunChatTurnInput {\n identity: ChatTurnIdentity\n hooks: ChatTurnHooks\n /** Worker liveness hook. When omitted, trace flush is awaited inline\n * before the stream closes. */\n waitUntil?: (p: Promise<unknown>) => void\n /** Structured logger for swallowed hook errors. Defaults to\n * `console.error` so failures surface without product wiring. */\n log?: (message: string, meta?: Record<string, unknown>) => void\n}\n\nexport interface ChatTurnResult {\n /** NDJSON body — return this as the platform `Response` body. */\n body: ReadableStream<Uint8Array>\n /** Content type for the response. */\n contentType: 'application/x-ndjson'\n}\n\nconst encoder = new TextEncoder()\n\nfunction encodeLine(event: ChatStreamEvent): Uint8Array {\n return encoder.encode(`${JSON.stringify(event)}\\n`)\n}\n\nfunction defaultLog(message: string, meta?: Record<string, unknown>): void {\n if (meta) console.error(message, meta)\n else console.error(message)\n}\n\n/**\n * Run one chat turn. Returns immediately with a `ReadableStream` body;\n * the turn executes as the body is pulled. Never rejects — backend\n * failures surface as `error` + `session.run.failed` events.\n */\nexport function handleChatTurn(input: RunChatTurnInput): ChatTurnResult {\n const log = input.log ?? defaultLog\n const { identity, hooks } = input\n\n const body = new ReadableStream<Uint8Array>({\n start: async (controller) => {\n const emit = async (event: ChatStreamEvent): Promise<void> => {\n controller.enqueue(encodeLine(event))\n if (hooks.onEvent) {\n try {\n await hooks.onEvent(event)\n } catch (err) {\n log('[chat-engine] onEvent hook threw', {\n error: err instanceof Error ? err.message : String(err),\n })\n }\n }\n }\n\n try {\n await emit({\n type: 'session.run.started',\n data: {\n sessionId: identity.sessionId,\n tenantId: identity.tenantId,\n turnIndex: identity.turnIndex,\n },\n })\n\n const producer = hooks.produce()\n for await (const event of producer.stream) {\n await emit(event)\n }\n const rawFinal = producer.finalText()\n const finalText = hooks.transformFinalText\n ? await hooks.transformFinalText(rawFinal)\n : rawFinal\n\n await hooks.persistAssistantMessage({ identity, finalText })\n if (hooks.onTurnComplete) {\n try {\n await hooks.onTurnComplete({ identity, finalText })\n } catch (err) {\n log('[chat-engine] onTurnComplete threw', {\n error: err instanceof Error ? err.message : String(err),\n })\n }\n }\n\n await emit({\n type: 'session.run.completed',\n data: { sessionId: identity.sessionId },\n })\n } catch (err) {\n const message = err instanceof Error ? err.message : String(err)\n log('[chat-engine] turn failed', { error: message })\n await emit({ type: 'error', data: { message } })\n await emit({\n type: 'session.run.failed',\n data: { sessionId: identity.sessionId, message },\n })\n } finally {\n if (hooks.traceFlush) {\n const flush = hooks.traceFlush().catch((err) =>\n log('[chat-engine] traceFlush threw', {\n error: err instanceof Error ? err.message : String(err),\n }),\n )\n if (input.waitUntil) input.waitUntil(flush)\n else await flush\n }\n controller.close()\n }\n },\n })\n\n return { body, contentType: 'application/x-ndjson' }\n}\n","/**\n * Derive a stable executionId from the run identity. The same\n * `(projectId, sessionId, turnIndex)` tuple yields the same id — so a\n * client retry of the same turn lands on the same substrate execution\n * and the orchestrator's buffer replays instead of starting a second\n * prompt.\n *\n * Format is readable, not hashed: operators grepping orchestrator logs\n * for `gtm-agent:thread-abc:3` find the run without translating an\n * opaque id. Substrate executionIds are not a secrecy boundary.\n *\n * Wire integration:\n * - Sandbox PromptOptions accepts `executionId` and `lastEventId`.\n * Products pass this id to make cross-process reconnect land on the\n * same substrate execution instead of spawning a duplicate run.\n */\nexport function deriveExecutionId(input: {\n projectId: string\n sessionId: string\n turnIndex: number\n}): string {\n return `${input.projectId}:${input.sessionId}:${input.turnIndex}`\n}\n","/**\n *\n * `improve` — the ONE public, surface-pluggable RSI verb.\n *\n * A thin facade over agent-eval's `selfImprove` (the held-out-gated closed\n * loop). It removes the two things a caller otherwise has to know to drive the\n * loop by hand: WHICH `MutableSurface` of the profile is being optimized, and\n * WHICH `SurfaceProposer` mutates that surface. You name a `surface`; the\n * facade picks the matching default proposer, extracts the baseline surface from\n * the profile, runs `selfImprove`, and (on a ship verdict) writes the promoted\n * winner back into the corresponding profile field.\n *\n * - `surface: 'prompt'` → `gepaProposer` mutates `profile.prompt.systemPrompt`.\n * - `surface: 'skills'` → `skillOptProposer` mutates a skills document string.\n * - `surface: 'rollout-policy'` → `rolloutPolicyProposer` mutates the\n * inference-time `StructuralRolloutPolicy` dials ({ k, repairRounds, testgen })\n * persisted in `profile.extensions['structural-rollout']` — deterministic\n * bounded neighbor enumeration; the held-out gate does the deciding. No-op\n * (nothing proposed, nothing shipped) when the profile has no such extension.\n * - `surface` ∈ {`tools`, `mcp`, `hooks`, `code`} → no zero-config default\n * proposer exists (a code/config proposer needs caller-supplied wiring — a\n * worktree repo root, a candidate generator, a serializer). The facade\n * requires an explicit `opts.generator` for these and throws a `ConfigError`\n * otherwise. This is a designed boundary, not a missing default: there is\n * no safe value the facade could invent for those seams.\n *\n * Everything else (`scenarios`, `judge`, `agent`, `budget`, `llm`) passes\n * straight through to `selfImprove`.\n *\n * @experimental\n */\n\nimport {\n gepaProposer,\n gitWorktreeAdapter,\n skillOptProposer,\n} from '@tangle-network/agent-eval/campaign'\nimport {\n type DispatchContext,\n type JudgeConfig,\n type MutableSurface,\n type Scenario,\n type SelfImproveBudget,\n type SelfImproveLlm,\n type SelfImproveOptions,\n type SelfImproveResult,\n type SurfaceProposer,\n selfImprove,\n} from '@tangle-network/agent-eval/contract'\nimport type { AgentProfile } from '@tangle-network/agent-interface'\nimport { ConfigError } from '../errors'\nimport type { LocalHarness } from '../mcp/local-harness'\nimport { assertModelAllowed } from '../runtime/supervise/model-policy'\nimport { agenticGenerator, type Verifier } from './agentic-generator'\nimport { type CandidateGenerator, improvementDriver } from './improvement-driver'\nimport { rawTraceDistiller } from './raw-trace-distiller'\nimport {\n applyRolloutPolicyToProfile,\n normalizeRolloutPolicy,\n rolloutPolicyProposer,\n serializeRolloutPolicy,\n structuralRolloutPolicyFromProfile,\n} from './rollout-policy'\n\n/** The agent-profile lever `improve` optimizes. Mirrors the AgentProfile-law\n * profile levers; `code` is the implementation-tier surface, `rollout-policy`\n * the inference-time structuralRollout dials\n * (`profile.extensions['structural-rollout']`). */\nexport type ImproveSurface =\n | 'prompt'\n | 'skills'\n | 'tools'\n | 'mcp'\n | 'hooks'\n | 'code'\n | 'rollout-policy'\n\nexport interface ImproveOptions<TScenario extends Scenario, TArtifact> {\n /** Which profile lever to optimize. Default `'prompt'`. Selects the default\n * generator + the baseline-surface extraction shape. */\n surface?: ImproveSurface\n /** The `SurfaceProposer` that mutates the surface. When unset, the facade\n * picks the default for `surface` (`gepaProposer` for prompt, `skillOptProposer`\n * for skills); surfaces with no default REQUIRE this (fail-loud otherwise). */\n generator?: SurfaceProposer\n /** Gate mode. `'holdout'` (default) runs the held-out promotion gate;\n * `'none'` is a baseline-only run (`budget.generations = 0`). */\n gate?: 'holdout' | 'none'\n /** Scenarios to evaluate against. Passthrough to `selfImprove`. */\n scenarios: TScenario[]\n /** Judge that scores artifacts. Passthrough to `selfImprove`. */\n judge: JudgeConfig<TArtifact, TScenario>\n /** The agent under improvement — same shape as `selfImprove.agent`: it takes\n * the current surface + scenario + ctx and returns the artifact to judge. */\n agent: (surface: MutableSurface, scenario: TScenario, ctx: DispatchContext) => Promise<TArtifact>\n /** Budget + loop shape. Passthrough; `gate: 'none'` forces `generations = 0`. */\n budget?: SelfImproveBudget\n /** LLM config. Passthrough to `selfImprove` AND used to construct the default\n * reflective proposer (`gepaProposer`/`skillOptProposer`) when `generator` is unset. */\n llm?: SelfImproveLlm\n /** Restrict the run to this subset of models. When set, the reflection model\n * (`llm.model`, or the default when unset) must be a member, or `improve()` throws\n * a `ConfigError` before the generator is built. Unset = unrestricted. */\n allowedModels?: readonly string[]\n /** Run directory passthrough to `selfImprove`. Pass a REAL path to make the loop\n * durable: campaign cells + the loop provenance record land on the filesystem as\n * they complete, so a multi-hour search survives a process/infra death instead of\n * losing every generation with it (the default `mem://` run keeps everything\n * in-process). */\n runDir?: string\n /** Per-generation findings producer passthrough (see selfImprove.analyzeGeneration).\n * DEFAULT: the built-in failure distiller — after each generation it turns the\n * worst-scoring/errored cells into structured findings ({ scenario, composite,\n * notes, error }) for the NEXT proposal round, so the proposer reasons over what\n * actually failed instead of a static seed. Pass your own producer (e.g. a\n * trace-analyst over the runDir's traces) to replace it; pass `null` to disable\n * and keep the static `findings` all the way through. */\n analyzeGeneration?: SelfImproveOptions<TScenario, TArtifact>['analyzeGeneration'] | null\n /** META-HARNESS mode: instead of the ~400-char distilled findings, feed the\n * proposer RAW-TRACE FILESYSTEM CONTEXT — the PATHS into the prior generation's\n * real run traces under `runDir` (per-cell `spans.jsonl` event logs +\n * `cached-result.json` scores + artifacts) plus a `grep`/`cat`-to-diagnose\n * instruction — so the coding agent reads the actual failures itself rather than\n * a pre-summary. Requires a REAL `runDir` (that is where the traces live).\n * Ignored when `analyzeGeneration` is set explicitly (that wins) or is `null`\n * (disabled). Equivalent to `analyzeGeneration: rawTraceDistiller()`; this flag\n * is the one-line enable. Default `false` (the distiller stays the default). */\n rawTraceContext?: boolean\n /** CODE-surface wiring with prompt-parity DX: name `surface: 'code'`, point at a\n * repo, and the facade assembles the whole candidate pipeline — git worktrees\n * (`gitWorktreeAdapter`) driven by `improvementDriver` with the full agentic\n * generator (a real coding harness edits each candidate worktree; a `verify`\n * hook gates candidates before they are ever measured). Ignored when\n * `opts.generator` is supplied. Without either, `surface: 'code'` still fails\n * loud — there is no safe zero-config repo to invent. */\n code?: ImproveCodeOptions\n /** SKILLS-surface wiring for real skill-DOCUMENT optimization. Without this,\n * `surface: 'skills'` optimizes the profile's skills REFS array (file pointers)\n * — which `skillOptProposer` (a document patcher) cannot meaningfully edit.\n * Provide the document CONTENT to optimize + a `writeBack` to persist the\n * shipped winner (the profile ref points at a file the caller owns). This is\n * what makes skillOpt reachable through improve(). */\n skills?: ImproveSkillsOptions\n /** Storage passthrough to `selfImprove`; overrides the default chosen from `runDir`. */\n storage?: SelfImproveOptions<TScenario, TArtifact>['storage']\n}\n\nexport interface ImproveSkillsOptions {\n /** The skill document's current text — the baseline `skillOptProposer` patches. */\n document: string\n /** Persist the shipped winner document (write the file the profile ref points at).\n * Called only on a ship verdict. When omitted, the winner is still returned in\n * `result.raw.winner.surface` for the caller to materialize. */\n writeBack?: (winnerDocument: string) => void\n}\n\nexport interface ImproveCodeOptions {\n /** Repo root candidate worktrees fork from. */\n repoRoot: string\n /** Base ref candidates fork from. Default `main`. */\n baseRef?: string\n /** Directory worktrees are created under. Default `<repoRoot>/.worktrees`. */\n worktreeDir?: string\n /** Coding harness the agentic generator runs in each worktree. Default `claude`. */\n harness?: LocalHarness\n /** Verify a candidate worktree before it becomes a measurable surface; failures\n * feed the next shot (see `agenticGenerator.verify` / `commandVerifier`). */\n verify?: Verifier\n /** Per-shot wall-clock timeout for the harness (ms). */\n timeoutMs?: number\n /** Byte-producer override — the test seam and the escape hatch for custom\n * candidate production. When set, `harness`/`verify`/`timeoutMs` are unused. */\n generator?: CandidateGenerator\n}\n\nexport interface ImproveResult<TScenario extends Scenario, TArtifact> {\n /** The profile after improvement: the winner surface applied back into the\n * matching field when the gate shipped, else the input profile unchanged. */\n profile: AgentProfile\n /** True when `gateDecision === 'ship'`. */\n shipped: boolean\n /** Held-out lift (`winner − baseline` composite). */\n lift: number\n /** The five-valued gate verdict from `selfImprove`. */\n gateDecision: SelfImproveResult<TScenario, TArtifact>['gateDecision']\n /** Full `selfImprove` result for advanced inspection. */\n raw: SelfImproveResult<TScenario, TArtifact>\n}\n\n/** Default model id for the reflective drivers when `llm.model` is unset — a model the Tangle\n * router actually serves (callers should pass their own `llm.model`). */\nconst defaultReflectionModel = 'deepseek-v4-flash'\n\n/** The reflective proposers (`gepaProposer`/`skillOptProposer`) take a full\n * `LlmClientOptions`; `SelfImproveLlm` is the thin user-facing subset. */\nfunction llmClientOptions(llm: SelfImproveLlm | undefined): { baseUrl?: string; apiKey?: string } {\n return { baseUrl: llm?.baseUrl, apiKey: llm?.apiKey }\n}\n\n/** The default proposer for a surface, or `undefined` when the surface has no\n * zero-config default (the caller must supply `opts.generator`). */\nfunction defaultGeneratorFor(\n surface: ImproveSurface,\n llm: SelfImproveLlm | undefined,\n): SurfaceProposer | undefined {\n const model = llm?.model ?? defaultReflectionModel\n switch (surface) {\n case 'prompt':\n return gepaProposer({ llm: llmClientOptions(llm), model, target: 'agent system prompt' })\n case 'skills':\n return skillOptProposer({ llm: llmClientOptions(llm), model, target: 'agent skill document' })\n case 'rollout-policy':\n // Deterministic bounded enumeration — no LLM, so `llm` is unused here.\n return rolloutPolicyProposer()\n default:\n return undefined\n }\n}\n\n/** Extract the baseline surface a driver mutates from the profile field that\n * backs `surface`. `prompt`/`skills` are string surfaces; the config surfaces\n * serialize the matching profile record. */\nfunction baselineSurfaceFor(\n profile: AgentProfile,\n surface: ImproveSurface,\n skills?: ImproveSkillsOptions,\n): MutableSurface {\n switch (surface) {\n case 'prompt':\n return profile.prompt?.systemPrompt ?? ''\n case 'skills':\n // With a document supplied, optimize its CONTENT (the real skillOpt path);\n // otherwise fall back to the refs-array surface for back-compat.\n return skills?.document ?? JSON.stringify(profile.resources?.skills ?? [])\n case 'tools':\n return JSON.stringify(profile.tools ?? {})\n case 'mcp':\n return JSON.stringify(profile.mcp ?? {})\n case 'hooks':\n return JSON.stringify(profile.hooks ?? {})\n case 'rollout-policy': {\n // Empty surface when the profile never opted into structural rollout: the\n // proposer reads it as \"propose nothing\", so the loop runs baseline-only and\n // holds — tuning dials nothing consumes would ship dead config.\n const policy = structuralRolloutPolicyFromProfile(profile)\n return policy ? serializeRolloutPolicy(policy) : ''\n }\n case 'code':\n // A code surface is produced by the caller's generator from a worktree;\n // the facade has no worktree ref to seed, so the baseline is the empty\n // string (the driver opens its own worktree off `baseRef`).\n return ''\n }\n}\n\n/** The default `analyzeGeneration`: distill each generation's failing cells into\n * findings for the next proposal round. Deliberately dependency-free — judge notes\n * and errors are already the domain's own diagnosis (executable gates put their\n * reasons there); a trace-analyst can replace this wholesale via\n * `opts.analyzeGeneration`. Falls back to the static seed findings when the\n * generation had no failures, so a clean round never wipes the seed context. */\nfunction generationFailureDistiller<TScenario extends Scenario, TArtifact>(\n staticFindings: unknown[],\n): NonNullable<SelfImproveOptions<TScenario, TArtifact>['analyzeGeneration']> {\n const CAP = 12\n return async (input) => {\n const failures: Array<{ scenario: string; composite: number; notes: string; error?: string }> =\n []\n for (const candidate of input.candidates) {\n for (const rawCell of candidate.campaign.cells) {\n const cell = rawCell as unknown as Record<string, unknown>\n const scenario = String(cell.scenarioId ?? 'unknown')\n const error = typeof cell.error === 'string' ? cell.error : undefined\n const judgeScores =\n cell.judgeScores && typeof cell.judgeScores === 'object'\n ? Object.values(\n cell.judgeScores as Record<string, { composite?: number; notes?: string }>,\n )\n : []\n const composite =\n judgeScores.length === 0\n ? 0\n : judgeScores.reduce((sum, j) => sum + (j.composite ?? 0), 0) / judgeScores.length\n if (!error && composite >= 0.999) continue\n const notes = judgeScores\n .map((j) => j.notes)\n .filter((n): n is string => typeof n === 'string' && n.length > 0)\n .join('; ')\n .slice(0, 400)\n failures.push({\n scenario,\n composite: Number(composite.toFixed(3)),\n notes,\n ...(error ? { error: error.slice(0, 200) } : {}),\n })\n }\n }\n if (failures.length === 0) return staticFindings\n failures.sort((a, b) => a.composite - b.composite)\n return failures.slice(0, CAP)\n }\n}\n\n/** Assemble the code-surface proposer from `opts.code`: git worktrees + the\n * improvement driver + (by default) the full agentic generator. Returns\n * `undefined` when the surface is not `code` or no code options were given —\n * the caller then falls through to the fail-loud ConfigError. */\nfunction codeProposerFor(\n surface: ImproveSurface,\n code: ImproveCodeOptions | undefined,\n): SurfaceProposer | undefined {\n if (surface !== 'code' || !code) return undefined\n const generator =\n code.generator ??\n agenticGenerator({\n ...(code.harness ? { harness: code.harness } : {}),\n ...(code.verify ? { verify: code.verify } : {}),\n ...(code.timeoutMs ? { timeoutMs: code.timeoutMs } : {}),\n })\n return improvementDriver({\n worktree: gitWorktreeAdapter({\n repoRoot: code.repoRoot,\n ...(code.worktreeDir ? { worktreeDir: code.worktreeDir } : {}),\n }),\n generator,\n ...(code.baseRef ? { baseRef: code.baseRef } : {}),\n }) as SurfaceProposer\n}\n\n/** Parse a JSON winner surface (`skills`/`tools`/`mcp`/`hooks`) with a typed,\n * contextual error. A malformed generator output must fail loud here, not throw\n * a raw `SyntaxError` to the caller after a ship verdict. */\nfunction parseWinnerJson<T>(winner: string, surface: ImproveSurface): T {\n try {\n return JSON.parse(winner) as T\n } catch (cause) {\n throw new ConfigError(\n `improve(): the shipped '${surface}' winner is not valid JSON, so it cannot be applied back to the profile: ${\n (cause as Error).message\n }`,\n )\n }\n}\n\n/** Apply a promoted winner surface back into the profile field for `surface`.\n * Returns a shallow copy; never mutates the input profile. */\nfunction applyWinnerToProfile(\n profile: AgentProfile,\n surface: ImproveSurface,\n winner: MutableSurface,\n): AgentProfile {\n // Only string surfaces map cleanly back onto a profile field. A `CodeSurface`\n // winner (the `code` lever) is a worktree ref, not a profile value — the\n // caller materializes it from `raw.winner.surface`; the returned profile is\n // unchanged for that lever.\n if (typeof winner !== 'string') return profile\n switch (surface) {\n case 'prompt':\n return { ...profile, prompt: { ...profile.prompt, systemPrompt: winner } }\n case 'skills':\n return {\n ...profile,\n resources: { ...profile.resources, skills: parseWinnerJson(winner, surface) },\n }\n case 'tools':\n return { ...profile, tools: parseWinnerJson(winner, surface) }\n case 'mcp':\n return { ...profile, mcp: parseWinnerJson(winner, surface) }\n case 'hooks':\n return { ...profile, hooks: parseWinnerJson(winner, surface) }\n case 'rollout-policy': {\n // Parse + re-validate the winner against the policy's own invariants — a\n // custom generator's malformed dial must fail loud, not persist silently.\n const policy = normalizeRolloutPolicy(parseWinnerJson(winner, surface))\n if (!policy) {\n throw new ConfigError(\n `improve(): the shipped 'rollout-policy' winner is not a valid StructuralRolloutPolicy ` +\n `(integer k >= 1, repairRounds >= 0, testgen >= 0), so it cannot be applied: ${winner}`,\n )\n }\n return applyRolloutPolicyToProfile(profile, policy)\n }\n case 'code':\n return profile\n }\n}\n\n/**\n * Run the held-out-gated self-improvement loop on ONE profile surface.\n *\n * @example Optimize the system prompt, default holdout gate:\n *\n * const out = await improve(profile, findings, {\n * surface: 'prompt',\n * scenarios,\n * judge,\n * agent: (surface, scenario, ctx) => runAgent(surface, scenario, ctx.signal),\n * })\n * if (out.shipped) deploy(out.profile)\n */\nexport async function improve<TScenario extends Scenario, TArtifact>(\n profile: AgentProfile,\n findings: unknown[],\n opts: ImproveOptions<TScenario, TArtifact>,\n): Promise<ImproveResult<TScenario, TArtifact>> {\n const surface = opts.surface ?? 'prompt'\n const gate = opts.gate ?? 'holdout'\n\n // Fail loud before the generator is built: the reflection model must be in the allowed subset\n // (no-op when allowedModels is unset).\n assertModelAllowed(opts.llm?.model ?? defaultReflectionModel, opts.allowedModels)\n\n const proposer =\n opts.generator ?? defaultGeneratorFor(surface, opts.llm) ?? codeProposerFor(surface, opts.code)\n if (!proposer) {\n throw new ConfigError(\n surface === 'code'\n ? `improve(): surface 'code' needs either opts.generator or opts.code ({ repoRoot, ... }) — there is no safe zero-config repo to invent`\n : `improve(): surface '${surface}' has no default generator — pass opts.generator (a SurfaceProposer) explicitly`,\n )\n }\n\n const budget: SelfImproveBudget =\n gate === 'none' ? { ...opts.budget, generations: 0 } : { ...opts.budget }\n\n const raw = await selfImprove<TScenario, TArtifact>({\n agent: opts.agent,\n scenarios: opts.scenarios,\n judge: opts.judge,\n baselineSurface: baselineSurfaceFor(profile, surface, opts.skills),\n proposer,\n budget,\n llm: opts.llm,\n findings,\n ...(opts.runDir !== undefined ? { runDir: opts.runDir } : {}),\n ...(opts.storage !== undefined ? { storage: opts.storage } : {}),\n ...(opts.analyzeGeneration === null\n ? {}\n : {\n analyzeGeneration:\n opts.analyzeGeneration ??\n (opts.rawTraceContext\n ? rawTraceDistiller<TScenario, TArtifact>({ fallbackFindings: findings })\n : generationFailureDistiller<TScenario, TArtifact>(findings)),\n }),\n })\n\n const shipped = raw.gateDecision === 'ship'\n // When a skill DOCUMENT was optimized, the winner is document text — persist it\n // via writeBack (the profile ref points at the caller's file, unchanged) rather\n // than parsing it as a refs array. Otherwise use the standard field write-back.\n const usedSkillDocument = surface === 'skills' && opts.skills !== undefined\n if (shipped && usedSkillDocument && typeof raw.winner.surface === 'string') {\n opts.skills?.writeBack?.(raw.winner.surface)\n }\n const nextProfile =\n shipped && !usedSkillDocument\n ? applyWinnerToProfile(profile, surface, raw.winner.surface)\n : profile\n\n return { profile: nextProfile, shipped, lift: raw.lift, gateDecision: raw.gateDecision, raw }\n}\n","/**\n *\n * `improvementDriver` — the ONE reflective/agentic improvement proposer for\n * agent-eval's improvement loop. It implements `SurfaceProposer` and owns\n * the candidate lifecycle (worktree create → generate → finalize/discard,\n * × populationSize); it delegates the only thing that genuinely varies — HOW\n * a candidate change is produced — to a pluggable `CandidateGenerator`.\n *\n * There is no separate \"analyst driver\" vs \"autoresearch driver\": those are\n * the SAME driver at two settings of a dial.\n * - cheap reflective path → `reflectiveGenerator` (shots=1, no sandbox;\n * applies pre-drafted patches)\n * - full agentic path → `agenticGenerator` (shots=N, multi-shot\n * verify-in-session loop; an agent reads code +\n * report, edits, and re-tries on verifier failure)\n * Both emit changes into a worktree the driver finalizes into a\n * `CodeSurface{ worktreeRef }` the loop measures on the holdout. See\n * agent-eval's `docs/design/self-improvement-engine.md`.\n *\n * @experimental\n */\n\nimport type { AnalystFinding } from '@tangle-network/agent-eval'\nimport type {\n CodeSurface,\n LabeledScenarioStore,\n ProposeContext,\n SurfaceProposer,\n WorktreeAdapter,\n} from '@tangle-network/agent-eval/campaign'\n\n/** The byte-producing seam — the ONE thing that differs between the cheap\n * reflective path and the full agentic path. A generator makes (uncommitted)\n * changes inside `worktreePath`; the driver commits them via the worktree\n * adapter's `finalize`. */\nexport interface CandidateGenerator {\n kind: string\n /** Whether this generator can produce a candidate from an EMPTY findings set\n * and no phase-2 report — i.e. it draws its change signal from the repo and\n * the raw-trace filesystem context on disk, not only from pre-summarized\n * findings. An agentic coder (`agenticGenerator`) sets this: the seed repo +\n * raw traces ARE the signal, so it must still run the full `populationSize`\n * when the distiller yielded nothing (this is the meta-harness contract — the\n * agent diagnoses from the raw traces itself). A patch-applier\n * (`reflectiveGenerator`) leaves it unset — with no findings there is no\n * patch to draft, so the driver short-circuits rather than spin up worktrees\n * for a guaranteed no-op. Default `false`. */\n proposesWithoutFindings?: boolean\n generate(args: {\n /** The candidate worktree — a fresh checkout of baseRef. Write changes here. */\n worktreePath: string\n /** Phase-2 research report (analyst findings + diff), opaque. */\n report: unknown\n /** Findings resolved from the report or the loop context. */\n findings: AnalystFinding[]\n /** Handle to all captured data, to ground the change. */\n dataset?: LabeledScenarioStore\n /** DEPTH: max iterations the generator may take (agentic uses this; the\n * reflective generator ignores it). */\n maxShots: number\n signal: AbortSignal\n }): Promise<{ applied: boolean; summary: string }>\n}\n\nexport interface ImprovementDriverOptions {\n worktree: WorktreeAdapter\n generator: CandidateGenerator\n /** Base ref candidate worktrees fork from. Default `main`. */\n baseRef?: string\n}\n\n/** The one reflective/agentic improvement proposer (`SurfaceProposer`): owns the candidate worktree lifecycle and delegates HOW a change is produced to a pluggable `CandidateGenerator`. */\nexport function improvementDriver(opts: ImprovementDriverOptions): SurfaceProposer<AnalystFinding> {\n const baseRef = opts.baseRef ?? 'main'\n\n return {\n kind: `improvement:${opts.generator.kind}`,\n async propose(ctx: ProposeContext<AnalystFinding>) {\n const findings = resolveFindings(ctx)\n // No findings AND no report AND a generator that can only act on findings\n // (the reflective patch-applier) — propose nothing rather than spin up\n // worktrees for a guaranteed no-op. An agentic coder draws its signal from\n // the repo + raw traces on disk, so it opts in via `proposesWithoutFindings`\n // and still runs the full populationSize even on an empty findings set —\n // otherwise the FIRST generation (whose seed findings are empty and whose\n // rawTraceDistiller has not run yet) would always generate ZERO candidates.\n if (\n findings.length === 0 &&\n ctx.report === undefined &&\n !opts.generator.proposesWithoutFindings\n ) {\n return []\n }\n\n const surfaces: CodeSurface[] = []\n for (let i = 0; i < ctx.populationSize; i++) {\n if (ctx.signal.aborted) break\n const wt = await opts.worktree.create({\n baseRef,\n label: `${opts.generator.kind}-gen${ctx.generation}-cand${i}`,\n })\n // Once a worktree exists it MUST be accounted for: finalized into a\n // surface, or discarded. A throw from generate()/finalize() must not\n // leak the worktree + branch — discard best-effort, then rethrow loud.\n try {\n const { applied, summary } = await opts.generator.generate({\n worktreePath: wt.path,\n report: ctx.report,\n findings,\n dataset: ctx.dataset,\n maxShots: ctx.maxImprovementShots ?? 1,\n signal: ctx.signal,\n })\n if (!applied) {\n await opts.worktree.discard(wt)\n continue\n }\n surfaces.push(await opts.worktree.finalize(wt, summary))\n } catch (err) {\n // Best-effort cleanup; never mask the original failure.\n await opts.worktree.discard(wt).catch(() => {})\n throw err\n }\n }\n return surfaces\n },\n }\n}\n\n/** Phase-2 report carries `findings` when present; else fall back to the\n * loop's `ctx.findings`. The report is opaque to the substrate, so probe it\n * structurally. */\nfunction resolveFindings(ctx: ProposeContext<AnalystFinding>): AnalystFinding[] {\n const report = ctx.report\n if (report && typeof report === 'object' && 'findings' in report) {\n const f = (report as { findings: unknown }).findings\n if (Array.isArray(f) && f.length > 0) return f as AnalystFinding[]\n }\n return ctx.findings\n}\n","/**\n *\n * `rawTraceDistiller` — the meta-harness `analyzeGeneration` producer.\n *\n * The default `generationFailureDistiller` (in `improve.ts`) COMPRESSES each\n * generation's failing cells into ~400-char structured findings before the next\n * proposal round. That is the ACE-style recipe: a small summary is the proposer's\n * whole view of what went wrong. This producer does the opposite — the\n * meta-harness recipe (yoonholee.com/meta-harness): it does NOT summarize. It\n * points the coding-agent proposer at the generation's RAW run traces already on\n * disk under `runDir` — the durable per-cell `spans.jsonl` event logs,\n * `cached-result.json` scores, and any artifacts the substrate persisted — and\n * instructs the agent to `grep`/`cat`/`ls` them to diagnose the failures itself\n * (up to the harness's full context, ~millions of tokens, vs a ~400-char digest).\n *\n * It emits `AnalystFinding[]` so it drops into the SAME `opts.analyzeGeneration`\n * slot the default distiller uses, and renders through the same\n * `agenticGenerator` prompt path (`claim` + `recommended_action`). The findings\n * carry ABSOLUTE paths — the coding harness runs with `cwd` = a candidate\n * worktree, so a relative `runDir` would be uncattable from there.\n *\n * Runtime layout it reads (written by agent-eval's optimization loop):\n *\n * <runDir>/gen-<N>/ ← the generation dir (input.runDir)\n * candidate-<i>/ ← one candidate campaign (campaign.runDir)\n * <sanitized cellId>/ ← one scenario×rep cell\n * spans.jsonl ← the raw trace (event/span log)\n * cached-result.json ← the cell's score + artifact ref\n * <artifacts…> ← whatever the dispatch wrote\n *\n * @experimental\n */\n\nimport { type Dirent, existsSync, readdirSync } from 'node:fs'\nimport { basename, join, resolve } from 'node:path'\nimport { type AnalystFinding, makeFinding } from '@tangle-network/agent-eval'\nimport type { Scenario, SelfImproveOptions } from '@tangle-network/agent-eval/contract'\n\nconst ANALYST_ID = 'raw-trace-distiller'\n/** A cell counts as \"failing\" below this mean composite (matches the default\n * distiller's near-perfect threshold) or when it recorded an `error`. */\nconst PASS_THRESHOLD = 0.999\n\nexport interface RawTraceDistillerOptions {\n /** Anchor the emitted paths at this run root instead of the generation `runDir`\n * the loop passes in. Normally unset — each call points at that generation's\n * own directory (`input.runDir`). Pass an absolute path when you construct the\n * producer ahead of the loop and want a fixed anchor (e.g. a test fixture). */\n runDir?: string\n /** Max candidates to surface trace paths for, worst-scoring first. Default 12. */\n maxCandidates?: number\n /** Max failing cells to enumerate per candidate before collapsing the rest into\n * an \"ls the candidate dir\" pointer. Default 8. */\n maxCellsPerCandidate?: number\n /** Max concrete file paths to list per cell (the agent can always `ls` the dir\n * for the rest). Default 24. */\n maxFilesPerCell?: number\n /** Findings to fall back to when the generation had NO failing cells, so a\n * clean round never wipes the proposer's steering context. Mirrors the default\n * distiller's static-seed fallback. Default: a single instruction finding. */\n fallbackFindings?: unknown[]\n}\n\ninterface CellTrace {\n scenarioId: string\n composite: number\n error?: string\n cellDir: string\n files: string[]\n truncatedFiles: boolean\n}\n\n/**\n * Build an `analyzeGeneration` producer that feeds the proposer RAW-TRACE\n * FILESYSTEM CONTEXT — paths into the prior generation's real run traces plus a\n * grep/cat-to-diagnose instruction — instead of a pre-summarized digest.\n *\n * Drop-in for `opts.analyzeGeneration` on `improve()` / `selfImprove()`:\n *\n * await improve(profile, seedFindings, {\n * surface: 'code',\n * code: { repoRoot },\n * runDir: '/abs/run', // MUST be a real path — the traces live here\n * analyzeGeneration: rawTraceDistiller(),\n * scenarios, judge, agent,\n * })\n */\nexport function rawTraceDistiller<TScenario extends Scenario = Scenario, TArtifact = unknown>(\n options: RawTraceDistillerOptions = {},\n): NonNullable<SelfImproveOptions<TScenario, TArtifact>['analyzeGeneration']> {\n const maxCandidates = options.maxCandidates ?? 12\n const maxCellsPerCandidate = options.maxCellsPerCandidate ?? 8\n const maxFilesPerCell = options.maxFilesPerCell ?? 24\n\n return async (input) => {\n const genRoot = absoluteRunDir(options.runDir ?? input.runDir)\n const durable = isDurable(genRoot)\n\n // Rank candidates worst-first; the worst failures are the highest-signal\n // context for the next edit. Stable sort keeps equal-composite order.\n const ranked = [...input.candidates]\n .map((c) => ({\n surfaceHash: c.surfaceHash,\n composite: c.composite,\n campaignDir: absoluteRunDir(c.campaign.runDir),\n cells: failingCells(c.campaign, maxCellsPerCandidate, maxFilesPerCell),\n }))\n .sort((a, b) => a.composite - b.composite)\n .slice(0, maxCandidates)\n\n const totalFailingCells = ranked.reduce((n, c) => n + c.cells.length, 0)\n\n // A clean generation: keep the proposer's steering context rather than\n // wiping it (parity with the default distiller's static-seed fallback). An\n // EMPTY fallback array means there is no STATIC seed to preserve — it must NOT\n // wipe the context to nothing. Fall through to the default raw-trace\n // instruction so the meta-harness discipline stays live (the agent still\n // inspects the on-disk traces next round, and the finding's `raw-trace-context`\n // area keeps the agenticGenerator's diagnosis-evidence gate armed). A bare\n // `??` would return the empty array and silently disable both.\n if (totalFailingCells === 0) {\n if (options.fallbackFindings && options.fallbackFindings.length > 0) {\n return options.fallbackFindings\n }\n return [\n makeFinding({\n analyst_id: ANALYST_ID,\n severity: 'info',\n area: 'raw-trace-context',\n confidence: 1,\n claim: `Generation ${input.generation} had no failing cells. The full raw run traces are on disk under ${genRoot}.`,\n recommended_action: `To keep improving, grep/cat the raw traces under ${genRoot} (per-cell spans.jsonl + cached-result.json) to find the weakest passing runs, then make a targeted harness-code edit.`,\n evidence_refs: [{ kind: 'artifact', uri: genRoot }],\n metadata: { generation: input.generation, runDir: genRoot, failingCells: 0 },\n }),\n ]\n }\n\n const findings: AnalystFinding[] = []\n\n // 1. The meta-harness instruction: diagnose from the RAW traces, not a digest.\n findings.push(\n makeFinding({\n analyst_id: ANALYST_ID,\n severity: 'high',\n area: 'raw-trace-context',\n confidence: 1,\n claim: `Generation ${input.generation} produced ${totalFailingCells} failing/low-scoring cell(s) across ${ranked.length} candidate(s). Their FULL RAW run traces are on disk under ${genRoot} — the actual event logs (spans.jsonl), scores (cached-result.json), and artifacts, not a summary.${\n durable\n ? ''\n : ' (WARNING: this run root does not exist on disk — it looks like an in-memory run; pass a real runDir to improve() to get raw-trace context.)'\n }`,\n recommended_action: `Do NOT rely on a pre-summarized finding. Before editing, DIAGNOSE from the raw traces: run \\`grep\\`/\\`cat\\`/\\`ls\\` over the trace files and directories named in the following findings to see exactly what each failing run did and why it scored low, then make the smallest harness-code edit that fixes the dominant failure. Start with \\`grep -rIn \"error\" ${genRoot}\\` then \\`cat\\` the spans.jsonl of the worst cell.`,\n evidence_refs: [{ kind: 'artifact', uri: genRoot }],\n metadata: {\n generation: input.generation,\n runDir: genRoot,\n failingCells: totalFailingCells,\n candidates: ranked.length,\n },\n }),\n )\n\n // 2. One finding per failing candidate: its campaign dir + the concrete raw\n // trace files to grep/cat.\n for (const cand of ranked) {\n if (cand.cells.length === 0) continue\n const scenarioList = cand.cells.map((c) => c.scenarioId).join(', ')\n const fileLines = cand.cells\n .map((c) => {\n const header = ` cell ${c.scenarioId} (composite ${c.composite.toFixed(3)}${\n c.error ? `, error: ${truncate(c.error, 160)}` : ''\n }) — dir ${c.cellDir}`\n const files = c.files.map((f) => ` - ${f}`).join('\\n')\n const more = c.truncatedFiles ? `\\n - …(ls ${c.cellDir} for the rest)` : ''\n return c.files.length > 0 ? `${header}\\n${files}${more}` : header\n })\n .join('\\n')\n\n findings.push(\n makeFinding({\n analyst_id: ANALYST_ID,\n severity: cand.composite < 0.5 ? 'critical' : 'high',\n area: 'raw-trace-context',\n confidence: 1,\n subject: cand.surfaceHash,\n claim: `Candidate ${cand.surfaceHash} scored composite ${cand.composite.toFixed(3)} with ${cand.cells.length} failing cell(s) [${scenarioList}]. Its raw traces are under ${cand.campaignDir}.`,\n recommended_action: `grep/cat these raw trace files to diagnose WHY this candidate failed before editing:\\n${fileLines}\\nOr scan the whole candidate at once: \\`grep -rIn . ${cand.campaignDir}\\` and \\`ls -R ${cand.campaignDir}\\`.`,\n evidence_refs: [\n { kind: 'artifact', uri: cand.campaignDir },\n ...cand.cells.flatMap((c) =>\n c.files.map((f) => ({ kind: 'artifact' as const, uri: f })),\n ),\n ],\n metadata: {\n surfaceHash: cand.surfaceHash,\n composite: cand.composite,\n campaignDir: cand.campaignDir,\n cells: cand.cells.map((c) => ({\n scenarioId: c.scenarioId,\n composite: c.composite,\n cellDir: c.cellDir,\n files: c.files,\n ...(c.error ? { error: c.error } : {}),\n })),\n },\n }),\n )\n }\n\n return findings\n }\n}\n\n/** The failing cells of a candidate campaign, each with its on-disk trace files.\n * Mirrors the default distiller's per-cell composite (mean of judge composites,\n * 0 when a cell produced no judge score) and its failing predicate. */\nfunction failingCells(\n campaign: {\n runDir: string\n cells: ReadonlyArray<{\n cellId: string\n scenarioId: string\n error?: string\n judgeScores: Record<string, { composite?: number }>\n }>\n artifactsByPath?: Record<string, string>\n },\n maxCells: number,\n maxFiles: number,\n): CellTrace[] {\n const campaignDir = absoluteRunDir(campaign.runDir)\n const durable = isDurable(campaignDir)\n const out: CellTrace[] = []\n for (const cell of campaign.cells) {\n const scores = Object.values(cell.judgeScores ?? {})\n const composite =\n scores.length === 0\n ? 0\n : scores.reduce((sum, s) => sum + (s.composite ?? 0), 0) / scores.length\n if (!cell.error && composite >= PASS_THRESHOLD) continue\n\n const cellDir = join(campaignDir, sanitizeCellId(cell.cellId))\n const artifactPaths = artifactPathsForCell(campaign.artifactsByPath, cell.cellId)\n const discovered = durable ? listTraceFiles(cellDir) : []\n // Canonical anchors the substrate always writes, kept even when a mem:// run\n // never flushed them to disk (so the agent still learns the expected path).\n const canonical = [join(cellDir, 'spans.jsonl'), join(cellDir, 'cached-result.json')]\n const files = dedupeSorted([...discovered, ...artifactPaths, ...canonical])\n\n out.push({\n scenarioId: cell.scenarioId,\n composite: Number(composite.toFixed(3)),\n ...(cell.error ? { error: cell.error } : {}),\n cellDir,\n files: files.slice(0, maxFiles),\n truncatedFiles: files.length > maxFiles,\n })\n if (out.length >= maxCells) break\n }\n return out\n}\n\n/** Absolute paths of artifacts the campaign recorded for a cell. `artifactsByPath`\n * is keyed `${cellId}/${relPath}` → absolute path. */\nfunction artifactPathsForCell(\n artifactsByPath: Record<string, string> | undefined,\n cellId: string,\n): string[] {\n if (!artifactsByPath) return []\n const prefix = `${cellId}/`\n return Object.entries(artifactsByPath)\n .filter(([key]) => key.startsWith(prefix))\n .map(([, absPath]) => resolve(absPath))\n}\n\n/** Real files directly under `dir` and one level of sub-directories (artifacts\n * are sometimes nested). Absolute paths, sorted. `[]` when the dir is absent,\n * stale, unreadable, or contains symlinked dirs — trace context is advisory and\n * the canonical anchors below still tell the proposer where to inspect. */\nfunction listTraceFiles(dir: string): string[] {\n const out: string[] = []\n for (const entry of safeReadDir(dir)) {\n const full = join(dir, entry.name)\n if (entry.isFile()) {\n out.push(full)\n } else if (!entry.isSymbolicLink() && entry.isDirectory()) {\n for (const sub of safeReadDir(full)) {\n if (sub.isFile()) out.push(join(full, sub.name))\n }\n }\n }\n return out\n}\n\nfunction safeReadDir(dir: string): Dirent[] {\n try {\n return readdirSync(dir, { withFileTypes: true })\n } catch {\n return []\n }\n}\n\n/** Substrate cell-dir sanitization — must match agent-eval's\n * `cellId.replace(/[^a-zA-Z0-9_-]/g, '_')` so the computed dir matches disk. */\nfunction sanitizeCellId(cellId: string): string {\n return cellId.replace(/[^a-zA-Z0-9_-]/g, '_')\n}\n\n/** A run root is durable (has real files) when it is not an in-memory sentinel\n * and exists on disk. `mem://` runs keep everything in-process — no traces. */\nfunction isDurable(runDir: string): boolean {\n return !runDir.startsWith('mem://') && existsSync(runDir)\n}\n\n/** Resolve a run dir to absolute (the coding harness runs from a worktree cwd, so\n * relative paths are uncattable there). `mem://` sentinels pass through untouched. */\nfunction absoluteRunDir(runDir: string): string {\n return runDir.startsWith('mem://') ? runDir : resolve(runDir)\n}\n\nfunction dedupeSorted(paths: string[]): string[] {\n return [...new Set(paths)].sort((a, b) => {\n // Group by directory then filename for a stable, readable listing.\n const da = a.slice(0, a.length - basename(a).length)\n const db = b.slice(0, b.length - basename(b).length)\n return da === db ? basename(a).localeCompare(basename(b)) : da.localeCompare(db)\n })\n}\n\nfunction truncate(s: string, n: number): string {\n return s.length <= n ? s : `${s.slice(0, n - 1)}…`\n}\n","/**\n * `rolloutPolicyProposer` — the `'rollout-policy'` surface for `improve()`: the\n * inference-time `StructuralRolloutPolicy` dials { k, repairRounds, testgen } as a\n * held-out-gated optimizable surface.\n *\n * Why this seam: agent-eval's loop contract is already generic — `MutableSurface`\n * admits any string, documented as \"serialized tool config\" — so the policy rides\n * the SAME serialize→propose→gate→parse-back cycle the tools/mcp/hooks surfaces\n * use. No agent-eval changes; the only net-new piece is this proposer.\n *\n * Why deterministic: prompt-wording proposals are a measured zero on this stack,\n * and the policy space is tiny and fully enumerable. The proposer emits bounded\n * single-dial neighbors (k±2 in [1,10], repairRounds±1 in [0,3], testgen±3 in\n * [0,10], ≤4 per generation) and lets the held-out gate do ALL the deciding — an\n * LLM proposer would add cost and nondeterminism with nothing to reason about.\n *\n * Persistence: the policy lives in `profile.extensions['structural-rollout']`\n * (AgentProfile's designed slot for runtime-specific config). A gated winner is\n * written back there by `improve()`, the same profile-field write-back every other\n * config surface gets; `structuralRolloutPolicyFromProfile` is the read side a\n * runtime caller feeds to `structuralRollout({ policy })`.\n *\n * @experimental\n */\n\nimport type {\n MutableSurface,\n ProposeContext,\n ProposedCandidate,\n SurfaceProposer,\n} from '@tangle-network/agent-eval/campaign'\nimport type { AgentProfile } from '@tangle-network/agent-interface'\nimport {\n defaultStructuralRolloutPolicy,\n type StructuralRolloutPolicy,\n} from '../runtime/structural-rollout'\n\n/** The profile extensions namespace the policy persists under. */\nexport const ROLLOUT_POLICY_EXTENSION = 'structural-rollout'\n\n/** Proposal bounds per dial. These are the SEARCH bounds (what the proposer may\n * explore), chosen so every reachable value is a measured-sane recipe: k=1 is the\n * low-compute preset, testgen=0 disables check authoring, repairRounds caps where\n * the measured increment flattens (+1–3pp beyond round 2). */\nexport const ROLLOUT_POLICY_BOUNDS = {\n k: { min: 1, max: 10, step: 2 },\n repairRounds: { min: 0, max: 3, step: 1 },\n testgen: { min: 0, max: 10, step: 3 },\n} as const\n\n/** Max candidates per generation — the search space is 3 dials, so a small\n * neighborhood per generation converges without burning gate budget. */\nconst MAX_CANDIDATES_PER_GENERATION = 4\n\nconst clamp = (v: number, min: number, max: number) => Math.min(max, Math.max(min, v))\n\nconst isBoundedInt = (v: unknown, min: number): v is number =>\n typeof v === 'number' && Number.isInteger(v) && v >= min\n\n/** Parse a serialized policy surface. Defensive by design — the proposer reads\n * `ctx.currentSurface`, which the loop types as `string | CodeSurface`. Returns\n * `undefined` (never throws) for non-strings, malformed JSON, or a shape that\n * violates the policy's own invariants: the no-op signal. Unknown dials are\n * dropped; `diverse`/`temperature` ride through untouched (the proposer never\n * mutates them — `diverse` is a measured paired null). */\nexport function parseRolloutPolicy(surface: MutableSurface): StructuralRolloutPolicy | undefined {\n if (typeof surface !== 'string' || surface.trim().length === 0) return undefined\n let raw: unknown\n try {\n raw = JSON.parse(surface)\n } catch {\n return undefined\n }\n return normalizeRolloutPolicy(raw)\n}\n\n/** Normalize an untyped policy bag (a parsed surface or a profile extension) into\n * a full `StructuralRolloutPolicy`, defaults merged. Returns `undefined` when any\n * present dial violates the policy invariants (mirrors `resolvePolicy`: integer\n * k ≥ 1, repairRounds ≥ 0, testgen ≥ 0) — a corrupt config must read as \"not\n * configured\", never as a fabricated recipe. */\nexport function normalizeRolloutPolicy(raw: unknown): StructuralRolloutPolicy | undefined {\n if (typeof raw !== 'object' || raw === null || Array.isArray(raw)) return undefined\n const bag = raw as Record<string, unknown>\n const k = bag.k ?? defaultStructuralRolloutPolicy.k\n const repairRounds = bag.repairRounds ?? defaultStructuralRolloutPolicy.repairRounds\n const testgen = bag.testgen ?? defaultStructuralRolloutPolicy.testgen\n if (!isBoundedInt(k, 1) || !isBoundedInt(repairRounds, 0) || !isBoundedInt(testgen, 0)) {\n return undefined\n }\n return {\n k,\n repairRounds,\n testgen,\n ...(typeof bag.diverse === 'boolean' ? { diverse: bag.diverse } : {}),\n ...(typeof bag.temperature === 'number' ? { temperature: bag.temperature } : {}),\n }\n}\n\n/** Stable serialization — dial order is fixed so identical policies produce\n * identical surfaces (the loop dedupes/hashes candidates by surface content). */\nexport function serializeRolloutPolicy(policy: StructuralRolloutPolicy): string {\n return JSON.stringify({\n k: policy.k,\n repairRounds: policy.repairRounds,\n testgen: policy.testgen,\n ...(policy.diverse !== undefined ? { diverse: policy.diverse } : {}),\n ...(policy.temperature !== undefined ? { temperature: policy.temperature } : {}),\n })\n}\n\n/** Read the persisted policy off the profile. `undefined` when the profile does\n * not opt into structural rollout — the improve() surface no-ops then, because\n * tuning dials nothing consumes would ship dead config. */\nexport function structuralRolloutPolicyFromProfile(\n profile: AgentProfile,\n): StructuralRolloutPolicy | undefined {\n const bag = profile.extensions?.[ROLLOUT_POLICY_EXTENSION]\n if (bag === undefined) return undefined\n return normalizeRolloutPolicy(bag)\n}\n\n/** Persist a policy into the profile's extensions namespace. Shallow copy; never\n * mutates the input profile (the applyWinnerToProfile contract). */\nexport function applyRolloutPolicyToProfile(\n profile: AgentProfile,\n policy: StructuralRolloutPolicy,\n): AgentProfile {\n const bag: Record<string, unknown> = {\n k: policy.k,\n repairRounds: policy.repairRounds,\n testgen: policy.testgen,\n ...(policy.diverse !== undefined ? { diverse: policy.diverse } : {}),\n ...(policy.temperature !== undefined ? { temperature: policy.temperature } : {}),\n }\n return {\n ...profile,\n extensions: { ...profile.extensions, [ROLLOUT_POLICY_EXTENSION]: bag },\n }\n}\n\n/** All bounded single-dial neighbors of `policy`, in a fixed priority order: k\n * first (selection breadth carries 85–92% of the measured effect), then\n * repairRounds, then testgen. Steps clamp to the dial's bounds; clamped-to-no-op\n * and duplicate policies are dropped. */\nexport function enumerateNeighborPolicies(\n policy: StructuralRolloutPolicy,\n): StructuralRolloutPolicy[] {\n const moves: Array<{ dial: 'k' | 'repairRounds' | 'testgen'; delta: 1 | -1 }> = [\n { dial: 'k', delta: 1 },\n { dial: 'k', delta: -1 },\n { dial: 'repairRounds', delta: 1 },\n { dial: 'repairRounds', delta: -1 },\n { dial: 'testgen', delta: 1 },\n { dial: 'testgen', delta: -1 },\n ]\n const seen = new Set<string>([serializeRolloutPolicy(policy)])\n const neighbors: StructuralRolloutPolicy[] = []\n for (const move of moves) {\n const bounds = ROLLOUT_POLICY_BOUNDS[move.dial]\n const next = clamp(policy[move.dial] + move.delta * bounds.step, bounds.min, bounds.max)\n const candidate: StructuralRolloutPolicy = { ...policy, [move.dial]: next }\n const key = serializeRolloutPolicy(candidate)\n if (seen.has(key)) continue\n seen.add(key)\n neighbors.push(candidate)\n }\n return neighbors\n}\n\nfunction candidateLabel(base: StructuralRolloutPolicy, next: StructuralRolloutPolicy): string {\n for (const dial of ['k', 'repairRounds', 'testgen'] as const) {\n if (next[dial] !== base[dial]) return `${dial} ${base[dial]}→${next[dial]}`\n }\n return 'unchanged'\n}\n\n/**\n * The deterministic `SurfaceProposer` for the `'rollout-policy'` surface.\n *\n * Each generation: parse the current policy surface, enumerate its bounded\n * single-dial neighbors, and return at most `min(populationSize, 4)` of them,\n * rotating the enumeration window by generation so successive generations explore\n * different neighbors when nothing promoted. Proposes NOTHING when the surface\n * carries no policy (the profile never opted in) — an empty proposal is the\n * loop-native no-op, mirroring `improvementDriver`'s no-findings behavior.\n */\nexport function rolloutPolicyProposer(): SurfaceProposer {\n return {\n kind: 'rollout-policy',\n async propose(ctx: ProposeContext): Promise<ProposedCandidate[]> {\n const policy = parseRolloutPolicy(ctx.currentSurface)\n if (!policy) return []\n const neighbors = enumerateNeighborPolicies(policy)\n if (neighbors.length === 0) return []\n const cap = Math.max(1, Math.min(ctx.populationSize, MAX_CANDIDATES_PER_GENERATION))\n const start = (ctx.generation * cap) % neighbors.length\n const window: StructuralRolloutPolicy[] = []\n for (let i = 0; i < Math.min(cap, neighbors.length); i += 1) {\n window.push(neighbors[(start + i) % neighbors.length] as StructuralRolloutPolicy)\n }\n return window.map((candidate) => ({\n surface: serializeRolloutPolicy(candidate),\n label: candidateLabel(policy, candidate),\n rationale:\n 'bounded single-dial neighbor of the current structuralRollout policy; ' +\n 'the held-out gate decides (deterministic enumeration — the dial space is tiny ' +\n 'and prompt-style reflective proposals are a measured zero here)',\n }))\n },\n }\n}\n","/**\n *\n * `reflectiveGenerator` — the cheap, no-sandbox `CandidateGenerator`. It drafts\n * surface edits via the existing improvement adapter (`proposeFromFindings`,\n * one LLM patch per finding) and applies them as ONE coherent improvement into\n * the candidate worktree. `maxShots` is ignored — reflection is single-shot by\n * construction (the patches are already drafted).\n *\n * This is the `shots=1, sandbox=off` setting of the one improvement driver.\n * The `agenticGenerator` (a multi-shot verify-in-session loop) is the\n * `shots=N` setting — both plug into the same `improvementDriver`.\n *\n * @experimental\n */\n\nimport { spawnSync } from 'node:child_process'\nimport type { SurfaceImprovementEdit } from '../agent/improvement-adapter'\nimport type { ImprovementAdapter } from '../analyst-loop/types'\nimport type { CandidateGenerator } from './improvement-driver'\n\nexport interface ReflectiveGeneratorOptions {\n improvementAdapter: ImprovementAdapter<SurfaceImprovementEdit>\n}\n\n/** Cheap no-sandbox `CandidateGenerator` (the `shots=1` setting): draft surface edits via the improvement adapter and apply them as one coherent candidate. */\nexport function reflectiveGenerator(opts: ReflectiveGeneratorOptions): CandidateGenerator {\n return {\n kind: 'reflective',\n async generate({ worktreePath, findings }) {\n const batch = await opts.improvementAdapter.proposeFromFindings(findings)\n if (batch.edits.length === 0) return { applied: false, summary: '' }\n\n let applied = 0\n for (const edit of batch.edits) {\n if (applyPatch(edit.patch, worktreePath)) applied++\n }\n if (applied === 0) return { applied: false, summary: '' }\n\n const summary =\n batch.edits.length === 1\n ? batch.edits[0]!.summary\n : `analyst: ${applied} surface edit${applied === 1 ? '' : 's'}`\n return { applied: true, summary }\n },\n }\n}\n\n/** Mirror the improvement adapter's proven apply invocation, run inside the\n * candidate worktree (a fresh checkout of baseRef, so `-p0` paths match). */\nfunction applyPatch(patch: string, cwd: string): boolean {\n const result = spawnSync('git', ['apply', '--whitespace=fix', '-p0', '-'], {\n cwd,\n input: patch,\n encoding: 'utf-8',\n })\n return result.status === 0\n}\n","/**\n *\n * Pure readiness-decision helper. Maps a `KnowledgeReadinessReport` from\n * `@tangle-network/agent-eval` to a three-state branch (`ready` / `blocked` /\n * `caveat`) the runtime, route handlers, and UI shells can all switch on.\n *\n * Default `minimumScore` of 0.7 mirrors the readiness scoring scale in\n * agent-eval; callers tightening or loosening this should keep it consistent\n * across all entry points for the same product so the UI / metrics agree on\n * what \"caveat\" means.\n *\n * @stable\n */\n\nimport type { KnowledgeReadinessReport } from '@tangle-network/agent-eval'\n\nimport { ValidationError } from './errors'\nimport type { KnowledgeReadinessDecision } from './types'\n\nconst DEFAULT_MINIMUM_READINESS_SCORE = 0.7\n\n/**\n * Map a `KnowledgeReadinessReport` to a three-state branch (`ready` / `blocked` / `caveat`) the runtime, route handlers, and UI shells all switch on.\n *\n * @stable\n */\nexport function decideKnowledgeReadiness(\n report: KnowledgeReadinessReport,\n options: { minimumScore?: number } = {},\n): KnowledgeReadinessDecision {\n const minimumScore = options.minimumScore ?? DEFAULT_MINIMUM_READINESS_SCORE\n if (!Number.isFinite(minimumScore) || minimumScore < 0 || minimumScore > 1) {\n throw new ValidationError(\n `minimumScore must be a finite number in [0, 1]; received ${String(minimumScore)}`,\n )\n }\n const blockingGapIds = report.blockingMissingRequirements.map((requirement) => requirement.id)\n const nonBlockingGapIds = report.nonBlockingGaps.map((requirement) => requirement.id)\n if (blockingGapIds.length > 0) {\n return {\n passed: false,\n status: 'blocked',\n reason: report.reason,\n readinessScore: report.readinessScore,\n recommendedAction: report.recommendedAction,\n severity: report.severity,\n blockingGapIds,\n nonBlockingGapIds,\n }\n }\n if (report.readinessScore < minimumScore) {\n return {\n passed: false,\n status: 'caveat',\n reason: `Knowledge readiness score ${report.readinessScore.toFixed(3)} is below minimum ${minimumScore.toFixed(3)}.`,\n readinessScore: report.readinessScore,\n recommendedAction: report.recommendedAction,\n severity: report.severity,\n blockingGapIds,\n nonBlockingGapIds,\n }\n }\n return {\n passed: true,\n status: 'ready',\n reason: report.reason,\n readinessScore: report.readinessScore,\n recommendedAction: report.recommendedAction,\n severity: report.severity,\n blockingGapIds,\n nonBlockingGapIds,\n }\n}\n","/**\n * The product-facing backend selector for `runChatThroughRuntime` /\n * `runAgentTaskStream`: one call turns a `--backend {router,tcloud,cli-bridge,\n * sandbox}` choice into the `AgentExecutionBackend` the chat leg runs on.\n *\n * It is the `AgentExecutionBackend` sibling of `resolveSandboxClient` (which\n * resolves the `SandboxClient` a `runLoop` drives). Both exist for the same\n * reason: every in-process eval product hand-rolled the identical\n * \"`backend-name` → `createOpenAICompatibleBackend`\" branch, and the copies\n * drift. This is the single generic resolver they share.\n *\n * - `router` / `tcloud` / `cli-bridge` → OpenAI-compatible chat completions.\n * All three speak `POST {baseUrl}/chat/completions` in OpenAI's SSE shape —\n * the router (a.k.a. tcloud) IS that endpoint, and cli-bridge fronts a\n * harness CLI behind the same protocol at its own `/v1`. They differ only\n * in `baseUrl` / `apiKey` and the `kind` label a product wants on its\n * traces. cli-bridge REQUIRES `model` in the request body, so it MUST route\n * through `createOpenAICompatibleBackend` (which sends it), never a\n * transport that drops the field.\n * - `sandbox` → the caller's own domain backend. The sandbox variant carries\n * product specifics (system prompt, workspace id, in-box D1 executor) that\n * do NOT belong in the substrate, so the product passes a `sandboxBackend()`\n * seam that this resolver simply invokes.\n *\n * This resolver is PURE backend selection. Product concerns — credit hard-cuts,\n * fetch-capture shims, D1 platform wiring — stay as product-side WRAPPERS\n * around the returned backend. The OpenAI-compat passthrough fields (`tools`,\n * `toolChoice`, `responseFormat`, `temperature`, `maxTokens`, `fetchImpl`,\n * `retry`) are forwarded verbatim so a product can advertise its app tools,\n * preserve generation settings, or install a capturing fetch without\n * re-opening the branch this consolidation closes.\n */\n\nimport { createOpenAICompatibleBackend } from './backends'\nimport type { AgentBackendInput, AgentExecutionBackend } from './types'\n\n/** The transport a chat backend runs on. */\nexport type AgentBackendKind = 'router' | 'tcloud' | 'cli-bridge' | 'sandbox'\n\n/**\n * OpenAI-compat passthrough forwarded to `createOpenAICompatibleBackend` for\n * the `router` / `tcloud` / `cli-bridge` kinds. Mirrors that factory's optional\n * inputs so a product keeps its tool advertising / capture-fetch without\n * re-implementing the backend branch.\n */\ntype OpenAICompatPassthrough = Pick<\n Parameters<typeof createOpenAICompatibleBackend>[0],\n 'tools' | 'toolChoice' | 'responseFormat' | 'temperature' | 'maxTokens' | 'fetchImpl' | 'retry'\n>\n\nexport interface ResolveAgentBackendOptions<TInput extends AgentBackendInput = AgentBackendInput>\n extends OpenAICompatPassthrough {\n /** The chat transport to resolve. */\n kind: AgentBackendKind\n /**\n * Bearer credential for the OpenAI-compat kinds. Empty string is valid for a\n * loopback-anonymous cli-bridge; a `router`/`tcloud` route with an empty key\n * is a caller bug the product surfaces before calling in.\n */\n apiKey: string\n /** Base URL for the OpenAI-compat kinds. cli-bridge's is its `/v1`. */\n baseUrl: string\n /** Model id sent on every request. cli-bridge rejects a request without it. */\n model: string\n /** `kind` label stamped on the resolved backend + its traces. Defaults to `kind`. */\n label?: string\n /**\n * `sandbox` kind: the product's own domain backend. Required for that kind —\n * the substrate owns no product sandbox shape, so a `sandbox` resolution with\n * no seam is a caller bug, not a silent fallback.\n */\n sandboxBackend?: () => AgentExecutionBackend<TInput>\n}\n\n/**\n * Resolve the `AgentExecutionBackend` for the chosen `kind`. Reuse this instead\n * of hand-rolling the `createOpenAICompatibleBackend` branch in each product.\n */\nexport function resolveAgentBackend<TInput extends AgentBackendInput = AgentBackendInput>(\n opts: ResolveAgentBackendOptions<TInput>,\n): AgentExecutionBackend<TInput> {\n switch (opts.kind) {\n case 'router':\n case 'tcloud':\n case 'cli-bridge': {\n const passthrough: OpenAICompatPassthrough = {}\n // Forward only the fields a caller actually set — an explicit\n // `tools: []` / `undefined` would otherwise reach the factory and change\n // its request shape (some providers reject an empty `tools` array).\n if (opts.tools !== undefined) passthrough.tools = opts.tools\n if (opts.toolChoice !== undefined) passthrough.toolChoice = opts.toolChoice\n if (opts.responseFormat !== undefined) passthrough.responseFormat = opts.responseFormat\n if (opts.temperature !== undefined) passthrough.temperature = opts.temperature\n if (opts.maxTokens !== undefined) passthrough.maxTokens = opts.maxTokens\n if (opts.fetchImpl !== undefined) passthrough.fetchImpl = opts.fetchImpl\n if (opts.retry !== undefined) passthrough.retry = opts.retry\n return createOpenAICompatibleBackend<TInput>({\n apiKey: opts.apiKey,\n baseUrl: opts.baseUrl,\n model: opts.model,\n kind: opts.label ?? opts.kind,\n ...passthrough,\n })\n }\n case 'sandbox': {\n if (!opts.sandboxBackend) {\n throw new Error(\"resolveAgentBackend: kind 'sandbox' requires opts.sandboxBackend\")\n }\n return opts.sandboxBackend()\n }\n }\n}\n","/**\n *\n * The two top-level entry points:\n *\n * - `runAgentTask` — single-shot lifecycle for adapter-driven tasks.\n * - `runAgentTaskStream` — streaming lifecycle that delegates execution to an\n * `AgentExecutionBackend` (model API, sandbox, or custom iterable).\n *\n * Both gate the run on `KnowledgeReadinessReport` from `agent-eval`, emit the\n * same lifecycle event vocabulary (under different shapes — see `types.ts`),\n * and route session lifecycle through a pluggable `RuntimeSessionStore`.\n *\n * @stable\n */\n\nimport {\n acquisitionPlansForKnowledgeGaps,\n blockingKnowledgeEval,\n type ControlContext,\n type ControlEvalResult,\n type ControlRunResult,\n type DataAcquisitionPlan,\n FAILURE_CLASSES,\n type FailureClass,\n type KnowledgeReadinessReport,\n type RunRecord,\n runAgentControlLoop,\n scoreKnowledgeReadiness,\n type UserQuestion,\n userQuestionsForKnowledgeGaps,\n} from '@tangle-network/agent-eval'\n\nconst FAILURE_CLASS_SET = new Set<string>(FAILURE_CLASSES)\n\n/** True when a free-form control failure string is a canonical taxonomy\n * class — so only real taxonomy tags are promoted to the cross-agent\n * `RunRecord.failureClass` key; novel strings stay as `failureMode` detail. */\nfunction asFailureClass(value: string | undefined): FailureClass | undefined {\n return value && FAILURE_CLASS_SET.has(value) ? (value as FailureClass) : undefined\n}\n\n/** Stamp cross-cutting defaults onto adapter-projected RunRecords without\n * overriding anything the adapter set explicitly:\n * - `scenarioId` — the run's scenario, when the record omits one.\n * - `failureClass` — the control layer's failure classification promoted\n * onto the canonical cross-agent key, but ONLY when it's a real taxonomy\n * class. This is what lets the substrate aggregate failures across every\n * agent in one vocabulary instead of per-agent ad-hoc strings. */\nexport function applyRunRecordDefaults(\n records: RunRecord[],\n scenarioId: string,\n controlFailureClass: string | undefined,\n): RunRecord[] {\n const fc = asFailureClass(controlFailureClass)\n return records.map((record) => {\n let r = record\n if (r.scenarioId === undefined) r = { ...r, scenarioId }\n if (r.failureClass === undefined && fc) r = { ...r, failureClass: fc }\n return r\n })\n}\n\nimport { normalizeBackendStreamEvent } from './backends'\nimport { BackendTransportError, SessionMismatchError } from './errors'\nimport { decideKnowledgeReadiness } from './readiness'\nimport { newRuntimeSession, nowIso, touchSession } from './sessions'\nimport type {\n AgentBackendInput,\n AgentExecutionBackend,\n AgentKnowledgeProvider,\n AgentRuntimeEventSink,\n AgentTaskContext,\n AgentTaskRunResult,\n AgentTaskSpec,\n AgentTaskStatus,\n BackendErrorDetail,\n RunAgentTaskOptions,\n RunAgentTaskStreamOptions,\n RuntimeSession,\n RuntimeStreamEvent,\n} from './types'\n\n/**\n * Single-shot task lifecycle for adapter-driven tasks: readiness-gated, emits the runtime lifecycle event vocabulary, session-store pluggable.\n *\n * @stable\n */\nexport async function runAgentTask<\n TState,\n TAction,\n TActionResult,\n TEval extends ControlEvalResult = ControlEvalResult,\n>(\n options: RunAgentTaskOptions<TState, TAction, TActionResult, TEval>,\n): Promise<AgentTaskRunResult<TState, TAction, TActionResult, TEval>> {\n const task = options.task\n await emit(options.onEvent, { type: 'task_start', task })\n await emit(options.onEvent, { type: 'readiness_start', task })\n let knowledge = await buildReadiness(task, options.knowledge)\n await emit(options.onEvent, { type: 'readiness_end', task, knowledge })\n const questions = userQuestionsForKnowledgeGaps(knowledge.blockingMissingRequirements)\n const acquisitionPlans = acquisitionPlansForKnowledgeGaps([\n ...knowledge.blockingMissingRequirements,\n ...knowledge.nonBlockingGaps,\n ])\n const preflight = await runKnowledgePreflight(\n task,\n questions,\n acquisitionPlans,\n options.knowledge,\n options.onEvent,\n )\n if (\n options.knowledge?.refreshReadiness &&\n (Object.keys(preflight.userAnswers).length > 0 || preflight.acquiredEvidenceIds.length > 0)\n ) {\n await emit(options.onEvent, { type: 'readiness_start', task })\n knowledge = await options.knowledge.refreshReadiness({\n task,\n previous: knowledge,\n userAnswers: preflight.userAnswers,\n acquiredEvidenceIds: preflight.acquiredEvidenceIds,\n })\n await emit(options.onEvent, { type: 'readiness_end', task, knowledge })\n }\n\n await emit(options.onEvent, { type: 'control_start', task, knowledge })\n const scenarioId = options.scenarioId ?? task.id\n const control = await runAgentControlLoop<TState, TAction, TActionResult, TEval>({\n intent: task.intent,\n budget: task.budget,\n signal: options.signal,\n store: options.store,\n scenarioId,\n projectId: options.projectId,\n variantId: options.variantId,\n observe: ({ history, abortSignal }) =>\n options.adapter.observe({ task, knowledge, history, abortSignal }),\n validate: async ({ state, history, abortSignal }) => {\n const readinessEval = blockingKnowledgeEval(knowledge, {\n minimumScore: options.minimumReadinessScore,\n })\n const evals = await options.adapter.validate({\n task,\n knowledge,\n state,\n history,\n abortSignal,\n })\n return [readinessEval as TEval, ...evals]\n },\n decide: (ctx) => {\n if (isKnowledgeBlocked(ctx.evals)) {\n return (\n options.adapter.onKnowledgeBlocked?.({\n task,\n knowledge,\n questions,\n acquisitionPlans,\n }) ?? {\n type: 'stop',\n pass: false,\n score: knowledge.readinessScore,\n reason: `knowledge readiness blocked: ${knowledge.reason}`,\n }\n )\n }\n return options.adapter.decide(toAgentContext(task, knowledge, ctx))\n },\n act: (action, ctx) => options.adapter.act(action, toAgentContext(task, knowledge, ctx)),\n shouldStop: options.adapter.shouldStop\n ? (ctx) => options.adapter.shouldStop!(toAgentContext(task, knowledge, ctx))\n : undefined,\n getActionCostUsd: options.adapter.getActionCostUsd\n ? ({ action, result, state, evals, history }) =>\n options.adapter.getActionCostUsd!({ action, result, task, state, evals, history })\n : undefined,\n onStep: (step) => emit(options.onEvent, { type: 'control_step', task, step }),\n })\n await emit(options.onEvent, { type: 'control_end', task, control })\n const status = statusFromControl(control)\n await emit(options.onEvent, { type: 'task_end', task, status, reason: control.reason })\n\n return {\n task,\n status,\n knowledge,\n questions,\n acquisitionPlans,\n userAnswers: preflight.userAnswers,\n acquiredEvidenceIds: preflight.acquiredEvidenceIds,\n control,\n runRecords: applyRunRecordDefaults(\n options.adapter.projectRunRecords?.(control, task) ?? [],\n scenarioId,\n control.failureClass,\n ),\n }\n}\n\n/**\n * Streaming task lifecycle: delegates execution to an `AgentExecutionBackend` (model API, sandbox, or custom iterable) and yields lifecycle events as they happen.\n *\n * @stable\n */\nexport async function* runAgentTaskStream<TInput extends AgentBackendInput = AgentBackendInput>(\n options: RunAgentTaskStreamOptions<TInput>,\n): AsyncIterable<RuntimeStreamEvent> {\n const task = options.task\n const input = { task, ...(options.input ?? {}) } as TInput\n yield streamEvent({ type: 'task_start', task })\n\n yield streamEvent({ type: 'readiness_start', task })\n let knowledge = await buildReadiness(task, options.knowledge)\n const questions = userQuestionsForKnowledgeGaps(knowledge.blockingMissingRequirements)\n const acquisitionPlans = acquisitionPlansForKnowledgeGaps([\n ...knowledge.blockingMissingRequirements,\n ...knowledge.nonBlockingGaps,\n ])\n const preflight = await runKnowledgePreflightStream(\n task,\n questions,\n acquisitionPlans,\n options.knowledge,\n )\n for (const event of preflight.events) yield event\n if (\n options.knowledge?.refreshReadiness &&\n (Object.keys(preflight.userAnswers).length > 0 || preflight.acquiredEvidenceIds.length > 0)\n ) {\n yield streamEvent({ type: 'readiness_start', task })\n knowledge = await options.knowledge.refreshReadiness({\n task,\n previous: knowledge,\n userAnswers: preflight.userAnswers,\n acquiredEvidenceIds: preflight.acquiredEvidenceIds,\n })\n }\n const decision = decideKnowledgeReadiness(knowledge, {\n minimumScore: options.minimumReadinessScore,\n })\n yield streamEvent({ type: 'readiness_end', task, knowledge, decision })\n if (!decision.passed && decision.status === 'blocked') {\n const reason = `knowledge readiness blocked: ${decision.reason}`\n yield streamEvent({ type: 'task_end', task, status: 'blocked', reason })\n yield streamEvent({ type: 'final', task, status: 'blocked', reason })\n return\n }\n\n const store = options.sessionStore\n const existing = options.sessionId ? await store?.get(options.sessionId) : undefined\n const shouldResume = Boolean(options.resume && existing)\n let session =\n shouldResume && existing\n ? await resumeBackendSession(options.backend, existing, input, {\n task,\n knowledge,\n signal: options.signal,\n })\n : await startBackendSession(\n options.backend,\n input,\n { task, knowledge, signal: options.signal },\n options.sessionId,\n )\n await store?.put(session)\n const sessionEvent = streamEvent({\n type: shouldResume ? 'session_resumed' : 'session_created',\n task,\n session,\n })\n await store?.appendEvent?.(session.id, sessionEvent)\n yield sessionEvent\n\n const backendStart = streamEvent({\n type: 'backend_start',\n task,\n session,\n backend: options.backend.kind,\n })\n await store?.appendEvent?.(session.id, backendStart)\n yield backendStart\n\n let finalText = ''\n try {\n for await (const rawEvent of options.backend.stream(input, {\n task,\n knowledge,\n session,\n signal: options.signal,\n })) {\n const event = normalizeBackendStreamEvent(rawEvent, task, session)\n if (event.type === 'text_delta') finalText += event.text\n await store?.appendEvent?.(session.id, event)\n yield event\n }\n const completedStatus: AgentTaskStatus = 'completed'\n session = touchSession({ ...session, status: completedStatus })\n await store?.put(session)\n const backendEnd = streamEvent({\n type: 'backend_end',\n task,\n session,\n backend: options.backend.kind,\n })\n await store?.appendEvent?.(session.id, backendEnd)\n yield backendEnd\n const reason = 'backend completed'\n const taskEnd = streamEvent({ type: 'task_end', task, status: completedStatus, reason })\n await store?.appendEvent?.(session.id, taskEnd)\n yield taskEnd\n const final = streamEvent({\n type: 'final',\n task,\n session,\n status: completedStatus,\n reason,\n text: finalText || undefined,\n })\n await store?.appendEvent?.(session.id, final)\n yield final\n } catch (err) {\n const message = err instanceof Error ? err.message : String(err)\n session = touchSession({ ...session, status: options.signal?.aborted ? 'aborted' : 'failed' })\n await store?.put(session)\n let stopErrorMessage: string | undefined\n try {\n await options.backend.stop?.(session, message)\n } catch (stopErr) {\n stopErrorMessage = stopErr instanceof Error ? stopErr.message : String(stopErr)\n }\n const combinedMessage = stopErrorMessage\n ? `${message}; backend stop failed: ${stopErrorMessage}`\n : message\n // Typed transport detail — preserves status code + truncated body so\n // consumers can map onto `RunRecord.error` without re-parsing the log\n // string. Required by the runtime's fail-loud contract: silent empty\n // output for a 402 / 401 / 5xx hides the real failure mode.\n const errorDetail: BackendErrorDetail =\n err instanceof BackendTransportError\n ? {\n kind: 'transport',\n message: combinedMessage,\n status: err.status,\n body: err.body,\n }\n : { kind: 'backend', message: combinedMessage }\n const backendError = streamEvent({\n type: 'backend_error',\n task,\n session,\n backend: options.backend.kind,\n message: combinedMessage,\n recoverable: !options.signal?.aborted,\n error: errorDetail,\n })\n await store?.appendEvent?.(session.id, backendError)\n yield backendError\n const status: AgentTaskStatus = options.signal?.aborted ? 'aborted' : 'failed'\n const taskEnd = streamEvent({ type: 'task_end', task, status, reason: message })\n await store?.appendEvent?.(session.id, taskEnd)\n yield taskEnd\n const final = streamEvent({\n type: 'final',\n task,\n session,\n status,\n reason: message,\n text: finalText || undefined,\n error: errorDetail,\n })\n await store?.appendEvent?.(session.id, final)\n yield final\n }\n}\n\nasync function runKnowledgePreflight<\n TState,\n TAction,\n TActionResult,\n TEval extends ControlEvalResult,\n>(\n task: AgentTaskSpec,\n questions: UserQuestion[],\n acquisitionPlans: DataAcquisitionPlan[],\n provider: AgentKnowledgeProvider | undefined,\n onEvent: AgentRuntimeEventSink<TState, TAction, TActionResult, TEval> | undefined,\n): Promise<{ userAnswers: Record<string, string>; acquiredEvidenceIds: string[] }> {\n let userAnswers: Record<string, string> = {}\n let acquiredEvidenceIds: string[] = []\n if (questions.length > 0 && provider?.answerQuestions) {\n await emit(onEvent, { type: 'questions_start', task, questions })\n userAnswers = await provider.answerQuestions(questions, task)\n await emit(onEvent, { type: 'questions_end', task, questions, userAnswers })\n }\n if (acquisitionPlans.length > 0 && provider?.executeAcquisitionPlans) {\n await emit(onEvent, { type: 'acquisition_start', task, acquisitionPlans })\n acquiredEvidenceIds = await provider.executeAcquisitionPlans(acquisitionPlans, task)\n await emit(onEvent, {\n type: 'acquisition_end',\n task,\n acquisitionPlans,\n acquiredEvidenceIds,\n })\n }\n return { userAnswers, acquiredEvidenceIds }\n}\n\nasync function runKnowledgePreflightStream(\n task: AgentTaskSpec,\n questions: UserQuestion[],\n acquisitionPlans: DataAcquisitionPlan[],\n provider: AgentKnowledgeProvider | undefined,\n): Promise<{\n userAnswers: Record<string, string>\n acquiredEvidenceIds: string[]\n events: RuntimeStreamEvent[]\n}> {\n const events: RuntimeStreamEvent[] = []\n let userAnswers: Record<string, string> = {}\n let acquiredEvidenceIds: string[] = []\n if (questions.length > 0 && provider?.answerQuestions) {\n events.push(streamEvent({ type: 'questions_start', task, questions }))\n userAnswers = await provider.answerQuestions(questions, task)\n events.push(streamEvent({ type: 'questions_end', task, questions, userAnswers }))\n }\n if (acquisitionPlans.length > 0 && provider?.executeAcquisitionPlans) {\n events.push(streamEvent({ type: 'acquisition_start', task, acquisitionPlans }))\n acquiredEvidenceIds = await provider.executeAcquisitionPlans(acquisitionPlans, task)\n events.push(\n streamEvent({ type: 'acquisition_end', task, acquisitionPlans, acquiredEvidenceIds }),\n )\n }\n return { userAnswers, acquiredEvidenceIds, events }\n}\n\nfunction streamEvent<T extends Omit<RuntimeStreamEvent, 'timestamp'>>(\n event: T,\n): T & { timestamp: string } {\n return { ...event, timestamp: nowIso() }\n}\n\nasync function startBackendSession<TInput extends AgentBackendInput>(\n backend: AgentExecutionBackend<TInput>,\n input: TInput,\n context: { task: AgentTaskSpec; knowledge: KnowledgeReadinessReport; signal?: AbortSignal },\n requestedSessionId?: string,\n): Promise<RuntimeSession> {\n if (backend.start) return backend.start(input, { ...context, requestedSessionId })\n return newRuntimeSession(backend.kind, requestedSessionId)\n}\n\nasync function resumeBackendSession<TInput extends AgentBackendInput>(\n backend: AgentExecutionBackend<TInput>,\n session: RuntimeSession,\n input: TInput,\n context: { task: AgentTaskSpec; knowledge: KnowledgeReadinessReport; signal?: AbortSignal },\n): Promise<RuntimeSession> {\n if (session.backend !== backend.kind) {\n throw new SessionMismatchError(session.backend, backend.kind)\n }\n if (backend.resume) return backend.resume(session, input, context)\n return touchSession({ ...session, status: 'active' })\n}\n\nfunction buildReadiness(\n task: AgentTaskSpec,\n provider: AgentKnowledgeProvider | undefined,\n): Promise<KnowledgeReadinessReport> | KnowledgeReadinessReport {\n if (provider?.buildReadiness) return provider.buildReadiness(task)\n return scoreKnowledgeReadiness({\n taskId: task.id,\n requirements: task.requiredKnowledge ?? [],\n metadata: { domain: task.domain, ...task.metadata },\n })\n}\n\nfunction isKnowledgeBlocked(evals: ControlEvalResult[]): boolean {\n return evals.some((evalResult) => evalResult.id === 'knowledge-ready' && !evalResult.passed)\n}\n\nfunction statusFromControl(\n control: ControlRunResult<unknown, unknown, unknown, ControlEvalResult>,\n): AgentTaskStatus {\n if (control.stoppedBy === 'abort') return 'aborted'\n if (control.reason.includes('knowledge readiness blocked')) return 'blocked'\n if (control.pass) return 'completed'\n return 'failed'\n}\n\nasync function emit<TState, TAction, TActionResult, TEval extends ControlEvalResult>(\n sink: AgentRuntimeEventSink<TState, TAction, TActionResult, TEval> | undefined,\n event: Parameters<AgentRuntimeEventSink<TState, TAction, TActionResult, TEval>>[0],\n): Promise<void> {\n await sink?.(event)\n}\n\nfunction toAgentContext<TState, TAction, TActionResult, TEval extends ControlEvalResult>(\n task: AgentTaskSpec,\n knowledge: KnowledgeReadinessReport,\n ctx: ControlContext<TState, TAction, TActionResult, TEval>,\n): AgentTaskContext<TState, TAction, TActionResult, TEval> {\n return {\n task,\n knowledge,\n state: ctx.state,\n evals: ctx.evals,\n history: ctx.history,\n budget: ctx.budget,\n stepIndex: ctx.stepIndex,\n wallMs: ctx.wallMs,\n spentCostUsd: ctx.spentCostUsd,\n remainingCostUsd: ctx.remainingCostUsd,\n abortSignal: ctx.abortSignal,\n }\n}\n","/**\n *\n * Production-run lifecycle: record what the agent did on behalf of a customer,\n * what it cost, and how it ended.\n *\n * Three concerns live in this module:\n *\n * 1. **Lifecycle state machine** — `running` -> `completed | failed | cancelled`,\n * enforced by `RuntimeRunStateError`. Completion is idempotent for the same\n * status (a second `complete()` call is a no-op so retries / cleanup paths\n * don't double-fire side effects). A different terminal status is a state\n * error.\n *\n * 2. **Cost ledger** — every `llm_call` event the handle observes contributes\n * `tokensIn`, `tokensOut`, `costUsd`, and bumps `llmCalls`. Wall time is\n * measured from `startRuntimeRun()` to `complete()`. Surface via\n * `handle.cost()` for cost-per-task dashboards.\n *\n * 3. **Persistence adapter** — `RuntimeRunPersistenceAdapter` is the seam\n * consumers plug in to write a `RuntimeRunRow` to their D1 / postgres /\n * KV store. The adapter receives a sanitized row shape; no telemetry\n * payload bytes flow through it unless the consumer opts in via\n * `RuntimeRunOptions.telemetryEvents`.\n *\n * @stable\n */\n\nimport { RuntimeRunStateError, ValidationError } from './errors'\nimport type { AgentTaskSpec, RuntimeStreamEvent } from './types'\n\n/** @stable */\nexport type RuntimeRunStatus = 'running' | 'completed' | 'failed' | 'cancelled'\n\n/** @stable */\nexport interface RuntimeRunCost {\n /** Cumulative input tokens across every observed `llm_call` event. */\n tokensIn: number\n /** Cumulative output tokens across every observed `llm_call` event. */\n tokensOut: number\n /** Sum of `costUsd` from every observed `llm_call` event. */\n costUsd: number\n /** Wall time from `startRuntimeRun()` to `complete()` (or `now()` if not yet completed). */\n wallMs: number\n /** Count of `llm_call` events observed during the run. */\n llmCalls: number\n}\n\n/** @stable */\nexport interface RuntimeRunCompleteInput {\n status: Exclude<RuntimeRunStatus, 'running'>\n resultSummary?: string\n /** Optional explicit cost override; if omitted, the accumulated ledger is used. */\n cost?: Partial<RuntimeRunCost>\n /** Stable error message when `status === 'failed'`. */\n error?: string\n /** Additional adapter-specific fields merged into the persisted row. */\n metadata?: Record<string, unknown>\n}\n\n/** @stable */\nexport interface RuntimeRunRow {\n /** Stable runtime-side identifier. Adapters may translate to their own primary key. */\n id: string\n workspaceId: string\n sessionId?: string\n agentId?: string\n domain?: string\n taskId: string\n scenarioId?: string\n status: RuntimeRunStatus\n resultSummary?: string\n error?: string\n cost: RuntimeRunCost\n startedAt: string\n completedAt?: string\n metadata?: Record<string, unknown>\n}\n\n/** @stable */\nexport interface RuntimeRunPersistenceAdapter {\n /**\n * Called once when `handle.persist()` runs. Implementations write `row` to\n * their durable store (D1, postgres, KV) and return whatever the consumer\n * wants the caller to see (often the storage-side row id). Errors thrown\n * here propagate out of `persist()` so the caller can decide whether to\n * retry or log-and-continue.\n */\n upsert(row: RuntimeRunRow): Promise<void> | void\n}\n\n/** @stable */\nexport interface RuntimeRunOptions {\n workspaceId: string\n sessionId?: string\n agentId?: string\n taskSpec: AgentTaskSpec\n scenarioId?: string\n /** Optional persistence adapter; if omitted, `persist()` is a no-op. */\n adapter?: RuntimeRunPersistenceAdapter\n /** Override the row id; default = `${taskSpec.id}:${random suffix}`. */\n id?: string\n /** Override the clock; default = `Date.now()`. Useful for deterministic tests. */\n now?: () => number\n}\n\n/** @stable */\nexport interface RuntimeRunHandle {\n /** Stable id assigned at start. */\n readonly id: string\n readonly workspaceId: string\n readonly sessionId: string | undefined\n readonly taskSpec: AgentTaskSpec\n readonly status: RuntimeRunStatus\n\n /**\n * Observe a single `RuntimeStreamEvent`. The handle ignores non-cost events\n * (text deltas, tool calls) silently so consumers can pipe the whole stream\n * through `handle.observe`. `llm_call` events update the ledger.\n */\n observe(event: RuntimeStreamEvent): void\n\n /** Snapshot of the current cost ledger. Safe to call at any time. */\n cost(): RuntimeRunCost\n\n /**\n * Transition to a terminal state. Idempotent for the same status; throws\n * `RuntimeRunStateError` for a different terminal status (state machines\n * don't time-travel).\n */\n complete(input: RuntimeRunCompleteInput): void\n\n /** Build the current row without writing it. Useful for tests + dry runs. */\n toRow(metadata?: Record<string, unknown>): RuntimeRunRow\n\n /**\n * Persist the current row via the configured adapter. Must be called after\n * `complete()`. Idempotent for the same terminal state (the adapter sees\n * the same row on retry).\n */\n persist(metadata?: Record<string, unknown>): Promise<void>\n}\n\n/**\n *\n * Construct a runtime-run handle. The returned handle is mutable across its\n * lifetime; consumers should not share it across requests.\n *\n * @stable\n */\nexport function startRuntimeRun(options: RuntimeRunOptions): RuntimeRunHandle {\n if (!options.workspaceId) {\n throw new ValidationError('startRuntimeRun: workspaceId is required')\n }\n if (!options.taskSpec?.id) {\n throw new ValidationError('startRuntimeRun: taskSpec.id is required')\n }\n const now = options.now ?? Date.now\n const startedAtMs = now()\n const startedAt = new Date(startedAtMs).toISOString()\n const id = options.id ?? `${options.taskSpec.id}:${randomSuffix()}`\n\n let status: RuntimeRunStatus = 'running'\n let completedAtMs: number | undefined\n let resultSummary: string | undefined\n let error: string | undefined\n let completionMetadata: Record<string, unknown> | undefined\n\n const ledger: RuntimeRunCost = {\n tokensIn: 0,\n tokensOut: 0,\n costUsd: 0,\n wallMs: 0,\n llmCalls: 0,\n }\n\n const snapshotCost = (): RuntimeRunCost => ({\n tokensIn: ledger.tokensIn,\n tokensOut: ledger.tokensOut,\n costUsd: ledger.costUsd,\n wallMs: (completedAtMs ?? now()) - startedAtMs,\n llmCalls: ledger.llmCalls,\n })\n\n const buildRow = (extraMetadata?: Record<string, unknown>): RuntimeRunRow => ({\n id,\n workspaceId: options.workspaceId,\n sessionId: options.sessionId,\n agentId: options.agentId,\n domain: options.taskSpec.domain,\n taskId: options.taskSpec.id,\n scenarioId: options.scenarioId,\n status,\n resultSummary,\n error,\n cost: snapshotCost(),\n startedAt,\n completedAt: completedAtMs !== undefined ? new Date(completedAtMs).toISOString() : undefined,\n metadata: mergeMetadata(completionMetadata, extraMetadata),\n })\n\n return {\n id,\n workspaceId: options.workspaceId,\n sessionId: options.sessionId,\n taskSpec: options.taskSpec,\n get status() {\n return status\n },\n observe(event) {\n if (event.type !== 'llm_call') return\n ledger.llmCalls += 1\n if (typeof event.tokensIn === 'number' && Number.isFinite(event.tokensIn)) {\n ledger.tokensIn += event.tokensIn\n }\n if (typeof event.tokensOut === 'number' && Number.isFinite(event.tokensOut)) {\n ledger.tokensOut += event.tokensOut\n }\n if (typeof event.costUsd === 'number' && Number.isFinite(event.costUsd)) {\n ledger.costUsd += event.costUsd\n }\n },\n cost: snapshotCost,\n complete(input) {\n // JS callers can bypass the `Exclude<…, 'running'>` type; enforce the\n // state machine at runtime as well.\n if ((input.status as RuntimeRunStatus) === 'running') {\n throw new ValidationError('complete() requires a terminal status, got \"running\"')\n }\n if (status !== 'running') {\n if (status === input.status) return\n throw new RuntimeRunStateError(\n `Cannot transition runtime run from \"${status}\" to \"${input.status}\"`,\n )\n }\n status = input.status\n completedAtMs = now()\n resultSummary = input.resultSummary\n error = input.error\n completionMetadata = input.metadata\n if (input.cost) {\n if (typeof input.cost.tokensIn === 'number' && Number.isFinite(input.cost.tokensIn)) {\n ledger.tokensIn = input.cost.tokensIn\n }\n if (typeof input.cost.tokensOut === 'number' && Number.isFinite(input.cost.tokensOut)) {\n ledger.tokensOut = input.cost.tokensOut\n }\n if (typeof input.cost.costUsd === 'number' && Number.isFinite(input.cost.costUsd)) {\n ledger.costUsd = input.cost.costUsd\n }\n if (typeof input.cost.llmCalls === 'number' && Number.isFinite(input.cost.llmCalls)) {\n ledger.llmCalls = input.cost.llmCalls\n }\n }\n },\n toRow(metadata) {\n return buildRow(metadata)\n },\n async persist(metadata) {\n if (status === 'running') {\n throw new RuntimeRunStateError('Cannot persist a runtime run before complete() is called')\n }\n if (!options.adapter) return\n await options.adapter.upsert(buildRow(metadata))\n },\n }\n}\n\nfunction mergeMetadata(\n base: Record<string, unknown> | undefined,\n extra: Record<string, unknown> | undefined,\n): Record<string, unknown> | undefined {\n if (!base && !extra) return undefined\n return { ...(base ?? {}), ...(extra ?? {}) }\n}\n\nfunction randomSuffix(): string {\n // 8 chars of base36 — sufficient for in-process uniqueness. Callers needing\n // stronger guarantees pass `options.id` explicitly.\n return Math.random().toString(36).slice(2, 10)\n}\n","/**\n *\n * Sanitization for runtime telemetry. The rule: nothing user-controlled leaks\n * unless the caller opts in with a `RuntimeTelemetryOptions` flag. This is the\n * envelope that ends up in `agent_run.metadata.runtimeEvents` on every\n * consumer, so the default must be safe.\n *\n * @stable\n */\n\nimport type {\n ControlEvalResult,\n ControlRunResult,\n ControlStep,\n DataAcquisitionPlan,\n KnowledgeReadinessReport,\n KnowledgeRequirement,\n UserQuestion,\n} from '@tangle-network/agent-eval'\n\nimport type {\n AgentRuntimeEvent,\n AgentTaskSpec,\n AgentTaskStatus,\n RuntimeSession,\n RuntimeStreamEvent,\n} from './types'\n\n/** @stable */\nexport interface RuntimeTelemetryOptions {\n /**\n * Include raw task inputs. Off by default because task inputs often contain\n * customer facts, credentials, source text, or internal IDs.\n */\n includeInputs?: boolean\n /** Include requirement descriptions. Secret requirements are always redacted. */\n includeRequirementDescriptions?: boolean\n /** Include evidence IDs. Off by default; counts are safer for shared reports. */\n includeEvidenceIds?: boolean\n /** Include user answers from question preflight. Off by default. */\n includeUserAnswers?: boolean\n /** Include action payloads and action results for control steps. Off by default. */\n includeControlPayloads?: boolean\n /** Include task metadata. Off by default because metadata may carry IDs or policy internals. */\n includeMetadata?: boolean\n /** Include eval detail/evidence strings. Off by default because validators may echo private input. */\n includeEvalDetails?: boolean\n}\n\n/** @stable */\nexport interface SanitizedKnowledgeRequirement {\n id: string\n description?: string\n requiredFor: string[]\n category: KnowledgeRequirement['category']\n acquisitionMode: KnowledgeRequirement['acquisitionMode']\n importance: KnowledgeRequirement['importance']\n freshness: KnowledgeRequirement['freshness']\n sensitivity: KnowledgeRequirement['sensitivity']\n confidenceNeeded: number\n currentConfidence: number\n evidenceCount: number\n evidenceIds?: string[]\n fallbackPolicy: KnowledgeRequirement['fallbackPolicy']\n}\n\n/** @stable */\nexport interface SanitizedKnowledgeReadinessReport {\n taskId: string\n readinessScore: number\n recommendedAction: KnowledgeReadinessReport['recommendedAction']\n severity: KnowledgeReadinessReport['severity']\n reason: string\n blockingMissingRequirements: SanitizedKnowledgeRequirement[]\n nonBlockingGaps: SanitizedKnowledgeRequirement[]\n evidenceCount: number\n evidenceIds?: string[]\n missingRequirementIds: string[]\n}\n\n/** Strip PII and large blobs from a `KnowledgeReadinessReport` for safe telemetry emission. @stable */\nexport function sanitizeKnowledgeReadinessReport(\n report: KnowledgeReadinessReport,\n options: RuntimeTelemetryOptions = {},\n): SanitizedKnowledgeReadinessReport {\n return {\n taskId: report.taskId,\n readinessScore: report.readinessScore,\n recommendedAction: report.recommendedAction,\n severity: report.severity,\n reason: report.reason,\n blockingMissingRequirements: report.blockingMissingRequirements.map((requirement) =>\n sanitizeKnowledgeRequirement(requirement, options),\n ),\n nonBlockingGaps: report.nonBlockingGaps.map((requirement) =>\n sanitizeKnowledgeRequirement(requirement, options),\n ),\n evidenceCount: report.bundle.evidenceIds.length,\n evidenceIds: options.includeEvidenceIds ? report.bundle.evidenceIds : undefined,\n missingRequirementIds: report.bundle.missing.map((requirement) => requirement.id),\n }\n}\n\n/** Reduce an `AgentRuntimeEvent` to a PII-safe, serializable plain object for telemetry. @stable */\nexport function sanitizeAgentRuntimeEvent<\n TState,\n TAction,\n TActionResult,\n TEval extends ControlEvalResult,\n>(\n event: AgentRuntimeEvent<TState, TAction, TActionResult, TEval>,\n options: RuntimeTelemetryOptions = {},\n): Record<string, unknown> {\n const base = { type: event.type, task: sanitizeTask(event.task, options) }\n if (\n event.type === 'readiness_start' ||\n event.type === 'task_start' ||\n event.type === 'control_start'\n ) {\n return event.type === 'control_start'\n ? { ...base, knowledge: sanitizeKnowledgeReadinessReport(event.knowledge, options) }\n : base\n }\n if (event.type === 'readiness_end') {\n return { ...base, knowledge: sanitizeKnowledgeReadinessReport(event.knowledge, options) }\n }\n if (event.type === 'questions_start') {\n return {\n ...base,\n questions: event.questions.map((question) => sanitizeQuestion(question, options)),\n }\n }\n if (event.type === 'questions_end') {\n return {\n ...base,\n questions: event.questions.map((question) => sanitizeQuestion(question, options)),\n userAnswers: options.includeUserAnswers ? event.userAnswers : redactRecord(event.userAnswers),\n }\n }\n if (event.type === 'acquisition_start') {\n return { ...base, acquisitionPlans: event.acquisitionPlans.map(sanitizeAcquisitionPlan) }\n }\n if (event.type === 'acquisition_end') {\n return {\n ...base,\n acquisitionPlans: event.acquisitionPlans.map(sanitizeAcquisitionPlan),\n acquiredEvidenceCount: event.acquiredEvidenceIds.length,\n acquiredEvidenceIds: options.includeEvidenceIds ? event.acquiredEvidenceIds : undefined,\n }\n }\n if (event.type === 'control_step') {\n return { ...base, step: sanitizeControlStep(event.step, options) }\n }\n if (event.type === 'control_end') {\n return { ...base, control: sanitizeControlRun(event.control, options) }\n }\n return { ...base, status: event.status, reason: event.reason }\n}\n\n/** Reduce a `RuntimeStreamEvent` to a PII-safe, serializable plain object for telemetry. @stable */\nexport function sanitizeRuntimeStreamEvent(\n event: RuntimeStreamEvent,\n options: RuntimeTelemetryOptions = {},\n): Record<string, unknown> {\n const withTask = 'task' in event && event.task ? { task: sanitizeTask(event.task, options) } : {}\n const withSession =\n 'session' in event && event.session\n ? { session: sanitizeRuntimeSession(event.session, options) }\n : {}\n\n if (event.type === 'readiness_end') {\n return {\n type: event.type,\n ...withTask,\n timestamp: event.timestamp,\n decision: event.decision,\n knowledge: sanitizeKnowledgeReadinessReport(event.knowledge, options),\n }\n }\n if (event.type === 'questions_start') {\n return {\n type: event.type,\n ...withTask,\n timestamp: event.timestamp,\n questions: event.questions.map((question) => sanitizeQuestion(question, options)),\n }\n }\n if (event.type === 'questions_end') {\n return {\n type: event.type,\n ...withTask,\n timestamp: event.timestamp,\n questions: event.questions.map((question) => sanitizeQuestion(question, options)),\n userAnswers: options.includeUserAnswers ? event.userAnswers : redactRecord(event.userAnswers),\n }\n }\n if (event.type === 'acquisition_start') {\n return {\n type: event.type,\n ...withTask,\n timestamp: event.timestamp,\n acquisitionPlans: event.acquisitionPlans.map(sanitizeAcquisitionPlan),\n }\n }\n if (event.type === 'acquisition_end') {\n return {\n type: event.type,\n ...withTask,\n timestamp: event.timestamp,\n acquisitionPlans: event.acquisitionPlans.map(sanitizeAcquisitionPlan),\n acquiredEvidenceCount: event.acquiredEvidenceIds.length,\n acquiredEvidenceIds: options.includeEvidenceIds ? event.acquiredEvidenceIds : undefined,\n }\n }\n if (event.type === 'tool_call') {\n return {\n type: event.type,\n ...withTask,\n ...withSession,\n timestamp: event.timestamp,\n toolName: event.toolName,\n toolCallId: event.toolCallId,\n args: options.includeControlPayloads ? event.args : undefined,\n }\n }\n if (event.type === 'tool_result') {\n return {\n type: event.type,\n ...withTask,\n ...withSession,\n timestamp: event.timestamp,\n toolName: event.toolName,\n toolCallId: event.toolCallId,\n result: options.includeControlPayloads ? event.result : undefined,\n }\n }\n if (event.type === 'llm_call') {\n return {\n type: event.type,\n ...withTask,\n ...withSession,\n timestamp: event.timestamp,\n model: event.model,\n tokensIn: event.tokensIn,\n tokensOut: event.tokensOut,\n costUsd: event.costUsd,\n latencyMs: event.latencyMs,\n finishReason: event.finishReason,\n }\n }\n if (event.type === 'artifact') {\n return {\n type: event.type,\n ...withTask,\n ...withSession,\n timestamp: event.timestamp,\n artifactId: event.artifactId,\n name: event.name,\n mimeType: event.mimeType,\n uri: options.includeEvidenceIds ? event.uri : undefined,\n content: options.includeControlPayloads ? event.content : undefined,\n metadata: options.includeMetadata ? event.metadata : undefined,\n }\n }\n if (event.type === 'proposal_created') {\n return {\n type: event.type,\n ...withTask,\n ...withSession,\n timestamp: event.timestamp,\n proposalId: event.proposalId,\n title: options.includeControlPayloads ? event.title : undefined,\n content: options.includeControlPayloads ? event.content : undefined,\n status: event.status,\n }\n }\n if (event.type === 'final') {\n // Surface error `kind` + `status` always — operators need failure\n // classification regardless of telemetry payload opt-in. `body` follows\n // the same gating as raw payloads (`includeControlPayloads`) because it\n // can echo user-visible text from the upstream provider's error page.\n const sanitizedError =\n event.error !== undefined\n ? {\n kind: event.error.kind,\n message: event.error.message,\n status: event.error.status,\n body: options.includeControlPayloads ? event.error.body : undefined,\n }\n : undefined\n return {\n type: event.type,\n ...withTask,\n ...withSession,\n timestamp: event.timestamp,\n status: event.status,\n reason: event.reason,\n text: options.includeControlPayloads ? event.text : undefined,\n metadata: options.includeMetadata ? event.metadata : undefined,\n ...(sanitizedError !== undefined ? { error: sanitizedError } : {}),\n }\n }\n return {\n type: event.type,\n ...withTask,\n ...withSession,\n timestamp: 'timestamp' in event ? event.timestamp : undefined,\n ...pickPublicStreamFields(event),\n }\n}\n\nfunction sanitizeTask(\n task: AgentTaskSpec,\n options: RuntimeTelemetryOptions,\n): Record<string, unknown> {\n return {\n id: task.id,\n intent: task.intent,\n domain: task.domain,\n inputs: options.includeInputs ? task.inputs : task.inputs ? '[redacted]' : undefined,\n requiredKnowledge: task.requiredKnowledge?.map((requirement) =>\n sanitizeKnowledgeRequirement(requirement, options),\n ),\n metadata: options.includeMetadata ? task.metadata : task.metadata ? '[redacted]' : undefined,\n }\n}\n\nfunction sanitizeRuntimeSession(\n session: RuntimeSession,\n options: RuntimeTelemetryOptions,\n): Record<string, unknown> {\n return {\n id: session.id,\n backend: session.backend,\n status: session.status,\n hasResumeToken: Boolean(session.resumeToken),\n createdAt: session.createdAt,\n updatedAt: session.updatedAt,\n metadata: options.includeMetadata\n ? session.metadata\n : session.metadata\n ? '[redacted]'\n : undefined,\n }\n}\n\nfunction sanitizeKnowledgeRequirement(\n requirement: KnowledgeRequirement,\n options: RuntimeTelemetryOptions,\n): SanitizedKnowledgeRequirement {\n const includeDescription =\n options.includeRequirementDescriptions && requirement.sensitivity !== 'secret'\n return {\n id: requirement.id,\n description: includeDescription ? requirement.description : undefined,\n requiredFor: requirement.requiredFor,\n category: requirement.category,\n acquisitionMode: requirement.acquisitionMode,\n importance: requirement.importance,\n freshness: requirement.freshness,\n sensitivity: requirement.sensitivity,\n confidenceNeeded: requirement.confidenceNeeded,\n currentConfidence: requirement.currentConfidence,\n evidenceCount: requirement.evidenceIds.length,\n evidenceIds: options.includeEvidenceIds ? requirement.evidenceIds : undefined,\n fallbackPolicy: requirement.fallbackPolicy,\n }\n}\n\nfunction sanitizeQuestion(\n question: UserQuestion,\n options: RuntimeTelemetryOptions,\n): Record<string, unknown> {\n return {\n id: question.id,\n question:\n options.includeRequirementDescriptions && question.answerType !== 'credential'\n ? question.question\n : undefined,\n reason: options.includeRequirementDescriptions ? question.reason : undefined,\n requirementId: question.requirementId,\n importance: question.importance,\n answerType: question.answerType,\n impactIfUnknown: options.includeRequirementDescriptions ? question.impactIfUnknown : undefined,\n optionCount: question.options?.length ?? 0,\n }\n}\n\nfunction sanitizeAcquisitionPlan(plan: DataAcquisitionPlan): Record<string, unknown> {\n return {\n id: plan.id,\n requirementIds: plan.requirementIds,\n mode: plan.mode,\n priority: plan.priority,\n expectedEvidenceCount: plan.expectedEvidenceIds?.length ?? 0,\n questionCount: plan.questions?.length ?? 0,\n }\n}\n\nfunction sanitizeControlStep<TState, TAction, TActionResult, TEval extends ControlEvalResult>(\n step: ControlStep<TState, TAction, TActionResult, TEval>,\n options: RuntimeTelemetryOptions,\n): Record<string, unknown> {\n const actionOutcome = step.actionOutcome\n return {\n index: step.index,\n decisionType: step.decision.type,\n reason: step.decision.reason,\n action:\n options.includeControlPayloads && step.decision.type === 'continue'\n ? step.decision.action\n : undefined,\n result: options.includeControlPayloads && actionOutcome?.ok ? actionOutcome.result : undefined,\n actionOk: actionOutcome?.ok,\n actionError: actionOutcome?.ok === false ? actionOutcome.error : undefined,\n durationMs: actionOutcome?.durationMs,\n evalsBefore: summarizeEvals(step.evalsBefore, options),\n evalsAfter: summarizeEvals(step.evalsAfter, options),\n startedAt: step.startedAt,\n endedAt: step.endedAt,\n }\n}\n\nfunction sanitizeControlRun<TState, TAction, TActionResult, TEval extends ControlEvalResult>(\n control: ControlRunResult<TState, TAction, TActionResult, TEval>,\n options: RuntimeTelemetryOptions,\n): Record<string, unknown> {\n return {\n pass: control.pass,\n completed: control.completed,\n reason: control.reason,\n score: control.score,\n stepCount: control.steps.length,\n wallMs: control.wallMs,\n spentCostUsd: control.spentCostUsd,\n failureClass: control.failureClass,\n stoppedBy: control.stoppedBy,\n runId: control.runId,\n runtimeErrorCount: control.runtimeErrors.length,\n finalEvals: summarizeEvals(control.finalEvals, options),\n }\n}\n\nfunction summarizeEvals(\n evals: ControlEvalResult[],\n options: RuntimeTelemetryOptions,\n): Array<Record<string, unknown>> {\n return evals.map((evalResult) => ({\n id: evalResult.id,\n passed: evalResult.passed,\n score: evalResult.score,\n severity: evalResult.severity,\n objective: evalResult.objective,\n detail: options.includeEvalDetails ? evalResult.detail : undefined,\n evidence: options.includeEvalDetails ? evalResult.evidence : undefined,\n }))\n}\n\nfunction redactRecord(record: Record<string, string>): Record<string, string> {\n return Object.fromEntries(Object.keys(record).map((key) => [key, '[redacted]']))\n}\n\nfunction pickPublicStreamFields(event: RuntimeStreamEvent): Record<string, unknown> {\n if (event.type === 'session_created' || event.type === 'session_resumed') return {}\n if (event.type === 'backend_start' || event.type === 'backend_end')\n return { backend: event.backend }\n if (event.type === 'backend_error') {\n // `error.body` is the truncated upstream response — it can carry\n // user-visible text (a `free_tier_limit` envelope is safe, but an HTML\n // error page from a misconfigured proxy may echo the request URL with\n // query string). Redact body by default; surface `kind` + `status` so\n // operators can still classify the failure without raw text.\n const sanitizedError =\n event.error !== undefined\n ? {\n kind: event.error.kind,\n status: event.error.status,\n }\n : undefined\n return {\n backend: event.backend,\n message: event.message,\n recoverable: event.recoverable,\n ...(sanitizedError !== undefined ? { error: sanitizedError } : {}),\n }\n }\n if (event.type === 'task_end') return { status: event.status, reason: event.reason }\n if (event.type === 'text_delta' || event.type === 'reasoning_delta') return { text: event.text }\n return {}\n}\n\n/** @stable */\nexport interface RuntimeEventCollector<\n TState = unknown,\n TAction = unknown,\n TActionResult = unknown,\n TEval extends ControlEvalResult = ControlEvalResult,\n> {\n onEvent: (event: AgentRuntimeEvent<TState, TAction, TActionResult, TEval>) => void\n events: Array<Record<string, unknown>>\n}\n\n/** @stable */\nexport type RuntimeStreamEventSink = (event: RuntimeStreamEvent) => void\n\n/** @stable */\nexport interface RuntimeStreamEventSummary {\n /** Total count of sanitized events collected. */\n eventCount: number\n /** Count of events per `type`. Useful for log-line summaries. */\n eventCountsByType: Record<string, number>\n /** First session id observed in a `session_created` / `session_resumed` event, if any. */\n firstSessionId?: string\n /** Last `final` event's status, if a final event was observed. */\n finalStatus?: AgentTaskStatus\n /** Last `final` event's reason, if a final event was observed. */\n finalReason?: string\n /** Concatenated `text_delta.text` across the stream, even when payloads are redacted. */\n finalText: string\n}\n\n/** @stable */\nexport interface RuntimeStreamEventCollector {\n onEvent: RuntimeStreamEventSink\n events: Array<Record<string, unknown>>\n /** Snapshot of a small streaming-flavored summary derived from collected events. */\n summary(): RuntimeStreamEventSummary\n}\n\n/** Build an in-memory collector that sanitizes and accumulates `AgentRuntimeEvent`s for inspection. @stable */\nexport function createRuntimeEventCollector<\n TState = unknown,\n TAction = unknown,\n TActionResult = unknown,\n TEval extends ControlEvalResult = ControlEvalResult,\n>(\n options: RuntimeTelemetryOptions = {},\n): RuntimeEventCollector<TState, TAction, TActionResult, TEval> {\n const events: Array<Record<string, unknown>> = []\n return {\n events,\n onEvent: (event) => {\n events.push(sanitizeAgentRuntimeEvent(event, options))\n },\n }\n}\n\n/**\n *\n * Streaming-event counterpart of `createRuntimeEventCollector`. Pass each\n * event yielded by `runAgentTaskStream` through `onEvent` and read the\n * sanitized copies off `events`; the same `RuntimeTelemetryOptions` redaction\n * flags apply. Kept distinct from `createRuntimeEventCollector` because the\n * stream and non-stream event shapes overlap on `type` literals — dispatching\n * on `type` alone would misroute events.\n *\n * @stable\n */\nexport function createRuntimeStreamEventCollector(\n options: RuntimeTelemetryOptions = {},\n): RuntimeStreamEventCollector {\n const events: Array<Record<string, unknown>> = []\n const eventCountsByType: Record<string, number> = {}\n let firstSessionId: string | undefined\n let finalStatus: AgentTaskStatus | undefined\n let finalReason: string | undefined\n let finalText = ''\n return {\n events,\n onEvent: (event) => {\n events.push(sanitizeRuntimeStreamEvent(event, options))\n eventCountsByType[event.type] = (eventCountsByType[event.type] ?? 0) + 1\n if (event.type === 'text_delta') finalText += event.text\n if (\n !firstSessionId &&\n (event.type === 'session_created' || event.type === 'session_resumed')\n ) {\n firstSessionId = event.session.id\n }\n if (event.type === 'final') {\n finalStatus = event.status\n finalReason = event.reason\n }\n },\n summary() {\n return {\n eventCount: events.length,\n eventCountsByType: { ...eventCountsByType },\n firstSessionId,\n finalStatus,\n finalReason,\n finalText,\n }\n },\n }\n}\n","/**\n *\n * Server-Sent Events serialization for runtime telemetry streams.\n *\n * Newline-safe by construction: any newline in `id` or `event` is collapsed to\n * a space (browsers terminate fields on newline), and multi-line `data`\n * payloads are split into one `data:` line per source line so JSON.stringify\n * output transports cleanly.\n *\n * @stable\n */\n\nimport type { KnowledgeReadinessReport } from '@tangle-network/agent-eval'\nimport type { RuntimeTelemetryOptions } from './sanitize'\nimport { sanitizeKnowledgeReadinessReport, sanitizeRuntimeStreamEvent } from './sanitize'\nimport type { RuntimeStreamEvent } from './types'\n\n/** @stable */\nexport interface ServerSentEventOptions {\n event?: string\n id?: string\n retry?: number\n}\n\n/** @stable */\nexport function encodeServerSentEvent(data: unknown, options: ServerSentEventOptions = {}): string {\n const lines: string[] = []\n if (options.id) lines.push(`id: ${stripNewlines(options.id)}`)\n if (options.event) lines.push(`event: ${stripNewlines(options.event)}`)\n if (typeof options.retry === 'number' && Number.isFinite(options.retry) && options.retry >= 0) {\n lines.push(`retry: ${Math.floor(options.retry)}`)\n }\n\n const payload = typeof data === 'string' ? data : JSON.stringify(data)\n for (const line of payload.split(/\\r?\\n/)) {\n lines.push(`data: ${line}`)\n }\n return `${lines.join('\\n')}\\n\\n`\n}\n\n/** Serialize a `KnowledgeReadinessReport` as a Server-Sent Event string. @stable */\nexport function readinessServerSentEvent(\n report: KnowledgeReadinessReport,\n options: RuntimeTelemetryOptions & ServerSentEventOptions = {},\n): string {\n const { event, id, retry, ...telemetryOptions } = options\n return encodeServerSentEvent(\n {\n type: 'readiness',\n readiness: sanitizeKnowledgeReadinessReport(report, telemetryOptions),\n },\n { event, id, retry },\n )\n}\n\n/** Serialize a `RuntimeStreamEvent` as a Server-Sent Event string. @stable */\nexport function runtimeStreamServerSentEvent(\n event: RuntimeStreamEvent,\n options: RuntimeTelemetryOptions & ServerSentEventOptions = {},\n): string {\n const { event: sseEvent, id, retry, ...telemetryOptions } = options\n return encodeServerSentEvent(sanitizeRuntimeStreamEvent(event, telemetryOptions), {\n event: sseEvent,\n id,\n retry,\n })\n}\n\nfunction stripNewlines(value: string): string {\n return value.replace(/[\\r\\n]/g, ' ')\n}\n","/**\n * Bounded turn-level tool-dispatch loop.\n *\n * `runAgentTaskStream` runs ONE model turn; `runLoop` orchestrates DELEGATED\n * multi-agent topologies (refine / fanout-vote). Neither is the everyday\n * interactive shape: a chat turn where the model may emit tool calls, each is\n * executed, the results are folded back, and the turn re-runs until the model\n * stops (or a turn cap). Every agent app hand-rolls that loop — this is it,\n * as a reusable primitive.\n *\n * Substrate-neutral by design: the caller supplies `streamTurn` (wrapping\n * whatever backend / `runAgentTaskStream` it uses) and `executeToolCall`\n * (routing to its executors). This module owns the LOOP; the caller owns the\n * model and the executors. `Raw` (streaming variant) is the caller's own\n * event type. The only imported contract is the runtime hook type: hooks are\n * execution-scoped observers, not part of the agent profile.\n */\n\nimport type { RuntimeDecisionEvidenceRef, RuntimeHooks } from './runtime-hooks'\nimport { notifyRuntimeDecisionPoint, notifyRuntimeHookEvent } from './runtime-hooks'\n\nexport interface ToolLoopCall {\n toolCallId?: string\n toolName: string\n args: Record<string, unknown>\n}\n\n/** Outcome of one tool dispatch — structurally compatible with a hub/integration\n * tool-outcome union, so callers can fold either through the loop. */\nexport type ToolCallOutcome =\n | { ok: true; result: unknown }\n | { ok: false; code: string; message: string; status?: number }\n\n/** Runaway-backstop: stops an infinite tool loop where cost is unmetered. Set\n * far above any legitimate workflow — this is a watchdog, not a policy cap.\n * Legitimate per-call budgets come from `maxCostUsd` + `costOf`. */\nconst RUNAWAY_BACKSTOP_TURNS = 200\nconst DEFAULT_DECISION_CONTEXT_CHARS = 12_000\nconst FAILURE_RECOVERY_ACTIONS = ['retry', 'verify', 'continue', 'stop']\n/** Consecutive identical calls (same tool + canonical-JSON args) that trigger\n * stuck-loop detection. The window resets on any different call. */\nconst STUCK_LOOP_THRESHOLD = 3\n\n/** One OpenAI-shaped tool-call entry carried on an assistant message. */\nexport interface ToolLoopAssistantToolCall {\n id: string\n type: 'function'\n function: { name: string; arguments: string }\n}\n\n/**\n * A message in the running conversation the loop sends to `streamTurn`.\n *\n * The base `{ role, content }` covers `system` / `user` / plain `assistant`\n * turns. Two optional fields carry the OpenAI function-calling contract so a\n * strict model (Claude, and any OpenAI-compatible provider that validates tool\n * history) reads its own tool use back instead of re-issuing the same call:\n *\n * - an assistant turn that emitted tool calls carries `tool_calls`, and its\n * `content` is `null` when the turn was tool-only;\n * - each tool result is its own `{ role: 'tool', tool_call_id, content }`\n * message keyed to the call that produced it.\n *\n * Widening is additive: a `streamTurn` that reads only `role` + `content` still\n * works; one that forwards the whole message to an OpenAI-compatible endpoint\n * now sends correct tool history.\n */\nexport type ToolLoopMessage = {\n role: string\n content: string | null\n tool_calls?: ToolLoopAssistantToolCall[]\n tool_call_id?: string\n}\n\n/** A tool-call id is required to key a `role: 'tool'` result back to its call.\n * When the model omitted one, derive a stable id from the tool name so the\n * assistant `tool_calls` entry and its `tool` result still match. */\nfunction toolCallId(call: ToolLoopCall): string {\n return call.toolCallId ?? `call_${call.toolName}`\n}\n\n/** The assistant turn that emitted `pending`, in OpenAI shape: text content\n * (null when the turn was tool-only) plus its `tool_calls` array. */\nfunction assistantToolCallMessage(turnText: string, pending: ToolLoopCall[]): ToolLoopMessage {\n return {\n role: 'assistant',\n content: turnText.trim() || null,\n tool_calls: pending.map((call) => ({\n id: toolCallId(call),\n type: 'function',\n function: { name: call.toolName, arguments: JSON.stringify(call.args) },\n })),\n }\n}\n\n/** One `role: 'tool'` result message keyed to its call by `tool_call_id`. */\nfunction toolResultMessage(call: ToolLoopCall, content: string): ToolLoopMessage {\n return { role: 'tool', tool_call_id: toolCallId(call), content }\n}\n\nfunction defaultRender(label: string, outcome: ToolCallOutcome): string {\n if (outcome.ok) return `- ${label} → ok: ${JSON.stringify(outcome.result)}`\n return `- ${label} → failed (${outcome.code}): ${outcome.message}`\n}\n\n// ── Awaitable variant (drain-only callers, tests) ──────────────────────────\n\nexport type ToolLoopEvent =\n | { type: 'text'; text: string }\n | { type: 'tool_call'; call: ToolLoopCall }\n | { type: 'other'; event: unknown }\n\n/** Why the loop stopped. `completed` = model finished naturally; `stuck-loop` =\n * ≥3 consecutive identical tool calls (same tool + args); `backstop` = hit the\n * runaway-backstop cap (200 by default); `deadline` = wall-clock deadlineMs\n * exceeded; `budget` = maxCostUsd exhausted. Non-`completed` stops are infra /\n * resource outcomes — eval scoring must distinguish them from capability failure. */\nexport type ToolLoopStopReason = 'completed' | 'stuck-loop' | 'backstop' | 'deadline' | 'budget'\n\nexport interface ToolLoopResult {\n finalText: string\n toolResults: Array<{ call: ToolLoopCall; label: string; outcome: ToolCallOutcome }>\n turns: number\n stopReason: ToolLoopStopReason\n /** @deprecated Use `stopReason !== 'completed'` instead. */\n cappedOut: boolean\n}\n\nexport interface RunToolLoopOptions {\n systemPrompt: string\n userMessage: string\n priorMessages?: ToolLoopMessage[]\n streamTurn: (messages: ToolLoopMessage[]) => AsyncIterable<ToolLoopEvent>\n executeToolCall: (call: ToolLoopCall) => Promise<ToolCallOutcome>\n isExecutableTool: (toolName: string) => boolean\n /** Runaway-backstop cap. Default 200 — set far above any legitimate workflow.\n * For per-workflow limits, use `maxCostUsd` or `deadlineMs` instead. */\n maxToolTurns?: number\n /** Wall-clock deadline in ms since epoch (Date.now()-based). When exceeded the\n * loop stops with stopReason `deadline`. */\n deadlineMs?: number\n /** Maximum total cost in USD. Requires `costOf` to meter each tool call. */\n maxCostUsd?: number\n /** Return the USD cost of one outcome. Required for `maxCostUsd` to work. */\n costOf?: (call: ToolLoopCall, outcome: ToolCallOutcome) => number\n renderResult?: (label: string, outcome: ToolCallOutcome) => string\n labelFor?: (call: ToolLoopCall) => string\n runId?: string\n scenarioId?: string\n hooks?: RuntimeHooks\n}\n\n/** Run the bounded tool loop and return the final text + every executed tool\n * outcome. Awaitable — callers needing to stream events to a UI use\n * {@link streamToolLoop}. */\nexport async function runToolLoop(opts: RunToolLoopOptions): Promise<ToolLoopResult> {\n const backstop = opts.maxToolTurns ?? RUNAWAY_BACKSTOP_TURNS\n const render = opts.renderResult ?? defaultRender\n const labelFor = opts.labelFor ?? ((c: ToolLoopCall) => c.toolName)\n const runId = opts.runId ?? `agent-run-${randomSuffix()}`\n const messages: ToolLoopMessage[] = [\n { role: 'system', content: opts.systemPrompt },\n ...(opts.priorMessages ?? []),\n { role: 'user', content: opts.userMessage },\n ]\n const observer = createToolLoopObserver(opts.hooks, runId, opts.scenarioId)\n const toolResults: ToolLoopResult['toolResults'] = []\n let finalText = ''\n let turns = 0\n let accumulatedCostUsd = 0\n // Stuck-loop detection: track the last canonical-JSON call signature and how\n // many consecutive times we've seen it.\n let lastCallHash: string | null = null\n let consecutiveCount = 0\n\n observer.loopBefore(backstop, messages.length)\n\n for (let toolTurn = 0; ; toolTurn++) {\n turns++\n\n // Wall-clock deadline check — before every new turn.\n if (opts.deadlineMs !== undefined && Date.now() >= opts.deadlineMs) {\n observer.loopAfter({ turns, toolResults: toolResults.length, stopReason: 'deadline' })\n return { finalText, toolResults, turns, stopReason: 'deadline', cappedOut: true }\n }\n\n let turnText = ''\n const pending: ToolLoopCall[] = []\n const turnEventId = observer.turnBefore(toolTurn, messages.length)\n for await (const ev of opts.streamTurn([...messages])) {\n if (ev.type === 'text') {\n turnText += ev.text\n finalText += ev.text\n } else if (ev.type === 'tool_call' && opts.isExecutableTool(ev.call.toolName)) {\n pending.push(ev.call)\n }\n }\n if (pending.length === 0) {\n observer.turnAfter(toolTurn, turnEventId, {\n pendingToolCalls: 0,\n finalTextChars: finalText.length,\n })\n break\n }\n\n // Runaway backstop — the model keeps emitting calls past the safety ceiling.\n if (toolTurn >= backstop) {\n observer.turnAfter(toolTurn, turnEventId, {\n pendingToolCalls: pending.length,\n stopReason: 'backstop',\n })\n observer.loopAfter({ turns, toolResults: toolResults.length, stopReason: 'backstop' })\n return { finalText, toolResults, turns, stopReason: 'backstop', cappedOut: true }\n }\n\n // The assistant turn that emitted the calls, carrying its tool_calls array,\n // so a strict model reads its own tool use back in OpenAI shape.\n messages.push(assistantToolCallMessage(turnText, pending))\n const outcomes: ExecutedToolCall[] = []\n for (const [callIndex, call] of pending.entries()) {\n // Stuck-loop detection: hash the first pending call each turn (a model\n // stuck in a loop re-issues the same call repeatedly, not alternating calls).\n const callHash = canonicalCallHash(call)\n if (callHash === lastCallHash) {\n consecutiveCount++\n } else {\n lastCallHash = callHash\n consecutiveCount = 1\n }\n if (consecutiveCount >= STUCK_LOOP_THRESHOLD) {\n observer.turnAfter(toolTurn, turnEventId, {\n pendingToolCalls: pending.length,\n stopReason: 'stuck-loop',\n })\n observer.loopAfter({ turns, toolResults: toolResults.length, stopReason: 'stuck-loop' })\n return { finalText, toolResults, turns, stopReason: 'stuck-loop', cappedOut: true }\n }\n\n const callEventId = observer.toolCallBefore(toolTurn, turnEventId, callIndex, call)\n let outcome: ToolCallOutcome\n try {\n outcome = await opts.executeToolCall(call)\n } catch (err) {\n outcome = {\n ok: false,\n code: 'executor_error',\n message: err instanceof Error ? err.message : String(err),\n }\n }\n\n // Budget check after each tool call.\n if (opts.maxCostUsd !== undefined && opts.costOf !== undefined) {\n accumulatedCostUsd += opts.costOf(call, outcome)\n if (accumulatedCostUsd >= opts.maxCostUsd) {\n const label = labelFor(call)\n toolResults.push({ call, label, outcome })\n messages.push(toolResultMessage(call, render(label, outcome)))\n observer.toolCallAfter(toolTurn, callEventId, call, outcome)\n observer.turnAfter(toolTurn, turnEventId, {\n pendingToolCalls: pending.length,\n stopReason: 'budget',\n })\n observer.loopAfter({ turns, toolResults: toolResults.length, stopReason: 'budget' })\n return { finalText, toolResults, turns, stopReason: 'budget', cappedOut: true }\n }\n }\n\n const label = labelFor(call)\n const rendered = render(label, outcome)\n toolResults.push({ call, label, outcome })\n outcomes.push({ call, label, outcome, rendered })\n // One role:'tool' message per result, keyed to its call by tool_call_id.\n messages.push(toolResultMessage(call, rendered))\n observer.toolCallAfter(toolTurn, callEventId, call, outcome)\n }\n observer.failureRecovery({\n toolTurn,\n messages,\n turnText,\n outcomes,\n })\n observer.turnAfter(toolTurn, turnEventId, {\n pendingToolCalls: pending.length,\n toolResults: outcomes.map((item) => ({\n toolName: item.call.toolName,\n toolCallId: item.call.toolCallId,\n ok: item.outcome.ok,\n })),\n failedToolCalls: outcomes.filter((item) => !item.outcome.ok).length,\n })\n }\n observer.loopAfter({ turns, toolResults: toolResults.length, stopReason: 'completed' })\n return { finalText, toolResults, turns, stopReason: 'completed', cappedOut: false }\n}\n\n// ── Streaming variant (SSE chat runtimes + per-event telemetry) ────────────\n\nexport type StreamToolLoopYield<Raw> =\n | { kind: 'event'; event: Raw }\n | {\n kind: 'tool_result'\n toolName: string\n toolCallId?: string\n label: string\n outcome: ToolCallOutcome\n }\n | { kind: 'capped'; pending: number; stopReason: Exclude<ToolLoopStopReason, 'completed'> }\n\nexport interface StreamToolLoopOptions<Raw> {\n systemPrompt: string\n userMessage: string\n priorMessages?: ToolLoopMessage[]\n streamTurn: (messages: ToolLoopMessage[]) => AsyncIterable<Raw>\n extractText: (event: Raw) => string\n extractToolCall: (event: Raw) => ToolLoopCall | null\n isExecutableTool: (toolName: string) => boolean\n executeToolCall: (call: ToolLoopCall) => Promise<ToolCallOutcome>\n /** Runaway-backstop cap. Default 200 — set far above any legitimate workflow. */\n maxToolTurns?: number\n /** Wall-clock deadline in ms since epoch (Date.now()-based). */\n deadlineMs?: number\n /** Maximum total cost in USD. Requires `costOf` to meter each tool call. */\n maxCostUsd?: number\n /** Return the USD cost of one outcome. Required for `maxCostUsd` to work. */\n costOf?: (call: ToolLoopCall, outcome: ToolCallOutcome) => number\n renderResult?: (label: string, outcome: ToolCallOutcome) => string\n labelFor?: (call: ToolLoopCall) => string\n runId?: string\n scenarioId?: string\n hooks?: RuntimeHooks\n}\n\n/** Streaming bounded tool loop: yields each raw turn event (the caller maps +\n * telemetries + re-emits it) and each executed `tool_result`; emits one\n * `capped` if it stops for any non-completed reason with calls still pending. */\nexport async function* streamToolLoop<Raw>(\n opts: StreamToolLoopOptions<Raw>,\n): AsyncGenerator<StreamToolLoopYield<Raw>, void, unknown> {\n const backstop = opts.maxToolTurns ?? RUNAWAY_BACKSTOP_TURNS\n const render = opts.renderResult ?? defaultRender\n const labelFor = opts.labelFor ?? ((c: ToolLoopCall) => c.toolName)\n const runId = opts.runId ?? `agent-run-${randomSuffix()}`\n const messages: ToolLoopMessage[] = [\n { role: 'system', content: opts.systemPrompt },\n ...(opts.priorMessages ?? []),\n { role: 'user', content: opts.userMessage },\n ]\n const observer = createToolLoopObserver(opts.hooks, runId, opts.scenarioId)\n let accumulatedCostUsd = 0\n let lastCallHash: string | null = null\n let consecutiveCount = 0\n\n observer.loopBefore(backstop, messages.length)\n\n for (let toolTurn = 0; ; toolTurn++) {\n // Wall-clock deadline check before every new turn.\n if (opts.deadlineMs !== undefined && Date.now() >= opts.deadlineMs) {\n observer.loopAfter({ turns: toolTurn + 1, stopReason: 'deadline' })\n yield { kind: 'capped', pending: 0, stopReason: 'deadline' }\n return\n }\n\n let turnText = ''\n const pending: ToolLoopCall[] = []\n const turnEventId = observer.turnBefore(toolTurn, messages.length)\n for await (const event of opts.streamTurn([...messages])) {\n yield { kind: 'event', event }\n turnText += opts.extractText(event)\n const call = opts.extractToolCall(event)\n if (call && opts.isExecutableTool(call.toolName)) pending.push(call)\n }\n if (pending.length === 0) {\n observer.turnAfter(toolTurn, turnEventId, { pendingToolCalls: 0 })\n observer.loopAfter({ turns: toolTurn + 1, stopReason: 'completed' })\n return\n }\n\n // Runaway backstop.\n if (toolTurn >= backstop) {\n observer.turnAfter(toolTurn, turnEventId, {\n pendingToolCalls: pending.length,\n stopReason: 'backstop',\n })\n observer.loopAfter({ turns: toolTurn + 1, stopReason: 'backstop' })\n yield { kind: 'capped', pending: pending.length, stopReason: 'backstop' }\n return\n }\n\n // The assistant turn that emitted the calls, carrying its tool_calls array,\n // so a strict model reads its own tool use back in OpenAI shape.\n messages.push(assistantToolCallMessage(turnText, pending))\n const outcomes: ExecutedToolCall[] = []\n for (const [callIndex, call] of pending.entries()) {\n // Stuck-loop detection.\n const callHash = canonicalCallHash(call)\n if (callHash === lastCallHash) {\n consecutiveCount++\n } else {\n lastCallHash = callHash\n consecutiveCount = 1\n }\n if (consecutiveCount >= STUCK_LOOP_THRESHOLD) {\n observer.turnAfter(toolTurn, turnEventId, {\n pendingToolCalls: pending.length,\n stopReason: 'stuck-loop',\n })\n observer.loopAfter({ turns: toolTurn + 1, stopReason: 'stuck-loop' })\n yield { kind: 'capped', pending: pending.length, stopReason: 'stuck-loop' }\n return\n }\n\n const callEventId = observer.toolCallBefore(toolTurn, turnEventId, callIndex, call)\n let outcome: ToolCallOutcome\n try {\n outcome = await opts.executeToolCall(call)\n } catch (err) {\n outcome = {\n ok: false,\n code: 'executor_error',\n message: err instanceof Error ? err.message : String(err),\n }\n }\n\n // Budget check after each tool call.\n if (opts.maxCostUsd !== undefined && opts.costOf !== undefined) {\n accumulatedCostUsd += opts.costOf(call, outcome)\n if (accumulatedCostUsd >= opts.maxCostUsd) {\n const label = labelFor(call)\n yield {\n kind: 'tool_result',\n toolName: call.toolName,\n toolCallId: call.toolCallId,\n label,\n outcome,\n }\n messages.push(toolResultMessage(call, render(label, outcome)))\n observer.toolCallAfter(toolTurn, callEventId, call, outcome)\n observer.turnAfter(toolTurn, turnEventId, {\n pendingToolCalls: pending.length,\n stopReason: 'budget',\n })\n observer.loopAfter({ turns: toolTurn + 1, stopReason: 'budget' })\n yield { kind: 'capped', pending: pending.length, stopReason: 'budget' }\n return\n }\n }\n\n const label = labelFor(call)\n yield {\n kind: 'tool_result',\n toolName: call.toolName,\n toolCallId: call.toolCallId,\n label,\n outcome,\n }\n const rendered = render(label, outcome)\n outcomes.push({ call, label, outcome, rendered })\n // One role:'tool' message per result, keyed to its call by tool_call_id.\n messages.push(toolResultMessage(call, rendered))\n observer.toolCallAfter(toolTurn, callEventId, call, outcome)\n }\n observer.failureRecovery({\n toolTurn,\n messages,\n turnText,\n outcomes,\n })\n observer.turnAfter(toolTurn, turnEventId, {\n pendingToolCalls: pending.length,\n toolResults: outcomes.map((item) => ({\n toolName: item.call.toolName,\n toolCallId: item.call.toolCallId,\n ok: item.outcome.ok,\n })),\n failedToolCalls: outcomes.filter((item) => !item.outcome.ok).length,\n })\n }\n}\n\ninterface ExecutedToolCall {\n call: ToolLoopCall\n label: string\n outcome: ToolCallOutcome\n rendered: string\n}\n\ninterface NotifyToolFailureRecoveryOptions {\n hooks?: RuntimeHooks\n runId: string\n scenarioId?: string\n stepIndex: number\n messages: ToolLoopMessage[]\n turnText: string\n outcomes: ExecutedToolCall[]\n}\n\ninterface NotifyToolLoopEventOptions {\n hooks?: RuntimeHooks\n runId: string\n scenarioId?: string\n target: 'agent.run' | 'agent.turn' | 'agent.tool_call'\n phase: 'before' | 'after' | 'error' | 'event'\n id?: string\n stepIndex?: number\n parentId?: string\n payload?: Record<string, unknown>\n metadata?: Record<string, unknown>\n}\n\ninterface ToolLoopObserver {\n loopBefore(maxToolTurns: number, messageCount: number): void\n loopAfter(payload: Record<string, unknown>): void\n turnBefore(toolTurn: number, messageCount: number): string\n turnAfter(toolTurn: number, turnEventId: string, payload: Record<string, unknown>): void\n toolCallBefore(\n toolTurn: number,\n turnEventId: string,\n callIndex: number,\n call: ToolLoopCall,\n ): string\n toolCallAfter(\n toolTurn: number,\n callEventId: string,\n call: ToolLoopCall,\n outcome: ToolCallOutcome,\n ): void\n failureRecovery(options: {\n toolTurn: number\n messages: ToolLoopMessage[]\n turnText: string\n outcomes: ExecutedToolCall[]\n }): void\n}\n\nfunction createToolLoopObserver(\n hooks: RuntimeHooks | undefined,\n runId: string,\n scenarioId: string | undefined,\n): ToolLoopObserver {\n const loopEventId = `${runId}:agent.run`\n return {\n loopBefore: (maxToolTurns, messageCount) => {\n notifyToolLoopEvent({\n hooks,\n runId,\n scenarioId,\n target: 'agent.run',\n phase: 'before',\n id: `${loopEventId}:before`,\n payload: { maxToolTurns, messageCount },\n })\n },\n loopAfter: (payload) => {\n notifyToolLoopEvent({\n hooks,\n runId,\n scenarioId,\n target: 'agent.run',\n phase: 'after',\n id: `${loopEventId}:after`,\n payload,\n })\n },\n turnBefore: (toolTurn, messageCount) => {\n const turnEventId = `${loopEventId}:${toolTurn}`\n notifyToolLoopEvent({\n hooks,\n runId,\n scenarioId,\n target: 'agent.turn',\n phase: 'before',\n id: turnEventId,\n stepIndex: toolTurn,\n parentId: loopEventId,\n payload: { messageCount },\n })\n return turnEventId\n },\n turnAfter: (toolTurn, turnEventId, payload) => {\n notifyToolLoopEvent({\n hooks,\n runId,\n scenarioId,\n target: 'agent.turn',\n phase: 'after',\n id: `${turnEventId}:after`,\n stepIndex: toolTurn,\n parentId: turnEventId,\n payload,\n })\n },\n toolCallBefore: (toolTurn, turnEventId, callIndex, call) => {\n const callEventId = `${turnEventId}:tool-call:${callIndex}`\n notifyToolLoopEvent({\n hooks,\n runId,\n scenarioId,\n target: 'agent.tool_call',\n phase: 'before',\n id: callEventId,\n stepIndex: toolTurn,\n parentId: turnEventId,\n payload: toolCallPayload(call),\n })\n return callEventId\n },\n toolCallAfter: (toolTurn, callEventId, call, outcome) => {\n notifyToolLoopEvent({\n hooks,\n runId,\n scenarioId,\n target: 'agent.tool_call',\n phase: 'after',\n id: `${callEventId}:after`,\n stepIndex: toolTurn,\n parentId: callEventId,\n payload: { ...toolCallPayload(call), outcome: outcomePayload(outcome) },\n })\n },\n failureRecovery: (options) => {\n notifyToolFailureRecovery({\n hooks,\n runId,\n scenarioId,\n stepIndex: options.toolTurn,\n messages: options.messages,\n turnText: options.turnText,\n outcomes: options.outcomes,\n })\n },\n }\n}\n\nfunction notifyToolLoopEvent(options: NotifyToolLoopEventOptions): void {\n notifyRuntimeHookEvent(options.hooks, {\n id: options.id ?? `${options.runId}:${options.target}:${options.phase}`,\n runId: options.runId,\n scenarioId: options.scenarioId,\n target: options.target,\n phase: options.phase,\n timestamp: Date.now(),\n stepIndex: options.stepIndex,\n parentId: options.parentId,\n payload: options.payload,\n metadata: { producer: 'tool-loop', ...options.metadata },\n })\n}\n\nfunction notifyToolFailureRecovery(options: NotifyToolFailureRecoveryOptions): void {\n const failed = options.outcomes.filter((item) => !item.outcome.ok)\n if (failed.length === 0) return\n\n const evidence: RuntimeDecisionEvidenceRef[] = []\n for (const item of failed) {\n const id = item.call.toolCallId ?? `${options.stepIndex}:${item.label}`\n evidence.push({\n source: 'tool_call',\n id,\n detail: `${item.call.toolName} ${stringifySafe(item.call.args, 2_000)}`,\n metadata: { toolName: item.call.toolName, label: item.label },\n })\n evidence.push({\n source: 'tool_result',\n id: `${id}:result`,\n detail: item.rendered,\n metadata: failureMetadata(item.outcome),\n })\n }\n\n notifyRuntimeDecisionPoint(options.hooks, {\n id: `${options.runId}:agent.turn:${options.stepIndex}:failure-recovery`,\n runId: options.runId,\n scenarioId: options.scenarioId,\n stepIndex: options.stepIndex,\n kind: 'retry',\n candidateActions: [...FAILURE_RECOVERY_ACTIONS],\n context: renderDecisionContext(options.messages, options.turnText, options.outcomes),\n evidence,\n metadata: {\n target: 'failure-recovery',\n source: 'agent.turn',\n failedToolCount: failed.length,\n toolNames: failed.map((item) => item.call.toolName),\n },\n })\n}\n\nfunction toolCallPayload(call: ToolLoopCall): Record<string, unknown> {\n return {\n toolName: call.toolName,\n toolCallId: call.toolCallId,\n argsPreview: stringifySafe(call.args, 2_000),\n }\n}\n\nfunction outcomePayload(outcome: ToolCallOutcome): Record<string, unknown> {\n if (!outcome.ok) {\n return {\n ok: false,\n code: outcome.code,\n message: trimText(outcome.message, 2_000),\n status: outcome.status,\n }\n }\n return {\n ok: true,\n resultPreview: stringifySafe(outcome.result, 2_000),\n }\n}\n\nfunction failureMetadata(outcome: ToolCallOutcome): Record<string, unknown> | undefined {\n if (outcome.ok) return undefined\n return {\n code: outcome.code,\n message: outcome.message,\n status: outcome.status,\n }\n}\n\nfunction renderDecisionContext(\n messages: ToolLoopMessage[],\n turnText: string,\n outcomes: ExecutedToolCall[],\n): string {\n const recent = messages.slice(-6).map((message) => `[${message.role}]\\n${message.content ?? ''}`)\n const assistant = turnText.trim() ? [`[assistant]\\n${turnText}`] : []\n const toolResults = [`[tool results]\\n${outcomes.map((item) => item.rendered).join('\\n')}`]\n return trimText(\n [...recent, ...assistant, ...toolResults].join('\\n\\n'),\n DEFAULT_DECISION_CONTEXT_CHARS,\n )\n}\n\n/** Canonical identifier for a tool call used by stuck-loop detection.\n * Keys are sorted so `{b:1,a:2}` and `{a:2,b:1}` produce the same hash. */\nfunction canonicalCallHash(call: ToolLoopCall): string {\n const sortedArgs = Object.fromEntries(\n Object.entries(call.args).sort(([a], [b]) => a.localeCompare(b)),\n )\n return `${call.toolName}:${JSON.stringify(sortedArgs)}`\n}\n\nfunction stringifySafe(value: unknown, max: number): string {\n let text: string\n try {\n text = JSON.stringify(value) ?? String(value)\n } catch {\n text = String(value)\n }\n return trimText(text, max)\n}\n\nfunction trimText(text: string, max: number): string {\n if (text.length <= max) return text\n return `${text.slice(0, max)}…`\n}\n\nfunction randomSuffix(len = 8): string {\n return Math.random()\n .toString(36)\n .slice(2, 2 + len)\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA0CO,IAAM,mBAAN,cAA+B,MAAM;AAAA,EAC1C,YAAY,aAAqB,cAAsB;AACrD;AAAA,MACE,iCAAiC,WAAW,MAAM,YAAY;AAAA,IAChE;AACA,SAAK,OAAO;AAAA,EACd;AACF;AAGO,IAAM,wBAAN,cAAoC,MAAM;AAAA,EAC/C,YAAY,YAAoB;AAC9B,UAAM,iDAAiD,UAAU,IAAI;AACrE,SAAK,OAAO;AAAA,EACd;AACF;AAOO,IAAM,qBAA8C,CAAC,QAAQ;AAClE,MAAI,eAAe,sBAAuB,QAAO;AACjD,MAAI,eAAe,OAAO;AACxB,UAAM,OAAO,IAAI;AACjB,UAAM,UAAU,IAAI,QAAQ,YAAY;AACxC,QAAI,SAAS,gBAAgB,SAAS,eAAgB,QAAO;AAC7D,QACE,QAAQ,SAAS,YAAY,KAC7B,QAAQ,SAAS,WAAW,KAC5B,QAAQ,SAAS,cAAc,KAC/B,QAAQ,SAAS,gBAAgB,KACjC,Q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AG,QAAQ,GAAG,WAAW,GAAG,WAAW,EAAE,KAAK,MAAM;AAAA,IACrD;AAAA,EACF;AACF;AAIA,SAAS,kBAAkB,MAA4B;AACrD,QAAM,aAAa,OAAO;AAAA,IACxB,OAAO,QAAQ,KAAK,IAAI,EAAE,KAAK,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,MAAM,EAAE,cAAc,CAAC,CAAC;AAAA,EACjE;AACA,SAAO,GAAG,KAAK,QAAQ,IAAI,KAAK,UAAU,UAAU,CAAC;AACvD;AAEA,SAAS,cAAc,OAAgB,KAAqB;AAC1D,MAAI;AACJ,MAAI;AACF,WAAO,KAAK,UAAU,KAAK,KAAK,OAAO,KAAK;AAAA,EAC9C,QAAQ;AACN,WAAO,OAAO,KAAK;AAAA,EACrB;AACA,SAAO,SAAS,MAAM,GAAG;AAC3B;AAEA,SAAS,SAAS,MAAc,KAAqB;AACnD,MAAI,KAAK,UAAU,IAAK,QAAO;AAC/B,SAAO,GAAG,KAAK,MAAM,GAAG,GAAG,CAAC;AAC9B;AAEA,SAASD,cAAa,MAAM,GAAW;AACrC,SAAO,KAAK,OAAO,EAChB,SAAS,EAAE,EACX,MAAM,GAAG,IAAI,GAAG;AACrB;","names":["resolve","emit","randomSuffix","label"]}
1
+ {"version":3,"sources":["../src/candidate-execution/claim.ts","../src/candidate-execution/claim-file-formats.ts","../src/candidate-execution/claim-terminal.ts","../src/candidate-execution/digest.ts","../src/candidate-execution/exact-object.ts","../src/candidate-execution/cleanup.ts","../src/candidate-execution/execution-window.ts","../src/candidate-execution/prepared-state.ts","../src/candidate-execution/artifacts.ts","../src/candidate-execution/git-materialize.ts","../src/candidate-execution/types.ts","../src/candidate-execution/claim-plan.ts","../src/candidate-execution/claim-file-store.ts","../src/candidate-execution/model-settlement.ts","../src/candidate-execution/dispose.ts","../src/candidate-execution/executor-capture.ts","../src/candidate-execution/finalize.ts","../src/candidate-execution/output-artifacts.ts","../src/candidate-execution/protected-redaction.ts","../src/candidate-execution/outcome-evidence.ts","../src/candidate-execution/benchmark-grader.ts","../src/candidate-execution/protected-trace-store.ts","../src/candidate-execution/execute.ts","../src/candidate-execution/prepare.ts","../src/candidate-execution/verify.ts","../src/candidate-execution/protected-model-port.ts","../src/candidate-execution/recover.ts","../src/conversation/call-policy.ts","../src/conversation/headers.ts","../src/conversation/turn-id.ts","../src/conversation/run-conversation.ts","../src/conversation/conversation-backend.ts","../src/conversation/define-conversation.ts","../src/conversation/journal.ts","../src/conversation/journal-sql.ts","../src/conversation/run-persona.ts","../src/durable/chat-engine.ts","../src/durable/execution-handle.ts","../src/improvement/improve.ts","../src/improvement/improvement-driver.ts","../src/improvement/raw-trace-distiller.ts","../src/improvement/rollout-policy.ts","../src/improvement/reflective-generator.ts","../src/readiness.ts","../src/resolve-agent-backend.ts","../src/run.ts","../src/runtime-run.ts","../src/sanitize.ts","../src/sse.ts","../src/tool-loop.ts"],"sourcesContent":["/** Durable one-shot lifecycle for candidate execution attempts. */\n\nimport { createHash, randomBytes, timingSafeEqual } from 'node:crypto'\nimport { readFile } from 'node:fs/promises'\nimport {\n type AgentCandidateArtifactRef,\n type AgentCandidateAttemptPolicy,\n type AgentCandidateResolvedModel,\n agentCandidateResolvedModelSchema,\n type Sha256Digest,\n} from '@tangle-network/agent-interface'\nimport {\n CLAIM_FORMAT_VERSION,\n PENDING_FORMAT_VERSION,\n type PersistedAgentCandidateExecutionClaim,\n type PersistedAgentCandidateExecutionPending,\n type PersistedAgentCandidateExecutionPhase,\n type PersistedAgentCandidateExecutionTerminal,\n PHASE_FORMAT_VERSION,\n TERMINAL_FORMAT_VERSION,\n} from './claim-file-formats'\nimport {\n assertRecoveryMatchesStaged,\n assertTerminalAllowedInPhase,\n assertTerminalMatchesClaim,\n recoveredTerminalRecord,\n rejectedFinish,\n rejectedStage,\n requireStagedTerminal,\n sealTerminalDigest,\n sealTerminalRecordValue,\n terminalRecord,\n} from './claim-terminal'\nimport { candidateCleanupTimeout, candidateResultTimeout } from './cleanup'\nimport { canonicalCandidateDigest, immutableCandidateValue } from './digest'\nimport { assertExactObjectKeys as assertExactKeys } from './exact-object'\n\n/** Non-secret identities a trusted recovery worker needs to close an abandoned attempt. */\nexport interface AgentCandidateExecutionCleanupHandles {\n readonly preparationId: string\n readonly modelGrantDigest: Sha256Digest\n readonly resolvedModel: AgentCandidateResolvedModel\n readonly traceRunId: string\n readonly cleanupTimeoutMs: number\n readonly memory?: {\n readonly accessDigest: Sha256Digest\n readonly effectiveNamespace: string\n }\n}\n\n/** Immutable signed identity stored for one execution attempt. */\nexport interface AgentCandidateExecutionClaim {\n readonly executionId: string\n readonly attempt: number\n readonly maxAttempts: number\n readonly retryPolicy: AgentCandidateAttemptPolicy['retryPolicy']\n readonly bundleDigest: Sha256Digest\n readonly executionPlanDigest: Sha256Digest\n /** Frozen plan identity with only attempt number and per-attempt grant identity normalized. */\n readonly retryLineageDigest: Sha256Digest\n /** The winning lease stops authorizing a new terminal write at this instant. */\n readonly leaseExpiresAtMs: number\n /** Frozen budget for task verification, executable grading, and receipt construction. */\n readonly resultTimeoutMs: number\n /** Non-secret handles retained so an expired attempt can be closed and reconciled. */\n readonly cleanup: AgentCandidateExecutionCleanupHandles\n}\n\n/** Secret capability required to finish the acquired attempt. */\nexport interface AgentCandidateExecutionLease {\n readonly executionId: string\n readonly attempt: number\n readonly token: string\n readonly expiresAtMs: number\n}\n\n/** Only the first class is retryable, and only when the closed model ledger has zero calls. */\nexport type AgentCandidateExecutionFailureClass =\n | 'pre-model-infrastructure'\n | 'execution'\n | 'post-model-infrastructure'\n | 'unknown'\n\n/** Exact fixed-point usage proven by the closed evaluator model ledger. */\nexport interface AgentCandidateExecutionUsage {\n readonly costUsdNanos: number\n readonly inputTokens: number\n readonly outputTokens: number\n readonly cachedInputTokens: number\n readonly reasoningTokens: number\n readonly modelCalls: number\n}\n\n/** Evaluator-owned terminal facts staged durably before the terminal CAS. */\nexport type AgentCandidateExecutionTerminalResult =\n | {\n readonly schemaVersion: 1\n readonly status: 'succeeded'\n readonly usage: AgentCandidateExecutionUsage\n readonly modelSettlement: AgentCandidateArtifactRef\n readonly taskOutcome: AgentCandidateArtifactRef\n readonly benchmarkResult: AgentCandidateArtifactRef\n readonly runReceipt: AgentCandidateArtifactRef\n }\n | {\n readonly schemaVersion: 1\n readonly status: 'failed'\n readonly failureClass: AgentCandidateExecutionFailureClass\n readonly usage: AgentCandidateExecutionUsage\n readonly modelSettlement: AgentCandidateArtifactRef\n readonly failureEvidence?: AgentCandidateArtifactRef\n }\n\n/** Durable terminal record for one acquired execution attempt. */\nexport type AgentCandidateExecutionTerminalRecord = AgentCandidateExecutionTerminalResult & {\n readonly executionId: string\n readonly attempt: number\n readonly bundleDigest: Sha256Digest\n readonly executionPlanDigest: Sha256Digest\n /** RFC 8785 SHA-256 of this record with `terminalDigest` omitted. */\n readonly terminalDigest: Sha256Digest\n}\n\n/** Monotonic durable phase: the second value means candidate code could have started. */\nexport type AgentCandidateExecutionPhase = 'claimed' | 'candidate-may-run'\n\n/** Trusted, independently observed closure facts for one expired winning lease. */\nexport interface AgentCandidateExecutionRecoveryEvidence {\n readonly failureClass: AgentCandidateExecutionFailureClass\n readonly usage: AgentCandidateExecutionUsage\n readonly modelSettlement: AgentCandidateArtifactRef\n readonly failureEvidence?: AgentCandidateArtifactRef\n readonly process: {\n readonly stopped: true\n readonly executionPlanDigest: Sha256Digest\n }\n readonly model: {\n readonly closed: true\n readonly preparationId: string\n readonly grantDigest: Sha256Digest\n }\n readonly memory?: {\n readonly closed: true\n readonly preparationId: string\n readonly accessDigest: Sha256Digest\n readonly effectiveNamespace: string\n }\n}\n\nexport interface AgentCandidateExecutionAttemptRef {\n readonly executionId: string\n readonly attempt: number\n}\n\n/** Persisted state available to a fresh trusted recovery worker after a crash. */\nexport interface AgentCandidateExecutionAttemptRecord {\n readonly claim: AgentCandidateExecutionClaim\n readonly phase: AgentCandidateExecutionPhase\n /** Durable outbox content written before the terminal compare-and-set. */\n readonly staged?: AgentCandidateExecutionTerminalRecord\n readonly terminal?: AgentCandidateExecutionTerminalRecord\n}\n\n/** Result of atomically claiming one execution attempt. */\nexport type AgentCandidateExecutionClaimResult =\n | {\n readonly acquired: true\n readonly claim: AgentCandidateExecutionClaim\n readonly lease: AgentCandidateExecutionLease\n }\n | {\n readonly acquired: false\n readonly reason: 'already-claimed'\n /** The durable winner already occupying this execution-attempt slot. */\n readonly claim: AgentCandidateExecutionClaim\n /** True only when every signed claim field matches the durable winner. */\n readonly exactReplay: boolean\n }\n | {\n readonly acquired: false\n readonly reason: 'retry-not-eligible'\n readonly claim: AgentCandidateExecutionClaim\n readonly detail: AgentCandidateRetryRejection\n }\n\n/** Result of atomically recording an attempt's terminal facts. */\nexport type AgentCandidateExecutionFinishResult =\n | {\n readonly finished: true\n readonly terminal: AgentCandidateExecutionTerminalRecord\n }\n | {\n readonly finished: false\n readonly terminal: AgentCandidateExecutionTerminalRecord\n /** True when a repeated finish supplied the same terminal digest. */\n readonly exactReplay: boolean\n }\n\n/** Result of durably staging the one immutable terminal outbox entry. */\nexport type AgentCandidateExecutionStageResult =\n | {\n readonly staged: true\n readonly terminal: AgentCandidateExecutionTerminalRecord\n }\n | {\n readonly staged: false\n readonly terminal: AgentCandidateExecutionTerminalRecord\n readonly exactReplay: boolean\n }\n\n/** Result of crossing the irreversible candidate-may-run boundary. */\nexport type AgentCandidateExecutionPhaseResult =\n | { readonly marked: true; readonly phase: 'candidate-may-run' }\n | { readonly marked: false; readonly phase: 'candidate-may-run' }\n\nexport type AgentCandidateRetryRejection =\n | 'prior-attempt-missing'\n | 'prior-attempt-running'\n | 'prior-attempt-succeeded'\n | 'prior-attempt-spent-model-calls'\n | 'prior-attempt-not-pre-model-infrastructure'\n | 'retry-lineage-mismatch'\n\n/**\n * Atomic one-shot store for candidate execution attempts.\n *\n * Implementations must linearize both methods across every process sharing the\n * store. Terminal publication is deliberately two-step: `stageTerminal`\n * fsyncs the complete immutable outbox record, then `finish` publishes exactly\n * those staged bytes by digest. A crash between the two leaves recoverable\n * evidence rather than an ambiguous completed run.\n */\nexport interface AgentCandidateExecutionClaimStore {\n tryClaim(claim: AgentCandidateExecutionClaim): Promise<AgentCandidateExecutionClaimResult>\n getAttempt(\n attempt: AgentCandidateExecutionAttemptRef,\n ): Promise<AgentCandidateExecutionAttemptRecord | undefined>\n /** Persist the point after which candidate code may have run. */\n markCandidateMayRun(\n lease: AgentCandidateExecutionLease,\n ): Promise<AgentCandidateExecutionPhaseResult>\n /** Fsync the complete terminal record into the durable outbox. */\n stageTerminal(\n lease: AgentCandidateExecutionLease,\n result: AgentCandidateExecutionTerminalResult,\n ): Promise<AgentCandidateExecutionStageResult>\n /** Publish exactly the staged terminal identified by `terminalDigest`. */\n finish(\n lease: AgentCandidateExecutionLease,\n terminalDigest: Sha256Digest,\n ): Promise<AgentCandidateExecutionFinishResult>\n /**\n * Write a failed terminal only after the lease expired and a trusted worker\n * independently proved process death plus model and memory closure.\n */\n recoverExpired(\n attempt: AgentCandidateExecutionAttemptRef,\n evidence: AgentCandidateExecutionRecoveryEvidence,\n ): Promise<AgentCandidateExecutionFinishResult>\n}\n\ninterface StoredClaim {\n claim: AgentCandidateExecutionClaim\n leaseDigest: Sha256Digest\n phase: AgentCandidateExecutionPhase\n staged?: AgentCandidateExecutionTerminalRecord\n terminal?: AgentCandidateExecutionTerminalRecord\n}\n\nfunction attemptRecord(\n claim: AgentCandidateExecutionClaim,\n phase: AgentCandidateExecutionPhase,\n staged?: AgentCandidateExecutionTerminalRecord,\n terminal?: AgentCandidateExecutionTerminalRecord,\n): AgentCandidateExecutionAttemptRecord {\n return Object.freeze({\n claim,\n phase,\n ...(staged ? { staged } : {}),\n ...(terminal ? { terminal } : {}),\n })\n}\n\nexport interface InMemoryAgentCandidateExecutionClaimStoreOptions {\n /** Testable evaluator clock; defaults to `Date.now`. */\n now?: () => number\n}\n\n/** Single-process lifecycle implementation. */\nexport class InMemoryAgentCandidateExecutionClaimStore\n implements AgentCandidateExecutionClaimStore\n{\n private readonly claims = new Map<string, StoredClaim>()\n private readonly now: () => number\n\n constructor(options: InMemoryAgentCandidateExecutionClaimStoreOptions = {}) {\n this.now = options.now ?? Date.now\n }\n\n async tryClaim(\n requested: AgentCandidateExecutionClaim,\n ): Promise<AgentCandidateExecutionClaimResult> {\n const claim = sealClaim(requested)\n const slot = claimSlot(claim)\n const existing = this.claims.get(slot)\n if (existing) return rejectedExistingClaim(existing.claim, claim)\n assertUnexpiredLease(claim.leaseExpiresAtMs, this.now())\n\n const retryRejection = retryRejectionFromMemory(this.claims, claim)\n if (retryRejection) return rejectedRetry(claim, retryRejection)\n\n const lease = newLease(claim)\n // No await may occur between the read and write: this is the linearization\n // point for every caller sharing this store instance.\n this.claims.set(slot, {\n claim,\n leaseDigest: leaseDigest(lease),\n phase: 'claimed',\n })\n return Object.freeze({ acquired: true, claim, lease })\n }\n\n async getAttempt(\n requestedAttempt: AgentCandidateExecutionAttemptRef,\n ): Promise<AgentCandidateExecutionAttemptRecord | undefined> {\n const attempt = sealAttemptRef(requestedAttempt)\n const stored = this.claims.get(claimSlot(attempt))\n return stored\n ? attemptRecord(stored.claim, stored.phase, stored.staged, stored.terminal)\n : undefined\n }\n\n async markCandidateMayRun(\n requestedLease: AgentCandidateExecutionLease,\n ): Promise<AgentCandidateExecutionPhaseResult> {\n const lease = sealLease(requestedLease)\n const stored = this.requireClaim(lease)\n assertLease(stored.leaseDigest, stored.claim.leaseExpiresAtMs, lease)\n if (stored.phase === 'candidate-may-run') {\n return Object.freeze({ marked: false, phase: 'candidate-may-run' })\n }\n if (stored.staged || stored.terminal) {\n throw new Error('candidate execution terminal was staged before candidate-may-run phase')\n }\n assertUnexpiredLease(stored.claim.leaseExpiresAtMs, this.now())\n stored.phase = 'candidate-may-run'\n return Object.freeze({ marked: true, phase: 'candidate-may-run' })\n }\n\n async stageTerminal(\n requestedLease: AgentCandidateExecutionLease,\n result: AgentCandidateExecutionTerminalResult,\n ): Promise<AgentCandidateExecutionStageResult> {\n const lease = sealLease(requestedLease)\n const stored = this.requireClaim(lease)\n assertLease(stored.leaseDigest, stored.claim.leaseExpiresAtMs, lease)\n const terminal = terminalRecord(stored.claim, result)\n if (stored.staged) return rejectedStage(stored.staged, terminal)\n assertTerminalAllowedInPhase(stored.phase, terminal)\n assertUnexpiredLease(stored.claim.leaseExpiresAtMs, this.now())\n stored.staged = terminal\n return Object.freeze({ staged: true, terminal })\n }\n\n async finish(\n requestedLease: AgentCandidateExecutionLease,\n requestedTerminalDigest: Sha256Digest,\n ): Promise<AgentCandidateExecutionFinishResult> {\n const lease = sealLease(requestedLease)\n const terminalDigest = sealTerminalDigest(requestedTerminalDigest)\n const stored = this.requireClaim(lease)\n assertLease(stored.leaseDigest, stored.claim.leaseExpiresAtMs, lease)\n const staged = requireStagedTerminal(stored.staged, terminalDigest)\n if (stored.terminal) return rejectedFinish(stored.terminal, terminalDigest)\n assertUnexpiredLease(stored.claim.leaseExpiresAtMs, this.now())\n\n // The terminal assignment is the in-memory finish linearization point and\n // publishes the exact immutable object already present in the outbox.\n stored.terminal = staged\n return Object.freeze({ finished: true, terminal: staged })\n }\n\n async recoverExpired(\n requestedAttempt: AgentCandidateExecutionAttemptRef,\n evidence: AgentCandidateExecutionRecoveryEvidence,\n ): Promise<AgentCandidateExecutionFinishResult> {\n const attempt = sealAttemptRef(requestedAttempt)\n const stored = this.requireClaim(attempt, 'candidate execution recovery')\n const recovered = recoveredTerminalRecord(stored.claim, stored.phase, evidence)\n if (stored.staged) assertRecoveryMatchesStaged(stored.staged, recovered)\n const requestedDigest = stored.staged?.terminalDigest ?? recovered.terminalDigest\n if (stored.terminal) return rejectedFinish(stored.terminal, requestedDigest)\n assertExpiredLease(stored.claim.leaseExpiresAtMs, this.now())\n const terminal = stored.staged ?? recovered\n assertRecoveryMatchesStaged(terminal, recovered)\n stored.staged ??= terminal\n stored.terminal = terminal\n return Object.freeze({ finished: true, terminal })\n }\n\n private requireClaim(\n attempt: Pick<AgentCandidateExecutionLease, 'executionId' | 'attempt'>,\n operation = 'candidate execution lease',\n ): StoredClaim {\n const stored = this.claims.get(claimSlot(attempt))\n if (!stored) throw new Error(`${operation} does not name an acquired attempt`)\n return stored\n }\n}\n\nconst SHA256_PATTERN = /^sha256:[a-f0-9]{64}$/\nconst LEASE_TOKEN_PATTERN = /^candidate-execution-lease-v1\\.[A-Za-z0-9_-]{43}$/\nconst PREPARATION_ID_PATTERN = /^candidate-preparation-v1\\.[A-Za-z0-9_-]{43}$/\n\nfunction sealClaim(claim: AgentCandidateExecutionClaim): AgentCandidateExecutionClaim {\n assertExactKeys(\n claim,\n [\n 'executionId',\n 'attempt',\n 'maxAttempts',\n 'retryPolicy',\n 'bundleDigest',\n 'executionPlanDigest',\n 'retryLineageDigest',\n 'leaseExpiresAtMs',\n 'resultTimeoutMs',\n 'cleanup',\n ],\n 'candidate execution claim',\n )\n assertExecutionId(claim.executionId)\n if (!Number.isSafeInteger(claim.attempt) || claim.attempt < 1) {\n throw new Error('candidate execution claim attempt must be a positive safe integer')\n }\n if (!Number.isSafeInteger(claim.maxAttempts) || claim.maxAttempts < 1) {\n throw new Error('candidate execution claim maxAttempts must be a positive safe integer')\n }\n if (claim.attempt > claim.maxAttempts) {\n throw new Error('candidate execution claim attempt exceeds maxAttempts')\n }\n if (!['none', 'pre-model-infrastructure-only'].includes(claim.retryPolicy)) {\n throw new Error('candidate execution claim retryPolicy is invalid')\n }\n if (claim.retryPolicy === 'none' && claim.maxAttempts !== 1) {\n throw new Error('candidate execution claim retryPolicy none requires maxAttempts 1')\n }\n assertSha256Digest(claim.bundleDigest, 'bundleDigest')\n assertSha256Digest(claim.executionPlanDigest, 'executionPlanDigest')\n assertSha256Digest(claim.retryLineageDigest, 'retryLineageDigest')\n assertPositiveTimestamp(claim.leaseExpiresAtMs, 'leaseExpiresAtMs')\n candidateResultTimeout(claim.resultTimeoutMs, claim.resultTimeoutMs)\n const cleanup = sealCleanupHandles(claim.cleanup)\n return Object.freeze({\n executionId: claim.executionId,\n attempt: claim.attempt,\n maxAttempts: claim.maxAttempts,\n retryPolicy: claim.retryPolicy,\n bundleDigest: claim.bundleDigest,\n executionPlanDigest: claim.executionPlanDigest,\n retryLineageDigest: claim.retryLineageDigest,\n leaseExpiresAtMs: claim.leaseExpiresAtMs,\n resultTimeoutMs: claim.resultTimeoutMs,\n cleanup,\n })\n}\n\nfunction sealCleanupHandles(\n cleanup: AgentCandidateExecutionCleanupHandles,\n): AgentCandidateExecutionCleanupHandles {\n assertExactKeys(\n cleanup,\n cleanup.memory\n ? [\n 'preparationId',\n 'modelGrantDigest',\n 'resolvedModel',\n 'traceRunId',\n 'cleanupTimeoutMs',\n 'memory',\n ]\n : ['preparationId', 'modelGrantDigest', 'resolvedModel', 'traceRunId', 'cleanupTimeoutMs'],\n 'candidate execution cleanup handles',\n )\n if (!PREPARATION_ID_PATTERN.test(cleanup.preparationId)) {\n throw new Error('candidate execution cleanup preparationId is invalid')\n }\n assertSha256Digest(cleanup.modelGrantDigest, 'cleanup modelGrantDigest')\n const resolvedModel = immutableCandidateValue(\n agentCandidateResolvedModelSchema.parse(cleanup.resolvedModel),\n )\n assertBoundedIdentifier(cleanup.traceRunId, 'cleanup traceRunId', 512)\n const cleanupTimeoutMs = candidateCleanupTimeout(cleanup.cleanupTimeoutMs)\n const memory = cleanup.memory ? sealMemoryCleanupHandle(cleanup.memory) : undefined\n return Object.freeze({\n preparationId: cleanup.preparationId,\n modelGrantDigest: cleanup.modelGrantDigest,\n resolvedModel,\n traceRunId: cleanup.traceRunId,\n cleanupTimeoutMs,\n ...(memory ? { memory } : {}),\n })\n}\n\nfunction sealMemoryCleanupHandle(\n memory: NonNullable<AgentCandidateExecutionCleanupHandles['memory']>,\n): NonNullable<AgentCandidateExecutionCleanupHandles['memory']> {\n assertExactKeys(\n memory,\n ['accessDigest', 'effectiveNamespace'],\n 'candidate execution memory cleanup handle',\n )\n assertSha256Digest(memory.accessDigest, 'memory accessDigest')\n assertBoundedIdentifier(memory.effectiveNamespace, 'memory effectiveNamespace', 1_024)\n return Object.freeze({\n accessDigest: memory.accessDigest,\n effectiveNamespace: memory.effectiveNamespace,\n })\n}\n\nfunction sealAttemptRef(\n attempt: AgentCandidateExecutionAttemptRef,\n): AgentCandidateExecutionAttemptRef {\n assertExactKeys(attempt, ['executionId', 'attempt'], 'candidate execution attempt reference')\n assertExecutionId(attempt.executionId)\n if (!Number.isSafeInteger(attempt.attempt) || attempt.attempt < 1) {\n throw new Error('candidate execution attempt reference must have a positive safe attempt')\n }\n return Object.freeze({ executionId: attempt.executionId, attempt: attempt.attempt })\n}\n\nfunction sealLease(lease: AgentCandidateExecutionLease): AgentCandidateExecutionLease {\n assertExactKeys(\n lease,\n ['executionId', 'attempt', 'token', 'expiresAtMs'],\n 'candidate execution lease',\n )\n if (lease.executionId.length === 0 || !Number.isSafeInteger(lease.attempt) || lease.attempt < 1) {\n throw new Error('candidate execution lease identity is invalid')\n }\n if (!LEASE_TOKEN_PATTERN.test(lease.token)) {\n throw new Error('candidate execution lease token is invalid')\n }\n assertPositiveTimestamp(lease.expiresAtMs, 'lease expiresAtMs')\n return Object.freeze({\n executionId: lease.executionId,\n attempt: lease.attempt,\n token: lease.token,\n expiresAtMs: lease.expiresAtMs,\n })\n}\n\nfunction newLease(claim: AgentCandidateExecutionClaim): AgentCandidateExecutionLease {\n return Object.freeze({\n executionId: claim.executionId,\n attempt: claim.attempt,\n token: `candidate-execution-lease-v1.${randomBytes(32).toString('base64url')}`,\n expiresAtMs: claim.leaseExpiresAtMs,\n })\n}\n\nfunction leaseDigest(lease: AgentCandidateExecutionLease): Sha256Digest {\n return sha256(lease.token)\n}\n\nfunction assertLease(\n expectedDigest: Sha256Digest,\n expectedExpiresAtMs: number,\n lease: AgentCandidateExecutionLease,\n): void {\n const expected = Buffer.from(expectedDigest)\n const actual = Buffer.from(leaseDigest(lease))\n if (\n expected.length !== actual.length ||\n !timingSafeEqual(expected, actual) ||\n lease.expiresAtMs !== expectedExpiresAtMs\n ) {\n throw new Error('candidate execution lease is invalid')\n }\n}\n\nfunction claimSlot(claim: Pick<AgentCandidateExecutionClaim, 'executionId' | 'attempt'>): string {\n return createHash('sha256')\n .update(JSON.stringify([claim.executionId, claim.attempt]), 'utf8')\n .digest('hex')\n}\n\nfunction retryRejectionFromMemory(\n claims: ReadonlyMap<string, StoredClaim>,\n claim: AgentCandidateExecutionClaim,\n): AgentCandidateRetryRejection | undefined {\n if (claim.attempt === 1) return undefined\n const prior = claims.get(\n claimSlot({ executionId: claim.executionId, attempt: claim.attempt - 1 }),\n )\n return retryRejection(claim, prior)\n}\n\nfunction retryRejection(\n claim: AgentCandidateExecutionClaim,\n prior:\n | {\n claim: AgentCandidateExecutionClaim\n terminal?: AgentCandidateExecutionTerminalRecord\n }\n | undefined,\n): AgentCandidateRetryRejection | undefined {\n if (!prior) return 'prior-attempt-missing'\n if (\n claim.retryPolicy !== 'pre-model-infrastructure-only' ||\n prior.claim.retryPolicy !== claim.retryPolicy ||\n prior.claim.maxAttempts !== claim.maxAttempts ||\n prior.claim.bundleDigest !== claim.bundleDigest ||\n prior.claim.retryLineageDigest !== claim.retryLineageDigest\n ) {\n return 'retry-lineage-mismatch'\n }\n if (!prior.terminal) return 'prior-attempt-running'\n if (prior.terminal.status === 'succeeded') return 'prior-attempt-succeeded'\n if (prior.terminal.usage.modelCalls !== 0) return 'prior-attempt-spent-model-calls'\n if (prior.terminal.failureClass !== 'pre-model-infrastructure') {\n return 'prior-attempt-not-pre-model-infrastructure'\n }\n return undefined\n}\n\nfunction rejectedExistingClaim(\n existing: AgentCandidateExecutionClaim,\n requested: AgentCandidateExecutionClaim,\n): AgentCandidateExecutionClaimResult {\n return Object.freeze({\n acquired: false,\n reason: 'already-claimed',\n claim: existing,\n exactReplay: canonicalCandidateDigest(existing) === canonicalCandidateDigest(requested),\n })\n}\n\nfunction rejectedRetry(\n claim: AgentCandidateExecutionClaim,\n detail: AgentCandidateRetryRejection,\n): AgentCandidateExecutionClaimResult {\n return Object.freeze({ acquired: false, reason: 'retry-not-eligible', claim, detail })\n}\n\nasync function readClaim(path: string): Promise<StoredClaim> {\n const parsed = await readJsonObject(path, 'claim')\n const record = parsed as Partial<PersistedAgentCandidateExecutionClaim>\n if (record.version !== CLAIM_FORMAT_VERSION) {\n throw new Error(`candidate execution claim at ${path} has unsupported version`)\n }\n assertExactKeys(\n parsed,\n [\n 'version',\n 'executionId',\n 'attempt',\n 'maxAttempts',\n 'retryPolicy',\n 'bundleDigest',\n 'executionPlanDigest',\n 'retryLineageDigest',\n 'leaseExpiresAtMs',\n 'resultTimeoutMs',\n 'cleanup',\n 'phase',\n 'leaseDigest',\n ],\n `candidate execution claim at ${path}`,\n )\n const claim = sealClaim({\n executionId: requireString(record.executionId, path, 'executionId'),\n attempt: requireNumber(record.attempt, path, 'attempt'),\n maxAttempts: requireNumber(record.maxAttempts, path, 'maxAttempts'),\n retryPolicy: requireRetryPolicy(record.retryPolicy, path),\n bundleDigest: requireString(record.bundleDigest, path, 'bundleDigest') as Sha256Digest,\n executionPlanDigest: requireString(\n record.executionPlanDigest,\n path,\n 'executionPlanDigest',\n ) as Sha256Digest,\n retryLineageDigest: requireString(\n record.retryLineageDigest,\n path,\n 'retryLineageDigest',\n ) as Sha256Digest,\n leaseExpiresAtMs: requireNumber(record.leaseExpiresAtMs, path, 'leaseExpiresAtMs'),\n resultTimeoutMs: requireNumber(record.resultTimeoutMs, path, 'resultTimeoutMs'),\n cleanup: requireObject(\n record.cleanup,\n path,\n 'cleanup',\n ) as unknown as AgentCandidateExecutionCleanupHandles,\n })\n const persistedLeaseDigest = requireString(\n record.leaseDigest,\n path,\n 'leaseDigest',\n ) as Sha256Digest\n assertSha256Digest(persistedLeaseDigest, 'leaseDigest')\n if (record.phase !== 'claimed') {\n throw new Error(`candidate execution claim at ${path} has invalid initial phase`)\n }\n return { claim, leaseDigest: persistedLeaseDigest, phase: 'claimed' }\n}\n\nasync function readClaimIfPresent(path: string): Promise<StoredClaim | undefined> {\n try {\n return await readClaim(path)\n } catch (error) {\n if (isMissingError(error)) return undefined\n throw error\n }\n}\n\nasync function readTerminal(path: string): Promise<AgentCandidateExecutionTerminalRecord> {\n const parsed = await readJsonObject(path, 'terminal record')\n const record = parsed as Partial<PersistedAgentCandidateExecutionTerminal>\n if (record.version !== TERMINAL_FORMAT_VERSION) {\n throw new Error(`candidate execution terminal record at ${path} has unsupported version`)\n }\n assertExactKeys(parsed, ['version', 'terminal'], `candidate execution terminal record at ${path}`)\n return sealTerminalRecordValue(\n requireObject(record.terminal, path, 'terminal'),\n `candidate execution terminal record at ${path}`,\n )\n}\n\nasync function readTerminalIfPresent(\n path: string,\n): Promise<AgentCandidateExecutionTerminalRecord | undefined> {\n try {\n return await readTerminal(path)\n } catch (error) {\n if (isMissingError(error)) return undefined\n throw error\n }\n}\n\ntype ReadCandidateExecutionTransition =\n | { kind: 'phase' }\n | { kind: 'pending'; terminal: AgentCandidateExecutionTerminalRecord }\n\nasync function readTransitionIfPresent(\n path: string,\n claim: AgentCandidateExecutionClaim,\n): Promise<ReadCandidateExecutionTransition | undefined> {\n let parsed: Record<string, unknown>\n try {\n parsed = await readJsonObject(path, 'transition record')\n } catch (error) {\n if (isMissingError(error)) return undefined\n throw error\n }\n if (parsed.kind === 'candidate-execution-phase') {\n const record = parsed as unknown as PersistedAgentCandidateExecutionPhase\n if (record.version !== PHASE_FORMAT_VERSION) {\n throw new Error(`candidate execution phase record at ${path} has unsupported version`)\n }\n assertExactKeys(\n parsed,\n ['version', 'kind', 'executionId', 'attempt', 'executionPlanDigest', 'phase'],\n `candidate execution phase record at ${path}`,\n )\n if (\n record.executionId !== claim.executionId ||\n record.attempt !== claim.attempt ||\n record.executionPlanDigest !== claim.executionPlanDigest ||\n record.phase !== 'candidate-may-run'\n ) {\n throw new Error(`candidate execution phase record at ${path} does not match its claim`)\n }\n return { kind: 'phase' }\n }\n if (parsed.kind === 'candidate-execution-pending-terminal') {\n const record = parsed as unknown as PersistedAgentCandidateExecutionPending\n if (record.version !== PENDING_FORMAT_VERSION) {\n throw new Error(`candidate execution pending record at ${path} has unsupported version`)\n }\n assertExactKeys(\n parsed,\n ['version', 'kind', 'terminal'],\n `candidate execution pending record at ${path}`,\n )\n const terminal = sealTerminalRecordValue(\n requireObject(record.terminal, path, 'terminal'),\n `candidate execution pending record at ${path}`,\n )\n assertTerminalMatchesClaim(terminal, claim, path)\n return { kind: 'pending', terminal }\n }\n throw new Error(`candidate execution transition record at ${path} has invalid kind`)\n}\n\nasync function readJsonObject(path: string, kind: string): Promise<Record<string, unknown>> {\n let parsed: unknown\n try {\n parsed = JSON.parse(await readFile(path, 'utf8'))\n } catch (error) {\n if (isMissingError(error)) throw error\n throw new Error(`candidate execution ${kind} at ${path} is unreadable`, { cause: error })\n }\n if (parsed === null || typeof parsed !== 'object' || Array.isArray(parsed)) {\n throw new Error(`candidate execution ${kind} at ${path} is not an object`)\n }\n return parsed as Record<string, unknown>\n}\n\nfunction assertSameSlot(\n existing: Pick<AgentCandidateExecutionClaim, 'executionId' | 'attempt'>,\n requested: Pick<AgentCandidateExecutionClaim, 'executionId' | 'attempt'>,\n path: string,\n): void {\n if (existing.executionId !== requested.executionId || existing.attempt !== requested.attempt) {\n throw new Error(`candidate execution record at ${path} does not match its claim slot`)\n }\n}\n\nfunction assertSha256Digest(value: string, field: string): void {\n if (!SHA256_PATTERN.test(value)) {\n throw new Error(`candidate execution claim ${field} must be a lowercase sha256 digest`)\n }\n}\n\nfunction requireString(value: unknown, path: string, field: string): string {\n if (typeof value !== 'string') {\n throw new Error(`candidate execution record at ${path} has invalid ${field}`)\n }\n return value\n}\n\nfunction requireNumber(value: unknown, path: string, field: string): number {\n if (typeof value !== 'number') {\n throw new Error(`candidate execution record at ${path} has invalid ${field}`)\n }\n return value\n}\n\nfunction requireObject(value: unknown, path: string, field: string): Record<string, unknown> {\n if (value === null || typeof value !== 'object' || Array.isArray(value)) {\n throw new Error(`candidate execution record at ${path} has invalid ${field}`)\n }\n return value as Record<string, unknown>\n}\n\nfunction requireRetryPolicy(\n value: unknown,\n path: string,\n): AgentCandidateAttemptPolicy['retryPolicy'] {\n if (value !== 'none' && value !== 'pre-model-infrastructure-only') {\n throw new Error(`candidate execution record at ${path} has invalid retryPolicy`)\n }\n return value\n}\n\nfunction assertExecutionId(value: unknown): asserts value is string {\n if (typeof value !== 'string' || !/^[A-Za-z0-9._:-]{1,200}$/.test(value)) {\n throw new Error('candidate execution claim executionId is invalid')\n }\n}\n\nfunction assertBoundedIdentifier(\n value: unknown,\n label: string,\n maxLength: number,\n): asserts value is string {\n if (\n typeof value !== 'string' ||\n value.length === 0 ||\n value.length > maxLength ||\n hasControlCharacter(value)\n ) {\n throw new Error(`candidate execution ${label} is invalid`)\n }\n}\n\nfunction hasControlCharacter(value: string): boolean {\n for (let index = 0; index < value.length; index++) {\n const code = value.charCodeAt(index)\n if (code < 0x20 || code === 0x7f) return true\n }\n return false\n}\n\nfunction assertPositiveTimestamp(value: unknown, label: string): asserts value is number {\n if (!Number.isSafeInteger(value) || (value as number) <= 0) {\n throw new Error(`candidate execution ${label} must be a positive safe timestamp`)\n }\n}\n\nfunction assertClock(value: number): void {\n if (!Number.isSafeInteger(value) || value < 0) {\n throw new Error('candidate execution claim-store clock returned an invalid timestamp')\n }\n}\n\nfunction assertUnexpiredLease(expiresAtMs: number, nowMs: number): void {\n assertClock(nowMs)\n if (nowMs >= expiresAtMs) throw new Error('candidate execution lease has expired')\n}\n\nfunction assertExpiredLease(expiresAtMs: number, nowMs: number): void {\n assertClock(nowMs)\n if (nowMs < expiresAtMs) throw new Error('candidate execution lease has not expired')\n}\n\nfunction sha256(value: string): Sha256Digest {\n return `sha256:${createHash('sha256').update(value, 'utf8').digest('hex')}`\n}\n\nfunction isMissingError(error: unknown): boolean {\n return isNodeError(error, 'ENOENT')\n}\n\nfunction isNodeError(error: unknown, code: string): boolean {\n return (\n error !== null &&\n typeof error === 'object' &&\n 'code' in error &&\n (error as { code?: unknown }).code === code\n )\n}\n\nexport const candidateClaimFileInternals = Object.freeze({\n assertExpiredLease,\n assertLease,\n assertSameSlot,\n assertUnexpiredLease,\n attemptRecord,\n claimSlot,\n leaseDigest,\n newLease,\n readClaim,\n readClaimIfPresent,\n readTerminal,\n readTerminalIfPresent,\n readTransitionIfPresent,\n rejectedExistingClaim,\n rejectedRetry,\n retryRejection,\n sealAttemptRef,\n sealClaim,\n sealLease,\n})\n\nexport { candidateExecutionClaim } from './claim-plan'\n","import type { Sha256Digest } from '@tangle-network/agent-interface'\n\nimport type { AgentCandidateExecutionClaim, AgentCandidateExecutionTerminalRecord } from './claim'\n\nexport const CLAIM_FORMAT_VERSION = 7\nexport const PENDING_FORMAT_VERSION = 1\nexport const TERMINAL_FORMAT_VERSION = 3\nexport const PHASE_FORMAT_VERSION = 1\n\nexport interface PersistedAgentCandidateExecutionClaim extends AgentCandidateExecutionClaim {\n version: typeof CLAIM_FORMAT_VERSION\n phase: 'claimed'\n leaseDigest: Sha256Digest\n}\n\nexport interface PersistedAgentCandidateExecutionPending {\n version: typeof PENDING_FORMAT_VERSION\n kind: 'candidate-execution-pending-terminal'\n terminal: AgentCandidateExecutionTerminalRecord\n}\n\nexport interface PersistedAgentCandidateExecutionPhase {\n version: typeof PHASE_FORMAT_VERSION\n kind: 'candidate-execution-phase'\n executionId: string\n attempt: number\n executionPlanDigest: Sha256Digest\n phase: 'candidate-may-run'\n}\n\nexport interface PersistedAgentCandidateExecutionTerminal {\n version: typeof TERMINAL_FORMAT_VERSION\n terminal: AgentCandidateExecutionTerminalRecord\n}\n","import type { AgentCandidateArtifactRef, Sha256Digest } from '@tangle-network/agent-interface'\nimport { agentCandidateArtifactRefSchema } from '@tangle-network/agent-interface'\n\nimport type {\n AgentCandidateExecutionClaim,\n AgentCandidateExecutionFailureClass,\n AgentCandidateExecutionFinishResult,\n AgentCandidateExecutionPhase,\n AgentCandidateExecutionRecoveryEvidence,\n AgentCandidateExecutionStageResult,\n AgentCandidateExecutionTerminalRecord,\n AgentCandidateExecutionTerminalResult,\n AgentCandidateExecutionUsage,\n} from './claim'\nimport { canonicalCandidateDigest, immutableCandidateValue } from './digest'\nimport { assertExactObjectKeys as assertExactKeys } from './exact-object'\n\nconst SHA256_PATTERN = /^sha256:[a-f0-9]{64}$/\n\nexport function terminalRecord(\n claim: AgentCandidateExecutionClaim,\n result: AgentCandidateExecutionTerminalResult,\n): AgentCandidateExecutionTerminalRecord {\n const terminal = sealTerminalResult(result)\n const value = {\n executionId: claim.executionId,\n attempt: claim.attempt,\n bundleDigest: claim.bundleDigest,\n executionPlanDigest: claim.executionPlanDigest,\n ...terminal,\n }\n return immutableCandidateValue({\n ...value,\n terminalDigest: canonicalCandidateDigest(value),\n }) as AgentCandidateExecutionTerminalRecord\n}\n\nexport function recoveredTerminalRecord(\n claim: AgentCandidateExecutionClaim,\n phase: AgentCandidateExecutionPhase,\n evidence: AgentCandidateExecutionRecoveryEvidence,\n): AgentCandidateExecutionTerminalRecord {\n const recovered = sealRecoveryEvidence(evidence, claim)\n return terminalRecord(claim, {\n schemaVersion: 1,\n status: 'failed',\n failureClass:\n recovered.failureClass === 'pre-model-infrastructure' && phase !== 'claimed'\n ? 'unknown'\n : recovered.failureClass,\n usage: recovered.usage,\n modelSettlement: recovered.modelSettlement,\n ...(recovered.failureEvidence ? { failureEvidence: recovered.failureEvidence } : {}),\n })\n}\n\nexport function assertTerminalAllowedInPhase(\n phase: AgentCandidateExecutionPhase,\n terminal: AgentCandidateExecutionTerminalRecord,\n): void {\n if (\n phase === 'candidate-may-run' &&\n terminal.status === 'failed' &&\n terminal.failureClass === 'pre-model-infrastructure'\n ) {\n throw new Error('candidate execution crossed candidate-may-run before pre-model failure')\n }\n if (\n phase === 'claimed' &&\n (terminal.status === 'succeeded' ||\n (terminal.status === 'failed' &&\n (terminal.failureClass === 'execution' ||\n terminal.failureClass === 'post-model-infrastructure')))\n ) {\n throw new Error('candidate execution terminal requires candidate-may-run phase')\n }\n}\n\nexport function rejectedFinish(\n existing: AgentCandidateExecutionTerminalRecord,\n requestedTerminalDigest: Sha256Digest,\n): AgentCandidateExecutionFinishResult {\n return Object.freeze({\n finished: false,\n terminal: existing,\n exactReplay: existing.terminalDigest === requestedTerminalDigest,\n })\n}\n\nexport function rejectedStage(\n existing: AgentCandidateExecutionTerminalRecord,\n requested: AgentCandidateExecutionTerminalRecord,\n): AgentCandidateExecutionStageResult {\n return Object.freeze({\n staged: false,\n terminal: existing,\n exactReplay: existing.terminalDigest === requested.terminalDigest,\n })\n}\n\nexport function requireStagedTerminal(\n staged: AgentCandidateExecutionTerminalRecord | undefined,\n terminalDigest: Sha256Digest,\n): AgentCandidateExecutionTerminalRecord {\n if (!staged) throw new Error('candidate execution terminal has not been staged')\n if (staged.terminalDigest !== terminalDigest) {\n throw new Error('candidate execution terminal digest does not match staged outbox')\n }\n return staged\n}\n\nexport function sealTerminalDigest(value: Sha256Digest): Sha256Digest {\n assertSha256Digest(value, 'terminalDigest')\n return value\n}\n\nexport function assertRecoveryMatchesStaged(\n staged: AgentCandidateExecutionTerminalRecord,\n recovered: AgentCandidateExecutionTerminalRecord,\n): void {\n if (\n canonicalCandidateDigest(staged.usage) !== canonicalCandidateDigest(recovered.usage) ||\n canonicalCandidateDigest(staged.modelSettlement) !==\n canonicalCandidateDigest(recovered.modelSettlement)\n ) {\n throw new Error('candidate execution recovery evidence does not match staged model evidence')\n }\n}\n\nexport function sealTerminalRecordValue(\n value: Record<string, unknown>,\n label: string,\n): AgentCandidateExecutionTerminalRecord {\n const status = requireTerminalStatus(value.status, label)\n assertExactKeys(\n value,\n status === 'succeeded'\n ? [\n 'executionId',\n 'attempt',\n 'bundleDigest',\n 'executionPlanDigest',\n 'terminalDigest',\n 'schemaVersion',\n 'status',\n 'usage',\n 'modelSettlement',\n 'taskOutcome',\n 'benchmarkResult',\n 'runReceipt',\n ]\n : [\n 'executionId',\n 'attempt',\n 'bundleDigest',\n 'executionPlanDigest',\n 'terminalDigest',\n 'schemaVersion',\n 'status',\n 'failureClass',\n 'usage',\n 'modelSettlement',\n ...(value.failureEvidence ? ['failureEvidence'] : []),\n ],\n label,\n )\n const identity = {\n executionId: requireString(value.executionId, label, 'executionId'),\n attempt: requireNumber(value.attempt, label, 'attempt'),\n bundleDigest: requireString(value.bundleDigest, label, 'bundleDigest') as Sha256Digest,\n executionPlanDigest: requireString(\n value.executionPlanDigest,\n label,\n 'executionPlanDigest',\n ) as Sha256Digest,\n }\n assertExecutionId(identity.executionId)\n if (!Number.isSafeInteger(identity.attempt) || identity.attempt < 1) {\n throw new Error(`${label} has invalid attempt`)\n }\n assertSha256Digest(identity.bundleDigest, 'bundleDigest')\n assertSha256Digest(identity.executionPlanDigest, 'executionPlanDigest')\n const result = sealTerminalResult(\n status === 'succeeded'\n ? {\n schemaVersion: requireNumber(value.schemaVersion, label, 'schemaVersion') as 1,\n status,\n usage: requireObject(\n value.usage,\n label,\n 'usage',\n ) as unknown as AgentCandidateExecutionUsage,\n modelSettlement: requireArtifactRef(value.modelSettlement, label, 'modelSettlement'),\n taskOutcome: requireArtifactRef(value.taskOutcome, label, 'taskOutcome'),\n benchmarkResult: requireArtifactRef(value.benchmarkResult, label, 'benchmarkResult'),\n runReceipt: requireArtifactRef(value.runReceipt, label, 'runReceipt'),\n }\n : {\n schemaVersion: requireNumber(value.schemaVersion, label, 'schemaVersion') as 1,\n status,\n failureClass: requireFailureClass(value.failureClass, label),\n usage: requireObject(\n value.usage,\n label,\n 'usage',\n ) as unknown as AgentCandidateExecutionUsage,\n modelSettlement: requireArtifactRef(value.modelSettlement, label, 'modelSettlement'),\n ...(value.failureEvidence\n ? {\n failureEvidence: requireArtifactRef(\n value.failureEvidence,\n label,\n 'failureEvidence',\n ),\n }\n : {}),\n },\n )\n const material = { ...identity, ...result }\n const terminalDigest = requireString(\n value.terminalDigest,\n label,\n 'terminalDigest',\n ) as Sha256Digest\n assertSha256Digest(terminalDigest, 'terminalDigest')\n if (terminalDigest !== canonicalCandidateDigest(material)) {\n throw new Error(`${label} has invalid terminalDigest`)\n }\n return immutableCandidateValue({\n ...material,\n terminalDigest,\n }) as AgentCandidateExecutionTerminalRecord\n}\n\nexport function assertTerminalMatchesClaim(\n terminal: AgentCandidateExecutionTerminalRecord,\n claim: AgentCandidateExecutionClaim,\n path: string,\n): void {\n if (\n terminal.executionId !== claim.executionId ||\n terminal.attempt !== claim.attempt ||\n terminal.bundleDigest !== claim.bundleDigest ||\n terminal.executionPlanDigest !== claim.executionPlanDigest\n ) {\n throw new Error(`candidate execution terminal record at ${path} does not match its claim`)\n }\n}\n\nexport function assertTerminalMatchesStaged(\n terminal: AgentCandidateExecutionTerminalRecord,\n staged: AgentCandidateExecutionTerminalRecord,\n path: string,\n): void {\n if (\n terminal.terminalDigest !== staged.terminalDigest ||\n canonicalCandidateDigest(terminal) !== canonicalCandidateDigest(staged)\n ) {\n throw new Error(`candidate execution terminal record at ${path} differs from staged outbox`)\n }\n}\n\nfunction sealRecoveryEvidence(\n evidence: AgentCandidateExecutionRecoveryEvidence,\n claim: AgentCandidateExecutionClaim,\n): AgentCandidateExecutionRecoveryEvidence {\n assertExactKeys(\n evidence,\n [\n 'failureClass',\n 'usage',\n 'modelSettlement',\n 'process',\n 'model',\n ...(evidence.failureEvidence ? ['failureEvidence'] : []),\n ...(evidence.memory ? ['memory'] : []),\n ],\n 'candidate execution recovery evidence',\n )\n assertFailureClass(evidence.failureClass)\n const usage = sealUsage(evidence.usage)\n if (evidence.failureClass === 'pre-model-infrastructure' && usage.modelCalls !== 0) {\n throw new Error('pre-model infrastructure failure cannot contain model calls')\n }\n const modelSettlement = sealArtifactRef(evidence.modelSettlement, 'modelSettlement')\n const failureEvidence = evidence.failureEvidence\n ? sealArtifactRef(evidence.failureEvidence, 'failureEvidence')\n : undefined\n assertExactKeys(\n evidence.process,\n ['stopped', 'executionPlanDigest'],\n 'candidate execution process closure evidence',\n )\n if (\n evidence.process.stopped !== true ||\n evidence.process.executionPlanDigest !== claim.executionPlanDigest\n ) {\n throw new Error('candidate execution recovery does not prove the claimed process stopped')\n }\n assertExactKeys(\n evidence.model,\n ['closed', 'preparationId', 'grantDigest'],\n 'candidate execution model closure evidence',\n )\n if (\n evidence.model.closed !== true ||\n evidence.model.preparationId !== claim.cleanup.preparationId ||\n evidence.model.grantDigest !== claim.cleanup.modelGrantDigest\n ) {\n throw new Error('candidate execution recovery does not prove the claimed model grant closed')\n }\n if (claim.cleanup.memory) {\n if (!evidence.memory) {\n throw new Error('candidate execution recovery is missing memory closure evidence')\n }\n assertExactKeys(\n evidence.memory,\n ['closed', 'preparationId', 'accessDigest', 'effectiveNamespace'],\n 'candidate execution memory closure evidence',\n )\n if (\n evidence.memory.closed !== true ||\n evidence.memory.preparationId !== claim.cleanup.preparationId ||\n evidence.memory.accessDigest !== claim.cleanup.memory.accessDigest ||\n evidence.memory.effectiveNamespace !== claim.cleanup.memory.effectiveNamespace\n ) {\n throw new Error(\n 'candidate execution recovery does not prove the claimed memory access closed',\n )\n }\n } else if (evidence.memory !== undefined) {\n throw new Error('candidate execution recovery has unexpected memory closure evidence')\n }\n return Object.freeze({\n failureClass: evidence.failureClass,\n usage,\n modelSettlement,\n ...(failureEvidence ? { failureEvidence } : {}),\n process: Object.freeze({ ...evidence.process }),\n model: Object.freeze({ ...evidence.model }),\n ...(evidence.memory ? { memory: Object.freeze({ ...evidence.memory }) } : {}),\n })\n}\n\nfunction sealTerminalResult(\n result: AgentCandidateExecutionTerminalResult,\n): AgentCandidateExecutionTerminalResult {\n if (result.status !== 'succeeded' && result.status !== 'failed') {\n throw new Error('candidate execution terminal status is invalid')\n }\n assertExactKeys(\n result,\n result.status === 'succeeded'\n ? [\n 'schemaVersion',\n 'status',\n 'usage',\n 'modelSettlement',\n 'taskOutcome',\n 'benchmarkResult',\n 'runReceipt',\n ]\n : [\n 'schemaVersion',\n 'status',\n 'failureClass',\n 'usage',\n 'modelSettlement',\n ...(result.failureEvidence ? ['failureEvidence'] : []),\n ],\n 'candidate execution terminal result',\n )\n if (result.schemaVersion !== 1) {\n throw new Error('candidate execution terminal schemaVersion must be 1')\n }\n const usage = sealUsage(result.usage)\n const modelSettlement = sealArtifactRef(result.modelSettlement, 'modelSettlement')\n if (result.status === 'succeeded') {\n return Object.freeze({\n schemaVersion: 1,\n status: 'succeeded',\n usage,\n modelSettlement,\n taskOutcome: sealArtifactRef(result.taskOutcome, 'taskOutcome'),\n benchmarkResult: sealArtifactRef(result.benchmarkResult, 'benchmarkResult'),\n runReceipt: sealArtifactRef(result.runReceipt, 'runReceipt'),\n })\n }\n assertFailureClass(result.failureClass)\n if (result.failureClass === 'pre-model-infrastructure' && usage.modelCalls !== 0) {\n throw new Error('pre-model infrastructure failure cannot contain model calls')\n }\n return Object.freeze({\n schemaVersion: 1,\n status: 'failed',\n failureClass: result.failureClass,\n usage,\n modelSettlement,\n ...(result.failureEvidence\n ? { failureEvidence: sealArtifactRef(result.failureEvidence, 'failureEvidence') }\n : {}),\n })\n}\n\nfunction sealUsage(usage: AgentCandidateExecutionUsage): AgentCandidateExecutionUsage {\n assertExactKeys(\n usage,\n [\n 'costUsdNanos',\n 'inputTokens',\n 'outputTokens',\n 'cachedInputTokens',\n 'reasoningTokens',\n 'modelCalls',\n ],\n 'candidate execution terminal usage',\n )\n for (const [field, value] of Object.entries(usage)) {\n assertCount(value, `terminal usage ${field}`)\n }\n return Object.freeze({\n costUsdNanos: usage.costUsdNanos,\n inputTokens: usage.inputTokens,\n outputTokens: usage.outputTokens,\n cachedInputTokens: usage.cachedInputTokens,\n reasoningTokens: usage.reasoningTokens,\n modelCalls: usage.modelCalls,\n })\n}\n\nfunction sealArtifactRef(ref: AgentCandidateArtifactRef, label: string): AgentCandidateArtifactRef {\n const parsed = agentCandidateArtifactRefSchema.parse(ref)\n if (!Number.isSafeInteger(parsed.byteLength)) {\n throw new Error(`candidate execution terminal ${label} byteLength exceeds safe integer range`)\n }\n return immutableCandidateValue(parsed)\n}\n\nfunction requireArtifactRef(\n value: unknown,\n path: string,\n field: string,\n): AgentCandidateArtifactRef {\n return requireObject(value, path, field) as unknown as AgentCandidateArtifactRef\n}\n\nfunction requireString(value: unknown, path: string, field: string): string {\n if (typeof value !== 'string') {\n throw new Error(`candidate execution record at ${path} has invalid ${field}`)\n }\n return value\n}\n\nfunction requireNumber(value: unknown, path: string, field: string): number {\n if (typeof value !== 'number') {\n throw new Error(`candidate execution record at ${path} has invalid ${field}`)\n }\n return value\n}\n\nfunction requireObject(value: unknown, path: string, field: string): Record<string, unknown> {\n if (value === null || typeof value !== 'object' || Array.isArray(value)) {\n throw new Error(`candidate execution record at ${path} has invalid ${field}`)\n }\n return value as Record<string, unknown>\n}\n\nfunction requireTerminalStatus(\n value: unknown,\n path: string,\n): AgentCandidateExecutionTerminalResult['status'] {\n if (value !== 'succeeded' && value !== 'failed') {\n throw new Error(`candidate execution terminal record at ${path} has invalid status`)\n }\n return value\n}\n\nfunction requireFailureClass(value: unknown, path: string): AgentCandidateExecutionFailureClass {\n try {\n assertFailureClass(value)\n return value\n } catch (error) {\n throw new Error(`candidate execution terminal record at ${path} has invalid failureClass`, {\n cause: error,\n })\n }\n}\n\nfunction assertFailureClass(value: unknown): asserts value is AgentCandidateExecutionFailureClass {\n if (\n value !== 'pre-model-infrastructure' &&\n value !== 'execution' &&\n value !== 'post-model-infrastructure' &&\n value !== 'unknown'\n ) {\n throw new Error('candidate execution failureClass is invalid')\n }\n}\n\nfunction assertExecutionId(value: unknown): asserts value is string {\n if (typeof value !== 'string' || !/^[A-Za-z0-9._:-]{1,200}$/.test(value)) {\n throw new Error('candidate execution claim executionId is invalid')\n }\n}\n\nfunction assertSha256Digest(value: string, field: string): void {\n if (!SHA256_PATTERN.test(value)) {\n throw new Error(`candidate execution claim ${field} must be a lowercase sha256 digest`)\n }\n}\n\nfunction assertCount(value: unknown, label: string): asserts value is number {\n if (!Number.isSafeInteger(value) || (value as number) < 0) {\n throw new Error(`candidate execution ${label} must be a non-negative safe integer`)\n }\n}\n","import { createHash } from 'node:crypto'\nimport { canonicalJson } from '@tangle-network/agent-eval'\nimport type { AgentCandidateEmbeddedArtifact, Sha256Digest } from '@tangle-network/agent-interface'\n\nimport { contentAddress } from '../durable/spawn-journal'\nimport type { CanonicalCandidateDocument } from './types'\n\nexport function sha256Bytes(bytes: Uint8Array): Sha256Digest {\n return `sha256:${createHash('sha256').update(bytes).digest('hex')}`\n}\n\nexport function canonicalCandidateBytes(value: unknown): Uint8Array {\n return Buffer.from(canonicalJson(value), 'utf8')\n}\n\nexport function canonicalCandidateDigest(value: unknown): Sha256Digest {\n return contentAddress(value) as Sha256Digest\n}\n\n/** Returns a detached, deeply frozen JSON value with canonical number normalization. */\nexport function immutableCandidateValue<T>(value: T): T {\n return deepFreezeCandidate(\n JSON.parse(Buffer.from(canonicalCandidateBytes(value)).toString('utf8')) as T,\n )\n}\n\nexport function canonicalCandidateDocument<T extends { digest: Sha256Digest }>(\n valueWithoutDigest: Omit<T, 'digest'>,\n): CanonicalCandidateDocument<T> {\n const bytes = canonicalCandidateBytes(valueWithoutDigest)\n const digest = canonicalCandidateDigest(valueWithoutDigest)\n if (sha256Bytes(bytes) !== digest) {\n throw new Error('canonical candidate serializers disagree on document digest')\n }\n const storedBytes = Uint8Array.from(bytes)\n const value = immutableCandidateValue({ ...valueWithoutDigest, digest }) as T\n return Object.freeze({\n value,\n get bytes(): Uint8Array {\n return Uint8Array.from(storedBytes)\n },\n digest,\n })\n}\n\nexport function embeddedCandidateArtifact(bytes: Uint8Array): AgentCandidateEmbeddedArtifact {\n return {\n encoding: 'base64',\n content: Buffer.from(bytes).toString('base64'),\n sha256: sha256Bytes(bytes),\n byteLength: bytes.byteLength,\n }\n}\n\nexport function omitTopLevelDigest<T extends { digest: Sha256Digest }>(\n value: T,\n): Omit<T, 'digest'> {\n const { digest: _digest, ...rest } = value\n return rest\n}\n\nexport function deepFreezeCandidate<T>(value: T, seen = new Set<object>()): T {\n if (\n value === null ||\n typeof value !== 'object' ||\n ArrayBuffer.isView(value) ||\n seen.has(value as object)\n ) {\n return value\n }\n seen.add(value as object)\n for (const child of Object.values(value as Record<string, unknown>)) {\n deepFreezeCandidate(child, seen)\n }\n return Object.freeze(value)\n}\n","/** Reject unknown fields while requiring every declared non-optional field. */\nexport function assertExactObjectKeys(\n value: unknown,\n required: readonly string[],\n label: string,\n optional: readonly string[] = [],\n): void {\n if (value === null || typeof value !== 'object' || Array.isArray(value)) {\n throw new Error(`${label} must be an object`)\n }\n const allowed = new Set([...required, ...optional])\n if (allowed.size !== required.length + optional.length) {\n throw new Error(`${label} exact-key contract contains duplicate fields`)\n }\n for (const key of Object.keys(value)) {\n if (!allowed.has(key)) throw new Error(`${label} contains unknown field ${key}`)\n }\n for (const key of required) {\n if (!(key in value)) throw new Error(`${label} is missing field ${key}`)\n }\n}\n","export const DEFAULT_CANDIDATE_CLEANUP_TIMEOUT_MS = 30_000\n/** Largest delay Node schedules without clamping to one millisecond. */\nexport const MAX_CANDIDATE_TIMER_INTERVAL_MS = 2_147_483_647\n\nexport function candidateCleanupTimeout(timeoutMs: number | undefined): number {\n const effective = timeoutMs ?? DEFAULT_CANDIDATE_CLEANUP_TIMEOUT_MS\n if (\n !Number.isSafeInteger(effective) ||\n effective <= 0 ||\n effective > MAX_CANDIDATE_TIMER_INTERVAL_MS\n ) {\n throw new Error('candidate cleanup timeout is outside the supported timer range')\n }\n return effective\n}\n\nexport function candidateCleanupDeadline(timeoutMs: number | undefined): number {\n return Date.now() + candidateCleanupTimeout(timeoutMs)\n}\n\n/** Freeze a separate result-construction budget; defaults to the task wall limit. */\nexport function candidateResultTimeout(\n timeoutMs: number | undefined,\n taskTimeoutMs: number,\n): number {\n const effective = timeoutMs ?? taskTimeoutMs\n if (\n !Number.isSafeInteger(effective) ||\n effective <= 0 ||\n effective > MAX_CANDIDATE_TIMER_INTERVAL_MS\n ) {\n throw new Error('candidate result timeout is outside the supported timer range')\n }\n return effective\n}\n\n/** Bound an evaluator cleanup call while keeping late rejection observed. */\nexport async function withinCandidateCleanupDeadline<T>(\n operation: () => Promise<T>,\n deadlineAtMs: number,\n label: string,\n): Promise<T> {\n const remainingMs = deadlineAtMs - Date.now()\n if (remainingMs <= 0) throw new CandidateCleanupTimeoutError(label)\n\n const pending = Promise.resolve().then(operation)\n void pending.catch(() => undefined)\n let timer: ReturnType<typeof setTimeout> | undefined\n try {\n const result = await Promise.race([\n pending,\n new Promise<never>((_resolve, reject) => {\n timer = setTimeout(() => reject(new CandidateCleanupTimeoutError(label)), remainingMs)\n }),\n ])\n // Exact-boundary completion is ambiguous under event-loop delay.\n if (Date.now() >= deadlineAtMs) throw new CandidateCleanupTimeoutError(label)\n return result\n } finally {\n if (timer) clearTimeout(timer)\n }\n}\n\n/**\n * Bound cancellable scoring/result work. Every side-effecting port called by\n * `operation` must honor the supplied signal before durable publication.\n */\nexport async function withinCandidateResultDeadline<T>(\n operation: (signal: AbortSignal) => Promise<T>,\n deadlineAtMs: number,\n label: string,\n): Promise<T> {\n const remainingMs = deadlineAtMs - Date.now()\n if (remainingMs <= 0) throw new CandidateResultTimeoutError(label)\n\n const controller = new AbortController()\n const timeoutError = new CandidateResultTimeoutError(label)\n const pending = Promise.resolve().then(() => operation(controller.signal))\n void pending.catch(() => undefined)\n let timer: ReturnType<typeof setTimeout> | undefined\n try {\n const result = await Promise.race([\n pending,\n new Promise<never>((_resolve, reject) => {\n timer = setTimeout(() => {\n controller.abort(timeoutError)\n reject(timeoutError)\n }, remainingMs)\n }),\n ])\n // Exact-boundary completion is ambiguous under event-loop delay.\n if (Date.now() >= deadlineAtMs) {\n controller.abort(timeoutError)\n throw timeoutError\n }\n return result\n } finally {\n if (timer) clearTimeout(timer)\n }\n}\n\nexport class CandidateCleanupTimeoutError extends Error {\n constructor(label: string) {\n super(`${label} did not complete before the evaluator cleanup deadline`)\n this.name = 'CandidateCleanupTimeoutError'\n }\n}\n\nexport class CandidateResultTimeoutError extends Error {\n constructor(label: string) {\n super(`${label} did not complete before the evaluator result deadline`)\n this.name = 'CandidateResultTimeoutError'\n }\n}\n","import { MAX_CANDIDATE_TIMER_INTERVAL_MS } from './cleanup'\n\nexport const CANDIDATE_TERMINAL_PERSISTENCE_MARGIN_MS = 10_000\nconst CANDIDATE_POST_RUN_CLEANUP_PHASES = 4\n\n/** Process stop, access closure, model evidence, and task/result evidence. */\nexport function candidatePostRunWindowMs(\n cleanupTimeoutMs: number,\n resultTimeoutMs: number,\n): number {\n const windowMs =\n cleanupTimeoutMs * CANDIDATE_POST_RUN_CLEANUP_PHASES +\n resultTimeoutMs +\n CANDIDATE_TERMINAL_PERSISTENCE_MARGIN_MS\n if (!Number.isSafeInteger(windowMs) || windowMs > MAX_CANDIDATE_TIMER_INTERVAL_MS) {\n throw new Error('candidate post-run window exceeds the supported timer range')\n }\n return windowMs\n}\n\n/** Maximum owner lifetime from claim through process stop, access closure, and terminal write. */\nexport function candidateExecutionOwnerWindowMs(\n timeoutMs: number,\n cleanupTimeoutMs: number,\n resultTimeoutMs: number,\n): number {\n const windowMs = timeoutMs + candidatePostRunWindowMs(cleanupTimeoutMs, resultTimeoutMs)\n if (!Number.isSafeInteger(windowMs) || windowMs > MAX_CANDIDATE_TIMER_INTERVAL_MS) {\n throw new Error('candidate execution and cleanup window exceeds the supported timer range')\n }\n return windowMs\n}\n\n/** Time reserved after scoring for failure evidence plus terminal publication. */\nexport function candidateTerminalWindowMs(cleanupTimeoutMs: number): number {\n const windowMs = cleanupTimeoutMs + CANDIDATE_TERMINAL_PERSISTENCE_MARGIN_MS\n if (!Number.isSafeInteger(windowMs) || windowMs > MAX_CANDIDATE_TIMER_INTERVAL_MS) {\n throw new Error('candidate terminal window exceeds the supported timer range')\n }\n return windowMs\n}\n","import {\n agentCandidateExecutionPlanEvidenceSchema,\n agentCandidateMaterializationReceiptSchema,\n agentCandidateProfilePlanEvidenceSchema,\n} from '@tangle-network/agent-interface'\n\nimport { verifyMaterializedProfileWorkspace, verifyMaterializedWorkspace } from './artifacts'\nimport {\n canonicalCandidateBytes,\n canonicalCandidateDigest,\n canonicalCandidateDocument,\n immutableCandidateValue,\n omitTopLevelDigest,\n sha256Bytes,\n} from './digest'\nimport { verifyTaskCheckout } from './git-materialize'\nimport type {\n AgentCandidateExecutionPorts,\n AgentCandidateExecutorRequest,\n AgentCandidateProtectedModelActivation,\n AgentCandidateProtectedModelReservation,\n PreparedAgentCandidateExecution,\n} from './types'\nimport { CANDIDATE_TRACE_ENV, CANDIDATE_TRACE_TAGS, preparedCandidateBrand } from './types'\n\nexport interface PreparedCandidateState {\n ports: AgentCandidateExecutionPorts\n bundle: PreparedAgentCandidateExecution['bundle']\n executionId: string\n roots: PreparedAgentCandidateExecution['roots']\n profilePlan: PreparedAgentCandidateExecution['profilePlan']\n executionPlan: PreparedAgentCandidateExecution['executionPlan']\n materializationReceipt: PreparedAgentCandidateExecution['materializationReceipt']\n launch: PreparedAgentCandidateExecution['launch']\n instruction: PreparedAgentCandidateExecution['instruction']\n resolvedModel: PreparedAgentCandidateExecution['resolvedModel']\n preparationId: string\n reservationExpiresAtMs: number\n cleanupTimeoutMs: number\n resultTimeoutMs: number\n modelReservation: AgentCandidateProtectedModelReservation\n executorInputs: {\n taskFiles: ReadonlyArray<{\n path: string\n mode: 0o644 | 0o755\n bytes: Uint8Array\n }>\n candidateFiles?: ReadonlyArray<{\n path: string\n mode: 0o644 | 0o755\n bytes: Uint8Array\n }>\n profileFiles: ReadonlyArray<{\n path: string\n mode: 0o644 | 0o755\n bytes: Uint8Array\n }>\n }\n memoryReservation?: {\n preparationId: string\n accessDigest: `sha256:${string}`\n expiresAtMs: number\n effectiveNamespace: string\n }\n knowledge?: PreparedAgentCandidateExecution['knowledge']\n trace: PreparedAgentCandidateExecution['trace']\n memory: PreparedAgentCandidateExecution['memory']\n}\n\nconst stateByExecution = new WeakMap<PreparedAgentCandidateExecution, PreparedCandidateState>()\nconst lifecycleByExecution = new WeakMap<\n PreparedAgentCandidateExecution,\n {\n status:\n | 'prepared'\n | 'claiming'\n | 'claimed'\n | 'running'\n | 'settling'\n | 'disposing'\n | 'succeeded'\n | 'failed'\n | 'disposal-failed'\n | 'cleanup-failed'\n | 'disposed'\n }\n>()\n\nexport function createPreparedCandidateExecution(\n input: PreparedCandidateState,\n): PreparedAgentCandidateExecution {\n const state = detachPreparedCandidateState(input)\n assertPrivateCandidateIntegrity(state)\n const prepared = Object.freeze({\n bundle: state.bundle,\n executionId: state.executionId,\n roots: state.roots,\n profilePlan: evidenceView(state.profilePlan),\n executionPlan: evidenceView(state.executionPlan),\n materializationReceipt: state.materializationReceipt,\n launch: state.launch,\n instruction: bytesView(state.instruction, 'bytes'),\n resolvedModel: state.resolvedModel,\n ...(state.knowledge ? { knowledge: knowledgeView(state.knowledge) } : {}),\n trace: state.trace,\n memory: state.memory,\n [preparedCandidateBrand]: true as const,\n })\n stateByExecution.set(prepared, state)\n lifecycleByExecution.set(prepared, { status: 'prepared' })\n return prepared\n}\n\nexport function getPreparedCandidateState(\n prepared: PreparedAgentCandidateExecution,\n): PreparedCandidateState {\n const state = stateByExecution.get(prepared)\n if (!state || prepared[preparedCandidateBrand] !== true) {\n throw new Error('execution must come from prepareAgentCandidateExecution')\n }\n return state\n}\n\n/** Revalidates the exact private bytes immediately before execution or finalization. */\nexport function assertPreparedCandidateIntegrity(\n prepared: PreparedAgentCandidateExecution,\n): PreparedCandidateState {\n const state = getPreparedCandidateState(prepared)\n assertPrivateCandidateIntegrity(state)\n return state\n}\n\n/** Atomically reserves this in-memory prepared value before the first await. */\nexport function beginPreparedCandidateClaim(\n prepared: PreparedAgentCandidateExecution,\n): PreparedCandidateState {\n const state = assertPreparedCandidateIntegrity(prepared)\n transitionLifecycle(prepared, ['prepared'], 'claiming')\n return state\n}\n\n/** Claim an unexecuted preparation for explicit resource disposal. */\nexport function beginPreparedCandidateDisposal(\n prepared: PreparedAgentCandidateExecution,\n): PreparedCandidateState {\n const state = assertPreparedCandidateIntegrity(prepared)\n transitionLifecycle(prepared, ['prepared', 'disposal-failed', 'cleanup-failed'], 'disposing')\n return state\n}\n\nexport function markPreparedCandidateClaimed(prepared: PreparedAgentCandidateExecution): void {\n transitionLifecycle(prepared, ['claiming'], 'claimed')\n}\n\n/** Reveal protected values only after the durable claim and workspace checks succeed. */\nexport function beginPreparedCandidateRun(\n prepared: PreparedAgentCandidateExecution,\n modelAccess: AgentCandidateProtectedModelActivation,\n memoryAccess?: { env: Readonly<Record<string, string>> },\n): { state: PreparedCandidateState; request: AgentCandidateExecutorRequest } {\n const state = assertPreparedCandidateIntegrity(prepared)\n assertProtectedEnvironment(state, modelAccess.env, memoryAccess?.env)\n transitionLifecycle(prepared, ['claimed'], 'running')\n const completeEnvironment = immutableCandidateValue({\n ...state.launch.env,\n ...modelAccess.env,\n ...(memoryAccess?.env ?? {}),\n ...state.trace.env,\n })\n const material = state.executionPlan.value.material\n const request = Object.freeze({\n executionId: state.executionId,\n inputs: Object.freeze({\n task: workspaceInputView(material.task.workspace, state.executorInputs.taskFiles),\n ...(material.candidateWorkspace && state.executorInputs.candidateFiles\n ? {\n candidate: workspaceInputView(\n material.candidateWorkspace,\n state.executorInputs.candidateFiles,\n ),\n }\n : {}),\n profile: Object.freeze({\n files: Object.freeze(\n state.executorInputs.profileFiles.map((file) => profileFileView(file)),\n ),\n }),\n }),\n roots: state.roots.execution,\n profilePlan: evidenceView(state.profilePlan),\n executionPlan: evidenceView(state.executionPlan),\n materializationReceipt: state.materializationReceipt,\n launch: immutableCandidateValue({ ...state.launch, env: completeEnvironment }),\n instruction: bytesView(state.instruction, 'bytes'),\n resolvedModel: state.resolvedModel,\n hardLimits: Object.freeze({ timeoutMs: state.executionPlan.value.material.limits.timeoutMs }),\n observedLimits: Object.freeze({ maxSteps: state.executionPlan.value.material.limits.maxSteps }),\n ...(state.knowledge ? { knowledge: knowledgeView(state.knowledge) } : {}),\n trace: state.trace,\n memory: state.memory,\n })\n return { state, request }\n}\n\nexport function consumePreparedCandidateExecution(\n prepared: PreparedAgentCandidateExecution,\n outcome: 'succeeded' | 'failed' | 'disposed' | 'disposal-failed' | 'cleanup-failed',\n): void {\n transitionLifecycle(\n prepared,\n outcome === 'disposed' || outcome === 'disposal-failed' ? ['disposing'] : ['settling'],\n outcome,\n )\n}\n\nexport function beginPreparedCandidateSettlement(prepared: PreparedAgentCandidateExecution): void {\n transitionLifecycle(prepared, ['claiming', 'claimed', 'running'], 'settling')\n}\n\n/** Rechecks every mutable staging byte immediately before handing control to an executor. */\nexport async function assertPreparedCandidateWorkspaces(\n state: PreparedCandidateState,\n): Promise<void> {\n const plan = state.executionPlan.value.material\n await verifyMaterializedWorkspace(state.roots.staging.taskRoot, plan.task.workspace.material, {\n ignoredProtectedRootEntries: ['.git', '.sidecar'],\n })\n await verifyTaskCheckout(state.roots.staging.taskRoot, plan.task.repository)\n await verifyMaterializedProfileWorkspace(\n state.roots.staging.profileRoot,\n state.profilePlan.value.material,\n )\n if (plan.candidateWorkspace) {\n const candidateRoot = state.roots.staging.candidateRoot\n if (!candidateRoot) throw new Error('prepared candidate staging root is missing')\n await verifyMaterializedWorkspace(candidateRoot, plan.candidateWorkspace.material)\n } else if (state.roots.staging.candidateRoot !== undefined) {\n throw new Error('disabled candidate unexpectedly has a staging root')\n }\n}\n\nfunction detachPreparedCandidateState(input: PreparedCandidateState): PreparedCandidateState {\n const profilePlan = immutableCandidateValue(\n agentCandidateProfilePlanEvidenceSchema.parse(input.profilePlan.value),\n )\n const executionPlan = immutableCandidateValue(\n agentCandidateExecutionPlanEvidenceSchema.parse(input.executionPlan.value),\n )\n const receiptValue = immutableCandidateValue(\n agentCandidateMaterializationReceiptSchema.parse(input.materializationReceipt.value),\n )\n const materializationReceipt = canonicalCandidateDocument(\n omitTopLevelDigest(receiptValue),\n ) as PreparedAgentCandidateExecution['materializationReceipt']\n if (materializationReceipt.digest !== input.materializationReceipt.digest) {\n throw new Error('materialization receipt digest changed while sealing prepared execution')\n }\n return Object.freeze({\n ports: input.ports,\n bundle: input.bundle,\n executionId: input.executionId,\n roots: immutableCandidateValue(input.roots),\n profilePlan: Object.freeze({\n value: profilePlan,\n bytes: Uint8Array.from(input.profilePlan.bytes),\n written: Object.freeze([...input.profilePlan.written]),\n }),\n executionPlan: Object.freeze({\n value: executionPlan,\n bytes: Uint8Array.from(input.executionPlan.bytes),\n }),\n materializationReceipt,\n launch: immutableCandidateValue(input.launch),\n instruction: Object.freeze({\n bytes: Uint8Array.from(input.instruction.bytes),\n delivery: immutableCandidateValue(input.instruction.delivery),\n }),\n resolvedModel: immutableCandidateValue(input.resolvedModel),\n preparationId: input.preparationId,\n reservationExpiresAtMs: input.reservationExpiresAtMs,\n cleanupTimeoutMs: input.cleanupTimeoutMs,\n resultTimeoutMs: input.resultTimeoutMs,\n modelReservation: immutableCandidateValue(input.modelReservation),\n executorInputs: Object.freeze({\n taskFiles: immutableExecutorFiles(input.executorInputs.taskFiles),\n ...(input.executorInputs.candidateFiles\n ? { candidateFiles: immutableExecutorFiles(input.executorInputs.candidateFiles) }\n : {}),\n profileFiles: Object.freeze(\n input.executorInputs.profileFiles.map((file) =>\n Object.freeze({ ...file, bytes: Uint8Array.from(file.bytes) }),\n ),\n ),\n }),\n ...(input.memoryReservation\n ? { memoryReservation: immutableCandidateValue(input.memoryReservation) }\n : {}),\n ...(input.knowledge\n ? {\n knowledge: Object.freeze({\n snapshotId: input.knowledge.snapshotId,\n manifestDigest: input.knowledge.manifestDigest,\n manifest: Uint8Array.from(input.knowledge.manifest),\n }),\n }\n : {}),\n trace: immutableCandidateValue(input.trace),\n memory: immutableCandidateValue(input.memory),\n })\n}\n\nfunction assertPrivateCandidateIntegrity(state: PreparedCandidateState): void {\n const bundleMaterial = omitTopLevelDigest(state.bundle)\n if (canonicalCandidateDigest(bundleMaterial) !== state.bundle.digest) {\n throw new Error('prepared candidate bundle no longer matches its digest')\n }\n assertPlanEvidence(state.profilePlan.value, state.profilePlan.bytes, 'profile plan')\n assertPlanEvidence(state.executionPlan.value, state.executionPlan.bytes, 'execution plan')\n agentCandidateExecutionPlanEvidenceSchema.parse(state.executionPlan.value)\n\n const receipt = agentCandidateMaterializationReceiptSchema.parse(\n state.materializationReceipt.value,\n )\n const receiptBytes = canonicalCandidateBytes(omitTopLevelDigest(receipt))\n if (\n canonicalCandidateDigest(omitTopLevelDigest(receipt)) !== state.materializationReceipt.digest ||\n !Buffer.from(receiptBytes).equals(Buffer.from(state.materializationReceipt.bytes))\n ) {\n throw new Error('prepared materialization receipt no longer matches its canonical bytes')\n }\n\n const instruction = state.executionPlan.value.material.task.instruction\n if (\n sha256Bytes(state.instruction.bytes) !== instruction.sha256 ||\n state.instruction.bytes.byteLength !== instruction.byteLength ||\n JSON.stringify(state.instruction.delivery) !== JSON.stringify(instruction.delivery)\n ) {\n throw new Error('prepared instruction no longer matches the signed execution plan')\n }\n if (\n !/^candidate-preparation-v1\\.[A-Za-z0-9_-]{43}$/.test(state.preparationId) ||\n !Number.isSafeInteger(state.reservationExpiresAtMs) ||\n state.reservationExpiresAtMs <= 0 ||\n !Number.isSafeInteger(state.cleanupTimeoutMs) ||\n state.cleanupTimeoutMs <= 0 ||\n !Number.isSafeInteger(state.resultTimeoutMs) ||\n state.resultTimeoutMs <= 0 ||\n JSON.stringify(state.resolvedModel) !==\n JSON.stringify(state.executionPlan.value.material.model.resolved) ||\n state.modelReservation.digest !== state.executionPlan.value.material.model.access.grantDigest ||\n state.modelReservation.preparationId !== state.preparationId ||\n state.modelReservation.expiresAtMs !== state.reservationExpiresAtMs ||\n canonicalCandidateDigest(state.modelReservation.network) !==\n canonicalCandidateDigest(state.executionPlan.value.material.model.access.network) ||\n canonicalCandidateDigest(state.modelReservation.enforcedLimits) !==\n canonicalCandidateDigest(modelLimits(state.executionPlan.value.material.limits))\n ) {\n throw new Error('prepared model access no longer matches the signed execution plan')\n }\n assertExecutorInputs(state)\n if (\n (state.memory.mode === 'isolated' && !state.memoryReservation) ||\n (state.memory.mode === 'disabled' && state.memoryReservation)\n ) {\n throw new Error('prepared memory reservation does not match the signed execution plan')\n }\n if (\n state.memory.mode === 'isolated' &&\n state.memoryReservation &&\n (state.memoryReservation.preparationId !== state.preparationId ||\n state.memoryReservation.expiresAtMs !== state.reservationExpiresAtMs ||\n state.memoryReservation.effectiveNamespace !== state.memory.effectiveNamespace)\n ) {\n throw new Error('prepared memory reservation identity no longer matches the execution')\n }\n if (JSON.stringify(state.memory) !== JSON.stringify(state.executionPlan.value.material.memory)) {\n throw new Error('prepared memory no longer matches the signed execution plan')\n }\n\n const expectedTags = {\n [CANDIDATE_TRACE_TAGS.executionId]: state.executionId,\n [CANDIDATE_TRACE_TAGS.bundleDigest]: state.bundle.digest,\n [CANDIDATE_TRACE_TAGS.executionPlanDigest]: state.executionPlan.value.digest,\n [CANDIDATE_TRACE_TAGS.materializationReceiptDigest]: state.materializationReceipt.digest,\n }\n const expectedTraceEnvironment = {\n [CANDIDATE_TRACE_ENV.executionId]: state.executionId,\n [CANDIDATE_TRACE_ENV.bundleDigest]: state.bundle.digest,\n [CANDIDATE_TRACE_ENV.executionPlanDigest]: state.executionPlan.value.digest,\n [CANDIDATE_TRACE_ENV.materializationReceiptDigest]: state.materializationReceipt.digest,\n [CANDIDATE_TRACE_ENV.traceRunId]: state.trace.runId,\n }\n if (\n !state.trace.runId.startsWith(\n `${state.executionId}:attempt-${state.executionPlan.value.material.attempt.number}:`,\n ) ||\n canonicalCandidateDigest(state.trace.tags) !== canonicalCandidateDigest(expectedTags) ||\n canonicalCandidateDigest(state.trace.env) !== canonicalCandidateDigest(expectedTraceEnvironment)\n ) {\n throw new Error('prepared trace identity no longer matches the signed execution')\n }\n}\n\nfunction assertPlanEvidence(\n evidence:\n | PreparedAgentCandidateExecution['profilePlan']['value']\n | PreparedAgentCandidateExecution['executionPlan']['value'],\n bytes: Uint8Array,\n label: string,\n): void {\n const expected = canonicalCandidateBytes(evidence.material)\n if (\n sha256Bytes(expected) !== evidence.digest ||\n !Buffer.from(expected).equals(Buffer.from(bytes)) ||\n evidence.artifact.sha256 !== evidence.digest ||\n evidence.artifact.byteLength !== bytes.byteLength ||\n !('content' in evidence.artifact) ||\n !Buffer.from(evidence.artifact.content, 'base64').equals(Buffer.from(bytes))\n ) {\n throw new Error(`prepared ${label} no longer matches its canonical bytes`)\n }\n}\n\nfunction evidenceView<T extends { value: unknown; bytes: Uint8Array }>(evidence: T): T {\n const bytes = Uint8Array.from(evidence.bytes)\n return Object.freeze({\n ...evidence,\n get bytes(): Uint8Array {\n return Uint8Array.from(bytes)\n },\n })\n}\n\nfunction bytesView<T extends { bytes: Uint8Array }>(value: T, key: 'bytes'): T {\n const bytes = Uint8Array.from(value.bytes)\n return Object.freeze({\n ...value,\n get [key](): Uint8Array {\n return Uint8Array.from(bytes)\n },\n })\n}\n\nfunction knowledgeView(\n knowledge: NonNullable<PreparedAgentCandidateExecution['knowledge']>,\n): NonNullable<PreparedAgentCandidateExecution['knowledge']> {\n const manifest = Uint8Array.from(knowledge.manifest)\n return Object.freeze({\n snapshotId: knowledge.snapshotId,\n manifestDigest: knowledge.manifestDigest,\n get manifest(): Uint8Array {\n return Uint8Array.from(manifest)\n },\n })\n}\n\nfunction workspaceInputView(\n snapshot: AgentCandidateExecutorRequest['inputs']['task']['snapshot'],\n sourceFiles: PreparedCandidateState['executorInputs']['taskFiles'],\n): AgentCandidateExecutorRequest['inputs']['task'] {\n return Object.freeze({\n snapshot,\n files: Object.freeze(sourceFiles.map((file) => profileFileView(file))),\n })\n}\n\nfunction profileFileView(\n source: PreparedCandidateState['executorInputs']['profileFiles'][number],\n): AgentCandidateExecutorRequest['inputs']['profile']['files'][number] {\n const bytes = Uint8Array.from(source.bytes)\n return Object.freeze({\n path: source.path,\n mode: source.mode,\n get bytes(): Uint8Array {\n return Uint8Array.from(bytes)\n },\n })\n}\n\nfunction assertExecutorInputs(state: PreparedCandidateState): void {\n const material = state.executionPlan.value.material\n assertWorkspaceExecutorFiles(state.executorInputs.taskFiles, material.task.workspace.material)\n if (material.candidateWorkspace) {\n if (!state.executorInputs.candidateFiles) {\n throw new Error('prepared candidate executor files are missing')\n }\n assertWorkspaceExecutorFiles(\n state.executorInputs.candidateFiles,\n material.candidateWorkspace.material,\n )\n } else if (state.executorInputs.candidateFiles) {\n throw new Error('disabled candidate has executor files')\n }\n\n const expectedFiles = state.profilePlan.value.material.files\n if (state.executorInputs.profileFiles.length !== expectedFiles.length) {\n throw new Error('prepared profile executor files do not match the signed profile plan')\n }\n for (let index = 0; index < expectedFiles.length; index++) {\n const expected = expectedFiles[index]\n const actual = state.executorInputs.profileFiles[index]\n if (\n !expected ||\n !actual ||\n actual.path !== expected.relPath ||\n actual.mode !== expected.mode ||\n sha256Bytes(actual.bytes) !== expected.contentSha256\n ) {\n throw new Error('prepared profile executor files do not match the signed profile plan')\n }\n }\n}\n\nfunction assertWorkspaceExecutorFiles(\n actualFiles: PreparedCandidateState['executorInputs']['taskFiles'],\n expected: PreparedAgentCandidateExecution['executionPlan']['value']['material']['task']['workspace']['material'],\n): void {\n if (actualFiles.length !== expected.files.length) {\n throw new Error('prepared workspace executor files do not match the signed manifest')\n }\n for (let index = 0; index < expected.files.length; index++) {\n const actual = actualFiles[index]\n const planned = expected.files[index]\n if (\n !actual ||\n !planned ||\n actual.path !== planned.path ||\n actual.mode !== planned.mode ||\n actual.bytes.byteLength !== planned.byteLength ||\n sha256Bytes(actual.bytes) !== planned.sha256\n ) {\n throw new Error('prepared workspace executor files do not match the signed manifest')\n }\n }\n}\n\nfunction immutableExecutorFiles(\n files: PreparedCandidateState['executorInputs']['taskFiles'],\n): ReadonlyArray<{ path: string; mode: 0o644 | 0o755; bytes: Uint8Array }> {\n return Object.freeze(\n files.map((file) => Object.freeze({ ...file, bytes: Uint8Array.from(file.bytes) })),\n )\n}\n\nfunction modelLimits(\n limits: PreparedAgentCandidateExecution['executionPlan']['value']['material']['limits'],\n): AgentCandidateProtectedModelReservation['enforcedLimits'] {\n return {\n maxModelCalls: limits.maxModelCalls,\n maxInputTokens: limits.maxInputTokens,\n maxOutputTokens: limits.maxOutputTokens,\n maxCostUsd: limits.maxCostUsd,\n }\n}\n\nfunction transitionLifecycle(\n prepared: PreparedAgentCandidateExecution,\n expected: ReadonlyArray<\n | 'prepared'\n | 'claiming'\n | 'claimed'\n | 'running'\n | 'settling'\n | 'disposing'\n | 'succeeded'\n | 'failed'\n | 'disposal-failed'\n | 'cleanup-failed'\n | 'disposed'\n >,\n next:\n | 'claiming'\n | 'claimed'\n | 'running'\n | 'settling'\n | 'disposing'\n | 'succeeded'\n | 'failed'\n | 'disposal-failed'\n | 'cleanup-failed'\n | 'disposed',\n): void {\n const lifecycle = lifecycleByExecution.get(prepared)\n if (!lifecycle || !expected.includes(lifecycle.status)) {\n throw new Error(`prepared candidate execution is already ${lifecycle?.status ?? 'unknown'}`)\n }\n lifecycle.status = next\n}\n\nfunction assertProtectedEnvironment(\n state: PreparedCandidateState,\n modelEnvironment: Readonly<Record<string, string>>,\n memoryEnvironment: Readonly<Record<string, string>> | undefined,\n): void {\n const seen = new Set([...Object.keys(state.launch.env), ...Object.keys(state.trace.env)])\n for (const [name, value] of [\n ...Object.entries(modelEnvironment),\n ...Object.entries(memoryEnvironment ?? {}),\n ]) {\n if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(name) || typeof value !== 'string' || value.length < 8) {\n throw new Error('protected model activation contains an invalid environment binding')\n }\n if (seen.has(name)) {\n throw new Error(`protected model activation collides with environment binding ${name}`)\n }\n seen.add(name)\n }\n}\n","import { constants as fsConstants } from 'node:fs'\nimport { lstat, open, readdir, realpath } from 'node:fs/promises'\nimport { relative, resolve, sep } from 'node:path'\n\nimport type {\n AgentCandidateArtifactRef,\n AgentCandidateCapturedArtifact,\n AgentCandidateProfilePlanMaterialV1,\n AgentCandidateWorkspaceManifestMaterialV1,\n AgentCandidateWorkspaceSnapshotEvidence,\n} from '@tangle-network/agent-interface'\n\nimport { canonicalCandidateBytes, sha256Bytes } from './digest'\nimport type { AgentCandidateArtifactPort } from './types'\n\nexport function artifactCacheKey(artifact: AgentCandidateCapturedArtifact): string {\n return `${artifact.sha256}:${artifact.byteLength}`\n}\n\nexport async function readVerifiedArtifact(\n artifact: AgentCandidateCapturedArtifact,\n port: AgentCandidateArtifactPort,\n): Promise<Uint8Array> {\n const bytes =\n 'content' in artifact\n ? Buffer.from(artifact.content, 'base64')\n : await port.read(artifact as AgentCandidateArtifactRef)\n verifyBytes(bytes, artifact.sha256, artifact.byteLength, 'candidate artifact')\n return Uint8Array.from(bytes)\n}\n\nexport function verifyBytes(\n bytes: Uint8Array,\n digest: string,\n byteLength: number,\n label: string,\n): void {\n if (bytes.byteLength !== byteLength) {\n throw new Error(`${label} byte length ${bytes.byteLength} does not match ${byteLength}`)\n }\n const actual = sha256Bytes(bytes)\n if (actual !== digest) {\n throw new Error(`${label} digest ${actual} does not match ${digest}`)\n }\n}\n\nexport async function verifyWorkspaceSnapshotArtifacts(\n snapshot: AgentCandidateWorkspaceSnapshotEvidence,\n port: AgentCandidateArtifactPort,\n): Promise<{ manifest: Uint8Array; archive: Uint8Array }> {\n const [manifest, archive] = await Promise.all([\n readVerifiedArtifact(snapshot.manifest, port),\n readVerifiedArtifact(snapshot.archive, port),\n ])\n const canonicalManifest = canonicalCandidateBytes(snapshot.material)\n if (!Buffer.from(manifest).equals(Buffer.from(canonicalManifest))) {\n throw new Error('workspace manifest artifact is not the exact canonical manifest material')\n }\n if (sha256Bytes(canonicalManifest) !== snapshot.digest) {\n throw new Error('workspace snapshot digest does not match its canonical manifest material')\n }\n return { manifest, archive }\n}\n\nexport async function verifyMaterializedWorkspace(\n root: string,\n expected: AgentCandidateWorkspaceManifestMaterialV1,\n options: { ignoredProtectedRootEntries?: readonly ('.git' | '.sidecar')[] } = {},\n): Promise<void> {\n const observed = await scanWorkspace(root, new Set(options.ignoredProtectedRootEntries ?? []))\n assertWorkspaceManifest(observed.manifest, expected)\n}\n\n/** Capture exact verified regular-file bytes for fresh isolated materialization. */\nexport async function readMaterializedWorkspaceFiles(\n root: string,\n expected: AgentCandidateWorkspaceManifestMaterialV1,\n options: { ignoredProtectedRootEntries?: readonly ('.git' | '.sidecar')[] } = {},\n): Promise<ReadonlyArray<{ path: string; mode: 0o644 | 0o755; bytes: Uint8Array }>> {\n const observed = await scanWorkspace(root, new Set(options.ignoredProtectedRootEntries ?? []))\n assertWorkspaceManifest(observed.manifest, expected)\n return observed.files.map((file) =>\n Object.freeze({ path: file.path, mode: file.mode, bytes: Uint8Array.from(file.bytes) }),\n )\n}\n\nfunction assertWorkspaceManifest(\n observed: AgentCandidateWorkspaceManifestMaterialV1,\n expected: AgentCandidateWorkspaceManifestMaterialV1,\n): void {\n if (!Buffer.from(canonicalCandidateBytes(observed)).equals(canonicalCandidateBytes(expected))) {\n throw new Error(\n 'materialized workspace files, modes, or bytes do not match the signed manifest',\n )\n }\n}\n\nexport async function verifyMaterializedProfileWorkspace(\n root: string,\n expected: AgentCandidateProfilePlanMaterialV1,\n): Promise<void> {\n const observed = await scanWorkspace(root, new Set())\n const observedProfile = observed.manifest.files.map(({ path, mode, sha256 }) => ({\n relPath: path,\n mode,\n contentSha256: sha256,\n }))\n if (\n !Buffer.from(canonicalCandidateBytes(observedProfile)).equals(\n canonicalCandidateBytes(expected.files),\n )\n ) {\n throw new Error('profile staging files, modes, or bytes do not match the signed profile plan')\n }\n}\n\nasync function scanWorkspace(\n root: string,\n ignoredProtectedRootEntries: ReadonlySet<string>,\n): Promise<{\n manifest: AgentCandidateWorkspaceManifestMaterialV1\n files: Array<{ path: string; mode: 0o644 | 0o755; bytes: Uint8Array }>\n}> {\n const absoluteRoot = resolve(root)\n const rootStats = await lstat(absoluteRoot)\n if (!rootStats.isDirectory() || rootStats.isSymbolicLink()) {\n throw new Error('workspace root must be a real directory')\n }\n if ((await realpath(absoluteRoot)) !== absoluteRoot) {\n throw new Error('workspace root has a symlinked path component')\n }\n const files: AgentCandidateWorkspaceManifestMaterialV1['files'] = []\n const capturedFiles: Array<{ path: string; mode: 0o644 | 0o755; bytes: Uint8Array }> = []\n\n async function visit(directory: string): Promise<void> {\n const entries = await readdir(directory, { withFileTypes: true })\n entries.sort((a, b) => (a.name < b.name ? -1 : a.name > b.name ? 1 : 0))\n for (const entry of entries) {\n if (directory === absoluteRoot && ignoredProtectedRootEntries.has(entry.name)) {\n continue\n }\n const absolute = resolve(directory, entry.name)\n const relPath = relative(absoluteRoot, absolute).split(sep).join('/')\n if (!relPath || relPath.startsWith('../') || relPath.includes('/../')) {\n throw new Error(`workspace entry escapes root: ${relPath}`)\n }\n const stats = await lstat(absolute)\n if (stats.isSymbolicLink()) {\n throw new Error(`workspace contains a symlink: ${relPath}`)\n }\n if (stats.isDirectory()) {\n await visit(absolute)\n continue\n }\n if (!stats.isFile()) {\n throw new Error(`workspace contains a non-regular entry: ${relPath}`)\n }\n const descriptor = await open(\n absolute,\n fsConstants.O_RDONLY |\n (typeof fsConstants.O_NOFOLLOW === 'number' ? fsConstants.O_NOFOLLOW : 0),\n )\n try {\n const openedStats = await descriptor.stat()\n if (!openedStats.isFile()) {\n throw new Error(`workspace contains a non-regular entry: ${relPath}`)\n }\n if (openedStats.nlink !== 1) {\n throw new Error(`workspace contains a hard-linked file: ${relPath}`)\n }\n const mode = openedStats.mode & 0o777\n if (mode !== 0o644 && mode !== 0o755) {\n throw new Error(`workspace file has unsupported mode ${mode.toString(8)}: ${relPath}`)\n }\n const bytes = await descriptor.readFile()\n const supportedMode = mode as 0o644 | 0o755\n files.push({\n path: relPath,\n mode: supportedMode,\n sha256: sha256Bytes(bytes),\n byteLength: bytes.byteLength,\n })\n capturedFiles.push({ path: relPath, mode: supportedMode, bytes: Uint8Array.from(bytes) })\n } finally {\n await descriptor.close()\n }\n }\n }\n\n await visit(absoluteRoot)\n files.sort((a, b) => (a.path < b.path ? -1 : a.path > b.path ? 1 : 0))\n capturedFiles.sort((a, b) => (a.path < b.path ? -1 : a.path > b.path ? 1 : 0))\n return {\n manifest: {\n schemaVersion: 1,\n kind: 'agent-candidate-workspace-manifest',\n files,\n },\n files: capturedFiles,\n }\n}\n","import { spawn } from 'node:child_process'\nimport { mkdir, mkdtemp, readFile, realpath, rm, stat } from 'node:fs/promises'\nimport { tmpdir } from 'node:os'\nimport { join, resolve } from 'node:path'\n\nimport type {\n AgentCandidateCode,\n AgentCandidateGitHubRepository,\n AgentCandidateGitHubResource,\n AgentCandidateWorkspaceManifestMaterialV1,\n} from '@tangle-network/agent-interface'\n\nimport { verifyBytes } from './artifacts'\nimport { canonicalCandidateBytes, sha256Bytes } from './digest'\nimport type { AgentCandidateRepositoryPort } from './types'\n\ninterface GitResult {\n stdout: Buffer\n stderr: Buffer\n}\n\nexport async function verifyCandidateCode(\n code: AgentCandidateCode,\n repositories: AgentCandidateRepositoryPort,\n patchBytes?: Uint8Array,\n): Promise<string | undefined> {\n if (code.kind === 'disabled') return undefined\n const repositoryRoot = await verifiedRepositoryRoot(code.repository, repositories)\n await assertCommitAndBaseTree(repositoryRoot, code.baseCommit, code.baseTree)\n\n if (code.kind === 'no-op') {\n await assertSafeTree(repositoryRoot, code.baseTree)\n return code.baseTree\n }\n if (!patchBytes) throw new Error('git-patch candidate is missing verified patch bytes')\n\n const temporary = await mkdtemp(join(tmpdir(), 'agent-candidate-git-'))\n try {\n const indexFile = join(temporary, 'index')\n await git(repositoryRoot, ['read-tree', code.baseTree], undefined, {\n GIT_INDEX_FILE: indexFile,\n })\n await git(\n repositoryRoot,\n ['apply', '--cached', '--binary', '--whitespace=nowarn', '-'],\n patchBytes,\n { GIT_INDEX_FILE: indexFile },\n )\n const candidateTree = (\n await git(repositoryRoot, ['write-tree'], undefined, { GIT_INDEX_FILE: indexFile })\n ).stdout\n .toString('utf8')\n .trim()\n if (candidateTree !== code.candidateTree) {\n throw new Error(\n `git patch materialized tree ${candidateTree} does not match ${code.candidateTree}`,\n )\n }\n await assertSafeTree(repositoryRoot, candidateTree)\n return candidateTree\n } finally {\n await rm(temporary, { recursive: true, force: true })\n }\n}\n\nexport async function readCandidateGitHubResource(\n resource: AgentCandidateGitHubResource,\n repositories: AgentCandidateRepositoryPort,\n): Promise<Uint8Array> {\n const repositoryRoot = await verifiedRepositoryRoot(resource.repository, repositories)\n const commitType = (await git(repositoryRoot, ['cat-file', '-t', resource.commit])).stdout\n .toString('utf8')\n .trim()\n if (commitType !== 'commit') {\n throw new Error(`GitHub resource commit is not a commit object: ${resource.commit}`)\n }\n const listing = (\n await git(repositoryRoot, ['ls-tree', '-z', resource.commit, '--', resource.path])\n ).stdout\n const entries = parseTreeEntries(listing)\n if (entries.length !== 1 || entries[0]?.path !== resource.path) {\n throw new Error(`GitHub resource path is not one exact file: ${resource.path}`)\n }\n const entry = entries[0]\n if (!entry || entry.type !== 'blob' || (entry.mode !== '100644' && entry.mode !== '100755')) {\n throw new Error(`GitHub resource path is not a regular Git blob: ${resource.path}`)\n }\n const bytes = (await git(repositoryRoot, ['cat-file', 'blob', entry.object])).stdout\n verifyBytes(bytes, resource.sha256, resource.byteLength, `GitHub resource ${resource.path}`)\n return Uint8Array.from(bytes)\n}\n\nexport async function verifyTaskCheckout(\n taskRoot: string,\n expected: { baseCommit: string; baseTree: string },\n): Promise<void> {\n const root = resolve(taskRoot)\n const head = (await git(root, ['rev-parse', 'HEAD'])).stdout.toString('utf8').trim()\n if (head !== expected.baseCommit) {\n throw new Error(`task checkout HEAD ${head} does not match ${expected.baseCommit}`)\n }\n const tree = (await git(root, ['rev-parse', 'HEAD^{tree}'])).stdout.toString('utf8').trim()\n if (tree !== expected.baseTree) {\n throw new Error(`task checkout base tree ${tree} does not match ${expected.baseTree}`)\n }\n}\n\n/**\n * Apply an evaluator-captured binary diff in a detached object database and\n * prove its result tree exactly matches the captured after-state manifest.\n */\nexport async function verifyTaskOutcomePatch(input: {\n repositoryRoot: string\n baseCommit: string\n baseTree: string\n resultTree: string\n patch: Uint8Array\n afterState: AgentCandidateWorkspaceManifestMaterialV1\n}): Promise<{ resultTree: string; resultCommit: string }> {\n const repositoryRoot = resolve(input.repositoryRoot)\n await verifyTaskCheckout(repositoryRoot, input)\n const gitDir = resolve(\n (await git(repositoryRoot, ['rev-parse', '--absolute-git-dir'])).stdout.toString('utf8').trim(),\n )\n if ((await realpath(gitDir)) !== gitDir || gitDir.includes(':')) {\n throw new Error('task Git object store has an unsupported path')\n }\n await assertNoGitIndirection(repositoryRoot, gitDir, 'task repository')\n\n const temporary = await mkdtemp(join(tmpdir(), 'agent-candidate-task-outcome-'))\n try {\n const objectDirectory = join(temporary, 'objects')\n const indexFile = join(temporary, 'index')\n await mkdir(objectDirectory)\n const gitEnvironment = {\n GIT_INDEX_FILE: indexFile,\n GIT_OBJECT_DIRECTORY: objectDirectory,\n GIT_ALTERNATE_OBJECT_DIRECTORIES: join(gitDir, 'objects'),\n }\n await git(repositoryRoot, ['read-tree', input.baseTree], undefined, gitEnvironment)\n if (input.patch.byteLength > 0) {\n await git(\n repositoryRoot,\n ['apply', '--cached', '--binary', '--whitespace=nowarn', '-'],\n input.patch,\n gitEnvironment,\n )\n }\n const resultTree = (await git(repositoryRoot, ['write-tree'], undefined, gitEnvironment)).stdout\n .toString('utf8')\n .trim()\n if (resultTree !== input.resultTree) {\n throw new Error(\n `task outcome patch materialized tree ${resultTree} does not match ${input.resultTree}`,\n )\n }\n await assertSafeTree(repositoryRoot, resultTree, gitEnvironment)\n const observed = await workspaceManifestFromGitTree(repositoryRoot, resultTree, gitEnvironment)\n if (\n !Buffer.from(canonicalCandidateBytes(observed)).equals(\n Buffer.from(canonicalCandidateBytes(input.afterState)),\n )\n ) {\n throw new Error('task outcome after-state does not match the materialized result tree')\n }\n const resultCommit = (\n await git(\n repositoryRoot,\n ['commit-tree', resultTree, '-p', input.baseCommit],\n Buffer.from('candidate task outcome\\n', 'utf8'),\n {\n ...gitEnvironment,\n GIT_AUTHOR_NAME: 'Tangle Evaluator',\n GIT_AUTHOR_EMAIL: 'evaluator@tangle.tools',\n GIT_AUTHOR_DATE: '2000-01-01T00:00:00Z',\n GIT_COMMITTER_NAME: 'Tangle Evaluator',\n GIT_COMMITTER_EMAIL: 'evaluator@tangle.tools',\n GIT_COMMITTER_DATE: '2000-01-01T00:00:00Z',\n },\n )\n ).stdout\n .toString('utf8')\n .trim()\n const committedTree = (\n await git(repositoryRoot, ['rev-parse', `${resultCommit}^{tree}`], undefined, gitEnvironment)\n ).stdout\n .toString('utf8')\n .trim()\n if (committedTree !== resultTree) {\n throw new Error('task outcome evaluator commit does not bind the verified result tree')\n }\n return { resultTree, resultCommit }\n } finally {\n await rm(temporary, { recursive: true, force: true })\n }\n}\n\nasync function verifiedRepositoryRoot(\n repository: AgentCandidateGitHubRepository,\n repositories: AgentCandidateRepositoryPort,\n): Promise<string> {\n const repositoryRoot = resolve(await repositories.resolve(repository))\n const rootStats = await stat(repositoryRoot)\n if (!rootStats.isDirectory()) throw new Error('candidate repository path is not a directory')\n\n const origin = (await git(repositoryRoot, ['remote', 'get-url', 'origin'])).stdout\n .toString('utf8')\n .trim()\n const actual = parseGitHubRemote(origin)\n if (!actual || actual.owner !== repository.owner || actual.repo !== repository.repo) {\n throw new Error(\n `local repository origin ${origin || '<missing>'} does not match github.com/${repository.owner}/${repository.repo}`,\n )\n }\n\n const gitDirText = (await git(repositoryRoot, ['rev-parse', '--absolute-git-dir'])).stdout\n .toString('utf8')\n .trim()\n const gitDir = resolve(gitDirText)\n await assertNoGitIndirection(repositoryRoot, gitDir, 'candidate repository')\n return repositoryRoot\n}\n\nasync function assertNoGitIndirection(\n repositoryRoot: string,\n gitDir: string,\n label: string,\n): Promise<void> {\n const replacements = (\n await git(repositoryRoot, ['for-each-ref', '--format=%(refname)', 'refs/replace'])\n ).stdout\n .toString('utf8')\n .trim()\n if (replacements) throw new Error(`${label} contains Git replace refs`)\n for (const name of ['alternates', 'http-alternates']) {\n const path = join(gitDir, 'objects', 'info', name)\n try {\n const contents = await readFile(path, 'utf8')\n if (contents.trim()) throw new Error(`${label} uses forbidden Git ${name}`)\n } catch (error) {\n if (!isNoEntry(error)) throw error\n }\n }\n}\n\nasync function assertCommitAndBaseTree(\n repositoryRoot: string,\n commit: string,\n expectedTree: string,\n): Promise<void> {\n const type = (await git(repositoryRoot, ['cat-file', '-t', commit])).stdout\n .toString('utf8')\n .trim()\n if (type !== 'commit') throw new Error(`candidate base object is not a commit: ${commit}`)\n const actualTree = (await git(repositoryRoot, ['rev-parse', `${commit}^{tree}`])).stdout\n .toString('utf8')\n .trim()\n if (actualTree !== expectedTree) {\n throw new Error(`candidate base commit tree ${actualTree} does not match ${expectedTree}`)\n }\n}\n\nasync function assertSafeTree(\n repositoryRoot: string,\n tree: string,\n environment: Record<string, string> = {},\n): Promise<void> {\n const listing = (\n await git(repositoryRoot, ['ls-tree', '-rz', '--full-tree', tree], undefined, environment)\n ).stdout\n const entries = parseTreeEntries(listing)\n if (entries.length === 0) throw new Error('candidate Git tree cannot be empty')\n for (const entry of entries) {\n if (entry.type !== 'blob' || (entry.mode !== '100644' && entry.mode !== '100755')) {\n throw new Error(\n `candidate Git tree contains a symlink, submodule, or non-blob: ${entry.path}`,\n )\n }\n assertSafeGitPath(entry.path)\n }\n}\n\nasync function workspaceManifestFromGitTree(\n repositoryRoot: string,\n tree: string,\n environment: Record<string, string>,\n): Promise<AgentCandidateWorkspaceManifestMaterialV1> {\n const listing = (\n await git(repositoryRoot, ['ls-tree', '-rz', '--full-tree', tree], undefined, environment)\n ).stdout\n const entries = parseTreeEntries(listing)\n const files = await Promise.all(\n entries.map(async (entry) => {\n if (entry.type !== 'blob' || (entry.mode !== '100644' && entry.mode !== '100755')) {\n throw new Error(`task outcome tree contains a non-regular file: ${entry.path}`)\n }\n const bytes = (\n await git(repositoryRoot, ['cat-file', 'blob', entry.object], undefined, environment)\n ).stdout\n return {\n path: entry.path,\n mode: entry.mode === '100755' ? (0o755 as const) : (0o644 as const),\n sha256: sha256Bytes(bytes),\n byteLength: bytes.byteLength,\n }\n }),\n )\n files.sort((left, right) => left.path.localeCompare(right.path))\n return {\n schemaVersion: 1,\n kind: 'agent-candidate-workspace-manifest',\n files,\n }\n}\n\nfunction parseTreeEntries(bytes: Uint8Array): Array<{\n mode: string\n type: string\n object: string\n path: string\n}> {\n const raw = Buffer.from(bytes)\n const decoded = raw.toString('utf8')\n if (!Buffer.from(decoded, 'utf8').equals(raw)) {\n throw new Error('candidate Git tree contains a non-UTF-8 path')\n }\n const rows = decoded.split('\\0').filter(Boolean)\n return rows.map((row) => {\n const tab = row.indexOf('\\t')\n const header = row.slice(0, tab).split(' ')\n const path = row.slice(tab + 1)\n const [mode, type, object] = header\n if (tab < 1 || !mode || !type || !object || !path) {\n throw new Error('malformed Git tree entry')\n }\n return { mode, type, object, path }\n })\n}\n\nfunction assertSafeGitPath(path: string): void {\n if (\n !path ||\n path.startsWith('/') ||\n path.includes('\\\\') ||\n path.includes('\\0') ||\n hasControlCharacter(path) ||\n path.split('/').some((part) => !part || part === '.' || part === '..') ||\n path.split('/')[0]?.toLowerCase() === '.git'\n ) {\n throw new Error(`candidate Git tree contains an unsafe path: ${path}`)\n }\n}\n\nfunction hasControlCharacter(value: string): boolean {\n for (let index = 0; index < value.length; index++) {\n const code = value.charCodeAt(index)\n if (code < 0x20 || code === 0x7f) return true\n }\n return false\n}\n\nfunction parseGitHubRemote(value: string): { owner: string; repo: string } | undefined {\n const match = value.match(\n /^(?:https?:\\/\\/github\\.com\\/|ssh:\\/\\/git@github\\.com\\/|git@github\\.com:)([^/]+)\\/([^/]+?)(?:\\.git)?$/,\n )\n if (!match?.[1] || !match[2]) return undefined\n return { owner: match[1], repo: match[2] }\n}\n\nasync function git(\n repositoryRoot: string,\n args: string[],\n input?: Uint8Array,\n extraEnv: Record<string, string> = {},\n): Promise<GitResult> {\n const env = Object.fromEntries(\n Object.entries(process.env).filter(([name]) => !name.startsWith('GIT_')),\n ) as Record<string, string>\n Object.assign(env, {\n GIT_CONFIG_NOSYSTEM: '1',\n GIT_CONFIG_GLOBAL: '/dev/null',\n GIT_CONFIG_SYSTEM: '/dev/null',\n GIT_TERMINAL_PROMPT: '0',\n GIT_NO_REPLACE_OBJECTS: '1',\n LC_ALL: 'C',\n ...extraEnv,\n })\n const fullArgs = [\n '-c',\n 'core.hooksPath=/dev/null',\n '-c',\n 'protocol.file.allow=never',\n '-C',\n repositoryRoot,\n ...args,\n ]\n return await new Promise((resolveResult, reject) => {\n const child = spawn('git', fullArgs, { env, stdio: ['pipe', 'pipe', 'pipe'] })\n const stdout: Buffer[] = []\n const stderr: Buffer[] = []\n child.stdout.on('data', (chunk: Buffer) => stdout.push(chunk))\n child.stderr.on('data', (chunk: Buffer) => stderr.push(chunk))\n child.on('error', reject)\n child.on('close', (code, signal) => {\n const out = Buffer.concat(stdout)\n const err = Buffer.concat(stderr)\n if (code !== 0) {\n reject(\n new Error(\n `git ${args[0] ?? '<command>'} failed (${signal ?? code}): ${err.toString('utf8').trim()}`,\n ),\n )\n return\n }\n resolveResult({ stdout: out, stderr: err })\n })\n if (input) child.stdin.end(input)\n else child.stdin.end()\n })\n}\n\nfunction isNoEntry(error: unknown): boolean {\n return (\n typeof error === 'object' &&\n error !== null &&\n 'code' in error &&\n (error as { code?: string }).code === 'ENOENT'\n )\n}\n","import type { BenchmarkEvaluation, TraceStore } from '@tangle-network/agent-eval'\nimport type {\n AgentCandidateArtifactRef,\n AgentCandidateAttemptPolicy,\n AgentCandidateBundle,\n AgentCandidateCapturedArtifact,\n AgentCandidateContainer,\n AgentCandidateEffectiveMemory,\n AgentCandidateExecutionLimits,\n AgentCandidateExecutionPlanEvidence,\n AgentCandidateGitHubRepository,\n AgentCandidateInstructionDelivery,\n AgentCandidateMaterializationReceipt,\n AgentCandidateMemoryReceipt,\n AgentCandidateModelAccessNetwork,\n AgentCandidateOciPlatform,\n AgentCandidateProfilePlanEvidence,\n AgentCandidateResolvedModel,\n AgentCandidateRunReceiptV2,\n AgentCandidateSpend,\n AgentCandidateTaskOutcomeEvidence,\n AgentCandidateTermination,\n AgentCandidateWorkspaceManifestMaterialV1,\n AgentCandidateWorkspaceSnapshotEvidence,\n ReasoningEffort,\n Sha256Digest,\n} from '@tangle-network/agent-interface'\n\nexport const verifiedCandidateBrand: unique symbol = Symbol('verifiedAgentCandidate')\nexport const preparedCandidateBrand: unique symbol = Symbol('preparedAgentCandidate')\nexport const verifiedTaskOutcomeBrand: unique symbol = Symbol('verifiedTaskOutcome')\n\n/** Reads one content-addressed object from the closed S3/IPFS locator set. */\nexport interface AgentCandidateArtifactPort {\n read(ref: AgentCandidateArtifactRef): Promise<Uint8Array>\n}\n\nexport type AgentCandidateOutputPurpose =\n | 'task-manifest'\n | 'task-archive'\n | 'task-patch'\n | 'task-outcome'\n | 'memory-after-manifest'\n | 'memory-after-archive'\n | 'grader-evidence'\n | 'benchmark-result'\n | 'model-settlement'\n | 'trace'\n | 'run-receipt'\n | 'failure-evidence'\n\n/** Durable content-addressed evidence store controlled only by the evaluator. */\nexport interface AgentCandidateOutputArtifactPort extends AgentCandidateArtifactPort {\n /** Must be idempotent for identical bytes and return only a durable S3/IPFS locator. */\n put(input: {\n executionId: string\n purpose: AgentCandidateOutputPurpose\n bytes: Uint8Array\n /** Abort must prevent durable publication when it happens before resolution. */\n signal?: AbortSignal\n }): Promise<AgentCandidateArtifactRef>\n}\n\n/** Resolves a declared GitHub repository to an already-present local Git object store. */\nexport interface AgentCandidateRepositoryPort {\n resolve(repository: AgentCandidateGitHubRepository): Promise<string>\n}\n\nexport interface AgentCandidateVerificationPorts {\n artifacts: AgentCandidateArtifactPort\n repositories: AgentCandidateRepositoryPort\n}\n\n/**\n * Materializes an already-verified workspace archive.\n *\n * The runtime independently scans every resulting byte, mode, and path against\n * the signed manifest after this returns. Implementations may therefore unpack\n * any archive encoding, or no-op when the exact workspace is already present.\n */\nexport interface AgentCandidateWorkspacePort {\n materialize(input: {\n role: 'task' | 'candidate' | 'memory'\n snapshot: AgentCandidateWorkspaceSnapshotEvidence\n archive: Uint8Array\n destination: string\n }): Promise<void>\n}\n\nexport interface ResolvedAgentCandidateContainer {\n source: 'pinned-container' | 'evaluator-task-container'\n image: string\n indexDigest: Sha256Digest\n manifestDigest: Sha256Digest\n platform: AgentCandidateOciPlatform\n}\n\nexport interface AgentCandidateContainerPort {\n resolve(input: {\n candidate: AgentCandidateContainer | undefined\n evaluatorTaskContainer: ResolvedAgentCandidateContainer | undefined\n }): Promise<ResolvedAgentCandidateContainer>\n}\n\nexport interface AgentCandidateModelPort {\n resolve(input: {\n requested: string\n harness: AgentCandidateBundle['execution']['harness']\n reasoningEffort: NonNullable<AgentCandidateBundle['profile']['model']>['reasoningEffort']\n }): Promise<AgentCandidateResolvedModel>\n /**\n * Reserve a stable access identity without creating a live credential.\n * The reservation is scoped to `preparationId` and must automatically expire\n * at `expiresAtMs`, even if this call returns ambiguously to the runtime.\n */\n reserveGrant(input: {\n executionId: string\n preparationId: string\n expiresAtMs: number\n attempt: AgentCandidateAttemptPolicy\n bundleDigest: Sha256Digest\n resolved: AgentCandidateResolvedModel\n limits: AgentCandidateModelLimits\n }): Promise<AgentCandidateProtectedModelReservation>\n /** Create the live scoped credential only after the execution attempt is durably claimed. */\n activateGrant(input: {\n executionId: string\n preparationId: string\n grantDigest: Sha256Digest\n resolved: AgentCandidateResolvedModel\n deadlineAtMs: number\n }): Promise<AgentCandidateProtectedModelActivation>\n /**\n * Atomically revoke the grant, drain in-flight calls, and return its immutable final ledger.\n * This operation must be idempotent for the exact preparation and must also\n * settle a reservation that was never activated. It must never affect a\n * different preparation, even when both reservations report the same digest.\n */\n settleGrant(input: {\n executionId: string\n preparationId: string\n grantDigest: Sha256Digest\n resolved: AgentCandidateResolvedModel\n reason: 'completed' | 'failed' | 'timeout' | 'replayed' | 'preparation-failed' | 'abandoned'\n }): Promise<AgentCandidateProtectedModelSettlement>\n}\n\n/** Limits mechanically enforced by the evaluator-owned model gateway. */\nexport type AgentCandidateModelLimits = Pick<\n AgentCandidateExecutionLimits,\n 'maxModelCalls' | 'maxInputTokens' | 'maxOutputTokens' | 'maxCostUsd'\n>\n\nexport interface AgentCandidateProtectedModelReservation {\n preparationId: string\n digest: Sha256Digest\n /** Evaluator service must expire and revoke this reservation at this epoch millisecond. */\n expiresAtMs: number\n /** The gateway must stop calls before any one of these limits is exceeded. */\n enforcedLimits: AgentCandidateModelLimits\n /** Exact public endpoint exception; every other candidate destination stays blocked. */\n network: AgentCandidateModelAccessNetwork\n}\n\nexport interface AgentCandidateProtectedModelActivation {\n /** Injected only into the trusted executor after all pre-launch checks pass. */\n env: Readonly<Record<string, string>>\n}\n\n/** One evaluator-gateway call in the final, revoked model-access ledger. */\nexport interface AgentCandidateProtectedModelCall {\n callId: string\n /** Router-generated public response identity. */\n generationId: string\n /** Exact protected agent-eval LLM span produced from the router ledger. */\n traceSpanId: string\n status: 'succeeded' | 'failed'\n model: string\n startedAtMs: number\n endedAtMs: number\n inputTokens: number\n outputTokens: number\n cachedInputTokens: number\n reasoningTokens: number\n /** Integer billionths of one US dollar; avoids floating-point ledger drift. */\n costUsdNanos: number\n}\n\nexport interface AgentCandidateProtectedModelSettlement {\n preparationId: string\n grantDigest: Sha256Digest\n closed: true\n calls: readonly AgentCandidateProtectedModelCall[]\n}\n\nexport interface AgentCandidateMemoryResetResult {\n preparationId: string\n accessDigest: Sha256Digest\n expiresAtMs: number\n evidence: AgentCandidateCapturedArtifact\n emptyStateDigest: Sha256Digest\n beforeState: AgentCandidateWorkspaceSnapshotEvidence\n}\n\nexport interface AgentCandidateMemoryPort {\n /**\n * Reset and reserve exact task memory without returning live access.\n * The service must scope the reservation to `preparationId`, automatically\n * revoke it at `expiresAtMs`, and never reuse it for another preparation.\n */\n reset(input: {\n executionId: string\n preparationId: string\n expiresAtMs: number\n effectiveNamespace: string\n seed?: Uint8Array\n seedDigest?: Sha256Digest\n }): Promise<AgentCandidateMemoryResetResult>\n /**\n * Create live scoped access only after the execution attempt is durably claimed.\n * Activation must match the exact preparation/access pair and may not extend expiry.\n */\n activate(input: {\n executionId: string\n preparationId: string\n accessDigest: Sha256Digest\n effectiveNamespace: string\n deadlineAtMs: number\n }): Promise<{ env: Readonly<Record<string, string>> }>\n /**\n * Revoke evaluator-owned access after process death or a failed preparation.\n * Must be idempotent and concurrency-safe for the exact preparation/access\n * pair and must never close a different preparation.\n */\n close(input: {\n executionId: string\n preparationId: string\n accessDigest: Sha256Digest\n effectiveNamespace: string\n reason: 'completed' | 'failed' | 'timeout' | 'replayed' | 'preparation-failed' | 'abandoned'\n }): Promise<{ closed: true }>\n}\n\nexport interface AgentCandidateExecutionPorts extends AgentCandidateVerificationPorts {\n workspaces: AgentCandidateWorkspacePort\n containers: AgentCandidateContainerPort\n models: AgentCandidateModelPort\n memory: AgentCandidateMemoryPort\n}\n\nexport interface AgentCandidateTaskExecution {\n executionId: string\n benchmark: string\n benchmarkVersion: string\n taskId: string\n splitDigest: Sha256Digest\n /** Exact agent-visible task instruction. The runtime rejects malformed Unicode. */\n instruction: string\n repository: {\n identity: string\n rootIdentity: string\n baseCommit: string\n baseTree: string\n }\n attempt: AgentCandidateAttemptPolicy\n model: {\n requested: string\n reasoningEffort: ReasoningEffort\n }\n /** Absolute paths inside the evaluator-owned execution environment. */\n executionRoots: {\n taskRoot: string\n candidateRoot?: string\n }\n /** Host-side staging roots. These are verified but never signed as container paths. */\n stagingRoots: {\n taskRoot: string\n candidateRoot?: string\n profileRoot: string\n }\n workspace: AgentCandidateWorkspaceSnapshotEvidence\n evaluatorTaskContainer?: ResolvedAgentCandidateContainer\n limits: AgentCandidateExecutionLimits\n}\n\nexport interface VerifiedAgentCandidate {\n readonly bundle: AgentCandidateBundle\n readonly materializedTree?: string\n readonly [verifiedCandidateBrand]: true\n}\n\nexport interface CanonicalCandidateDocument<T> {\n readonly value: T\n /** Canonical UTF-8 bytes of `value` with its top-level digest omitted. */\n readonly bytes: Uint8Array\n readonly digest: Sha256Digest\n}\n\nexport interface PreparedAgentCandidateLaunch {\n executable: string\n /** Complete fixed argv, including profile materializer flags but excluding task delivery. */\n args: readonly string[]\n env: Readonly<Record<string, string>>\n /** Informational subset already present at the tail of `args`; executors must not append twice. */\n flags: readonly string[]\n cwd: string\n}\n\nexport interface PreparedAgentCandidateInstruction {\n bytes: Uint8Array\n delivery: AgentCandidateInstructionDelivery\n}\n\nexport interface PreparedAgentCandidateTrace {\n runId: string\n tags: Readonly<Record<string, string>>\n env: Readonly<Record<string, string>>\n}\n\nexport interface PreparedAgentCandidateExecution {\n readonly bundle: AgentCandidateBundle\n readonly executionId: string\n readonly roots: {\n execution: {\n taskRoot: string\n candidateRoot?: string\n }\n staging: {\n taskRoot: string\n candidateRoot?: string\n profileRoot: string\n }\n }\n readonly profilePlan: {\n value: AgentCandidateProfilePlanEvidence\n bytes: Uint8Array\n written: readonly string[]\n }\n readonly executionPlan: {\n value: AgentCandidateExecutionPlanEvidence\n bytes: Uint8Array\n }\n readonly materializationReceipt: CanonicalCandidateDocument<AgentCandidateMaterializationReceipt>\n readonly launch: PreparedAgentCandidateLaunch\n readonly instruction: PreparedAgentCandidateInstruction\n readonly resolvedModel: AgentCandidateResolvedModel\n readonly knowledge?: {\n snapshotId: string\n manifestDigest: Sha256Digest\n manifest: Uint8Array\n }\n readonly trace: PreparedAgentCandidateTrace\n readonly memory: AgentCandidateEffectiveMemory\n readonly [preparedCandidateBrand]: true\n}\n\nexport interface AgentCandidateProtectedRunCapture {\n executionId: string\n termination: AgentCandidateTermination\n}\n\n/** Raw evaluator capture made only after the candidate process is dead. */\nexport interface AgentCandidateExecutorTaskOutcomeCapture {\n /** Claimed final tree. The runtime recomputes it independently from `gitDiff`. */\n resultTree: string\n /** Complete evaluator-captured workspace description after candidate execution. */\n afterState: AgentCandidateWorkspaceManifestMaterialV1\n /** Reproducible workspace archive corresponding to `afterState`. */\n archive: Uint8Array\n /** Exact binary patch from the signed task base to `afterState`. */\n gitDiff: Uint8Array\n}\n\n/** Raw isolated-memory capture made only after access has been revoked. */\nexport interface AgentCandidateExecutorMemoryCapture {\n readonly afterState: AgentCandidateWorkspaceManifestMaterialV1\n readonly archive: Uint8Array\n}\n\n/** Idempotent executor result after process death and trace drain. */\nexport interface AgentCandidateExecutorFinalCapture {\n readonly stopped: true\n readonly taskOutcome?: AgentCandidateExecutorTaskOutcomeCapture\n /** Required only when the prepared candidate uses isolated task memory. */\n readonly memoryAfter?: AgentCandidateExecutorMemoryCapture\n}\n\n/** Branded task outcome that has survived independent patch and tree verification. */\nexport interface VerifiedAgentCandidateTaskOutcome {\n readonly evidence: AgentCandidateTaskOutcomeEvidence & {\n readonly artifact: AgentCandidateArtifactRef\n }\n readonly patch: Uint8Array\n readonly [verifiedTaskOutcomeBrand]: true\n}\n\n/**\n * Evaluator-owned executable grader, pinned by immutable implementation bytes.\n *\n * `run` is an isolation boundary, not an arbitrary scoring callback. The\n * implementation admitted to that boundary is supplied by the runtime after\n * artifact verification. Implementations must derive every returned binding\n * digest from the bytes and task outcome they actually admitted, rather than\n * copying an expected digest from ambient configuration.\n */\nexport interface AgentCandidateBenchmarkGraderPort {\n readonly name: string\n readonly version: string\n readonly artifact: AgentCandidateArtifactRef\n run(input: {\n readonly executionId: string\n readonly termination: AgentCandidateTermination\n readonly outcome: VerifiedAgentCandidateTaskOutcome\n /** Exact verified artifact bytes. Each read returns a detached copy. */\n readonly implementation: {\n readonly byteLength: number\n readonly bytes: Uint8Array\n }\n /** Frozen result deadline; runners must stop work and side effects when aborted. */\n readonly signal: AbortSignal\n }): Promise<{\n readonly evaluation: BenchmarkEvaluation\n /** Raw grader output needed to audit or reproduce the normalized result. */\n readonly evidence: Uint8Array\n /** Runtime-checked binding between admitted code, task input, and raw output. */\n readonly binding: {\n /** Digest computed from the implementation bytes admitted to execution. */\n readonly implementationDigest: Sha256Digest\n /** Digest of the exact runtime-verified task outcome graded by this run. */\n readonly taskOutcomeDigest: Sha256Digest\n /** Digest computed from `evidence` before it leaves the execution boundary. */\n readonly outputDigest: Sha256Digest\n }\n }>\n}\n\n/** One detached request passed to the trusted environment-specific executor. */\nexport interface AgentCandidateExecutorRequest {\n readonly executionId: string\n /** Immutable bytes from which the executor creates fresh isolated workspaces. */\n readonly inputs: {\n readonly task: AgentCandidateExecutorWorkspaceInput\n readonly candidate?: AgentCandidateExecutorWorkspaceInput\n readonly profile: {\n readonly files: readonly AgentCandidateExecutorProfileFile[]\n }\n }\n readonly roots: PreparedAgentCandidateExecution['roots']['execution']\n readonly profilePlan: PreparedAgentCandidateExecution['profilePlan']\n readonly executionPlan: PreparedAgentCandidateExecution['executionPlan']\n readonly materializationReceipt: CanonicalCandidateDocument<AgentCandidateMaterializationReceipt>\n readonly launch: PreparedAgentCandidateLaunch\n readonly instruction: PreparedAgentCandidateInstruction\n readonly resolvedModel: AgentCandidateResolvedModel\n /** Mechanically enforced by the runtime plus executor process-death acknowledgement. */\n readonly hardLimits: Pick<AgentCandidateExecutionLimits, 'timeoutMs'>\n /** Validity bound checked against protected traces; generic black-box executors cannot preempt it. */\n readonly observedLimits: Pick<AgentCandidateExecutionLimits, 'maxSteps'>\n readonly knowledge?: PreparedAgentCandidateExecution['knowledge']\n readonly trace: PreparedAgentCandidateTrace\n readonly memory: AgentCandidateEffectiveMemory\n}\n\n/**\n * Executes one prepared request inside an evaluator-owned isolation boundary.\n *\n * `request.launch.env` is the complete allowlisted environment, including\n * protected model, memory, and trace bindings. Implementations must not merge\n * ambient host variables into it. The returned capture deliberately contains\n * no candidate-authored usage or score fields.\n */\nexport interface AgentCandidateExecutorPort {\n execute(\n request: AgentCandidateExecutorRequest,\n context: {\n traceStore: TraceStore\n /** Aborted by the runtime at the exact frozen wall-time deadline. */\n signal: AbortSignal\n /** Absolute epoch-millisecond deadline owned by the runtime. */\n deadlineAtMs: number\n },\n ): Promise<AgentCandidateProtectedRunCapture>\n /**\n * Kill any process/container still associated with the request, drain trace\n * writes, and capture the final task workspace before teardown.\n * The runtime calls this on success, failure, and timeout before model settlement.\n * Implementations must be idempotent and concurrency-safe for this exact\n * execution/plan pair because a fresh worker may repeat crash recovery.\n */\n stopAndCapture(\n request: AgentCandidateExecutorStopRequest,\n context: {\n traceStore: TraceStore\n reason: 'completed' | 'failed' | 'timeout'\n /** Aborted at the frozen execution deadline or evaluator cleanup deadline. */\n signal: AbortSignal\n /** Absolute execution deadline; a later stop acknowledgement cannot produce success. */\n deadlineAtMs: number\n },\n ): Promise<AgentCandidateExecutorFinalCapture>\n}\n\n/** Opaque process identity used for termination without re-exposing launch credentials. */\nexport interface AgentCandidateExecutorStopRequest {\n readonly executionId: string\n readonly executionPlanDigest: Sha256Digest\n}\n\nexport interface AgentCandidateExecutorWorkspaceInput {\n readonly snapshot: AgentCandidateWorkspaceSnapshotEvidence\n readonly files: readonly AgentCandidateExecutorWorkspaceFile[]\n}\n\nexport interface AgentCandidateExecutorWorkspaceFile {\n readonly path: string\n readonly mode: 0o644 | 0o755\n readonly bytes: Uint8Array\n}\n\nexport interface AgentCandidateExecutorProfileFile {\n readonly path: string\n readonly mode: 0o644 | 0o755\n readonly bytes: Uint8Array\n}\n\nexport type AgentCandidateRunFinalization =\n | {\n succeeded: true\n receipt: CanonicalCandidateDocument<AgentCandidateRunReceiptV2>\n artifacts: {\n modelSettlement: AgentCandidateArtifactRef\n taskOutcome: AgentCandidateArtifactRef\n benchmarkResult: AgentCandidateArtifactRef\n runReceipt: AgentCandidateArtifactRef\n }\n }\n | {\n succeeded: false\n reason: string\n partial: {\n executionId: string\n bundleDigest: Sha256Digest\n executionPlanDigest: Sha256Digest\n materializationReceiptDigest: Sha256Digest\n termination?: AgentCandidateTermination\n }\n /** Independent evaluator-gateway usage, even when execution or trace capture failed. */\n usage: AgentCandidateSpend | null\n }\n\n/** Protected trace tags that bind a run to one prepared candidate execution. */\nexport const CANDIDATE_TRACE_TAGS = {\n executionId: 'tangle.candidate.execution_id',\n bundleDigest: 'tangle.candidate.bundle_digest',\n executionPlanDigest: 'tangle.candidate.execution_plan_digest',\n materializationReceiptDigest: 'tangle.candidate.materialization_receipt_digest',\n} as const\n\n/** Environment keys used to propagate immutable candidate trace identity. */\nexport const CANDIDATE_TRACE_ENV = {\n executionId: 'TANGLE_CANDIDATE_EXECUTION_ID',\n bundleDigest: 'TANGLE_CANDIDATE_BUNDLE_DIGEST',\n executionPlanDigest: 'TANGLE_CANDIDATE_EXECUTION_PLAN_DIGEST',\n materializationReceiptDigest: 'TANGLE_CANDIDATE_MATERIALIZATION_RECEIPT_DIGEST',\n traceRunId: 'TANGLE_TRACE_RUN_ID',\n} as const\n\nexport type PreparedMemoryReceipt = AgentCandidateMemoryReceipt\n","import type { Sha256Digest } from '@tangle-network/agent-interface'\n\nimport { type AgentCandidateExecutionClaim, candidateClaimFileInternals } from './claim'\nimport { canonicalCandidateDigest } from './digest'\nimport { candidateExecutionOwnerWindowMs } from './execution-window'\nimport { assertPreparedCandidateIntegrity } from './prepared-state'\nimport type { PreparedAgentCandidateExecution } from './types'\n\n/** Extract the complete durable claim from a prepared execution. */\nexport function candidateExecutionClaim(\n prepared: PreparedAgentCandidateExecution,\n): AgentCandidateExecutionClaim {\n const state = assertPreparedCandidateIntegrity(prepared)\n const material = prepared.executionPlan.value.material\n const attempt = material.attempt\n const nowMs = Date.now()\n if (!Number.isSafeInteger(nowMs) || nowMs < 0) {\n throw new Error('candidate execution claim-store clock returned an invalid timestamp')\n }\n const leaseExpiresAtMs =\n nowMs +\n candidateExecutionOwnerWindowMs(\n material.limits.timeoutMs,\n state.cleanupTimeoutMs,\n state.resultTimeoutMs,\n )\n if (!Number.isSafeInteger(leaseExpiresAtMs) || leaseExpiresAtMs <= 0) {\n throw new Error('candidate execution leaseExpiresAtMs must be a positive safe timestamp')\n }\n if (leaseExpiresAtMs > state.reservationExpiresAtMs) {\n throw new Error(\n 'candidate preparation expires before its full execution and cleanup owner window',\n )\n }\n return candidateClaimFileInternals.sealClaim({\n executionId: prepared.executionId,\n attempt: attempt.number,\n maxAttempts: attempt.maxAttempts,\n retryPolicy: attempt.retryPolicy,\n bundleDigest: prepared.bundle.digest,\n executionPlanDigest: prepared.executionPlan.value.digest,\n retryLineageDigest: retryLineageDigest(prepared, state.resultTimeoutMs),\n leaseExpiresAtMs,\n resultTimeoutMs: state.resultTimeoutMs,\n cleanup: {\n preparationId: state.preparationId,\n modelGrantDigest: state.modelReservation.digest,\n resolvedModel: state.resolvedModel,\n traceRunId: state.trace.runId,\n cleanupTimeoutMs: state.cleanupTimeoutMs,\n ...(state.memoryReservation\n ? {\n memory: {\n accessDigest: state.memoryReservation.accessDigest,\n effectiveNamespace: state.memoryReservation.effectiveNamespace,\n },\n }\n : {}),\n },\n })\n}\n\nfunction retryLineageDigest(\n prepared: PreparedAgentCandidateExecution,\n resultTimeoutMs: number,\n): Sha256Digest {\n const material = prepared.executionPlan.value.material\n return canonicalCandidateDigest({\n resultTimeoutMs,\n executionPlan: {\n ...material,\n attempt: { ...material.attempt, number: 0 },\n model: {\n ...material.model,\n access: {\n ...material.model.access,\n grantDigest: `sha256:${'0'.repeat(64)}`,\n },\n },\n memory:\n material.memory.mode === 'disabled'\n ? material.memory\n : {\n mode: 'isolated',\n scope: 'task',\n effectiveNamespace: 'candidate/retry-lineage-normalized',\n reset: {\n kind: 'fresh',\n emptyStateDigest: material.memory.reset.emptyStateDigest,\n },\n beforeState: {\n digest: material.memory.beforeState.digest,\n material: material.memory.beforeState.material,\n manifest: {\n sha256: material.memory.beforeState.manifest.sha256,\n byteLength: material.memory.beforeState.manifest.byteLength,\n },\n archive: {\n sha256: material.memory.beforeState.archive.sha256,\n byteLength: material.memory.beforeState.archive.byteLength,\n },\n },\n ...(material.memory.seedDigest ? { seedDigest: material.memory.seedDigest } : {}),\n },\n },\n })\n}\n","import { randomUUID } from 'node:crypto'\nimport { linkSync } from 'node:fs'\nimport { mkdir, open, unlink } from 'node:fs/promises'\nimport { join } from 'node:path'\nimport type { Sha256Digest } from '@tangle-network/agent-interface'\n\nimport {\n type AgentCandidateExecutionAttemptRecord,\n type AgentCandidateExecutionAttemptRef,\n type AgentCandidateExecutionClaim,\n type AgentCandidateExecutionClaimResult,\n type AgentCandidateExecutionClaimStore,\n type AgentCandidateExecutionFinishResult,\n type AgentCandidateExecutionLease,\n type AgentCandidateExecutionPhase,\n type AgentCandidateExecutionPhaseResult,\n type AgentCandidateExecutionRecoveryEvidence,\n type AgentCandidateExecutionStageResult,\n type AgentCandidateExecutionTerminalRecord,\n type AgentCandidateExecutionTerminalResult,\n type AgentCandidateRetryRejection,\n candidateClaimFileInternals,\n} from './claim'\nimport {\n CLAIM_FORMAT_VERSION,\n PENDING_FORMAT_VERSION,\n PHASE_FORMAT_VERSION,\n TERMINAL_FORMAT_VERSION,\n} from './claim-file-formats'\nimport {\n assertRecoveryMatchesStaged,\n assertTerminalAllowedInPhase,\n assertTerminalMatchesClaim,\n assertTerminalMatchesStaged,\n recoveredTerminalRecord,\n rejectedFinish,\n rejectedStage,\n requireStagedTerminal,\n sealTerminalDigest,\n terminalRecord,\n} from './claim-terminal'\nimport { canonicalCandidateBytes } from './digest'\n\nconst {\n assertExpiredLease,\n assertLease,\n assertSameSlot,\n assertUnexpiredLease,\n attemptRecord,\n claimSlot,\n leaseDigest,\n newLease,\n readClaim,\n readClaimIfPresent,\n readTerminal,\n readTerminalIfPresent,\n readTransitionIfPresent,\n rejectedExistingClaim,\n rejectedRetry,\n retryRejection,\n sealAttemptRef,\n sealClaim,\n sealLease,\n} = candidateClaimFileInternals\n\nexport interface FileAgentCandidateExecutionClaimStoreOptions {\n /** Evaluator-owned directory shared by every process allowed to execute candidates. */\n directory: string\n /** Testable evaluator clock; defaults to `Date.now`. */\n now?: () => number\n}\n\n/** Cross-process lifecycle implemented as fsynced, create-if-absent records. */\nexport class FileAgentCandidateExecutionClaimStore implements AgentCandidateExecutionClaimStore {\n private readonly directory: string\n private readonly now: () => number\n\n constructor(options: FileAgentCandidateExecutionClaimStoreOptions) {\n if (options.directory.length === 0) {\n throw new Error('candidate execution claim directory must not be empty')\n }\n this.directory = options.directory\n this.now = options.now ?? Date.now\n }\n\n async tryClaim(\n requested: AgentCandidateExecutionClaim,\n ): Promise<AgentCandidateExecutionClaimResult> {\n const claim = sealClaim(requested)\n await mkdir(this.directory, { recursive: true })\n const claimPath = this.claimPath(claim)\n const existing = await readClaimIfPresent(claimPath)\n if (existing) {\n assertSameSlot(existing.claim, claim, claimPath)\n return rejectedExistingClaim(existing.claim, claim)\n }\n assertUnexpiredLease(claim.leaseExpiresAtMs, this.now())\n const retryFailure = await this.retryFailure(claim)\n if (retryFailure) return rejectedRetry(claim, retryFailure)\n\n const lease = newLease(claim)\n const acquired = await writeRecordIfAbsent(this.directory, claimPath, {\n version: CLAIM_FORMAT_VERSION,\n ...claim,\n phase: 'claimed',\n leaseDigest: leaseDigest(lease),\n })\n if (acquired) return Object.freeze({ acquired: true, claim, lease })\n\n const winner = await readClaim(claimPath)\n assertSameSlot(winner.claim, claim, claimPath)\n return rejectedExistingClaim(winner.claim, claim)\n }\n\n async getAttempt(\n requestedAttempt: AgentCandidateExecutionAttemptRef,\n ): Promise<AgentCandidateExecutionAttemptRecord | undefined> {\n return await this.storedAttempt(sealAttemptRef(requestedAttempt))\n }\n\n async markCandidateMayRun(\n requestedLease: AgentCandidateExecutionLease,\n ): Promise<AgentCandidateExecutionPhaseResult> {\n const lease = sealLease(requestedLease)\n const claimPath = this.claimPath(lease)\n const stored = await readClaim(claimPath)\n assertSameSlot(stored.claim, lease, claimPath)\n assertLease(stored.leaseDigest, stored.claim.leaseExpiresAtMs, lease)\n const state = await this.transitionState(stored.claim)\n if (state.phase === 'candidate-may-run') {\n return Object.freeze({ marked: false, phase: 'candidate-may-run' })\n }\n if (state.staged) {\n throw new Error('candidate execution terminal was staged before candidate-may-run phase')\n }\n assertUnexpiredLease(stored.claim.leaseExpiresAtMs, this.now())\n const marked = await writeRecordIfAbsent(\n this.directory,\n this.transitionPath(stored.claim, 1),\n {\n version: PHASE_FORMAT_VERSION,\n kind: 'candidate-execution-phase',\n executionId: stored.claim.executionId,\n attempt: stored.claim.attempt,\n executionPlanDigest: stored.claim.executionPlanDigest,\n phase: 'candidate-may-run',\n },\n this.ownerPublication(stored.claim),\n )\n if (marked) return Object.freeze({ marked: true, phase: 'candidate-may-run' })\n const winner = await this.transitionState(stored.claim)\n if (winner.phase === 'candidate-may-run') {\n return Object.freeze({ marked: false, phase: 'candidate-may-run' })\n }\n throw new Error('candidate execution terminal was staged before candidate-may-run phase')\n }\n\n async stageTerminal(\n requestedLease: AgentCandidateExecutionLease,\n result: AgentCandidateExecutionTerminalResult,\n ): Promise<AgentCandidateExecutionStageResult> {\n const lease = sealLease(requestedLease)\n const claimPath = this.claimPath(lease)\n const stored = await readClaim(claimPath)\n assertSameSlot(stored.claim, lease, claimPath)\n assertLease(stored.leaseDigest, stored.claim.leaseExpiresAtMs, lease)\n const terminal = terminalRecord(stored.claim, result)\n const state = await this.transitionState(stored.claim)\n if (state.staged) return rejectedStage(state.staged, terminal)\n assertTerminalAllowedInPhase(state.phase, terminal)\n assertUnexpiredLease(stored.claim.leaseExpiresAtMs, this.now())\n const transition = state.phase === 'claimed' ? 1 : 2\n const staged = await writeRecordIfAbsent(\n this.directory,\n this.transitionPath(stored.claim, transition),\n {\n version: PENDING_FORMAT_VERSION,\n kind: 'candidate-execution-pending-terminal',\n terminal,\n },\n this.ownerPublication(stored.claim),\n )\n if (staged) return Object.freeze({ staged: true, terminal })\n const winner = await this.transitionState(stored.claim)\n if (!winner.staged) {\n throw new Error('candidate execution phase transition won while staging terminal')\n }\n return rejectedStage(winner.staged, terminal)\n }\n\n async finish(\n requestedLease: AgentCandidateExecutionLease,\n requestedTerminalDigest: Sha256Digest,\n ): Promise<AgentCandidateExecutionFinishResult> {\n const lease = sealLease(requestedLease)\n const terminalDigest = sealTerminalDigest(requestedTerminalDigest)\n const claimPath = this.claimPath(lease)\n const stored = await readClaim(claimPath)\n assertSameSlot(stored.claim, lease, claimPath)\n assertLease(stored.leaseDigest, stored.claim.leaseExpiresAtMs, lease)\n const state = await this.transitionState(stored.claim)\n const staged = requireStagedTerminal(state.staged, terminalDigest)\n const terminalPath = this.terminalPath(lease)\n const existing = await readTerminalIfPresent(terminalPath)\n if (existing) {\n assertTerminalMatchesClaim(existing, stored.claim, terminalPath)\n assertTerminalMatchesStaged(existing, staged, terminalPath)\n return rejectedFinish(existing, terminalDigest)\n }\n assertUnexpiredLease(stored.claim.leaseExpiresAtMs, this.now())\n const finished = await writeRecordIfAbsent(\n this.directory,\n terminalPath,\n {\n version: TERMINAL_FORMAT_VERSION,\n terminal: staged,\n },\n this.ownerPublication(stored.claim),\n )\n if (finished) return Object.freeze({ finished: true, terminal: staged })\n const winner = await readTerminal(terminalPath)\n assertSameSlot(winner, lease, terminalPath)\n assertTerminalMatchesClaim(winner, stored.claim, terminalPath)\n assertTerminalMatchesStaged(winner, staged, terminalPath)\n return rejectedFinish(winner, terminalDigest)\n }\n\n async recoverExpired(\n requestedAttempt: AgentCandidateExecutionAttemptRef,\n evidence: AgentCandidateExecutionRecoveryEvidence,\n ): Promise<AgentCandidateExecutionFinishResult> {\n const attempt = sealAttemptRef(requestedAttempt)\n const record = await this.storedAttempt(attempt)\n if (!record) throw new Error('candidate execution recovery does not name an acquired attempt')\n const recovered = recoveredTerminalRecord(record.claim, record.phase, evidence)\n if (record.staged) assertRecoveryMatchesStaged(record.staged, recovered)\n const requestedDigest = record.staged?.terminalDigest ?? recovered.terminalDigest\n if (record.terminal) return rejectedFinish(record.terminal, requestedDigest)\n assertExpiredLease(record.claim.leaseExpiresAtMs, this.now())\n\n let staged = record.staged\n if (!staged) {\n const transition = record.phase === 'claimed' ? 1 : 2\n const didStage = await writeRecordIfAbsent(\n this.directory,\n this.transitionPath(record.claim, transition),\n {\n version: PENDING_FORMAT_VERSION,\n kind: 'candidate-execution-pending-terminal',\n terminal: recovered,\n },\n )\n if (didStage) {\n staged = recovered\n } else {\n const winner = await this.transitionState(record.claim)\n if (!winner.staged) {\n throw new Error(\n 'candidate execution recovery lost terminal staging to a phase transition',\n )\n }\n assertRecoveryMatchesStaged(winner.staged, recovered)\n staged = winner.staged\n }\n }\n\n const terminalPath = this.terminalPath(attempt)\n const didFinish = await writeRecordIfAbsent(this.directory, terminalPath, {\n version: TERMINAL_FORMAT_VERSION,\n terminal: staged,\n })\n if (didFinish) return Object.freeze({ finished: true, terminal: staged })\n const winner = await readTerminal(terminalPath)\n assertSameSlot(winner, attempt, terminalPath)\n assertTerminalMatchesClaim(winner, record.claim, terminalPath)\n assertTerminalMatchesStaged(winner, staged, terminalPath)\n return rejectedFinish(winner, staged.terminalDigest)\n }\n\n private async storedAttempt(\n claim: Pick<AgentCandidateExecutionClaim, 'executionId' | 'attempt'>,\n ): Promise<AgentCandidateExecutionAttemptRecord | undefined> {\n const claimPath = this.claimPath(claim)\n const stored = await readClaimIfPresent(claimPath)\n if (!stored) return undefined\n assertSameSlot(stored.claim, claim, claimPath)\n const state = await this.transitionState(stored.claim)\n const terminalPath = this.terminalPath(claim)\n const terminal = await readTerminalIfPresent(terminalPath)\n if (terminal) {\n assertTerminalMatchesClaim(terminal, stored.claim, terminalPath)\n if (!state.staged) {\n throw new Error(\n `candidate execution terminal record at ${terminalPath} has no staged outbox`,\n )\n }\n assertTerminalMatchesStaged(terminal, state.staged, terminalPath)\n }\n return attemptRecord(stored.claim, state.phase, state.staged, terminal)\n }\n\n private async transitionState(claim: AgentCandidateExecutionClaim): Promise<{\n phase: AgentCandidateExecutionPhase\n staged?: AgentCandidateExecutionTerminalRecord\n }> {\n const firstPath = this.transitionPath(claim, 1)\n const first = await readTransitionIfPresent(firstPath, claim)\n if (!first) return { phase: 'claimed' }\n if (first.kind === 'pending') return { phase: 'claimed', staged: first.terminal }\n const secondPath = this.transitionPath(claim, 2)\n const second = await readTransitionIfPresent(secondPath, claim)\n if (!second) return { phase: 'candidate-may-run' }\n if (second.kind !== 'pending') {\n throw new Error(`candidate execution transition at ${secondPath} repeats the phase marker`)\n }\n return { phase: 'candidate-may-run', staged: second.terminal }\n }\n\n private async retryFailure(\n claim: AgentCandidateExecutionClaim,\n ): Promise<AgentCandidateRetryRejection | undefined> {\n if (claim.attempt === 1) return undefined\n return retryRejection(\n claim,\n await this.storedAttempt({\n executionId: claim.executionId,\n attempt: claim.attempt - 1,\n }),\n )\n }\n\n private ownerPublication(claim: AgentCandidateExecutionClaim): {\n authorizePublish: () => true\n } {\n return {\n authorizePublish: () => {\n assertUnexpiredLease(claim.leaseExpiresAtMs, this.now())\n return true\n },\n }\n }\n\n private claimPath(claim: Pick<AgentCandidateExecutionClaim, 'executionId' | 'attempt'>): string {\n return join(this.directory, `${claimSlot(claim)}.claim.json`)\n }\n\n private terminalPath(\n claim: Pick<AgentCandidateExecutionClaim, 'executionId' | 'attempt'>,\n ): string {\n return join(this.directory, `${claimSlot(claim)}.terminal.json`)\n }\n\n private transitionPath(\n claim: Pick<AgentCandidateExecutionClaim, 'executionId' | 'attempt'>,\n ordinal: 1 | 2,\n ): string {\n return join(this.directory, `${claimSlot(claim)}.transition-${ordinal}.json`)\n }\n}\n\nasync function writeRecordIfAbsent(\n directory: string,\n destination: string,\n record: object,\n options: {\n /** Synchronous authorization checked after temp fsync, immediately before atomic publication. */\n authorizePublish?: () => true\n } = {},\n): Promise<boolean> {\n const temporaryPath = join(directory, `.candidate-execution-${process.pid}-${randomUUID()}.tmp`)\n const handle = await open(temporaryPath, 'wx', 0o600)\n try {\n await handle.writeFile(\n Buffer.concat([Buffer.from(canonicalCandidateBytes(record)), Buffer.from('\\n')]),\n )\n await handle.sync()\n } finally {\n await handle.close()\n }\n\n let written = false\n try {\n if (options.authorizePublish && options.authorizePublish() !== true) {\n throw new Error('candidate execution record publication was not authorized')\n }\n // Authorization and the atomic filesystem call are one synchronous critical\n // section so the event loop cannot advance an injected lease clock between them.\n linkSync(temporaryPath, destination)\n written = true\n await syncDirectory(directory)\n } catch (error) {\n if (!isNodeError(error, 'EEXIST')) throw error\n } finally {\n await unlink(temporaryPath).catch((error: unknown) => {\n if (!isNodeError(error, 'ENOENT')) throw error\n })\n }\n return written\n}\n\nasync function syncDirectory(directory: string): Promise<void> {\n const handle = await open(directory, 'r')\n try {\n await handle.sync()\n } finally {\n await handle.close()\n }\n}\n\nfunction isNodeError(error: unknown, code: string): boolean {\n return (\n error !== null &&\n typeof error === 'object' &&\n 'code' in error &&\n (error as { code?: unknown }).code === code\n )\n}\n","import { isLlmSpan, type LlmSpan, type TraceStore } from '@tangle-network/agent-eval'\nimport type { AgentCandidateSpend } from '@tangle-network/agent-interface'\nimport type { AgentCandidateExecutionUsage } from './claim'\nimport { assertExactObjectKeys } from './exact-object'\nimport type {\n AgentCandidateProtectedModelCall,\n AgentCandidateProtectedModelSettlement,\n} from './types'\n\nconst USD_NANOS = 1_000_000_000\n\nexport interface SealedAgentCandidateModelSettlement {\n readonly value: AgentCandidateProtectedModelSettlement\n readonly usage: AgentCandidateSpend\n readonly fixedUsage: AgentCandidateExecutionUsage\n readonly costUsdNanos: number\n}\n\n/** Validate and detach the evaluator gateway's terminal, revoked call ledger. */\nexport function sealAgentCandidateModelSettlement(\n settlement: AgentCandidateProtectedModelSettlement,\n expected: { preparationId: string; grantDigest: string; model: string },\n): SealedAgentCandidateModelSettlement {\n assertExactObjectKeys(\n settlement,\n ['preparationId', 'grantDigest', 'closed', 'calls'],\n 'model settlement',\n )\n if (settlement.closed !== true) throw new Error('protected model grant is not closed')\n if (settlement.grantDigest !== expected.grantDigest) {\n throw new Error('protected model settlement grant digest does not match the reservation')\n }\n if (settlement.preparationId !== expected.preparationId) {\n throw new Error('protected model settlement preparation does not match the reservation')\n }\n if (!Array.isArray(settlement.calls)) {\n throw new Error('protected model settlement calls must be an array')\n }\n\n const callIds = new Set<string>()\n const spanIds = new Set<string>()\n let inputTokens = 0\n let outputTokens = 0\n let cachedInputTokens = 0\n let reasoningTokens = 0\n let hasCachedInput = false\n let costUsdNanos = 0\n const calls = settlement.calls.map((source, index) => {\n assertExactObjectKeys(\n source,\n [\n 'callId',\n 'generationId',\n 'traceSpanId',\n 'status',\n 'model',\n 'startedAtMs',\n 'endedAtMs',\n 'inputTokens',\n 'outputTokens',\n 'cachedInputTokens',\n 'reasoningTokens',\n 'costUsdNanos',\n ],\n `model settlement call ${index}`,\n )\n assertIdentifier(source.callId, `model settlement call ${index} callId`)\n assertIdentifier(source.generationId, `model settlement call ${index} generationId`)\n assertIdentifier(source.traceSpanId, `model settlement call ${index} traceSpanId`)\n if (source.traceSpanId !== source.generationId) {\n throw new Error(`model settlement call ${index} traceSpanId is not its router generationId`)\n }\n if (source.status !== 'succeeded' && source.status !== 'failed') {\n throw new Error(`model settlement call ${index} has an invalid status`)\n }\n if (callIds.has(source.callId))\n throw new Error('protected model settlement has duplicate call ids')\n if (spanIds.has(source.traceSpanId)) {\n throw new Error('protected model settlement has duplicate trace span ids')\n }\n callIds.add(source.callId)\n spanIds.add(source.traceSpanId)\n if (source.model !== expected.model) {\n throw new Error(`protected model settlement call ${index} has an unexpected model`)\n }\n assertTimestamp(source.startedAtMs, `model settlement call ${index} startedAtMs`)\n assertTimestamp(source.endedAtMs, `model settlement call ${index} endedAtMs`)\n if (source.endedAtMs < source.startedAtMs) {\n throw new Error(`model settlement call ${index} ended before it started`)\n }\n assertCount(source.inputTokens, `model settlement call ${index} inputTokens`)\n assertCount(source.outputTokens, `model settlement call ${index} outputTokens`)\n assertCount(source.cachedInputTokens, `model settlement call ${index} cachedInputTokens`)\n cachedInputTokens = safeAdd(\n cachedInputTokens,\n source.cachedInputTokens,\n 'cached input token total',\n )\n hasCachedInput = true\n assertCount(source.reasoningTokens, `model settlement call ${index} reasoningTokens`)\n reasoningTokens = safeAdd(reasoningTokens, source.reasoningTokens, 'reasoning token total')\n assertCount(source.costUsdNanos, `model settlement call ${index} costUsdNanos`)\n inputTokens = safeAdd(inputTokens, source.inputTokens, 'input token total')\n outputTokens = safeAdd(outputTokens, source.outputTokens, 'output token total')\n costUsdNanos = safeAdd(costUsdNanos, source.costUsdNanos, 'cost total')\n return Object.freeze({ ...source })\n })\n\n const usage = Object.freeze({\n costUsd: costUsdNanos / USD_NANOS,\n inputTokens,\n outputTokens,\n ...(hasCachedInput ? { cachedInputTokens } : {}),\n modelCalls: calls.length,\n })\n const fixedUsage = Object.freeze({\n costUsdNanos,\n inputTokens,\n outputTokens,\n cachedInputTokens,\n reasoningTokens,\n modelCalls: calls.length,\n })\n return Object.freeze({\n value: Object.freeze({\n preparationId: settlement.preparationId,\n grantDigest: settlement.grantDigest,\n closed: true as const,\n calls: Object.freeze(calls),\n }),\n usage,\n fixedUsage,\n costUsdNanos,\n })\n}\n\n/**\n * Append the only accepted LLM spans from the router's closed ledger.\n * Candidate and executor code may write tool/process spans, but never model usage.\n */\nexport async function appendAuthoritativeModelSettlementSpans(\n traceStore: TraceStore,\n runId: string,\n settlement: SealedAgentCandidateModelSettlement,\n): Promise<void> {\n const run = await traceStore.getRun(runId)\n if (!run) throw new Error(`protected trace run is missing before model settlement: ${runId}`)\n if (run.status === 'running' || run.endedAt === undefined) {\n throw new Error('protected trace run must be terminal before model spans are appended')\n }\n const existing = await traceStore.spans({ runId })\n if (existing.some(isLlmSpan)) {\n throw new Error(\n 'protected trace contains a model span not authored from the closed router ledger',\n )\n }\n const occupiedIds = new Set(existing.map((span) => span.spanId))\n for (const call of settlement.value.calls) {\n if (occupiedIds.has(call.traceSpanId)) {\n throw new Error(\n `protected trace span identity collides with router generation ${call.generationId}`,\n )\n }\n await traceStore.appendSpan({\n runId,\n spanId: call.traceSpanId,\n kind: 'llm',\n name: 'protected model call',\n model: call.model,\n messages: [],\n startedAt: call.startedAtMs,\n endedAt: call.endedAtMs,\n status: call.status === 'succeeded' ? 'ok' : 'error',\n inputTokens: call.inputTokens,\n outputTokens: call.outputTokens,\n cachedTokens: call.cachedInputTokens,\n reasoningTokens: call.reasoningTokens,\n costUsd: call.costUsdNanos / USD_NANOS,\n attributes: {\n 'tangle.protected_model.source': 'router-settlement',\n 'tangle.router.call_id': call.callId,\n 'tangle.router.generation_id': call.generationId,\n },\n })\n }\n}\n\n/** Match every protected trace span one-for-one against gateway call evidence. */\nexport function assertTraceMatchesModelSettlement(\n spans: readonly LlmSpan[],\n settlement: SealedAgentCandidateModelSettlement,\n): void {\n if (spans.length !== settlement.value.calls.length) {\n throw new Error(\n `protected trace model calls ${spans.length} do not match model ledger ${settlement.value.calls.length}`,\n )\n }\n const byId = new Map(spans.map((span) => [span.spanId, span]))\n if (byId.size !== spans.length) throw new Error('protected trace has duplicate model span ids')\n for (const call of settlement.value.calls) {\n const span = byId.get(call.traceSpanId)\n if (!span) {\n throw new Error(`protected trace is missing model ledger span ${call.traceSpanId}`)\n }\n assertTraceCall(span, call)\n }\n}\n\nexport function usdToNanos(value: number, label: string): number {\n if (!Number.isFinite(value) || value < 0) throw new Error(`${label} must be nonnegative`)\n const nanos = Math.round(value * USD_NANOS)\n if (!Number.isSafeInteger(nanos)) throw new Error(`${label} exceeds fixed-point range`)\n return nanos\n}\n\nfunction assertTraceCall(span: LlmSpan, call: AgentCandidateProtectedModelCall): void {\n if (span.model !== call.model) {\n throw new Error(`protected trace span ${span.spanId} model does not match model ledger`)\n }\n if (\n span.startedAt !== call.startedAtMs ||\n span.endedAt !== call.endedAtMs ||\n span.status !== (call.status === 'succeeded' ? 'ok' : 'error')\n ) {\n throw new Error(\n `protected trace span ${span.spanId} timing or status does not match model ledger`,\n )\n }\n if (\n span.attributes?.['tangle.protected_model.source'] !== 'router-settlement' ||\n span.attributes?.['tangle.router.call_id'] !== call.callId ||\n span.attributes?.['tangle.router.generation_id'] !== call.generationId\n ) {\n throw new Error(`protected trace span ${span.spanId} lacks router settlement provenance`)\n }\n for (const [name, traced, settled] of [\n ['inputTokens', span.inputTokens, call.inputTokens],\n ['outputTokens', span.outputTokens, call.outputTokens],\n ['cachedInputTokens', span.cachedTokens ?? 0, call.cachedInputTokens],\n ['reasoningTokens', span.reasoningTokens ?? 0, call.reasoningTokens],\n ] as const) {\n if (traced === undefined || traced !== settled) {\n throw new Error(\n `protected trace span ${span.spanId} ${name} ${traced} does not match model ledger ${settled}`,\n )\n }\n }\n if (span.costUsd === undefined) {\n throw new Error(`protected trace span ${span.spanId} is missing costUsd`)\n }\n const tracedCost = usdToNanos(span.costUsd, `protected trace span ${span.spanId} costUsd`)\n if (tracedCost !== call.costUsdNanos) {\n throw new Error(\n `protected trace span ${span.spanId} costUsdNanos ${tracedCost} does not match model ledger ${call.costUsdNanos}`,\n )\n }\n}\n\nfunction assertIdentifier(value: unknown, label: string): asserts value is string {\n if (typeof value !== 'string' || value.length === 0 || value.length > 256) {\n throw new Error(`${label} must be a non-empty bounded string`)\n }\n}\n\nfunction assertCount(value: unknown, label: string): asserts value is number {\n if (!Number.isSafeInteger(value) || (value as number) < 0) {\n throw new Error(`${label} must be a nonnegative safe integer`)\n }\n}\n\nfunction assertTimestamp(value: unknown, label: string): asserts value is number {\n if (!Number.isSafeInteger(value) || (value as number) <= 0) {\n throw new Error(`${label} must be a positive safe integer`)\n }\n}\n\nfunction safeAdd(left: number, right: number, label: string): number {\n const total = left + right\n if (!Number.isSafeInteger(total)) throw new Error(`${label} exceeds safe integer range`)\n return total\n}\n","import { candidateCleanupDeadline, withinCandidateCleanupDeadline } from './cleanup'\nimport { sealAgentCandidateModelSettlement } from './model-settlement'\nimport {\n assertPreparedCandidateIntegrity,\n beginPreparedCandidateDisposal,\n consumePreparedCandidateExecution,\n} from './prepared-state'\nimport type { PreparedAgentCandidateExecution } from './types'\n\nexport interface DisposePreparedAgentCandidateOptions {\n cleanupTimeoutMs?: number\n}\n\n/** Revoke reservations held by a prepared candidate that will not be executed. */\nexport async function disposePreparedAgentCandidateExecution(\n prepared: PreparedAgentCandidateExecution,\n options: DisposePreparedAgentCandidateOptions = {},\n): Promise<{ disposed: true }> {\n const initialState = assertPreparedCandidateIntegrity(prepared)\n const cleanupTimeoutMs = options.cleanupTimeoutMs ?? initialState.cleanupTimeoutMs\n if (cleanupTimeoutMs > initialState.cleanupTimeoutMs) {\n throw new Error('disposal cleanup timeout exceeds the frozen preparation bound')\n }\n const cleanupDeadlineAtMs = candidateCleanupDeadline(cleanupTimeoutMs)\n const state = beginPreparedCandidateDisposal(prepared)\n const cleanup: Array<Promise<unknown>> = []\n\n if (state.memory.mode === 'isolated') {\n const reservation = state.memoryReservation\n if (!reservation) throw new Error('isolated memory reservation is missing')\n cleanup.push(\n withinCandidateCleanupDeadline(\n async () => {\n const closed = await state.ports.memory.close({\n executionId: state.executionId,\n preparationId: reservation.preparationId,\n accessDigest: reservation.accessDigest,\n effectiveNamespace: reservation.effectiveNamespace,\n reason: 'abandoned',\n })\n if (closed.closed !== true || Object.keys(closed).some((key) => key !== 'closed')) {\n throw new Error('abandoned isolated memory access did not acknowledge closure')\n }\n },\n cleanupDeadlineAtMs,\n 'isolated memory disposal',\n ),\n )\n }\n\n cleanup.push(\n withinCandidateCleanupDeadline(\n async () => {\n const settlement = sealAgentCandidateModelSettlement(\n await state.ports.models.settleGrant({\n executionId: state.executionId,\n preparationId: state.preparationId,\n grantDigest: state.modelReservation.digest,\n resolved: state.resolvedModel,\n reason: 'abandoned',\n }),\n {\n preparationId: state.preparationId,\n grantDigest: state.modelReservation.digest,\n model: state.resolvedModel.model,\n },\n )\n if (settlement.usage.modelCalls !== 0) {\n throw new Error('unexecuted model reservation unexpectedly contains calls')\n }\n },\n cleanupDeadlineAtMs,\n 'model reservation disposal',\n ),\n )\n\n const results = await Promise.allSettled(cleanup)\n const failures = results\n .filter((result): result is PromiseRejectedResult => result.status === 'rejected')\n .map((result) => result.reason)\n if (failures.length > 0) {\n consumePreparedCandidateExecution(prepared, 'disposal-failed')\n throw new AggregateError(failures, 'candidate preparation disposal failed')\n }\n\n consumePreparedCandidateExecution(prepared, 'disposed')\n return Object.freeze({ disposed: true as const })\n}\n","import {\n agentCandidateTerminationSchema,\n agentCandidateWorkspaceManifestMaterialSchema,\n} from '@tangle-network/agent-interface'\nimport { assertExactObjectKeys as assertExactKeys } from './exact-object'\nimport type { AgentCandidateExecutorFinalCapture, AgentCandidateProtectedRunCapture } from './types'\n\n/** Validate and detach the only candidate-authored fields accepted from execution. */\nexport function sealAgentCandidateProtectedRunCapture(\n value: unknown,\n): AgentCandidateProtectedRunCapture {\n const capture = requireRecord(value, 'candidate execution capture')\n assertExactKeys(capture, ['executionId', 'termination'], 'candidate execution capture')\n if (typeof capture.executionId !== 'string' || capture.executionId.length === 0) {\n throw new Error('candidate execution capture has an invalid executionId')\n }\n return Object.freeze({\n executionId: capture.executionId,\n termination: Object.freeze(agentCandidateTerminationSchema.parse(capture.termination)),\n })\n}\n\n/** Validate, detach, and freeze evaluator-owned evidence captured after process death. */\nexport function sealAgentCandidateExecutorFinalCapture(\n value: unknown,\n): AgentCandidateExecutorFinalCapture {\n const capture = requireRecord(value, 'candidate final capture')\n assertExactKeys(capture, ['stopped'], 'candidate final capture', ['taskOutcome', 'memoryAfter'])\n if (capture.stopped !== true) {\n throw new Error('candidate final capture does not prove process death')\n }\n\n const taskOutcome = capture.taskOutcome ? sealTaskOutcomeCapture(capture.taskOutcome) : undefined\n const memoryAfter = capture.memoryAfter ? sealMemoryCapture(capture.memoryAfter) : undefined\n return Object.freeze({\n stopped: true,\n ...(taskOutcome ? { taskOutcome } : {}),\n ...(memoryAfter ? { memoryAfter: Object.freeze(memoryAfter) } : {}),\n })\n}\n\nfunction sealMemoryCapture(\n value: unknown,\n): NonNullable<AgentCandidateExecutorFinalCapture['memoryAfter']> {\n const capture = requireRecord(value, 'candidate memory capture')\n assertExactKeys(capture, ['afterState', 'archive'], 'candidate memory capture')\n if (!(capture.archive instanceof Uint8Array)) {\n throw new Error('candidate memory capture archive must be a byte array')\n }\n return Object.freeze({\n afterState: Object.freeze(\n agentCandidateWorkspaceManifestMaterialSchema.parse(capture.afterState),\n ),\n archive: Uint8Array.from(capture.archive),\n })\n}\n\nfunction sealTaskOutcomeCapture(\n value: unknown,\n): NonNullable<AgentCandidateExecutorFinalCapture['taskOutcome']> {\n const capture = requireRecord(value, 'candidate task capture')\n assertExactKeys(\n capture,\n ['resultTree', 'afterState', 'archive', 'gitDiff'],\n 'candidate task capture',\n )\n if (\n typeof capture.resultTree !== 'string' ||\n !/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/.test(capture.resultTree)\n ) {\n throw new Error('candidate task capture resultTree is not a Git object id')\n }\n if (!(capture.archive instanceof Uint8Array) || !(capture.gitDiff instanceof Uint8Array)) {\n throw new Error('candidate task capture archive and gitDiff must be byte arrays')\n }\n const afterState = agentCandidateWorkspaceManifestMaterialSchema.parse(capture.afterState)\n return Object.freeze({\n resultTree: capture.resultTree,\n afterState: Object.freeze(afterState),\n archive: Uint8Array.from(capture.archive),\n gitDiff: Uint8Array.from(capture.gitDiff),\n })\n}\n\nfunction requireRecord(value: unknown, label: string): Record<string, unknown> {\n if (!value || typeof value !== 'object' || Array.isArray(value)) {\n throw new Error(`${label} must be an object`)\n }\n return value as Record<string, unknown>\n}\n","import { mkdtemp, rm } from 'node:fs/promises'\nimport { tmpdir } from 'node:os'\nimport { join } from 'node:path'\n\nimport type { Span, TraceStore } from '@tangle-network/agent-eval'\nimport { isLlmSpan, REDACTION_VERSION } from '@tangle-network/agent-eval'\nimport type {\n AgentCandidateBenchmarkResultEvidence,\n AgentCandidateMemoryReceipt,\n AgentCandidateModelSettlementEvidence,\n AgentCandidateRunReceiptV2,\n AgentCandidateSpend,\n AgentCandidateTermination,\n} from '@tangle-network/agent-interface'\nimport {\n agentCandidateRunReceiptV2Schema,\n agentCandidateWorkspaceSnapshotEvidenceSchema,\n} from '@tangle-network/agent-interface'\n\nimport { readMaterializedWorkspaceFiles } from './artifacts'\nimport {\n canonicalCandidateBytes,\n canonicalCandidateDocument,\n embeddedCandidateArtifact,\n sha256Bytes,\n} from './digest'\nimport {\n sealAgentCandidateExecutorFinalCapture,\n sealAgentCandidateProtectedRunCapture,\n} from './executor-capture'\nimport {\n assertTraceMatchesModelSettlement,\n type SealedAgentCandidateModelSettlement,\n usdToNanos,\n} from './model-settlement'\nimport { persistCandidateOutputArtifact } from './output-artifacts'\nimport type { PreparedCandidateState } from './prepared-state'\nimport {\n assertNoProtectedBytes,\n type ProtectedRedactionReport,\n redactProtectedReason,\n redactProtectedValue,\n} from './protected-redaction'\nimport {\n type AgentCandidateExecutorFinalCapture,\n type AgentCandidateOutputArtifactPort,\n type AgentCandidateProtectedRunCapture,\n type AgentCandidateRunFinalization,\n CANDIDATE_TRACE_TAGS,\n type VerifiedAgentCandidateTaskOutcome,\n} from './types'\n\ninterface CandidateFinalizationEvidence {\n finalCapture: AgentCandidateExecutorFinalCapture\n modelSettlement: AgentCandidateModelSettlementEvidence & {\n artifact: import('@tangle-network/agent-interface').AgentCandidateArtifactRef\n }\n taskOutcome: VerifiedAgentCandidateTaskOutcome\n benchmarkResult: AgentCandidateBenchmarkResultEvidence & {\n artifact: import('@tangle-network/agent-interface').AgentCandidateArtifactRef\n }\n outputArtifacts: AgentCandidateOutputArtifactPort\n}\n\n/** Builds a candidate run receipt exclusively from protected trace and memory evidence. */\nexport async function finalizeAgentCandidateRun(\n state: PreparedCandidateState,\n capture: AgentCandidateProtectedRunCapture,\n traceStore: TraceStore,\n settlement: SealedAgentCandidateModelSettlement,\n evidence: CandidateFinalizationEvidence,\n protectedValues: readonly string[],\n writeRedactionReport?: ProtectedRedactionReport,\n signal?: AbortSignal,\n): Promise<AgentCandidateRunFinalization> {\n let termination: AgentCandidateTermination | undefined\n try {\n signal?.throwIfAborted()\n const protectedCapture = sealAgentCandidateProtectedRunCapture(capture)\n if (protectedCapture.executionId !== state.executionId) {\n throw new Error('protected capture execution id does not match the prepared execution')\n }\n termination = protectedCapture.termination\n if (\n termination.kind === 'timeout' &&\n termination.timeoutMs !== state.executionPlan.value.material.limits.timeoutMs\n ) {\n throw new Error('timeout termination does not match the frozen execution limit')\n }\n\n const run = await traceStore.getRun(state.trace.runId)\n if (!run) throw new Error(`protected trace run is missing: ${state.trace.runId}`)\n if (run.status === 'running' || run.endedAt === undefined) {\n throw new Error('protected trace run is not terminal')\n }\n assertTraceBindings(run.tags, state)\n\n const [spans, events, budget, artifacts] = await Promise.all([\n traceStore.spans({ runId: run.runId }),\n traceStore.events({ runId: run.runId }),\n traceStore.budget(run.runId),\n traceStore.artifacts(run.runId),\n ])\n const orderedSpans = [...spans].sort(\n (a, b) => a.startedAt - b.startedAt || compareStrings(a.spanId, b.spanId),\n )\n const orderedEvents = [...events].sort(\n (a, b) => a.timestamp - b.timestamp || compareStrings(a.eventId, b.eventId),\n )\n const orderedBudget = [...budget].sort(\n (a, b) => a.timestamp - b.timestamp || compareStrings(a.dimension, b.dimension),\n )\n const orderedArtifacts = [...artifacts].sort((a, b) =>\n compareStrings(a.artifactId, b.artifactId),\n )\n\n const modelSpans = orderedSpans.filter(isLlmSpan)\n assertTraceMatchesModelSettlement(modelSpans, settlement)\n const usage = settlement.usage\n enforceLimits(state, run.startedAt, run.endedAt, orderedSpans, settlement)\n const finalCapture = sealAgentCandidateExecutorFinalCapture(evidence.finalCapture)\n const memory = await memoryReceipt(\n state,\n finalCapture,\n evidence.outputArtifacts,\n protectedValues,\n signal,\n )\n\n const redacted = redactProtectedValue(\n {\n schemaVersion: 1,\n run: { ...run, redactionVersion: REDACTION_VERSION },\n spans: orderedSpans,\n events: orderedEvents,\n budget: orderedBudget,\n artifacts: orderedArtifacts,\n },\n protectedValues,\n )\n const combinedByRule = { ...(writeRedactionReport?.byRule ?? {}) }\n for (const [rule, count] of Object.entries(redacted.report.byRule)) {\n combinedByRule[rule] = (combinedByRule[rule] ?? 0) + count\n }\n const traceMaterial = {\n ...(redacted.value as Record<string, unknown>),\n evaluatorLimits: { resultTimeoutMs: state.resultTimeoutMs },\n redaction: {\n version: REDACTION_VERSION,\n redactionCount:\n (writeRedactionReport?.redactionCount ?? 0) + redacted.report.redactionCount,\n byRule: combinedByRule,\n },\n }\n const traceBytes = canonicalCandidateBytes(traceMaterial)\n assertNoProtectedBytes(traceBytes, protectedValues)\n const traceArtifact = await persistCandidateOutputArtifact(evidence.outputArtifacts, {\n executionId: state.executionId,\n purpose: 'trace',\n bytes: traceBytes,\n signal,\n })\n const trace = {\n schemaVersion: 1 as const,\n artifact: traceArtifact,\n eventCount:\n 1 +\n orderedSpans.length +\n orderedEvents.length +\n orderedBudget.length +\n orderedArtifacts.length,\n modelCallCount: modelSpans.length,\n }\n const document = canonicalCandidateDocument<AgentCandidateRunReceiptV2>({\n schemaVersion: 2,\n kind: 'agent-candidate-run',\n digestAlgorithm: 'rfc8785-sha256',\n bundleDigest: state.bundle.digest,\n materializationReceiptDigest: state.materializationReceipt.digest,\n executionPlanDigest: state.executionPlan.value.digest,\n memory,\n usage,\n modelUsage: { resolved: state.resolvedModel, usage },\n trace,\n termination,\n fixedUsage: settlement.fixedUsage,\n modelSettlement: evidence.modelSettlement,\n taskOutcome: evidence.taskOutcome.evidence,\n benchmarkResult: evidence.benchmarkResult,\n })\n agentCandidateRunReceiptV2Schema.parse(document.value)\n const runReceipt = await persistCandidateOutputArtifact(evidence.outputArtifacts, {\n executionId: state.executionId,\n purpose: 'run-receipt',\n bytes: document.bytes,\n signal,\n })\n return {\n succeeded: true,\n receipt: document,\n artifacts: {\n modelSettlement: evidence.modelSettlement.artifact,\n taskOutcome: evidence.taskOutcome.evidence.artifact,\n benchmarkResult: evidence.benchmarkResult.artifact,\n runReceipt,\n },\n }\n } catch (error) {\n return {\n ...failedAgentCandidateRun(\n state,\n redactProtectedReason(\n error instanceof Error ? error.message : String(error),\n protectedValues,\n ),\n termination,\n settlement.usage,\n ),\n }\n }\n}\n\nfunction assertTraceBindings(\n tags: Record<string, string> | undefined,\n state: PreparedCandidateState,\n): void {\n const expected = state.trace.tags\n for (const name of Object.values(CANDIDATE_TRACE_TAGS)) {\n if (tags?.[name] !== expected[name]) {\n throw new Error(`protected trace is not bound to prepared execution tag ${name}`)\n }\n }\n}\n\nfunction enforceLimits(\n state: PreparedCandidateState,\n startedAt: number,\n endedAt: number,\n spans: Span[],\n settlement: SealedAgentCandidateModelSettlement,\n): void {\n const limits = state.executionPlan.value.material.limits\n const usage = settlement.usage\n // The runtime-owned Date.now deadline decides when the process must stop.\n // This separately rejects a receipt whose evaluator-owned trace claims a\n // longer run; neither clock can make an over-limit execution admissible.\n const wallMs = endedAt - startedAt\n if (!Number.isFinite(wallMs) || wallMs < 0 || wallMs > limits.timeoutMs) {\n throw new Error(`protected trace wall time ${wallMs} exceeds ${limits.timeoutMs}`)\n }\n const steps = spans.filter((span) => span.kind === 'tool').length\n const checks: Array<[number, number, string]> = [\n [steps, limits.maxSteps, 'tool steps'],\n [usage.modelCalls, limits.maxModelCalls, 'model calls'],\n [usage.inputTokens, limits.maxInputTokens, 'input tokens'],\n [usage.outputTokens, limits.maxOutputTokens, 'output tokens'],\n ]\n for (const [actual, limit, label] of checks) {\n if (actual > limit) throw new Error(`protected ${label} ${actual} exceeds ${limit}`)\n }\n if (settlement.costUsdNanos > usdToNanos(limits.maxCostUsd, 'frozen maxCostUsd')) {\n throw new Error(`protected cost USD ${usage.costUsd} exceeds ${limits.maxCostUsd}`)\n }\n}\n\nasync function memoryReceipt(\n state: PreparedCandidateState,\n capture: AgentCandidateExecutorFinalCapture,\n outputArtifacts: AgentCandidateOutputArtifactPort,\n protectedValues: readonly string[],\n signal?: AbortSignal,\n): Promise<AgentCandidateMemoryReceipt> {\n signal?.throwIfAborted()\n if (state.memory.mode === 'disabled') {\n if (capture.memoryAfter !== undefined) {\n throw new Error('disabled memory cannot return an after-state')\n }\n return { mode: 'disabled' }\n }\n if (!capture.memoryAfter) throw new Error('isolated memory is missing its protected after-state')\n const afterState = capture.memoryAfter.afterState\n const archive = Uint8Array.from(capture.memoryAfter.archive)\n if (archive.byteLength === 0) throw new Error('isolated memory archive cannot be empty')\n const manifestBytes = canonicalCandidateBytes(afterState)\n assertNoProtectedBytes(manifestBytes, protectedValues)\n assertNoProtectedBytes(archive, protectedValues)\n const provisionalSnapshot = agentCandidateWorkspaceSnapshotEvidenceSchema.parse({\n schemaVersion: 1,\n kind: 'agent-candidate-workspace-snapshot',\n digest: sha256Bytes(manifestBytes),\n material: afterState,\n manifest: embeddedCandidateArtifact(manifestBytes),\n archive: embeddedCandidateArtifact(archive),\n })\n const root = await mkdtemp(join(tmpdir(), 'agent-candidate-memory-after-'))\n try {\n await state.ports.workspaces.materialize({\n role: 'memory',\n snapshot: provisionalSnapshot,\n archive: Uint8Array.from(archive),\n destination: root,\n })\n const files = await readMaterializedWorkspaceFiles(root, afterState)\n for (const file of files) assertNoProtectedBytes(file.bytes, protectedValues)\n signal?.throwIfAborted()\n } finally {\n await rm(root, { recursive: true, force: true })\n }\n const [manifest, archiveRef] = await Promise.all([\n persistCandidateOutputArtifact(outputArtifacts, {\n executionId: state.executionId,\n purpose: 'memory-after-manifest',\n bytes: manifestBytes,\n signal,\n }),\n persistCandidateOutputArtifact(outputArtifacts, {\n executionId: state.executionId,\n purpose: 'memory-after-archive',\n bytes: archive,\n signal,\n }),\n ])\n const snapshot = agentCandidateWorkspaceSnapshotEvidenceSchema.parse({\n schemaVersion: 1,\n kind: 'agent-candidate-workspace-snapshot',\n digest: sha256Bytes(manifestBytes),\n material: afterState,\n manifest,\n archive: archiveRef,\n })\n return {\n mode: 'isolated',\n scope: 'task',\n effectiveNamespace: state.memory.effectiveNamespace,\n resetEvidenceDigest: state.memory.reset.evidence.sha256,\n beforeStateDigest: state.memory.beforeState.digest,\n afterState: snapshot,\n }\n}\n\nexport function failedAgentCandidateRun(\n state: PreparedCandidateState,\n reason: string,\n termination?: AgentCandidateTermination,\n usage: AgentCandidateSpend | null = null,\n): AgentCandidateRunFinalization & { succeeded: false } {\n return {\n succeeded: false,\n reason,\n partial: {\n executionId: state.executionId,\n bundleDigest: state.bundle.digest,\n executionPlanDigest: state.executionPlan.value.digest,\n materializationReceiptDigest: state.materializationReceipt.digest,\n ...(termination ? { termination } : {}),\n },\n usage,\n }\n}\n\nfunction compareStrings(a: string, b: string): number {\n return a < b ? -1 : a > b ? 1 : 0\n}\n","import {\n type AgentCandidateArtifactRef,\n agentCandidateArtifactRefSchema,\n} from '@tangle-network/agent-interface'\n\nimport { verifyBytes } from './artifacts'\nimport { immutableCandidateValue, sha256Bytes } from './digest'\nimport type { AgentCandidateOutputArtifactPort, AgentCandidateOutputPurpose } from './types'\n\n/** Persist evaluator evidence, read it back, and bind the returned locator to the exact bytes. */\nexport async function persistCandidateOutputArtifact(\n port: AgentCandidateOutputArtifactPort,\n input: {\n executionId: string\n purpose: AgentCandidateOutputPurpose\n bytes: Uint8Array\n signal?: AbortSignal\n },\n): Promise<AgentCandidateArtifactRef> {\n input.signal?.throwIfAborted()\n const bytes = Uint8Array.from(input.bytes)\n const expectedDigest = sha256Bytes(bytes)\n const ref = agentCandidateArtifactRefSchema.parse(\n await port.put({\n executionId: input.executionId,\n purpose: input.purpose,\n bytes: Uint8Array.from(bytes),\n ...(input.signal ? { signal: input.signal } : {}),\n }),\n )\n input.signal?.throwIfAborted()\n if (ref.sha256 !== expectedDigest || ref.byteLength !== bytes.byteLength) {\n throw new Error('candidate output locator does not identify the submitted bytes')\n }\n const stored = await port.read(ref)\n input.signal?.throwIfAborted()\n verifyBytes(stored, expectedDigest, bytes.byteLength, 'persisted candidate output')\n return immutableCandidateValue(ref)\n}\n","import {\n DEFAULT_REDACTION_RULES,\n REDACTION_VERSION,\n type RedactionRule,\n redactString,\n} from '@tangle-network/agent-eval'\n\nexport interface ProtectedRedactionReport {\n version: string\n redactionCount: number\n byRule: Record<string, number>\n}\n\n/** Redact protected values at the first persistence boundary, including object keys and bytes. */\nexport function redactProtectedValue<T>(\n value: T,\n protectedValues: readonly string[],\n): { value: T; report: ProtectedRedactionReport } {\n const report: ProtectedRedactionReport = {\n version: REDACTION_VERSION,\n redactionCount: 0,\n byRule: {},\n }\n const rules = protectedRedactionRules(protectedValues)\n const redacted = redactNode(value, protectedValues, rules, report) as T\n assertNoProtectedEvidence(redacted, protectedValues)\n return { value: redacted, report }\n}\n\nexport function redactProtectedReason(reason: string, protectedValues: readonly string[]): string {\n try {\n return redactProtectedValue(reason, protectedValues).value\n } catch {\n return 'candidate execution failed with a protected error'\n }\n}\n\nexport function assertNoProtectedEvidence(\n value: unknown,\n protectedValues: readonly string[],\n): void {\n if (value instanceof Uint8Array) {\n assertNoProtectedBytes(value, protectedValues)\n return\n }\n if (typeof value === 'string') {\n for (const protectedValue of protectedValueVariants(protectedValues)) {\n if (value.includes(protectedValue)) {\n throw new Error('protected value survived candidate evidence redaction')\n }\n }\n if (decodedBase64ContainsProtectedValue(value, protectedValues)) {\n throw new Error('base64 protected value survived candidate evidence redaction')\n }\n return\n }\n if (Array.isArray(value)) {\n for (const entry of value) assertNoProtectedEvidence(entry, protectedValues)\n return\n }\n if (value && typeof value === 'object') {\n for (const [key, entry] of Object.entries(value)) {\n assertNoProtectedEvidence(key, protectedValues)\n assertNoProtectedEvidence(entry, protectedValues)\n }\n }\n}\n\nexport function assertNoProtectedBytes(\n bytes: Uint8Array,\n protectedValues: readonly string[],\n): void {\n if (containsProtectedBytes(bytes, protectedValues)) {\n throw new Error('protected value survived candidate evidence byte redaction')\n }\n}\n\nfunction redactNode(\n value: unknown,\n protectedValues: readonly string[],\n rules: readonly RedactionRule[],\n report: ProtectedRedactionReport,\n): unknown {\n if (value instanceof Uint8Array) {\n if (containsProtectedBytes(value, protectedValues)) {\n recordRedaction(report, 'candidate-access-binary', 1)\n return Uint8Array.from(Buffer.from('[redacted:candidate-access-binary]', 'utf8'))\n }\n return Uint8Array.from(value)\n }\n if (typeof value === 'string') {\n if (decodedBase64ContainsProtectedValue(value, protectedValues)) {\n recordRedaction(report, 'candidate-access-binary', 1)\n return '[redacted:candidate-access-binary]'\n }\n const redacted = redactString(value, [...rules])\n for (const [rule, count] of Object.entries(redacted.report.byRule)) {\n recordRedaction(report, rule, count)\n }\n return redacted.output\n }\n if (Array.isArray(value)) {\n return value.map((entry) => redactNode(entry, protectedValues, rules, report))\n }\n if (value && typeof value === 'object') {\n const entries: Array<[string, unknown]> = []\n const seenKeys = new Set<string>()\n for (const [key, entry] of Object.entries(value)) {\n const redactedKey = redactNode(key, protectedValues, rules, report)\n if (typeof redactedKey !== 'string' || seenKeys.has(redactedKey)) {\n throw new Error('protected evidence redaction produced an ambiguous object key')\n }\n seenKeys.add(redactedKey)\n entries.push([redactedKey, redactNode(entry, protectedValues, rules, report)])\n }\n return Object.fromEntries(entries)\n }\n return value\n}\n\nfunction protectedRedactionRules(protectedValues: readonly string[]): RedactionRule[] {\n const exactRules = protectedValueVariants(protectedValues)\n .sort((left, right) => right.length - left.length || left.localeCompare(right))\n .map((value, index) => ({\n id: `candidate-access-${index}`,\n pattern: new RegExp(escapeRegularExpression(value), 'g'),\n replacement: '[redacted:candidate-access]',\n }))\n return [...exactRules, ...DEFAULT_REDACTION_RULES]\n}\n\nfunction recordRedaction(report: ProtectedRedactionReport, rule: string, count: number): void {\n if (count <= 0) return\n report.redactionCount += count\n report.byRule[rule] = (report.byRule[rule] ?? 0) + count\n}\n\nfunction containsProtectedBytes(bytes: Uint8Array, protectedValues: readonly string[]): boolean {\n const source = Buffer.from(bytes)\n return protectedValueVariants(protectedValues).some((value) =>\n source.includes(Buffer.from(value, 'utf8')),\n )\n}\n\nfunction decodedBase64ContainsProtectedValue(\n value: string,\n protectedValues: readonly string[],\n): boolean {\n if (value.length < 4 || value.length % 4 !== 0 || !/^[A-Za-z0-9+/]*={0,2}$/.test(value)) {\n return false\n }\n try {\n return containsProtectedBytes(Buffer.from(value, 'base64'), protectedValues)\n } catch {\n return false\n }\n}\n\nfunction protectedValueVariants(protectedValues: readonly string[]): string[] {\n const variants = new Set<string>()\n for (const value of normalizedProtectedValues(protectedValues)) {\n variants.add(value)\n variants.add(Buffer.from(value, 'utf8').toString('base64'))\n variants.add(Buffer.from(value, 'utf8').toString('base64url'))\n variants.add(encodeURIComponent(value))\n }\n return [...variants]\n}\n\nfunction normalizedProtectedValues(values: readonly string[]): string[] {\n return [...new Set(values.filter((value) => value.length > 0))]\n}\n\nfunction escapeRegularExpression(value: string): string {\n return value.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&')\n}\n","import { mkdtemp, rm } from 'node:fs/promises'\nimport { tmpdir } from 'node:os'\nimport { join } from 'node:path'\n\nimport type { BenchmarkEvaluation } from '@tangle-network/agent-eval'\nimport {\n type AgentCandidateArtifactRef,\n type AgentCandidateBenchmarkResultEvidence,\n type AgentCandidateModelSettlementEvidence,\n type AgentCandidateResolvedModel,\n type AgentCandidateTaskOutcomeEvidence,\n type AgentCandidateTermination,\n agentCandidateBenchmarkResultEvidenceSchema,\n agentCandidateModelSettlementEvidenceSchema,\n agentCandidateTaskOutcomeEvidenceSchema,\n agentCandidateWorkspaceSnapshotEvidenceSchema,\n type Sha256Digest,\n} from '@tangle-network/agent-interface'\n\nimport { readMaterializedWorkspaceFiles } from './artifacts'\nimport { runBoundCandidateBenchmarkGrader } from './benchmark-grader'\nimport {\n canonicalCandidateBytes,\n embeddedCandidateArtifact,\n immutableCandidateValue,\n sha256Bytes,\n} from './digest'\nimport { verifyTaskOutcomePatch } from './git-materialize'\nimport type { SealedAgentCandidateModelSettlement } from './model-settlement'\nimport { persistCandidateOutputArtifact } from './output-artifacts'\nimport type { PreparedCandidateState } from './prepared-state'\nimport { assertNoProtectedBytes } from './protected-redaction'\nimport type {\n AgentCandidateBenchmarkGraderPort,\n AgentCandidateExecutorTaskOutcomeCapture,\n AgentCandidateOutputArtifactPort,\n VerifiedAgentCandidateTaskOutcome,\n} from './types'\nimport { verifiedTaskOutcomeBrand } from './types'\n\nexport type PersistedAgentCandidateModelSettlement = AgentCandidateModelSettlementEvidence & {\n artifact: AgentCandidateArtifactRef\n}\n\nexport type PersistedAgentCandidateBenchmarkResult = AgentCandidateBenchmarkResultEvidence & {\n artifact: AgentCandidateArtifactRef\n}\n\n/** Persist the closed evaluator model ledger as canonical V2 receipt evidence. */\nexport async function persistCandidateModelSettlement(\n state: PreparedCandidateState,\n settlement: SealedAgentCandidateModelSettlement,\n outputArtifacts: AgentCandidateOutputArtifactPort,\n): Promise<PersistedAgentCandidateModelSettlement> {\n return await persistCandidateModelSettlementEvidence(\n {\n executionId: state.executionId,\n executionPlanDigest: state.executionPlan.value.digest,\n resolvedModel: state.resolvedModel,\n },\n settlement,\n outputArtifacts,\n )\n}\n\n/** Persist a closed model ledger when only durable recovery identity remains. */\nexport async function persistCandidateModelSettlementEvidence(\n identity: {\n executionId: string\n executionPlanDigest: Sha256Digest\n resolvedModel: AgentCandidateResolvedModel\n },\n settlement: SealedAgentCandidateModelSettlement,\n outputArtifacts: AgentCandidateOutputArtifactPort,\n): Promise<PersistedAgentCandidateModelSettlement> {\n const material = {\n schemaVersion: 2 as const,\n kind: 'agent-candidate-model-settlement-material' as const,\n executionPlanDigest: identity.executionPlanDigest,\n preparationId: settlement.value.preparationId,\n grantDigest: settlement.value.grantDigest,\n closed: true as const,\n resolved: identity.resolvedModel,\n calls: settlement.value.calls.map((call) => ({\n callId: call.callId,\n generationId: call.generationId,\n traceSpanId: call.traceSpanId,\n status: call.status,\n model: call.model,\n startedAtMs: call.startedAtMs,\n endedAtMs: call.endedAtMs,\n inputTokens: call.inputTokens,\n outputTokens: call.outputTokens,\n cachedInputTokens: call.cachedInputTokens ?? 0,\n reasoningTokens: call.reasoningTokens ?? 0,\n costUsdNanos: call.costUsdNanos,\n })),\n usage: settlement.fixedUsage,\n }\n const bytes = canonicalCandidateBytes(material)\n const digest = sha256Bytes(bytes)\n const artifact = await persistCandidateOutputArtifact(outputArtifacts, {\n executionId: identity.executionId,\n purpose: 'model-settlement',\n bytes,\n })\n return immutableCandidateValue(\n agentCandidateModelSettlementEvidenceSchema.parse({\n schemaVersion: 1,\n kind: 'agent-candidate-model-settlement',\n digest,\n material,\n artifact,\n }),\n ) as PersistedAgentCandidateModelSettlement\n}\n\n/** Recompute the result tree from the patch, then persist its exact task evidence. */\nexport async function persistVerifiedCandidateTaskOutcome(\n state: PreparedCandidateState,\n capture: AgentCandidateExecutorTaskOutcomeCapture,\n outputArtifacts: AgentCandidateOutputArtifactPort,\n protectedValues: readonly string[],\n signal?: AbortSignal,\n): Promise<VerifiedAgentCandidateTaskOutcome> {\n signal?.throwIfAborted()\n const patch = Uint8Array.from(capture.gitDiff)\n const archive = Uint8Array.from(capture.archive)\n if (archive.byteLength === 0) throw new Error('candidate task archive cannot be empty')\n assertNoProtectedBytes(patch, protectedValues)\n assertNoProtectedBytes(archive, protectedValues)\n const afterState = immutableCandidateValue(capture.afterState)\n const repository = state.executionPlan.value.material.task.repository\n const verified = await verifyTaskOutcomePatch({\n repositoryRoot: state.roots.staging.taskRoot,\n baseCommit: repository.baseCommit,\n baseTree: repository.baseTree,\n resultTree: capture.resultTree,\n patch,\n afterState,\n })\n signal?.throwIfAborted()\n const manifestBytes = canonicalCandidateBytes(afterState)\n assertNoProtectedBytes(manifestBytes, protectedValues)\n const provisionalSnapshot = agentCandidateWorkspaceSnapshotEvidenceSchema.parse({\n schemaVersion: 1,\n kind: 'agent-candidate-workspace-snapshot',\n digest: sha256Bytes(manifestBytes),\n material: afterState,\n manifest: embeddedCandidateArtifact(manifestBytes),\n archive: embeddedCandidateArtifact(archive),\n })\n await verifyTaskOutcomeArchive(state, provisionalSnapshot, archive, protectedValues)\n signal?.throwIfAborted()\n const [manifest, archiveRef, gitDiff] = await Promise.all([\n persistCandidateOutputArtifact(outputArtifacts, {\n executionId: state.executionId,\n purpose: 'task-manifest',\n bytes: manifestBytes,\n signal,\n }),\n persistCandidateOutputArtifact(outputArtifacts, {\n executionId: state.executionId,\n purpose: 'task-archive',\n bytes: archive,\n signal,\n }),\n persistCandidateOutputArtifact(outputArtifacts, {\n executionId: state.executionId,\n purpose: 'task-patch',\n bytes: patch,\n signal,\n }),\n ])\n const snapshot = agentCandidateWorkspaceSnapshotEvidenceSchema.parse({\n schemaVersion: 1,\n kind: 'agent-candidate-workspace-snapshot',\n digest: sha256Bytes(manifestBytes),\n material: afterState,\n manifest,\n archive: archiveRef,\n })\n const material = {\n schemaVersion: 1 as const,\n kind: 'agent-candidate-task-outcome-material' as const,\n executionPlanDigest: state.executionPlan.value.digest,\n baseRepository: {\n identity: repository.identity,\n rootIdentity: repository.rootIdentity,\n commit: repository.baseCommit,\n tree: repository.baseTree,\n },\n resultRepository: {\n identity: repository.identity,\n rootIdentity: repository.rootIdentity,\n commit: verified.resultCommit,\n tree: verified.resultTree,\n },\n afterState: snapshot,\n gitDiff: {\n format: 'git-diff-binary' as const,\n artifact: gitDiff,\n },\n }\n const bytes = canonicalCandidateBytes(material)\n const digest = sha256Bytes(bytes)\n const artifact = await persistCandidateOutputArtifact(outputArtifacts, {\n executionId: state.executionId,\n purpose: 'task-outcome',\n bytes,\n signal,\n })\n const evidence = immutableCandidateValue(\n agentCandidateTaskOutcomeEvidenceSchema.parse({\n schemaVersion: 1,\n kind: 'agent-candidate-task-outcome',\n digest,\n material,\n artifact,\n }),\n ) as AgentCandidateTaskOutcomeEvidence & { artifact: AgentCandidateArtifactRef }\n const storedPatch = Uint8Array.from(patch)\n return Object.freeze({\n evidence,\n get patch(): Uint8Array {\n return Uint8Array.from(storedPatch)\n },\n [verifiedTaskOutcomeBrand]: true as const,\n })\n}\n\n/** Grade only a runtime-verified outcome and persist both raw and normalized evidence. */\nexport async function persistCandidateBenchmarkResult(\n state: PreparedCandidateState,\n termination: AgentCandidateTermination,\n outcome: VerifiedAgentCandidateTaskOutcome,\n grader: AgentCandidateBenchmarkGraderPort,\n outputArtifacts: AgentCandidateOutputArtifactPort,\n protectedValues: readonly string[],\n signal?: AbortSignal,\n): Promise<PersistedAgentCandidateBenchmarkResult> {\n signal?.throwIfAborted()\n const frozenTermination = immutableCandidateValue(termination)\n const graded = await runBoundCandidateBenchmarkGrader({\n executionId: state.executionId,\n termination: frozenTermination,\n outcome,\n grader,\n artifacts: outputArtifacts,\n signal,\n })\n signal?.throwIfAborted()\n const evaluation = normalizeEvaluation(graded.evaluation, frozenTermination)\n const rawEvidence = Uint8Array.from(graded.evidence)\n if (rawEvidence.byteLength === 0) throw new Error('candidate benchmark evidence cannot be empty')\n assertNoProtectedBytes(rawEvidence, protectedValues)\n const evidenceRef = await persistCandidateOutputArtifact(outputArtifacts, {\n executionId: state.executionId,\n purpose: 'grader-evidence',\n bytes: rawEvidence,\n signal,\n })\n const task = state.executionPlan.value.material.task\n const material = {\n schemaVersion: 1 as const,\n kind: 'agent-candidate-benchmark-result-material' as const,\n executionPlanDigest: state.executionPlan.value.digest,\n taskOutcomeDigest: outcome.evidence.digest,\n benchmark: {\n name: task.benchmark,\n version: task.benchmarkVersion,\n taskId: task.taskId,\n splitDigest: task.splitDigest,\n },\n grader: {\n name: graded.grader.name,\n version: graded.grader.version,\n artifact: graded.grader.artifact,\n },\n evidence: evidenceRef,\n score: evaluation.score,\n passed: evaluation.passed,\n dimensions: evaluation.dimensions,\n }\n const bytes = canonicalCandidateBytes(material)\n const digest = sha256Bytes(bytes)\n const artifact = await persistCandidateOutputArtifact(outputArtifacts, {\n executionId: state.executionId,\n purpose: 'benchmark-result',\n bytes,\n signal,\n })\n return immutableCandidateValue(\n agentCandidateBenchmarkResultEvidenceSchema.parse({\n schemaVersion: 1,\n kind: 'agent-candidate-benchmark-result',\n digest,\n material,\n artifact,\n }),\n ) as PersistedAgentCandidateBenchmarkResult\n}\n\nasync function verifyTaskOutcomeArchive(\n state: PreparedCandidateState,\n snapshot: ReturnType<typeof agentCandidateWorkspaceSnapshotEvidenceSchema.parse>,\n archive: Uint8Array,\n protectedValues: readonly string[],\n): Promise<void> {\n const root = await mkdtemp(join(tmpdir(), 'agent-candidate-task-archive-'))\n try {\n await state.ports.workspaces.materialize({\n role: 'task',\n snapshot,\n archive: Uint8Array.from(archive),\n destination: root,\n })\n const files = await readMaterializedWorkspaceFiles(root, snapshot.material)\n for (const file of files) assertNoProtectedBytes(file.bytes, protectedValues)\n } finally {\n await rm(root, { recursive: true, force: true })\n }\n}\n\nfunction normalizeEvaluation(\n evaluation: BenchmarkEvaluation,\n termination: AgentCandidateTermination,\n): { score: number; passed: boolean; dimensions: Array<{ name: string; score: number }> } {\n if (!evaluation || typeof evaluation !== 'object' || Array.isArray(evaluation)) {\n throw new Error('candidate benchmark evaluation must be an object')\n }\n assertUnitScore(evaluation.score, 'candidate benchmark score')\n if (evaluation.passed !== undefined && typeof evaluation.passed !== 'boolean') {\n throw new Error('candidate benchmark passed must be boolean')\n }\n const cleanExit = termination.kind === 'exit' && termination.exitCode === 0\n const dimensions = Object.entries(evaluation.dimensions ?? {})\n .map(([name, score]) => {\n if (!/^[a-z0-9]+(?:[._-][a-z0-9]+)*$/.test(name)) {\n throw new Error(`candidate benchmark dimension is not normalized: ${name}`)\n }\n assertUnitScore(score, `candidate benchmark dimension ${name}`)\n return { name, score: cleanExit ? score : 0 }\n })\n .sort((left, right) => left.name.localeCompare(right.name))\n return {\n score: cleanExit ? evaluation.score : 0,\n passed: cleanExit && (evaluation.passed ?? evaluation.score > 0),\n dimensions,\n }\n}\n\nfunction assertUnitScore(value: unknown, label: string): asserts value is number {\n if (typeof value !== 'number' || !Number.isFinite(value) || value < 0 || value > 1) {\n throw new Error(`${label} must be finite and within [0, 1]`)\n }\n}\n","import type { BenchmarkEvaluation } from '@tangle-network/agent-eval'\nimport type {\n AgentCandidateArtifactRef,\n AgentCandidateTermination,\n} from '@tangle-network/agent-interface'\n\nimport { readVerifiedArtifact } from './artifacts'\nimport { immutableCandidateValue, sha256Bytes } from './digest'\nimport type {\n AgentCandidateBenchmarkGraderPort,\n AgentCandidateOutputArtifactPort,\n VerifiedAgentCandidateTaskOutcome,\n} from './types'\n\nexport interface BoundAgentCandidateBenchmarkRun {\n readonly grader: {\n readonly name: string\n readonly version: string\n readonly artifact: AgentCandidateArtifactRef\n }\n readonly evaluation: BenchmarkEvaluation\n readonly evidence: Uint8Array\n}\n\n/**\n * Admit verified grader bytes to the evaluator runner and reject any result\n * that is not bound to those bytes, the exact task outcome, and its raw output.\n */\nexport async function runBoundCandidateBenchmarkGrader(input: {\n executionId: string\n termination: AgentCandidateTermination\n outcome: VerifiedAgentCandidateTaskOutcome\n grader: AgentCandidateBenchmarkGraderPort\n artifacts: AgentCandidateOutputArtifactPort\n signal?: AbortSignal\n}): Promise<BoundAgentCandidateBenchmarkRun> {\n input.signal?.throwIfAborted()\n const descriptor = snapshotGraderDescriptor(input.grader)\n const implementationBytes = await readVerifiedArtifact(descriptor.artifact, input.artifacts)\n if (implementationBytes.byteLength === 0) {\n throw new Error('candidate benchmark grader implementation cannot be empty')\n }\n const expectedImplementationDigest = sha256Bytes(implementationBytes)\n const termination = immutableCandidateValue(input.termination)\n const run = input.grader.run\n const result = await run(\n Object.freeze({\n executionId: input.executionId,\n termination,\n outcome: input.outcome,\n implementation: detachedImplementation(implementationBytes),\n signal: input.signal ?? new AbortController().signal,\n }),\n )\n input.signal?.throwIfAborted()\n assertExactRunnerResult(result)\n\n const evidence = Uint8Array.from(result.evidence)\n const outputDigest = sha256Bytes(evidence)\n if (result.binding.implementationDigest !== expectedImplementationDigest) {\n throw new Error(\n 'candidate benchmark grader executed implementation digest does not match its verified artifact',\n )\n }\n if (result.binding.taskOutcomeDigest !== input.outcome.evidence.digest) {\n throw new Error(\n 'candidate benchmark grader task outcome digest does not match verified outcome',\n )\n }\n if (result.binding.outputDigest !== outputDigest) {\n throw new Error('candidate benchmark grader raw output digest does not match returned evidence')\n }\n\n return Object.freeze({\n grader: descriptor,\n evaluation: result.evaluation,\n evidence,\n })\n}\n\nfunction snapshotGraderDescriptor(\n grader: AgentCandidateBenchmarkGraderPort,\n): BoundAgentCandidateBenchmarkRun['grader'] {\n if (!grader.name || !grader.version) {\n throw new Error('candidate benchmark grader name and version must be non-empty')\n }\n return immutableCandidateValue({\n name: grader.name,\n version: grader.version,\n artifact: grader.artifact,\n })\n}\n\nfunction detachedImplementation(bytes: Uint8Array): {\n readonly byteLength: number\n readonly bytes: Uint8Array\n} {\n const stored = Uint8Array.from(bytes)\n return Object.freeze({\n byteLength: stored.byteLength,\n get bytes(): Uint8Array {\n return Uint8Array.from(stored)\n },\n })\n}\n\nfunction assertExactRunnerResult(\n value: unknown,\n): asserts value is Awaited<ReturnType<AgentCandidateBenchmarkGraderPort['run']>> {\n if (value === null || typeof value !== 'object' || Array.isArray(value)) {\n throw new Error('candidate benchmark grader result must be an object')\n }\n const result = value as Record<string, unknown>\n const keys = Object.keys(result).sort()\n if (\n keys.length !== 3 ||\n keys[0] !== 'binding' ||\n keys[1] !== 'evaluation' ||\n keys[2] !== 'evidence'\n ) {\n throw new Error('candidate benchmark grader returned unknown or missing fields')\n }\n if (!(result.evidence instanceof Uint8Array)) {\n throw new Error('candidate benchmark grader evidence must be bytes')\n }\n if (\n result.binding === null ||\n typeof result.binding !== 'object' ||\n Array.isArray(result.binding)\n ) {\n throw new Error('candidate benchmark grader binding must be an object')\n }\n const bindingKeys = Object.keys(result.binding).sort()\n if (\n bindingKeys.length !== 3 ||\n bindingKeys[0] !== 'implementationDigest' ||\n bindingKeys[1] !== 'outputDigest' ||\n bindingKeys[2] !== 'taskOutcomeDigest'\n ) {\n throw new Error('candidate benchmark grader binding returned unknown or missing fields')\n }\n}\n","import { REDACTION_VERSION, type TraceStore } from '@tangle-network/agent-eval'\n\nimport { type ProtectedRedactionReport, redactProtectedValue } from './protected-redaction'\n\n/** Trace-store proxy that removes live credentials before any write reaches durable storage. */\nexport class ProtectedAgentCandidateTraceStore implements TraceStore {\n private readonly aggregate: ProtectedRedactionReport = {\n version: REDACTION_VERSION,\n redactionCount: 0,\n byRule: {},\n }\n\n constructor(\n private readonly inner: TraceStore,\n private readonly protectedValues: readonly string[],\n ) {}\n\n report(): ProtectedRedactionReport {\n return {\n version: this.aggregate.version,\n redactionCount: this.aggregate.redactionCount,\n byRule: { ...this.aggregate.byRule },\n }\n }\n\n async appendRun(run: Parameters<TraceStore['appendRun']>[0]): Promise<void> {\n await this.inner.appendRun(this.redact(run))\n }\n\n async updateRun(\n runId: Parameters<TraceStore['updateRun']>[0],\n patch: Parameters<TraceStore['updateRun']>[1],\n ): Promise<void> {\n await this.inner.updateRun(this.redact(runId), this.redact(patch))\n }\n\n async appendSpan(span: Parameters<TraceStore['appendSpan']>[0]): Promise<void> {\n if (span.kind === 'llm') {\n throw new Error('candidate executors cannot author protected model spans')\n }\n await this.inner.appendSpan(this.redact(span))\n }\n\n async updateSpan(\n spanId: Parameters<TraceStore['updateSpan']>[0],\n patch: Parameters<TraceStore['updateSpan']>[1],\n ): Promise<void> {\n if (patch.kind === 'llm') {\n throw new Error('candidate executors cannot author protected model spans')\n }\n await this.inner.updateSpan(this.redact(spanId), this.redact(patch))\n }\n\n async appendEvent(event: Parameters<TraceStore['appendEvent']>[0]): Promise<void> {\n await this.inner.appendEvent(this.redact(event))\n }\n\n async appendArtifact(artifact: Parameters<TraceStore['appendArtifact']>[0]): Promise<void> {\n await this.inner.appendArtifact(this.redact(artifact))\n }\n\n async appendBudgetEntry(entry: Parameters<TraceStore['appendBudgetEntry']>[0]): Promise<void> {\n await this.inner.appendBudgetEntry(this.redact(entry))\n }\n\n getRun(...args: Parameters<TraceStore['getRun']>): ReturnType<TraceStore['getRun']> {\n return this.inner.getRun(...args)\n }\n\n listRuns(...args: Parameters<TraceStore['listRuns']>): ReturnType<TraceStore['listRuns']> {\n return this.inner.listRuns(...args)\n }\n\n spans(...args: Parameters<TraceStore['spans']>): ReturnType<TraceStore['spans']> {\n return this.inner.spans(...args)\n }\n\n events(...args: Parameters<TraceStore['events']>): ReturnType<TraceStore['events']> {\n return this.inner.events(...args)\n }\n\n budget(...args: Parameters<TraceStore['budget']>): ReturnType<TraceStore['budget']> {\n return this.inner.budget(...args)\n }\n\n artifacts(...args: Parameters<TraceStore['artifacts']>): ReturnType<TraceStore['artifacts']> {\n return this.inner.artifacts(...args)\n }\n\n private redact<T>(value: T): T {\n const redacted = redactProtectedValue(value, this.protectedValues)\n this.aggregate.version = redacted.report.version\n this.aggregate.redactionCount += redacted.report.redactionCount\n for (const [rule, count] of Object.entries(redacted.report.byRule)) {\n this.aggregate.byRule[rule] = (this.aggregate.byRule[rule] ?? 0) + count\n }\n return redacted.value\n }\n}\n\n/** Recovery can read existing trace state but must never accept new unredactable writes. */\nexport class RecoveryAgentCandidateTraceStore implements TraceStore {\n constructor(private readonly inner: TraceStore) {}\n\n appendRun(): Promise<void> {\n return this.rejectWrite()\n }\n\n updateRun(): Promise<void> {\n return this.rejectWrite()\n }\n\n appendSpan(): Promise<void> {\n return this.rejectWrite()\n }\n\n updateSpan(): Promise<void> {\n return this.rejectWrite()\n }\n\n appendEvent(): Promise<void> {\n return this.rejectWrite()\n }\n\n appendArtifact(): Promise<void> {\n return this.rejectWrite()\n }\n\n appendBudgetEntry(): Promise<void> {\n return this.rejectWrite()\n }\n\n getRun(...args: Parameters<TraceStore['getRun']>): ReturnType<TraceStore['getRun']> {\n return this.inner.getRun(...args)\n }\n\n listRuns(...args: Parameters<TraceStore['listRuns']>): ReturnType<TraceStore['listRuns']> {\n return this.inner.listRuns(...args)\n }\n\n spans(...args: Parameters<TraceStore['spans']>): ReturnType<TraceStore['spans']> {\n return this.inner.spans(...args)\n }\n\n events(...args: Parameters<TraceStore['events']>): ReturnType<TraceStore['events']> {\n return this.inner.events(...args)\n }\n\n budget(...args: Parameters<TraceStore['budget']>): ReturnType<TraceStore['budget']> {\n return this.inner.budget(...args)\n }\n\n artifacts(...args: Parameters<TraceStore['artifacts']>): ReturnType<TraceStore['artifacts']> {\n return this.inner.artifacts(...args)\n }\n\n private rejectWrite(): Promise<never> {\n return Promise.reject(new Error('expired candidate recovery cannot append trace evidence'))\n }\n}\n","import type { TraceStore } from '@tangle-network/agent-eval'\nimport type { AgentCandidateTermination } from '@tangle-network/agent-interface'\n\nimport type {\n AgentCandidateExecutionClaimStore,\n AgentCandidateExecutionFailureClass,\n AgentCandidateExecutionLease,\n AgentCandidateExecutionTerminalResult,\n} from './claim'\nimport { candidateExecutionClaim } from './claim-plan'\nimport {\n candidateCleanupDeadline,\n candidateCleanupTimeout,\n candidateResultTimeout,\n withinCandidateCleanupDeadline,\n withinCandidateResultDeadline,\n} from './cleanup'\nimport { canonicalCandidateBytes } from './digest'\nimport { candidatePostRunWindowMs, candidateTerminalWindowMs } from './execution-window'\nimport {\n sealAgentCandidateExecutorFinalCapture,\n sealAgentCandidateProtectedRunCapture,\n} from './executor-capture'\nimport { failedAgentCandidateRun, finalizeAgentCandidateRun } from './finalize'\nimport {\n appendAuthoritativeModelSettlementSpans,\n type SealedAgentCandidateModelSettlement,\n sealAgentCandidateModelSettlement,\n} from './model-settlement'\nimport {\n type PersistedAgentCandidateModelSettlement,\n persistCandidateBenchmarkResult,\n persistCandidateModelSettlement,\n persistVerifiedCandidateTaskOutcome,\n} from './outcome-evidence'\nimport { persistCandidateOutputArtifact } from './output-artifacts'\nimport {\n assertPreparedCandidateIntegrity,\n assertPreparedCandidateWorkspaces,\n beginPreparedCandidateClaim,\n beginPreparedCandidateRun,\n beginPreparedCandidateSettlement,\n consumePreparedCandidateExecution,\n markPreparedCandidateClaimed,\n type PreparedCandidateState,\n} from './prepared-state'\nimport { redactProtectedReason } from './protected-redaction'\nimport { ProtectedAgentCandidateTraceStore } from './protected-trace-store'\nimport type {\n AgentCandidateBenchmarkGraderPort,\n AgentCandidateExecutorFinalCapture,\n AgentCandidateExecutorPort,\n AgentCandidateExecutorRequest,\n AgentCandidateOutputArtifactPort,\n AgentCandidateProtectedModelActivation,\n AgentCandidateProtectedRunCapture,\n AgentCandidateRunFinalization,\n PreparedAgentCandidateExecution,\n} from './types'\n\nexport interface ExecutePreparedAgentCandidateOptions {\n executor: AgentCandidateExecutorPort\n grader: AgentCandidateBenchmarkGraderPort\n outputArtifacts: AgentCandidateOutputArtifactPort\n traceStore: TraceStore\n /** Long-lived evaluator-owned store shared by every process that can run this benchmark. */\n claimStore: AgentCandidateExecutionClaimStore\n /** Maximum time to prove process death and revoke protected access after a run ends. */\n cleanupTimeoutMs?: number\n /** Maximum time for task verification, executable grading, and receipt construction. */\n resultTimeoutMs?: number\n}\n\n/** Executes and finalizes one durably claimed candidate without exposing an unproven result. */\nexport async function executePreparedAgentCandidate(\n prepared: PreparedAgentCandidateExecution,\n options: ExecutePreparedAgentCandidateOptions,\n): Promise<AgentCandidateRunFinalization> {\n const initialState = assertPreparedCandidateIntegrity(prepared)\n const cleanupTimeoutMs = candidateCleanupTimeout(\n options.cleanupTimeoutMs ?? initialState.cleanupTimeoutMs,\n )\n if (cleanupTimeoutMs > initialState.cleanupTimeoutMs) {\n throw new Error('execution cleanup timeout exceeds the frozen preparation bound')\n }\n const resultTimeoutMs = candidateResultTimeout(\n options.resultTimeoutMs ?? initialState.resultTimeoutMs,\n initialState.resultTimeoutMs,\n )\n if (resultTimeoutMs > initialState.resultTimeoutMs) {\n throw new Error('execution result timeout exceeds the frozen preparation bound')\n }\n let state: PreparedCandidateState\n try {\n state = beginPreparedCandidateClaim(prepared)\n } catch (error) {\n return failedAgentCandidateRun(initialState, errorMessage(error))\n }\n\n try {\n // Mutable staging is only a preparation check. The executor receives the\n // detached file bytes sealed in private state, never these host paths.\n await assertPreparedCandidateWorkspaces(state)\n } catch (error) {\n return await failBeforeActivation(prepared, state, error, 'failed', cleanupTimeoutMs)\n }\n\n let acquired: Awaited<ReturnType<AgentCandidateExecutionClaimStore['tryClaim']>>\n try {\n acquired = await options.claimStore.tryClaim(candidateExecutionClaim(prepared))\n } catch (error) {\n return await failBeforeActivation(prepared, state, error, 'failed', cleanupTimeoutMs)\n }\n if (!acquired.acquired) {\n return await failBeforeActivation(\n prepared,\n state,\n new Error(\n acquired.reason === 'retry-not-eligible'\n ? `candidate execution retry is not eligible: ${acquired.detail}`\n : 'candidate execution attempt is already claimed',\n ),\n 'replayed',\n cleanupTimeoutMs,\n )\n }\n\n markPreparedCandidateClaimed(prepared)\n const postRunWindowMs = candidatePostRunWindowMs(cleanupTimeoutMs, resultTimeoutMs)\n // A caller may shorten cleanup for this invocation, but that must never buy\n // the candidate more execution time. The claim was frozen with the prepared\n // cleanup window, so recover the original task deadline from that value.\n const deadlineAtMs =\n acquired.claim.leaseExpiresAtMs -\n candidatePostRunWindowMs(state.cleanupTimeoutMs, state.resultTimeoutMs)\n const requiredLeaseExpiry = deadlineAtMs + postRunWindowMs\n if (\n Date.now() >= deadlineAtMs ||\n deadlineAtMs > state.reservationExpiresAtMs ||\n requiredLeaseExpiry > acquired.lease.expiresAtMs\n ) {\n return await failClaimedExecution(\n prepared,\n state,\n acquired.lease,\n options.claimStore,\n options.outputArtifacts,\n new Error('candidate claim no longer covers its full execution and cleanup window'),\n 'failed',\n cleanupTimeoutMs,\n 'pre-model-infrastructure',\n )\n }\n let activation: AgentCandidateProtectedModelActivation\n try {\n const activated = await withinCandidateCleanupDeadline(\n () =>\n state.ports.models.activateGrant({\n executionId: state.executionId,\n preparationId: state.preparationId,\n grantDigest: state.modelReservation.digest,\n resolved: state.resolvedModel,\n deadlineAtMs,\n }),\n Math.min(deadlineAtMs, candidateCleanupDeadline(cleanupTimeoutMs)),\n 'protected model activation',\n )\n activation = Object.freeze({ env: Object.freeze({ ...activated.env }) })\n } catch (error) {\n return await failClaimedExecution(\n prepared,\n state,\n acquired.lease,\n options.claimStore,\n options.outputArtifacts,\n new Error('protected model activation failed', { cause: error }),\n 'failed',\n cleanupTimeoutMs,\n 'pre-model-infrastructure',\n )\n }\n\n let memoryActivation: { env: Readonly<Record<string, string>> } | undefined\n if (state.memory.mode === 'isolated') {\n try {\n const reservation = state.memoryReservation\n if (!reservation) throw new Error('isolated memory reservation is missing')\n const activated = await withinCandidateCleanupDeadline(\n () =>\n state.ports.memory.activate({\n executionId: state.executionId,\n preparationId: reservation.preparationId,\n accessDigest: reservation.accessDigest,\n effectiveNamespace: reservation.effectiveNamespace,\n deadlineAtMs,\n }),\n Math.min(deadlineAtMs, candidateCleanupDeadline(cleanupTimeoutMs)),\n 'isolated memory activation',\n )\n memoryActivation = Object.freeze({ env: Object.freeze({ ...activated.env }) })\n } catch (error) {\n return await failClaimedExecution(\n prepared,\n state,\n acquired.lease,\n options.claimStore,\n options.outputArtifacts,\n new Error('isolated memory activation failed', { cause: error }),\n 'failed',\n cleanupTimeoutMs,\n 'pre-model-infrastructure',\n activation,\n )\n }\n }\n\n let request: AgentCandidateExecutorRequest\n try {\n request = beginPreparedCandidateRun(prepared, activation, memoryActivation).request\n } catch (error) {\n return await failClaimedExecution(\n prepared,\n state,\n acquired.lease,\n options.claimStore,\n options.outputArtifacts,\n error,\n 'failed',\n cleanupTimeoutMs,\n 'pre-model-infrastructure',\n activation,\n memoryActivation,\n )\n }\n\n try {\n const phase = await options.claimStore.markCandidateMayRun(acquired.lease)\n if (phase.phase !== 'candidate-may-run') {\n throw new Error('candidate claim did not persist the candidate-may-run phase')\n }\n } catch (error) {\n return await failClaimedExecution(\n prepared,\n state,\n acquired.lease,\n options.claimStore,\n options.outputArtifacts,\n new Error('candidate execution phase persistence failed', { cause: error }),\n 'failed',\n cleanupTimeoutMs,\n 'pre-model-infrastructure',\n activation,\n memoryActivation,\n )\n }\n if (Date.now() >= deadlineAtMs) {\n return await failClaimedExecution(\n prepared,\n state,\n acquired.lease,\n options.claimStore,\n options.outputArtifacts,\n new Error('candidate execution deadline elapsed while persisting its launch phase'),\n 'failed',\n cleanupTimeoutMs,\n 'unknown',\n activation,\n memoryActivation,\n )\n }\n\n const protectedValues = protectedEnvironmentValues(activation, memoryActivation)\n const protectedTraceStore = new ProtectedAgentCandidateTraceStore(\n options.traceStore,\n protectedValues,\n )\n const execution = await runAndStopExecutor(\n options.executor,\n request,\n protectedTraceStore,\n deadlineAtMs,\n cleanupTimeoutMs,\n )\n beginPreparedCandidateSettlement(prepared)\n const cleanupDeadlineAtMs = candidateCleanupDeadline(cleanupTimeoutMs)\n\n const accessReason =\n execution.kind === 'timeout' || execution.termination?.kind === 'timeout'\n ? 'timeout'\n : execution.kind === 'capture'\n ? 'completed'\n : 'failed'\n const [memoryClose, settlementResult] = await Promise.all([\n closeMemoryAccess(state, accessReason, cleanupDeadlineAtMs),\n settleModelGrant(state, accessReason, cleanupDeadlineAtMs),\n ])\n if (!execution.processStopped || !settlementResult.settlement || !memoryClose.closed) {\n consumePreparedCandidateExecution(prepared, 'failed')\n return failedAgentCandidateRun(\n state,\n redactProtectedReason(\n joinErrors(\n execution.error,\n !execution.processStopped\n ? new Error('candidate process termination is not proven')\n : undefined,\n memoryClose.error,\n settlementResult.error ??\n (!settlementResult.settlement ? new Error('model settlement failed') : undefined),\n new Error('candidate claim remains recoverable until protected cleanup is proven'),\n ),\n protectedValues,\n ),\n execution.termination,\n settlementResult.settlement?.usage ?? null,\n )\n }\n\n let modelSettlement: PersistedAgentCandidateModelSettlement\n try {\n modelSettlement = await withinCandidateCleanupDeadline(\n () =>\n persistCandidateModelSettlement(\n state,\n settlementResult.settlement as SealedAgentCandidateModelSettlement,\n options.outputArtifacts,\n ),\n candidateCleanupDeadline(cleanupTimeoutMs),\n 'candidate model settlement persistence',\n )\n } catch (error) {\n consumePreparedCandidateExecution(prepared, 'failed')\n return failedAgentCandidateRun(\n state,\n redactProtectedReason(\n joinErrors(\n error,\n new Error('candidate claim remains recoverable until settlement evidence is durable'),\n ),\n protectedValues,\n ),\n execution.termination,\n settlementResult.settlement.usage,\n )\n }\n\n let result: AgentCandidateRunFinalization\n const failureClass: AgentCandidateExecutionFailureClass =\n execution.kind === 'error' ? 'execution' : 'post-model-infrastructure'\n if (execution.kind === 'error') {\n result = failedAgentCandidateRun(\n state,\n redactProtectedReason(errorMessage(execution.error), protectedValues),\n execution.termination,\n settlementResult.settlement.usage,\n )\n } else if (!execution.finalCapture.taskOutcome) {\n result = failedAgentCandidateRun(\n state,\n 'candidate executor stopped without a captured task outcome',\n execution.termination,\n settlementResult.settlement.usage,\n )\n } else {\n const capture =\n execution.kind === 'capture'\n ? execution.capture\n : {\n executionId: state.executionId,\n termination: execution.termination,\n }\n try {\n const resultDeadlineAtMs = Math.min(\n Date.now() + resultTimeoutMs,\n acquired.lease.expiresAtMs - candidateTerminalWindowMs(cleanupTimeoutMs),\n )\n result = await withinCandidateResultDeadline(\n async (signal) => {\n await appendAuthoritativeModelSettlementSpans(\n options.traceStore,\n state.trace.runId,\n settlementResult.settlement as SealedAgentCandidateModelSettlement,\n )\n const taskOutcome = await persistVerifiedCandidateTaskOutcome(\n state,\n execution.finalCapture.taskOutcome!,\n options.outputArtifacts,\n protectedValues,\n signal,\n )\n const benchmarkResult = await persistCandidateBenchmarkResult(\n state,\n capture.termination,\n taskOutcome,\n options.grader,\n options.outputArtifacts,\n protectedValues,\n signal,\n )\n return await finalizeAgentCandidateRun(\n state,\n capture,\n options.traceStore,\n settlementResult.settlement as SealedAgentCandidateModelSettlement,\n {\n finalCapture: execution.finalCapture,\n modelSettlement,\n taskOutcome,\n benchmarkResult,\n outputArtifacts: options.outputArtifacts,\n },\n protectedValues,\n protectedTraceStore.report(),\n signal,\n )\n },\n resultDeadlineAtMs,\n 'candidate evidence finalization',\n )\n } catch (error) {\n result = failedAgentCandidateRun(\n state,\n redactProtectedReason(errorMessage(error), protectedValues),\n execution.termination,\n settlementResult.settlement.usage,\n )\n }\n }\n\n let terminal: AgentCandidateExecutionTerminalResult\n try {\n terminal = result.succeeded\n ? {\n schemaVersion: 1,\n status: 'succeeded',\n usage: settlementResult.settlement.fixedUsage,\n modelSettlement: result.artifacts.modelSettlement,\n taskOutcome: result.artifacts.taskOutcome,\n benchmarkResult: result.artifacts.benchmarkResult,\n runReceipt: result.artifacts.runReceipt,\n }\n : {\n schemaVersion: 1,\n status: 'failed',\n failureClass,\n usage: settlementResult.settlement.fixedUsage,\n modelSettlement: modelSettlement.artifact,\n failureEvidence: await withinCandidateCleanupDeadline(\n () =>\n persistFailureEvidence(\n state,\n result.reason,\n failureClass,\n execution.termination,\n options.outputArtifacts,\n ),\n acquired.lease.expiresAtMs,\n 'candidate failure-evidence persistence',\n ),\n }\n } catch (error) {\n consumePreparedCandidateExecution(prepared, 'failed')\n return failedAgentCandidateRun(\n state,\n redactProtectedReason(\n joinErrors(\n error,\n new Error('candidate claim remains recoverable until terminal evidence is durable'),\n ),\n protectedValues,\n ),\n execution.termination,\n settlementResult.settlement.usage,\n )\n }\n\n const finished = await finishClaim(\n options.claimStore,\n acquired.lease,\n terminal,\n acquired.lease.expiresAtMs,\n )\n if (finished) {\n consumePreparedCandidateExecution(prepared, result.succeeded ? 'succeeded' : 'failed')\n return result\n }\n\n consumePreparedCandidateExecution(prepared, 'failed')\n return failedAgentCandidateRun(\n state,\n 'candidate execution terminal record could not be persisted',\n execution.termination,\n settlementResult.settlement.usage,\n )\n}\n\ntype ExecutorOutcome =\n | {\n kind: 'capture'\n capture: AgentCandidateProtectedRunCapture\n termination: AgentCandidateTermination\n finalCapture: AgentCandidateExecutorFinalCapture\n processStopped: true\n error?: undefined\n }\n | {\n kind: 'timeout'\n termination: AgentCandidateTermination & { kind: 'timeout' }\n finalCapture: AgentCandidateExecutorFinalCapture\n processStopped: true\n error?: undefined\n }\n | {\n kind: 'error'\n error: unknown\n termination?: AgentCandidateTermination\n finalCapture?: AgentCandidateExecutorFinalCapture\n processStopped: boolean\n }\n\nasync function runAndStopExecutor(\n executor: AgentCandidateExecutorPort,\n request: AgentCandidateExecutorRequest,\n traceStore: TraceStore,\n deadlineAtMs: number,\n cleanupTimeoutMs: number,\n): Promise<ExecutorOutcome> {\n const timeoutMs = request.hardLimits.timeoutMs\n const timeoutError = new CandidateExecutionDeadlineError(timeoutMs)\n if (Date.now() >= deadlineAtMs) {\n return {\n kind: 'error',\n error: timeoutError,\n termination: { kind: 'timeout', timeoutMs },\n processStopped: true,\n }\n }\n const controller = new AbortController()\n let timer: ReturnType<typeof setTimeout> | undefined\n let timedOut = false\n let capture: AgentCandidateProtectedRunCapture | undefined\n let executionError: unknown\n const executionPromise = Promise.resolve().then(() =>\n executor.execute(request, {\n traceStore,\n signal: controller.signal,\n deadlineAtMs,\n }),\n )\n // A stopped process may still leave a buggy adapter promise pending. Attach a\n // terminal handler now so the deadline path cannot create an unhandled rejection.\n void executionPromise.catch(() => undefined)\n const deadlinePromise = new Promise<never>((_resolve, reject) => {\n timer = setTimeout(\n () => {\n timedOut = true\n controller.abort(timeoutError)\n reject(timeoutError)\n },\n Math.max(0, deadlineAtMs - Date.now()),\n )\n })\n void deadlinePromise.catch(() => undefined)\n try {\n capture = sealAgentCandidateProtectedRunCapture(\n await Promise.race([executionPromise, deadlinePromise]),\n )\n } catch (error) {\n executionError = error\n }\n\n if (!timedOut && capture && capture.executionId !== request.executionId) {\n executionError = new Error('candidate execution capture id does not match the request')\n capture = undefined\n } else if (!timedOut && capture && Date.now() >= deadlineAtMs) {\n // Promise resolution at the boundary is ambiguous under event-loop delay.\n // Fail closed unless completion is observed strictly before the deadline.\n timedOut = true\n executionError = timeoutError\n capture = undefined\n } else if (!timedOut && capture?.termination.kind === 'timeout') {\n executionError = new Error('candidate executor cannot declare the runtime-owned timeout')\n capture = undefined\n }\n\n if (!capture || timedOut) controller.abort(executionError)\n const stopReason = timedOut ? 'timeout' : capture ? 'completed' : 'failed'\n let stopped: unknown\n try {\n stopped = await withinCandidateCleanupDeadline(\n () =>\n executor.stopAndCapture(\n {\n executionId: request.executionId,\n executionPlanDigest: request.executionPlan.value.digest,\n },\n {\n traceStore,\n reason: stopReason,\n signal: controller.signal,\n deadlineAtMs,\n },\n ),\n Date.now() + cleanupTimeoutMs,\n 'candidate process termination',\n )\n if (\n !stopped ||\n typeof stopped !== 'object' ||\n (stopped as { stopped?: unknown }).stopped !== true\n ) {\n throw new Error('candidate executor did not acknowledge exact process termination')\n }\n } catch (stopError) {\n if (timer) clearTimeout(timer)\n controller.abort(stopError)\n return {\n kind: 'error',\n error: new Error(joinErrors(executionError, stopError)),\n ...(timedOut ? { termination: { kind: 'timeout', timeoutMs } } : {}),\n processStopped: false,\n }\n }\n\n let finalCapture: AgentCandidateExecutorFinalCapture\n try {\n finalCapture = sealAgentCandidateExecutorFinalCapture(stopped)\n } catch (captureError) {\n if (timer) clearTimeout(timer)\n controller.abort(captureError)\n return {\n kind: 'error',\n error: new Error(joinErrors(executionError, captureError)),\n ...(timedOut ? { termination: { kind: 'timeout', timeoutMs } } : {}),\n processStopped: true,\n }\n }\n\n if (Date.now() >= deadlineAtMs) {\n timedOut = true\n executionError = timeoutError\n capture = undefined\n controller.abort(timeoutError)\n }\n if (timer) clearTimeout(timer)\n\n if (timedOut) {\n return {\n kind: 'timeout',\n termination: { kind: 'timeout', timeoutMs },\n finalCapture,\n processStopped: true,\n }\n }\n if (executionError || !capture) {\n return {\n kind: 'error',\n error: executionError ?? new Error('candidate executor returned no capture'),\n finalCapture,\n processStopped: true,\n }\n }\n return {\n kind: 'capture',\n capture,\n termination: capture.termination,\n finalCapture,\n processStopped: true,\n }\n}\n\nasync function failBeforeActivation(\n prepared: PreparedAgentCandidateExecution,\n state: PreparedCandidateState,\n error: unknown,\n reason: 'failed' | 'replayed',\n cleanupTimeoutMs: number,\n): Promise<AgentCandidateRunFinalization> {\n beginPreparedCandidateSettlement(prepared)\n const cleanupDeadlineAtMs = candidateCleanupDeadline(cleanupTimeoutMs)\n const [memoryClose, settled] = await Promise.all([\n closeMemoryAccess(state, reason, cleanupDeadlineAtMs),\n settleModelGrant(state, reason, cleanupDeadlineAtMs),\n ])\n const cleanupProven = memoryClose.closed && settled.settlement !== undefined\n consumePreparedCandidateExecution(prepared, cleanupProven ? 'failed' : 'cleanup-failed')\n return failedAgentCandidateRun(\n state,\n redactProtectedReason(\n joinErrors(\n error,\n memoryClose.error,\n settled.error,\n !cleanupProven\n ? new Error('prepared access cleanup remains incomplete and may be retried by disposal')\n : undefined,\n ),\n [],\n ),\n undefined,\n settled.settlement?.usage ?? null,\n )\n}\n\nasync function failClaimedExecution(\n prepared: PreparedAgentCandidateExecution,\n state: PreparedCandidateState,\n lease: AgentCandidateExecutionLease,\n claimStore: AgentCandidateExecutionClaimStore,\n outputArtifacts: AgentCandidateOutputArtifactPort,\n error: unknown,\n reason: 'failed',\n cleanupTimeoutMs: number,\n failureClass: AgentCandidateExecutionFailureClass,\n activation?: AgentCandidateProtectedModelActivation,\n memoryActivation?: { env: Readonly<Record<string, string>> },\n): Promise<AgentCandidateRunFinalization> {\n beginPreparedCandidateSettlement(prepared)\n const cleanupDeadlineAtMs = candidateCleanupDeadline(cleanupTimeoutMs)\n const [memoryClose, settled] = await Promise.all([\n closeMemoryAccess(state, reason, cleanupDeadlineAtMs),\n settleModelGrant(state, reason, cleanupDeadlineAtMs),\n ])\n const protectedValues = protectedEnvironmentValues(activation, memoryActivation)\n const safeReason = redactProtectedReason(\n joinErrors(error, memoryClose.error, settled.error),\n protectedValues,\n )\n let finishFailed = false\n let persistenceFailure: unknown\n if (settled.settlement && memoryClose.closed) {\n try {\n const modelSettlement = await withinCandidateCleanupDeadline(\n () => persistCandidateModelSettlement(state, settled.settlement!, outputArtifacts),\n lease.expiresAtMs,\n 'candidate pre-run model-settlement persistence',\n )\n const failureEvidence = await withinCandidateCleanupDeadline(\n () => persistFailureEvidence(state, safeReason, failureClass, undefined, outputArtifacts),\n lease.expiresAtMs,\n 'candidate pre-run failure-evidence persistence',\n )\n finishFailed = !(await finishClaim(\n claimStore,\n lease,\n {\n schemaVersion: 1,\n status: 'failed',\n failureClass,\n usage: settled.settlement.fixedUsage,\n modelSettlement: modelSettlement.artifact,\n failureEvidence,\n },\n lease.expiresAtMs,\n ))\n } catch (persistenceError) {\n finishFailed = true\n persistenceFailure = persistenceError\n }\n }\n consumePreparedCandidateExecution(prepared, 'failed')\n return failedAgentCandidateRun(\n state,\n redactProtectedReason(\n joinErrors(\n safeReason,\n persistenceFailure,\n memoryClose.error,\n settled.error,\n !memoryClose.closed || !settled.settlement\n ? new Error('candidate claim remains recoverable until protected cleanup is proven')\n : undefined,\n finishFailed\n ? new Error('candidate execution terminal record could not be persisted')\n : undefined,\n ),\n protectedValues,\n ),\n undefined,\n settled.settlement?.usage ?? null,\n )\n}\n\nasync function closeMemoryAccess(\n state: PreparedCandidateState,\n reason: 'completed' | 'failed' | 'timeout' | 'replayed',\n cleanupDeadlineAtMs: number,\n): Promise<{ closed: true; error?: undefined } | { closed: false; error: unknown }> {\n if (state.memory.mode === 'disabled') return { closed: true }\n try {\n const reservation = state.memoryReservation\n if (!reservation) throw new Error('isolated memory reservation is missing')\n const closed = await withinCandidateCleanupDeadline(\n () =>\n state.ports.memory.close({\n executionId: state.executionId,\n preparationId: reservation.preparationId,\n accessDigest: reservation.accessDigest,\n effectiveNamespace: reservation.effectiveNamespace,\n reason,\n }),\n cleanupDeadlineAtMs,\n 'isolated memory closure',\n )\n if (closed.closed !== true || Object.keys(closed).some((key) => key !== 'closed')) {\n throw new Error('isolated memory access did not acknowledge closure')\n }\n return { closed: true }\n } catch (error) {\n return { closed: false, error }\n }\n}\n\nasync function settleModelGrant(\n state: PreparedCandidateState,\n reason: 'completed' | 'failed' | 'timeout' | 'replayed',\n cleanupDeadlineAtMs: number,\n): Promise<{\n settlement?: SealedAgentCandidateModelSettlement\n error?: unknown\n}> {\n try {\n const value = await withinCandidateCleanupDeadline(\n () =>\n state.ports.models.settleGrant({\n executionId: state.executionId,\n preparationId: state.preparationId,\n grantDigest: state.modelReservation.digest,\n resolved: state.resolvedModel,\n reason,\n }),\n cleanupDeadlineAtMs,\n 'protected model settlement',\n )\n return {\n settlement: sealAgentCandidateModelSettlement(value, {\n preparationId: state.preparationId,\n grantDigest: state.modelReservation.digest,\n model: state.resolvedModel.model,\n }),\n }\n } catch (error) {\n return { error: new Error('protected model settlement failed', { cause: error }) }\n }\n}\n\nasync function finishClaim(\n store: AgentCandidateExecutionClaimStore,\n lease: AgentCandidateExecutionLease,\n terminal: AgentCandidateExecutionTerminalResult,\n deadlineAtMs?: number,\n): Promise<boolean> {\n try {\n const staged = await withinCandidateCleanupDeadline(\n () => store.stageTerminal(lease, terminal),\n deadlineAtMs ?? lease.expiresAtMs,\n 'candidate terminal staging',\n )\n if (!staged.staged && !staged.exactReplay) return false\n const result = await withinCandidateCleanupDeadline(\n () => store.finish(lease, staged.terminal.terminalDigest),\n deadlineAtMs ?? lease.expiresAtMs,\n 'candidate terminal publication',\n )\n return result.finished || result.exactReplay\n } catch {\n return false\n }\n}\n\nasync function persistFailureEvidence(\n state: PreparedCandidateState,\n reason: string,\n failureClass: AgentCandidateExecutionFailureClass,\n termination: AgentCandidateTermination | undefined,\n outputArtifacts: AgentCandidateOutputArtifactPort,\n) {\n const bytes = canonicalCandidateBytes({\n schemaVersion: 1,\n kind: 'agent-candidate-execution-failure',\n executionId: state.executionId,\n bundleDigest: state.bundle.digest,\n executionPlanDigest: state.executionPlan.value.digest,\n failureClass,\n reason,\n ...(termination ? { termination } : {}),\n })\n return await persistCandidateOutputArtifact(outputArtifacts, {\n executionId: state.executionId,\n purpose: 'failure-evidence',\n bytes,\n })\n}\n\nfunction protectedEnvironmentValues(\n activation?: AgentCandidateProtectedModelActivation,\n memoryActivation?: { env: Readonly<Record<string, string>> },\n): string[] {\n return [...Object.values(activation?.env ?? {}), ...Object.values(memoryActivation?.env ?? {})]\n}\n\nfunction joinErrors(...errors: unknown[]): string {\n return errors\n .filter((error) => error !== undefined)\n .map(errorMessage)\n .join('; ')\n}\n\nfunction errorMessage(error: unknown): string {\n return error instanceof Error ? error.message : String(error)\n}\n\nclass CandidateExecutionDeadlineError extends Error {\n constructor(timeoutMs: number) {\n super(`candidate execution reached its frozen ${timeoutMs}ms deadline`)\n this.name = 'CandidateExecutionDeadlineError'\n }\n}\n","import { randomBytes } from 'node:crypto'\nimport { lstat, readdir } from 'node:fs/promises'\nimport { isAbsolute, posix, relative, resolve as resolveHostPath } from 'node:path'\n\nimport type {\n AgentCandidateConfigValue,\n AgentCandidateEffectiveMemory,\n AgentCandidateExecutionLimits,\n AgentCandidateExecutionPlanEvidence,\n AgentCandidateExecutionPlanMaterialV1,\n AgentCandidateMaterializationReceipt,\n AgentCandidateModelAccessNetwork,\n AgentCandidateResolvedModel,\n HarnessType,\n} from '@tangle-network/agent-interface'\nimport {\n agentCandidateContainerSchema,\n agentCandidateExecutionLimitsSchema,\n agentCandidateExecutionPlanEvidenceSchema,\n agentCandidateExecutionPlanMaterialSchema,\n agentCandidateMaterializationReceiptSchema,\n agentCandidateModelAccessNetworkSchema,\n agentCandidateWorkspaceSnapshotEvidenceSchema,\n sha256DigestSchema,\n} from '@tangle-network/agent-interface'\nimport {\n applyAgentCandidateWorkspacePlan,\n type HarnessId,\n materializeCandidateProfile,\n} from '@tangle-network/agent-profile-materialize'\n\nimport {\n readMaterializedWorkspaceFiles,\n readVerifiedArtifact,\n verifyMaterializedProfileWorkspace,\n verifyMaterializedWorkspace,\n verifyWorkspaceSnapshotArtifacts,\n} from './artifacts'\nimport {\n candidateCleanupDeadline,\n candidateCleanupTimeout,\n candidateResultTimeout,\n MAX_CANDIDATE_TIMER_INTERVAL_MS,\n withinCandidateCleanupDeadline,\n} from './cleanup'\nimport {\n canonicalCandidateBytes,\n canonicalCandidateDigest,\n canonicalCandidateDocument,\n embeddedCandidateArtifact,\n sha256Bytes,\n} from './digest'\nimport { candidateExecutionOwnerWindowMs } from './execution-window'\nimport { verifyTaskCheckout } from './git-materialize'\nimport { sealAgentCandidateModelSettlement, usdToNanos } from './model-settlement'\nimport { createPreparedCandidateExecution } from './prepared-state'\nimport {\n type AgentCandidateExecutionPorts,\n type AgentCandidateTaskExecution,\n CANDIDATE_TRACE_ENV,\n CANDIDATE_TRACE_TAGS,\n type PreparedAgentCandidateExecution,\n type ResolvedAgentCandidateContainer,\n type VerifiedAgentCandidate,\n} from './types'\nimport {\n getVerifiedCandidateState,\n verifiedArtifactBytes,\n verifiedResourceTextByDigest,\n} from './verify'\n\nconst MATERIALIZER_HARNESSES = new Set<HarnessType>([\n 'claude-code',\n 'claude',\n 'claudish',\n 'nanoclaw',\n 'codex',\n 'opencode',\n 'kimi-code',\n 'kimi',\n 'pi',\n 'gemini',\n 'hermes',\n 'openclaw',\n])\n\nconst MIN_RESERVATION_TTL_MS = 15 * 60_000\nconst PREPARED_HOLD_MARGIN_MS = 5 * 60_000\n\nexport interface PrepareAgentCandidateExecutionOptions {\n cleanupTimeoutMs?: number\n /** Maximum time for task verification, executable grading, and receipt construction. */\n resultTimeoutMs?: number\n}\n\n/** Materializes a verified candidate into one immutable evaluator-owned execution plan. */\nexport async function prepareAgentCandidateExecution(\n candidate: VerifiedAgentCandidate,\n task: AgentCandidateTaskExecution,\n ports: AgentCandidateExecutionPorts,\n options: PrepareAgentCandidateExecutionOptions = {},\n): Promise<PreparedAgentCandidateExecution> {\n const cleanupTimeoutMs = candidateCleanupTimeout(options.cleanupTimeoutMs)\n const verifiedState = getVerifiedCandidateState(candidate)\n assertSameVerificationPorts(verifiedState.ports, ports)\n const bundle = candidate.bundle\n const harness = materializerHarness(bundle.execution.harness)\n assertTaskInput(task, bundle.execution.instructionDelivery)\n const resultTimeoutMs = candidateResultTimeout(options.resultTimeoutMs, task.limits.timeoutMs)\n const ownerWindowMs = candidateExecutionOwnerWindowMs(\n task.limits.timeoutMs,\n cleanupTimeoutMs,\n resultTimeoutMs,\n )\n const reservationWindowMs = ownerWindowMs + PREPARED_HOLD_MARGIN_MS\n if (reservationWindowMs > MAX_CANDIDATE_TIMER_INTERVAL_MS) {\n throw new Error('candidate reservation window exceeds the supported timer range')\n }\n assertDisjointHostStagingRoots(task)\n\n const instructionBytes = Buffer.from(task.instruction, 'utf8')\n const instructionDigest = sha256Bytes(instructionBytes)\n\n const taskArtifacts = await verifyWorkspaceSnapshotArtifacts(task.workspace, ports.artifacts)\n await ports.workspaces.materialize({\n role: 'task',\n snapshot: task.workspace,\n archive: taskArtifacts.archive,\n destination: task.stagingRoots.taskRoot,\n })\n await verifyMaterializedWorkspace(task.stagingRoots.taskRoot, task.workspace.material, {\n ignoredProtectedRootEntries: ['.git', '.sidecar'],\n })\n await verifyTaskCheckout(task.stagingRoots.taskRoot, task.repository)\n const taskExecutorFiles = await readMaterializedWorkspaceFiles(\n task.stagingRoots.taskRoot,\n task.workspace.material,\n { ignoredProtectedRootEntries: ['.git', '.sidecar'] },\n )\n\n let candidateArchive: Uint8Array | undefined\n let candidateExecutorFiles:\n | ReadonlyArray<{ path: string; mode: 0o644 | 0o755; bytes: Uint8Array }>\n | undefined\n if (bundle.execution.workspace) {\n if (!task.stagingRoots.candidateRoot || !task.executionRoots.candidateRoot) {\n throw new Error('active candidate execution requires host and container candidate roots')\n }\n candidateArchive = await verifiedArtifactBytes(candidate, bundle.execution.workspace.archive)\n await ports.workspaces.materialize({\n role: 'candidate',\n snapshot: bundle.execution.workspace,\n archive: candidateArchive,\n destination: task.stagingRoots.candidateRoot,\n })\n await verifyMaterializedWorkspace(\n task.stagingRoots.candidateRoot,\n bundle.execution.workspace.material,\n )\n candidateExecutorFiles = await readMaterializedWorkspaceFiles(\n task.stagingRoots.candidateRoot,\n bundle.execution.workspace.material,\n )\n } else if (task.stagingRoots.candidateRoot || task.executionRoots.candidateRoot) {\n throw new Error('disabled code cannot receive a candidate workspace root')\n }\n\n await assertEmptyDirectory(task.stagingRoots.profileRoot)\n const profileWorkspacePlan = materializeCandidateProfile(bundle.profile, harness, {\n resolvedResources: verifiedResourceTextByDigest(candidate),\n })\n const profileApplication = applyAgentCandidateWorkspacePlan(\n profileWorkspacePlan,\n task.stagingRoots.profileRoot,\n bundle.execution.cwd.workspace,\n )\n await verifyMaterializedProfileWorkspace(\n task.stagingRoots.profileRoot,\n profileApplication.profilePlan.material,\n )\n const profilePlanBytes = await readVerifiedArtifact(\n profileApplication.profilePlan.artifact,\n ports.artifacts,\n )\n if (\n !Buffer.from(profilePlanBytes).equals(\n Buffer.from(canonicalCandidateBytes(profileApplication.profilePlan.material)),\n )\n ) {\n throw new Error('profile materializer did not capture exact canonical plan bytes')\n }\n\n const container = await resolveContainer(candidate, task, ports)\n const resolvedModel = await resolveModel(candidate, task, ports)\n const preparationId = `candidate-preparation-v1.${randomBytes(32).toString('base64url')}`\n const reservationExpiresAtMs = Date.now() + Math.max(MIN_RESERVATION_TTL_MS, reservationWindowMs)\n const modelReservation = await withinCandidateCleanupDeadline(\n () =>\n ports.models.reserveGrant({\n executionId: task.executionId,\n preparationId,\n expiresAtMs: reservationExpiresAtMs,\n attempt: task.attempt,\n bundleDigest: bundle.digest,\n resolved: resolvedModel,\n limits: modelLimits(task.limits),\n }),\n candidateCleanupDeadline(cleanupTimeoutMs),\n 'protected model reservation',\n )\n let preparedMemory: Awaited<ReturnType<typeof prepareMemory>> | undefined\n try {\n validateProtectedModelReservation(\n modelReservation,\n task.limits,\n preparationId,\n reservationExpiresAtMs,\n )\n preparedMemory = await prepareMemory(\n candidate,\n task,\n ports,\n preparationId,\n reservationExpiresAtMs,\n cleanupTimeoutMs,\n )\n const memory = preparedMemory.value\n const knowledge = bundle.knowledge\n ? {\n snapshotId: bundle.knowledge.snapshotId,\n manifestDigest: bundle.knowledge.manifest.sha256,\n manifest: await verifiedArtifactBytes(candidate, bundle.knowledge.manifest),\n }\n : undefined\n\n const baseLaunch = buildLaunch(candidate, task, profileApplication.flags)\n const publicEnv = mergePublicEnvironment(\n bundle.execution.env ?? {},\n profileApplication.env,\n bundle.execution.instructionDelivery.kind === 'utf8-file'\n ? {\n [bundle.execution.instructionDelivery.env]: {\n kind: 'public',\n value: bundle.execution.instructionDelivery.path,\n },\n }\n : {},\n )\n const routes = modelRoutes(bundle.profile, task.model.requested)\n const executionMaterial: AgentCandidateExecutionPlanMaterialV1 = {\n schemaVersion: 1,\n kind: 'agent-candidate-execution-plan-material',\n bundleDigest: bundle.digest,\n executionId: task.executionId,\n attempt: task.attempt,\n task: {\n benchmark: task.benchmark,\n benchmarkVersion: task.benchmarkVersion,\n taskId: task.taskId,\n splitDigest: task.splitDigest,\n instruction: {\n encoding: 'utf8',\n sha256: instructionDigest,\n byteLength: instructionBytes.byteLength,\n delivery: bundle.execution.instructionDelivery,\n },\n repository: task.repository,\n workspace: task.workspace,\n },\n workspaces: {\n taskRoot: task.executionRoots.taskRoot,\n ...(task.executionRoots.candidateRoot\n ? { candidateRoot: task.executionRoots.candidateRoot }\n : {}),\n },\n codeKind: bundle.code.kind,\n ...(bundle.execution.workspace ? { candidateWorkspace: bundle.execution.workspace } : {}),\n profile: profileApplication.application,\n harness: bundle.execution.harness,\n harnessVersion: bundle.execution.harnessVersion,\n container,\n model: {\n policy: 'single',\n resolved: resolvedModel,\n access: {\n kind: 'evaluator-mediated',\n grantDigest: modelReservation.digest,\n network: modelReservation.network,\n },\n routes,\n },\n launch: {\n executable: baseLaunch.executable,\n args: baseLaunch.args,\n env: publicEnv,\n cwd: bundle.execution.cwd,\n },\n ...(bundle.knowledge ? { knowledgeManifestDigest: bundle.knowledge.manifest.sha256 } : {}),\n memory,\n limits: task.limits,\n network: { mode: 'disabled' },\n }\n agentCandidateExecutionPlanMaterialSchema.parse(executionMaterial)\n const executionBytes = canonicalCandidateBytes(executionMaterial)\n const executionDigest = canonicalCandidateDigest(executionMaterial)\n if (sha256Bytes(executionBytes) !== executionDigest) {\n throw new Error('execution plan canonical serializers disagree')\n }\n const executionPlan: AgentCandidateExecutionPlanEvidence =\n agentCandidateExecutionPlanEvidenceSchema.parse({\n schemaVersion: 1,\n kind: 'agent-candidate-execution-plan',\n digest: executionDigest,\n material: executionMaterial,\n artifact: embeddedCandidateArtifact(executionBytes),\n })\n\n const entrypoint = candidateEntrypointReceipt(candidate)\n const materializationReceipt = canonicalCandidateDocument<AgentCandidateMaterializationReceipt>(\n {\n schemaVersion: 1,\n kind: 'agent-candidate-materialization',\n digestAlgorithm: 'rfc8785-sha256',\n bundleDigest: bundle.digest,\n profilePlan: profileApplication.profilePlan,\n executionPlan,\n ...(bundle.execution.workspace ? { candidateWorkspace: bundle.execution.workspace } : {}),\n codeKind: bundle.code.kind,\n ...(candidate.materializedTree ? { materializedTree: candidate.materializedTree } : {}),\n harness: bundle.execution.harness,\n harnessVersion: bundle.execution.harnessVersion,\n container,\n resolvedModel,\n ...(bundle.knowledge ? { knowledgeManifestDigest: bundle.knowledge.manifest.sha256 } : {}),\n ...(entrypoint ? { entrypoint } : {}),\n },\n )\n agentCandidateMaterializationReceiptSchema.parse(materializationReceipt.value)\n\n const traceRunId = `${task.executionId}:attempt-${task.attempt.number}:${canonicalCandidateDigest({ preparationId }).slice(7, 23)}`\n const traceTags = {\n [CANDIDATE_TRACE_TAGS.executionId]: task.executionId,\n [CANDIDATE_TRACE_TAGS.bundleDigest]: bundle.digest,\n [CANDIDATE_TRACE_TAGS.executionPlanDigest]: executionPlan.digest,\n [CANDIDATE_TRACE_TAGS.materializationReceiptDigest]: materializationReceipt.digest,\n }\n const traceEnv = {\n [CANDIDATE_TRACE_ENV.executionId]: task.executionId,\n [CANDIDATE_TRACE_ENV.bundleDigest]: bundle.digest,\n [CANDIDATE_TRACE_ENV.executionPlanDigest]: executionPlan.digest,\n [CANDIDATE_TRACE_ENV.materializationReceiptDigest]: materializationReceipt.digest,\n [CANDIDATE_TRACE_ENV.traceRunId]: traceRunId,\n }\n assertEnvironmentDisjoint(publicEnv, traceEnv)\n\n return createPreparedCandidateExecution({\n ports,\n bundle,\n executionId: task.executionId,\n roots: {\n execution: { ...task.executionRoots },\n staging: { ...task.stagingRoots },\n },\n profilePlan: {\n value: profileApplication.profilePlan,\n bytes: profilePlanBytes,\n written: [...profileApplication.application.mountPaths],\n },\n executionPlan: { value: executionPlan, bytes: executionBytes },\n materializationReceipt,\n launch: {\n executable: baseLaunch.executable,\n args: baseLaunch.args.map((value) => value.value),\n env: unwrapPublicEnvironment(publicEnv),\n flags: profileApplication.flags.map((value) => value.value),\n cwd: absoluteExecutionCwd(bundle.execution.cwd, task.executionRoots),\n },\n instruction: {\n bytes: Uint8Array.from(instructionBytes),\n delivery: bundle.execution.instructionDelivery,\n },\n resolvedModel,\n preparationId,\n reservationExpiresAtMs,\n cleanupTimeoutMs,\n resultTimeoutMs,\n modelReservation: {\n preparationId: modelReservation.preparationId,\n digest: modelReservation.digest,\n expiresAtMs: modelReservation.expiresAtMs,\n enforcedLimits: modelReservation.enforcedLimits,\n network: modelReservation.network,\n },\n executorInputs: {\n taskFiles: taskExecutorFiles,\n ...(candidateExecutorFiles ? { candidateFiles: candidateExecutorFiles } : {}),\n profileFiles: exactProfileExecutorFiles(\n profileWorkspacePlan.files,\n profileApplication.profilePlan.material.files,\n ),\n },\n ...(preparedMemory.accessDigest && preparedMemory.value.mode === 'isolated'\n ? {\n memoryReservation: {\n preparationId,\n accessDigest: preparedMemory.accessDigest,\n expiresAtMs: reservationExpiresAtMs,\n effectiveNamespace: preparedMemory.value.effectiveNamespace,\n },\n }\n : {}),\n ...(knowledge ? { knowledge } : {}),\n trace: { runId: traceRunId, tags: traceTags, env: traceEnv },\n memory,\n })\n } catch (error) {\n const cleanupDeadlineAtMs = candidateCleanupDeadline(cleanupTimeoutMs)\n const cleanup: Array<Promise<unknown>> = []\n if (preparedMemory?.value.mode === 'isolated') {\n const accessDigest = preparedMemory.accessDigest\n const effectiveNamespace = preparedMemory.value.effectiveNamespace\n if (!accessDigest) throw new Error('isolated memory preparation is missing access identity')\n cleanup.push(\n withinCandidateCleanupDeadline(\n async () => {\n const closed = await ports.memory.close({\n executionId: task.executionId,\n preparationId,\n accessDigest,\n effectiveNamespace,\n reason: 'preparation-failed',\n })\n if (closed.closed !== true || Object.keys(closed).some((key) => key !== 'closed')) {\n throw new Error('failed preparation did not close isolated memory access')\n }\n },\n cleanupDeadlineAtMs,\n 'failed preparation memory cleanup',\n ),\n )\n }\n cleanup.push(\n withinCandidateCleanupDeadline(\n async () => {\n const settlement = sealAgentCandidateModelSettlement(\n await ports.models.settleGrant({\n executionId: task.executionId,\n preparationId,\n grantDigest: modelReservation.digest,\n resolved: resolvedModel,\n reason: 'preparation-failed',\n }),\n {\n preparationId,\n grantDigest: modelReservation.digest,\n model: resolvedModel.model,\n },\n )\n if (settlement.usage.modelCalls !== 0) {\n throw new Error('failed preparation unexpectedly contains model calls')\n }\n },\n cleanupDeadlineAtMs,\n 'failed preparation model cleanup',\n ),\n )\n const cleanupResults = await Promise.allSettled(cleanup)\n const cleanupErrors = cleanupResults\n .filter((result): result is PromiseRejectedResult => result.status === 'rejected')\n .map((result) => result.reason)\n if (cleanupErrors.length > 0) {\n throw new Error(\n `candidate preparation failed and protected access cleanup failed: ${cleanupErrors.map(errorMessage).join('; ')}`,\n { cause: error },\n )\n }\n throw error\n }\n}\n\nfunction assertSameVerificationPorts(\n verified: AgentCandidateExecutionPorts | { artifacts: unknown; repositories: unknown },\n execution: AgentCandidateExecutionPorts,\n): void {\n if (\n verified.artifacts !== execution.artifacts ||\n verified.repositories !== execution.repositories\n ) {\n throw new Error(\n 'prepare must use the same artifact and repository ports that verified the bundle',\n )\n }\n}\n\nfunction assertTaskInput(\n task: AgentCandidateTaskExecution,\n delivery: VerifiedAgentCandidate['bundle']['execution']['instructionDelivery'],\n): void {\n const requiredStrings: Array<[string, string]> = [\n ['executionId', task.executionId],\n ['benchmark', task.benchmark],\n ['benchmarkVersion', task.benchmarkVersion],\n ['taskId', task.taskId],\n ['repository identity', task.repository.identity],\n ['repository root identity', task.repository.rootIdentity],\n ]\n for (const [name, value] of requiredStrings) {\n if (!value.trim()) throw new Error(`${name} must be non-empty`)\n }\n if (!/^[A-Za-z0-9._:-]{1,200}$/.test(task.executionId)) {\n throw new Error('executionId must be a stable filesystem-neutral identifier')\n }\n if (!task.instruction || !isWellFormedUnicode(task.instruction)) {\n throw new Error('task instruction must be non-empty well-formed Unicode')\n }\n sha256DigestSchema.parse(task.splitDigest)\n agentCandidateWorkspaceSnapshotEvidenceSchema.parse(task.workspace)\n agentCandidateExecutionLimitsSchema.parse(task.limits)\n if (!/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/.test(task.repository.baseCommit)) {\n throw new Error('task repository base commit is not a full Git object id')\n }\n if (!/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/.test(task.repository.baseTree)) {\n throw new Error('task repository base tree is not a full Git object id')\n }\n if (task.repository.baseCommit.length !== task.repository.baseTree.length) {\n throw new Error('task repository Git object formats disagree')\n }\n for (const [name, root] of [\n ['execution task root', task.executionRoots.taskRoot],\n ['execution candidate root', task.executionRoots.candidateRoot],\n ['staging task root', task.stagingRoots.taskRoot],\n ['staging candidate root', task.stagingRoots.candidateRoot],\n ['staging profile root', task.stagingRoots.profileRoot],\n ] as const) {\n if (root === undefined) continue\n const canonical = name.startsWith('execution')\n ? posix.isAbsolute(root) && posix.normalize(root) === root\n : isAbsolute(root) && resolveHostPath(root) === root\n if (!canonical) throw new Error(`${name} must be a canonical absolute path`)\n }\n if (\n !Number.isInteger(task.attempt.number) ||\n !Number.isInteger(task.attempt.maxAttempts) ||\n task.attempt.number < 1 ||\n task.attempt.number > task.attempt.maxAttempts ||\n (task.attempt.retryPolicy === 'none' && task.attempt.maxAttempts !== 1)\n ) {\n throw new Error('task attempt policy is invalid')\n }\n const limits = task.limits\n if (\n !Number.isInteger(limits.timeoutMs) ||\n limits.timeoutMs <= 0 ||\n limits.timeoutMs > MAX_CANDIDATE_TIMER_INTERVAL_MS ||\n !Number.isInteger(limits.maxSteps) ||\n limits.maxSteps <= 0 ||\n !Number.isInteger(limits.maxModelCalls) ||\n limits.maxModelCalls < 0 ||\n !Number.isInteger(limits.maxInputTokens) ||\n limits.maxInputTokens < 0 ||\n !Number.isInteger(limits.maxOutputTokens) ||\n limits.maxOutputTokens < 0 ||\n !Number.isFinite(limits.maxCostUsd) ||\n limits.maxCostUsd < 0\n ) {\n throw new Error('task execution limits are invalid')\n }\n usdToNanos(limits.maxCostUsd, 'task maxCostUsd')\n if (!task.model.requested.trim()) throw new Error('evaluator model request must be non-empty')\n if (task.evaluatorTaskContainer) {\n if (\n task.evaluatorTaskContainer.source !== 'evaluator-task-container' ||\n !task.evaluatorTaskContainer.image.trim() ||\n !task.evaluatorTaskContainer.platform.os.trim() ||\n !task.evaluatorTaskContainer.platform.architecture.trim()\n ) {\n throw new Error('evaluator task container evidence is incomplete')\n }\n sha256DigestSchema.parse(task.evaluatorTaskContainer.indexDigest)\n sha256DigestSchema.parse(task.evaluatorTaskContainer.manifestDigest)\n agentCandidateContainerSchema.parse({\n image: task.evaluatorTaskContainer.image,\n indexDigest: task.evaluatorTaskContainer.indexDigest,\n })\n }\n if (delivery.kind === 'utf8-file') {\n if (\n executionPathsOverlap(task.executionRoots.taskRoot, delivery.path) ||\n (task.executionRoots.candidateRoot !== undefined &&\n executionPathsOverlap(task.executionRoots.candidateRoot, delivery.path))\n ) {\n throw new Error('task instruction file must remain outside execution workspaces')\n }\n }\n}\n\nfunction executionPathsOverlap(left: string, right: string): boolean {\n const a = posix.normalize(left)\n const b = posix.normalize(right)\n return (\n a === b || b.startsWith(a === '/' ? '/' : `${a}/`) || a.startsWith(b === '/' ? '/' : `${b}/`)\n )\n}\n\nfunction assertDisjointHostStagingRoots(task: AgentCandidateTaskExecution): void {\n const roots = [\n task.stagingRoots.taskRoot,\n task.stagingRoots.candidateRoot,\n task.stagingRoots.profileRoot,\n ]\n .filter((value): value is string => value !== undefined)\n .map((value) => resolveHostPath(value))\n for (let left = 0; left < roots.length; left++) {\n for (let right = left + 1; right < roots.length; right++) {\n const a = roots[left]\n const b = roots[right]\n if (a && b && (a === b || isContainedPath(a, b) || isContainedPath(b, a))) {\n throw new Error('host task, candidate, and profile staging roots must be disjoint')\n }\n }\n }\n}\n\nfunction isContainedPath(parent: string, child: string): boolean {\n const path = relative(parent, child)\n return path !== '' && !path.startsWith('..') && !isAbsolute(path)\n}\n\nasync function assertEmptyDirectory(path: string): Promise<void> {\n const stats = await lstat(path)\n if (!stats.isDirectory() || stats.isSymbolicLink()) {\n throw new Error('profile staging root must be a real directory')\n }\n if ((await readdir(path)).length !== 0) {\n throw new Error('profile staging root must be empty before materialization')\n }\n}\n\nfunction materializerHarness(harness: HarnessType): HarnessId {\n if (!MATERIALIZER_HARNESSES.has(harness)) {\n throw new Error(\n `sealed candidate profile materialization is unsupported for harness ${harness}`,\n )\n }\n return harness as HarnessId\n}\n\nasync function resolveContainer(\n candidate: VerifiedAgentCandidate,\n task: AgentCandidateTaskExecution,\n ports: AgentCandidateExecutionPorts,\n): Promise<ResolvedAgentCandidateContainer> {\n const environment = candidate.bundle.execution.environment\n const pinned = environment.kind === 'pinned-container' ? environment.container : undefined\n if (environment.kind === 'evaluator-task-container' && !task.evaluatorTaskContainer) {\n throw new Error('evaluator-task-container candidate requires an evaluator-owned task image')\n }\n if (environment.kind === 'pinned-container' && task.evaluatorTaskContainer) {\n throw new Error('pinned candidate containers cannot be replaced by a task image')\n }\n const resolved = await ports.containers.resolve({\n candidate: pinned,\n evaluatorTaskContainer: task.evaluatorTaskContainer,\n })\n if (resolved.source !== environment.kind) throw new Error('resolved container source drifted')\n if (pinned && (resolved.image !== pinned.image || resolved.indexDigest !== pinned.indexDigest)) {\n throw new Error('resolved pinned container does not match the candidate image index')\n }\n if (\n task.evaluatorTaskContainer &&\n JSON.stringify(resolved) !== JSON.stringify(task.evaluatorTaskContainer)\n ) {\n throw new Error('resolved task container does not match evaluator-owned image evidence')\n }\n return resolved\n}\n\nasync function resolveModel(\n candidate: VerifiedAgentCandidate,\n task: AgentCandidateTaskExecution,\n ports: AgentCandidateExecutionPorts,\n): Promise<AgentCandidateResolvedModel> {\n const hints = candidate.bundle.profile.model\n if (hints?.default !== undefined && hints.default !== task.model.requested) {\n throw new Error('candidate model preference conflicts with the evaluator-owned model')\n }\n if (\n hints?.reasoningEffort !== undefined &&\n hints.reasoningEffort !== task.model.reasoningEffort\n ) {\n throw new Error('candidate reasoning effort conflicts with the evaluator-owned effort')\n }\n const resolved = await ports.models.resolve({\n requested: task.model.requested,\n harness: candidate.bundle.execution.harness,\n reasoningEffort: task.model.reasoningEffort,\n })\n if (\n resolved.requested !== task.model.requested ||\n resolved.reasoningEffort !== task.model.reasoningEffort\n ) {\n throw new Error('model resolver drifted from the evaluator-owned request')\n }\n return resolved\n}\n\nasync function prepareMemory(\n candidate: VerifiedAgentCandidate,\n task: AgentCandidateTaskExecution,\n ports: AgentCandidateExecutionPorts,\n preparationId: string,\n expiresAtMs: number,\n cleanupTimeoutMs: number,\n): Promise<{\n value: AgentCandidateEffectiveMemory\n accessDigest?: `sha256:${string}`\n}> {\n const policy = candidate.bundle.memory\n if (policy.mode === 'disabled') return { value: { mode: 'disabled' } }\n const seed = policy.seed ? await verifiedArtifactBytes(candidate, policy.seed) : undefined\n const executionSegment = canonicalCandidateDigest({ executionId: task.executionId }).slice(7)\n const taskSegment = canonicalCandidateDigest({ taskId: task.taskId }).slice(7)\n const preparationSegment = canonicalCandidateDigest({ preparationId }).slice(7, 23)\n const effectiveNamespace = `candidate/${candidate.bundle.digest.slice(7, 23)}/${executionSegment}/${taskSegment}/${preparationSegment}`\n const reset = await withinCandidateCleanupDeadline(\n () =>\n ports.memory.reset({\n executionId: task.executionId,\n preparationId,\n expiresAtMs,\n effectiveNamespace,\n ...(seed ? { seed } : {}),\n ...(policy.seed ? { seedDigest: policy.seed.sha256 } : {}),\n }),\n candidateCleanupDeadline(cleanupTimeoutMs),\n 'isolated memory reset',\n )\n try {\n if (\n reset.preparationId !== preparationId ||\n reset.expiresAtMs !== expiresAtMs ||\n !/^sha256:[a-f0-9]{64}$/.test(reset.accessDigest)\n ) {\n throw new Error('isolated memory reservation is not scoped to this preparation')\n }\n await readVerifiedArtifact(reset.evidence, ports.artifacts)\n await verifyWorkspaceSnapshotArtifacts(reset.beforeState, ports.artifacts)\n return {\n value: {\n mode: 'isolated',\n scope: 'task',\n effectiveNamespace,\n reset: {\n kind: 'fresh',\n evidence: reset.evidence,\n emptyStateDigest: reset.emptyStateDigest,\n },\n beforeState: reset.beforeState,\n ...(policy.seed ? { seedDigest: policy.seed.sha256 } : {}),\n },\n accessDigest: reset.accessDigest,\n }\n } catch (error) {\n try {\n const closed = await withinCandidateCleanupDeadline(\n () =>\n ports.memory.close({\n executionId: task.executionId,\n preparationId,\n accessDigest: reset.accessDigest,\n effectiveNamespace,\n reason: 'preparation-failed',\n }),\n candidateCleanupDeadline(cleanupTimeoutMs),\n 'invalid isolated memory reset cleanup',\n )\n if (closed.closed !== true || Object.keys(closed).some((key) => key !== 'closed')) {\n throw new Error('invalid isolated memory reset did not acknowledge closure')\n }\n } catch (closeError) {\n throw new Error('isolated memory preparation and cleanup both failed', {\n cause: new AggregateError([error, closeError]),\n })\n }\n throw error\n }\n}\n\nfunction buildLaunch(\n candidate: VerifiedAgentCandidate,\n task: AgentCandidateTaskExecution,\n profileFlags: AgentCandidateConfigValue[],\n): { executable: string; args: AgentCandidateConfigValue[] } {\n const launch = candidate.bundle.execution.launch\n if (launch.kind === 'container-command') {\n return { executable: launch.executable, args: [...(launch.args ?? []), ...profileFlags] }\n }\n const candidateRoot = task.executionRoots.candidateRoot\n if (!candidateRoot) throw new Error('candidate entrypoint requires a container candidate root')\n const entrypoint = posix.join(candidateRoot, launch.entrypoint)\n const candidateArgs = launch.args ?? []\n if (launch.interpreter) {\n return {\n executable: launch.interpreter,\n args: [{ kind: 'public', value: entrypoint }, ...candidateArgs, ...profileFlags],\n }\n }\n return { executable: entrypoint, args: [...candidateArgs, ...profileFlags] }\n}\n\nfunction mergePublicEnvironment(\n ...records: Array<Record<string, AgentCandidateConfigValue>>\n): Record<string, AgentCandidateConfigValue> {\n const output: Record<string, AgentCandidateConfigValue> = {}\n for (const record of records) {\n for (const [name, value] of Object.entries(record)) {\n const previous = output[name]\n if (previous && previous.value !== value.value) {\n throw new Error(`candidate and profile environment disagree on ${name}`)\n }\n output[name] = value\n }\n }\n return output\n}\n\nfunction unwrapPublicEnvironment(\n values: Record<string, AgentCandidateConfigValue>,\n): Record<string, string> {\n return Object.fromEntries(Object.entries(values).map(([name, value]) => [name, value.value]))\n}\n\nfunction modelRoutes(\n profile: VerifiedAgentCandidate['bundle']['profile'],\n requested: string,\n): AgentCandidateExecutionPlanMaterialV1['model']['routes'] {\n const routes: AgentCandidateExecutionPlanMaterialV1['model']['routes'] = [\n { kind: 'primary', requested },\n ]\n if (profile.model?.small) routes.push({ kind: 'small', requested })\n for (const name of Object.keys(profile.modes ?? {}).sort()) {\n if (profile.modes?.[name]?.model) routes.push({ kind: 'mode', name, requested })\n }\n for (const name of Object.keys(profile.subagents ?? {}).sort()) {\n if (profile.subagents?.[name]?.model) routes.push({ kind: 'subagent', name, requested })\n }\n return routes\n}\n\nfunction candidateEntrypointReceipt(\n candidate: VerifiedAgentCandidate,\n): { path: string; sha256: `sha256:${string}`; byteLength: number } | undefined {\n const launch = candidate.bundle.execution.launch\n const workspace = candidate.bundle.execution.workspace\n if (launch.kind !== 'candidate-entrypoint' || !workspace) return undefined\n const file = workspace.material.files.find((entry) => entry.path === launch.entrypoint)\n if (!file) throw new Error('candidate entrypoint is absent from the verified workspace')\n return { path: file.path, sha256: file.sha256, byteLength: file.byteLength }\n}\n\nfunction absoluteExecutionCwd(\n cwd: VerifiedAgentCandidate['bundle']['execution']['cwd'],\n roots: AgentCandidateTaskExecution['executionRoots'],\n): string {\n const root = cwd.workspace === 'task' ? roots.taskRoot : roots.candidateRoot\n if (!root) throw new Error('candidate cwd is missing its execution workspace root')\n const absolute = cwd.path === '.' ? root : posix.join(root, cwd.path)\n if (absolute !== root && !absolute.startsWith(`${root}/`)) {\n throw new Error('candidate cwd escapes its execution workspace')\n }\n return absolute\n}\n\nfunction validateProtectedModelReservation(\n reservation: {\n preparationId: string\n digest: string\n expiresAtMs: number\n enforcedLimits: {\n maxModelCalls: number\n maxInputTokens: number\n maxOutputTokens: number\n maxCostUsd: number\n }\n network: AgentCandidateModelAccessNetwork\n },\n expectedLimits: AgentCandidateExecutionLimits,\n preparationId: string,\n expiresAtMs: number,\n): void {\n if (!/^sha256:[a-f0-9]{64}$/.test(reservation.digest)) {\n throw new Error('protected model reservation has an invalid identity digest')\n }\n if (reservation.preparationId !== preparationId || reservation.expiresAtMs !== expiresAtMs) {\n throw new Error('protected model reservation is not scoped to this preparation')\n }\n const limits = modelLimits(expectedLimits)\n if (canonicalCandidateDigest(reservation.enforcedLimits) !== canonicalCandidateDigest(limits)) {\n throw new Error('protected model reservation does not enforce the frozen model limits')\n }\n const expectedNetworkMode = limits.maxModelCalls === 0 ? 'disabled' : 'gateway-only'\n const network = agentCandidateModelAccessNetworkSchema.parse(reservation.network)\n if (network.mode !== expectedNetworkMode) {\n throw new Error('protected model reservation has the wrong network policy for its call limit')\n }\n}\n\nfunction assertEnvironmentDisjoint(\n publicEnv: Record<string, AgentCandidateConfigValue>,\n traceEnv: Record<string, string>,\n): void {\n const seen = new Set(Object.keys(publicEnv))\n for (const name of Object.keys(traceEnv)) {\n if (seen.has(name)) throw new Error(`evaluator environment binding collides with ${name}`)\n seen.add(name)\n }\n}\n\nfunction modelLimits(limits: AgentCandidateExecutionLimits): {\n maxModelCalls: number\n maxInputTokens: number\n maxOutputTokens: number\n maxCostUsd: number\n} {\n return {\n maxModelCalls: limits.maxModelCalls,\n maxInputTokens: limits.maxInputTokens,\n maxOutputTokens: limits.maxOutputTokens,\n maxCostUsd: limits.maxCostUsd,\n }\n}\n\nfunction exactProfileExecutorFiles(\n sourceFiles: ReadonlyArray<{ relPath: string; content: string; mode?: number }>,\n expectedFiles: ReadonlyArray<{ relPath: string; mode: number; contentSha256: string }>,\n): Array<{ path: string; mode: 0o644 | 0o755; bytes: Uint8Array }> {\n const byPath = new Map(sourceFiles.map((file) => [file.relPath, file]))\n if (byPath.size !== sourceFiles.length || sourceFiles.length !== expectedFiles.length) {\n throw new Error('profile source files do not match the signed profile plan')\n }\n return expectedFiles.map((expected) => {\n const source = byPath.get(expected.relPath)\n const mode = source?.mode ?? 0o644\n const bytes = Buffer.from(source?.content ?? '', 'utf8')\n if (\n !source ||\n (mode !== 0o644 && mode !== 0o755) ||\n mode !== expected.mode ||\n sha256Bytes(bytes) !== expected.contentSha256\n ) {\n throw new Error('profile source files do not match the signed profile plan')\n }\n return { path: expected.relPath, mode, bytes: Uint8Array.from(bytes) }\n })\n}\n\nfunction isWellFormedUnicode(value: string): boolean {\n for (let index = 0; index < value.length; index++) {\n const code = value.charCodeAt(index)\n if (code >= 0xd800 && code <= 0xdbff) {\n const next = value.charCodeAt(index + 1)\n if (!(next >= 0xdc00 && next <= 0xdfff)) return false\n index++\n } else if (code >= 0xdc00 && code <= 0xdfff) {\n return false\n }\n }\n return true\n}\n\nfunction errorMessage(error: unknown): string {\n return error instanceof Error ? error.message : String(error)\n}\n","import type {\n AgentCandidateBundle,\n AgentCandidateCapturedArtifact,\n AgentCandidateResourceRef,\n Sha256Digest,\n} from '@tangle-network/agent-interface'\nimport { agentCandidateBundleSchema } from '@tangle-network/agent-interface'\n\nimport {\n artifactCacheKey,\n readVerifiedArtifact,\n verifyBytes,\n verifyWorkspaceSnapshotArtifacts,\n} from './artifacts'\nimport {\n canonicalCandidateBytes,\n canonicalCandidateDigest,\n deepFreezeCandidate,\n omitTopLevelDigest,\n} from './digest'\nimport { readCandidateGitHubResource, verifyCandidateCode } from './git-materialize'\nimport {\n type AgentCandidateVerificationPorts,\n type VerifiedAgentCandidate,\n verifiedCandidateBrand,\n} from './types'\n\ninterface VerifiedCandidateState {\n ports: AgentCandidateVerificationPorts\n artifactBytes: Map<string, Uint8Array>\n resourceBytes: Map<string, Uint8Array>\n}\n\nconst verifiedCandidateState = new WeakMap<VerifiedAgentCandidate, VerifiedCandidateState>()\n\n/** Verifies every digest, resource, workspace, and Git object in a candidate bundle. */\nexport async function verifyAgentCandidateBundle(\n input: unknown,\n ports: AgentCandidateVerificationPorts,\n): Promise<VerifiedAgentCandidate> {\n const parsed = agentCandidateBundleSchema.parse(input)\n const withoutDigest = omitTopLevelDigest(parsed)\n const actualDigest = canonicalCandidateDigest(withoutDigest)\n if (actualDigest !== parsed.digest) {\n throw new Error(`candidate bundle digest ${parsed.digest} does not match ${actualDigest}`)\n }\n const canonicalBytes = canonicalCandidateBytes(withoutDigest)\n verifyBytes(canonicalBytes, parsed.digest, canonicalBytes.byteLength, 'candidate bundle')\n\n const artifactBytes = new Map<string, Uint8Array>()\n const readArtifact = async (artifact: AgentCandidateCapturedArtifact): Promise<Uint8Array> => {\n const key = artifactCacheKey(artifact)\n const existing = artifactBytes.get(key)\n if (existing) return Uint8Array.from(existing)\n const bytes = await readVerifiedArtifact(artifact, ports.artifacts)\n artifactBytes.set(key, Uint8Array.from(bytes))\n return bytes\n }\n\n let patchBytes: Uint8Array | undefined\n if (parsed.code.kind === 'git-patch') {\n patchBytes = await readArtifact(parsed.code.patch.artifact)\n }\n const materializedTree = await verifyCandidateCode(parsed.code, ports.repositories, patchBytes)\n\n const resourceBytes = new Map<string, Uint8Array>()\n for (const resource of candidateResources(parsed)) {\n const bytes =\n resource.kind === 'inline'\n ? Buffer.from(resource.content, 'utf8')\n : await readCandidateGitHubResource(resource, ports.repositories)\n verifyBytes(\n bytes,\n resource.sha256,\n resource.byteLength,\n `candidate resource ${resource.name ?? (resource.kind === 'github' ? resource.path : '<unnamed>')}`,\n )\n resourceBytes.set(resourceKey(resource), Uint8Array.from(bytes))\n resourceBytes.set(resource.sha256, Uint8Array.from(bytes))\n }\n\n if (parsed.execution.workspace) {\n const workspace = await verifyWorkspaceSnapshotArtifacts(\n parsed.execution.workspace,\n ports.artifacts,\n )\n artifactBytes.set(artifactCacheKey(parsed.execution.workspace.manifest), workspace.manifest)\n artifactBytes.set(artifactCacheKey(parsed.execution.workspace.archive), workspace.archive)\n }\n if (parsed.knowledge) await readArtifact(parsed.knowledge.manifest)\n if (parsed.memory.mode === 'isolated' && parsed.memory.seed)\n await readArtifact(parsed.memory.seed)\n\n deepFreezeCandidate(parsed)\n const verified = Object.freeze({\n bundle: parsed,\n ...(materializedTree === undefined ? {} : { materializedTree }),\n [verifiedCandidateBrand]: true as const,\n })\n verifiedCandidateState.set(verified, { ports, artifactBytes, resourceBytes })\n return verified\n}\n\nexport function getVerifiedCandidateState(\n candidate: VerifiedAgentCandidate,\n): VerifiedCandidateState {\n const state = verifiedCandidateState.get(candidate)\n if (!state || candidate[verifiedCandidateBrand] !== true) {\n throw new Error('candidate must come from verifyAgentCandidateBundle')\n }\n return state\n}\n\nexport async function verifiedArtifactBytes(\n candidate: VerifiedAgentCandidate,\n artifact: AgentCandidateCapturedArtifact,\n): Promise<Uint8Array> {\n const state = getVerifiedCandidateState(candidate)\n const key = artifactCacheKey(artifact)\n const existing = state.artifactBytes.get(key)\n if (existing) return Uint8Array.from(existing)\n const bytes = await readVerifiedArtifact(artifact, state.ports.artifacts)\n state.artifactBytes.set(key, Uint8Array.from(bytes))\n return bytes\n}\n\nexport function verifiedResourceBytes(\n candidate: VerifiedAgentCandidate,\n resource: AgentCandidateResourceRef,\n): Uint8Array {\n const bytes = getVerifiedCandidateState(candidate).resourceBytes.get(resourceKey(resource))\n if (!bytes) {\n throw new Error(\n `candidate resource was not verified: ${resource.name ?? (resource.kind === 'github' ? resource.path : '<unnamed>')}`,\n )\n }\n return Uint8Array.from(bytes)\n}\n\nexport function verifiedResourceTextByDigest(\n candidate: VerifiedAgentCandidate,\n): ReadonlyMap<Sha256Digest, string> {\n const output = new Map<Sha256Digest, string>()\n for (const resource of candidateResources(candidate.bundle)) {\n const bytes = getVerifiedCandidateState(candidate).resourceBytes.get(resource.sha256)\n if (!bytes) throw new Error(`candidate resource digest was not verified: ${resource.sha256}`)\n output.set(resource.sha256, new TextDecoder('utf-8', { fatal: true }).decode(bytes))\n }\n return output\n}\n\nfunction candidateResources(bundle: AgentCandidateBundle): AgentCandidateResourceRef[] {\n const resources = bundle.profile.resources\n if (!resources) return []\n const output: AgentCandidateResourceRef[] = []\n for (const mount of resources.files ?? []) output.push(mount.resource)\n output.push(...(resources.tools ?? []))\n output.push(...(resources.skills ?? []))\n output.push(...(resources.agents ?? []))\n output.push(...(resources.commands ?? []))\n if (typeof resources.instructions === 'object') output.push(resources.instructions)\n return output\n}\n\nfunction resourceKey(resource: AgentCandidateResourceRef): string {\n return canonicalCandidateDigest(resource)\n}\n","import type {\n AgentCandidateModelAccessNetwork,\n AgentCandidateResolvedModel,\n Sha256Digest,\n} from '@tangle-network/agent-interface'\n\nimport { canonicalCandidateDigest, immutableCandidateValue } from './digest'\nimport { assertExactObjectKeys } from './exact-object'\nimport { sealAgentCandidateModelSettlement, usdToNanos } from './model-settlement'\nimport type {\n AgentCandidateModelLimits,\n AgentCandidateModelPort,\n AgentCandidateProtectedModelActivation,\n AgentCandidateProtectedModelReservation,\n AgentCandidateProtectedModelSettlement,\n} from './types'\n\nexport type AgentCandidateModelGrantReserveInput = Parameters<\n AgentCandidateModelPort['reserveGrant']\n>[0]\nexport type AgentCandidateModelGrantActivateInput = Parameters<\n AgentCandidateModelPort['activateGrant']\n>[0]\nexport type AgentCandidateModelGrantSettleInput = Parameters<\n AgentCandidateModelPort['settleGrant']\n>[0]\n\n/** Secret-free response from the service's reservation endpoint. */\nexport type AgentCandidateModelGrantReservation = AgentCandidateProtectedModelReservation\n\n/**\n * Narrow transport contract for a service that owns scoped model credentials\n * and the authoritative per-call usage ledger.\n *\n * An HTTP client can bind these methods to control-plane endpoints. Keeping\n * transport out of the runtime prevents parent credentials, endpoint paths,\n * and retry policy from becoming part of the portable candidate contract.\n */\nexport interface AgentCandidateModelGrantClient {\n reserve(input: AgentCandidateModelGrantReserveInput): Promise<AgentCandidateModelGrantReservation>\n activate(\n input: AgentCandidateModelGrantActivateInput,\n ): Promise<AgentCandidateProtectedModelActivation>\n settle(\n input: AgentCandidateModelGrantSettleInput,\n ): Promise<AgentCandidateProtectedModelSettlement>\n}\n\nexport interface CreateProtectedAgentCandidateModelPortOptions {\n client: AgentCandidateModelGrantClient\n /** Catalog/snapshot resolution stays separate from credential issuance. */\n resolveModel: AgentCandidateModelPort['resolve']\n /** The only public DNS name candidate processes may reach for inference. */\n gatewayDomain: string\n /** Exact environment names the activation endpoint must return, no more or fewer. */\n activationEnvNames: readonly string[]\n}\n\ninterface RememberedReservation {\n requestDigest: Sha256Digest\n responseDigest: Sha256Digest\n executionId: string\n preparationId: string\n grantDigest: Sha256Digest\n expiresAtMs: number\n resolved: AgentCandidateResolvedModel\n limits: AgentCandidateModelLimits\n maxCostUsdNanos: number\n activation: 'reserved' | 'activating' | 'activated'\n settlementDigest?: Sha256Digest\n settlementReason?: AgentCandidateModelGrantSettleInput['reason']\n}\n\ninterface RememberedSettlement {\n settlementDigest: Sha256Digest\n settlementReason: AgentCandidateModelGrantSettleInput['reason']\n expiresAtMs: number\n}\n\nconst MAX_RECENT_SETTLEMENTS = 4_096\nconst RECOVERED_SETTLEMENT_RETENTION_MS = 15 * 60 * 1_000\n\n/**\n * Bind a protected model-grant service to the immutable candidate runtime.\n *\n * The service remains the authority for expiry, admission, revocation, and\n * metering. This adapter independently checks every response before allowing\n * it to cross into candidate execution or durable receipt finalization.\n */\nexport function createProtectedAgentCandidateModelPort(\n options: CreateProtectedAgentCandidateModelPortOptions,\n): AgentCandidateModelPort {\n const gatewayDomain = assertGatewayDomain(options.gatewayDomain)\n const activationEnvNames = exactEnvironmentNames(options.activationEnvNames)\n const reservations = new Map<string, RememberedReservation>()\n const recentSettlements = new Map<string, RememberedSettlement>()\n\n return {\n resolve: async (input) => {\n const request = immutableCandidateValue(input)\n const resolved = validateResolvedModel(await options.resolveModel(request), request)\n return immutableCandidateValue(resolved)\n },\n\n reserveGrant: async (input) => {\n pruneExpiredState(reservations, recentSettlements, Date.now())\n const request = immutableCandidateValue(input)\n validateReserveInput(request)\n const requestDigest = canonicalCandidateDigest(request)\n const key = reservationKey(request.executionId, request.preparationId)\n if (recentSettlements.has(key)) {\n throw new Error('protected model reservation is already settled')\n }\n const previous = reservations.get(key)\n if (previous && previous.requestDigest !== requestDigest) {\n throw new Error('protected model reservation retry changed immutable input')\n }\n\n const reservation = validateReservation(\n await options.client.reserve(request),\n request,\n gatewayDomain,\n )\n const responseDigest = canonicalCandidateDigest(reservation)\n if (recentSettlements.has(key)) {\n throw new Error('protected model reservation completed after the grant was settled')\n }\n const recorded = previous ?? reservations.get(key)\n if (recorded && recorded.requestDigest !== requestDigest) {\n throw new Error('protected model reservation retry changed immutable input')\n }\n if (recorded && recorded.responseDigest !== responseDigest) {\n throw new Error('protected model reservation retry returned different evidence')\n }\n if (!recorded) {\n reservations.set(key, {\n requestDigest,\n responseDigest,\n executionId: request.executionId,\n preparationId: request.preparationId,\n grantDigest: reservation.digest,\n expiresAtMs: request.expiresAtMs,\n resolved: immutableCandidateValue(request.resolved),\n limits: immutableCandidateValue(request.limits),\n maxCostUsdNanos: usdToNanos(request.limits.maxCostUsd, 'reserved maxCostUsd'),\n activation: 'reserved',\n })\n }\n return reservation\n },\n\n activateGrant: async (input) => {\n pruneExpiredState(reservations, recentSettlements, Date.now())\n const request = immutableCandidateValue(input)\n const key = reservationKey(request.executionId, request.preparationId)\n if (recentSettlements.has(key)) throw new Error('protected model grant is already settled')\n const state = reservations.get(key)\n if (!state) throw new Error('protected model grant was not reserved by this port')\n assertGrantIdentity(state, request)\n if (state.settlementDigest) throw new Error('protected model grant is already settled')\n if (state.activation !== 'reserved') {\n throw new Error('protected model grant activation is single-use')\n }\n if (!Number.isSafeInteger(request.deadlineAtMs) || request.deadlineAtMs <= 0) {\n throw new Error('protected model activation deadline must be a positive safe integer')\n }\n if (request.deadlineAtMs <= Date.now()) {\n throw new Error('protected model activation deadline must be in the future')\n }\n if (request.deadlineAtMs > state.expiresAtMs) {\n throw new Error('protected model activation deadline exceeds the reserved expiry')\n }\n state.activation = 'activating'\n try {\n const activation = validateActivation(\n await options.client.activate(request),\n state.limits.maxModelCalls === 0 ? [] : activationEnvNames,\n )\n if (recentSettlements.has(key) || reservations.get(key) !== state) {\n throw new Error('protected model grant settled while activation was in flight')\n }\n state.activation = 'activated'\n return activation\n } catch (error) {\n state.activation = 'reserved'\n throw error\n }\n },\n\n settleGrant: async (input) => {\n const now = Date.now()\n pruneExpiredState(reservations, recentSettlements, now)\n const request = immutableCandidateValue(input)\n const key = reservationKey(request.executionId, request.preparationId)\n const state = reservations.get(key)\n if (state) assertGrantIdentity(state, request)\n const remembered = state ?? recentSettlements.get(key)\n if (remembered?.settlementReason && remembered.settlementReason !== request.reason) {\n throw new Error('protected model settlement retry changed the termination reason')\n }\n\n const sealed = sealAgentCandidateModelSettlement(await options.client.settle(request), {\n preparationId: request.preparationId,\n grantDigest: request.grantDigest,\n model: request.resolved.model,\n })\n if (state) assertWithinReservedLimits(sealed.fixedUsage, state)\n\n const settlementDigest = canonicalCandidateDigest(sealed.value)\n if (remembered?.settlementDigest && remembered.settlementDigest !== settlementDigest) {\n throw new Error('protected model settlement retry returned a different final ledger')\n }\n if (remembered?.settlementReason && remembered.settlementReason !== request.reason) {\n throw new Error('protected model settlement retry changed the termination reason')\n }\n const expiresAtMs = state?.expiresAtMs ?? now + RECOVERED_SETTLEMENT_RETENTION_MS\n if (state) {\n state.settlementDigest = settlementDigest\n state.settlementReason = request.reason\n }\n reservations.delete(key)\n rememberSettlement(recentSettlements, key, {\n settlementDigest,\n settlementReason: request.reason,\n expiresAtMs,\n })\n return sealed.value\n },\n }\n}\n\nfunction validateReserveInput(input: AgentCandidateModelGrantReserveInput): void {\n if (!Number.isSafeInteger(input.expiresAtMs) || input.expiresAtMs <= 0) {\n throw new Error('protected model reservation expiry must be a positive safe integer')\n }\n if (input.expiresAtMs <= Date.now()) {\n throw new Error('protected model reservation expiry must be in the future')\n }\n for (const [name, value] of [\n ['maxModelCalls', input.limits.maxModelCalls],\n ['maxInputTokens', input.limits.maxInputTokens],\n ['maxOutputTokens', input.limits.maxOutputTokens],\n ] as const) {\n if (!Number.isSafeInteger(value) || value < 0) {\n throw new Error(`protected model reservation ${name} must be a nonnegative safe integer`)\n }\n }\n usdToNanos(input.limits.maxCostUsd, 'reserved maxCostUsd')\n}\n\nfunction validateReservation(\n value: unknown,\n expected: AgentCandidateModelGrantReserveInput,\n gatewayDomain: string,\n): AgentCandidateModelGrantReservation {\n const source = exactRecord(\n value,\n ['preparationId', 'digest', 'expiresAtMs', 'enforcedLimits', 'network'],\n 'protected model reservation response',\n )\n if (source.preparationId !== expected.preparationId) {\n throw new Error('protected model reservation response changed preparation identity')\n }\n if (!isSha256Digest(source.digest)) {\n throw new Error('protected model reservation response has an invalid digest')\n }\n if (source.expiresAtMs !== expected.expiresAtMs) {\n throw new Error('protected model reservation response changed expiry')\n }\n exactRecord(\n source.enforcedLimits,\n ['maxModelCalls', 'maxInputTokens', 'maxOutputTokens', 'maxCostUsd'],\n 'protected model reservation enforced limits',\n )\n if (\n canonicalCandidateDigest(source.enforcedLimits) !== canonicalCandidateDigest(expected.limits)\n ) {\n throw new Error('protected model reservation response changed enforced limits')\n }\n\n const network = validateReservationNetwork(\n source.network,\n expected.limits.maxModelCalls,\n gatewayDomain,\n )\n return immutableCandidateValue({\n preparationId: source.preparationId,\n digest: source.digest,\n expiresAtMs: source.expiresAtMs,\n enforcedLimits: source.enforcedLimits,\n network,\n }) as AgentCandidateModelGrantReservation\n}\n\nfunction validateReservationNetwork(\n value: unknown,\n maxModelCalls: number,\n gatewayDomain: string,\n): AgentCandidateModelAccessNetwork {\n if (maxModelCalls === 0) {\n const source = exactRecord(value, ['mode'], 'protected model reservation network')\n if (source.mode !== 'disabled') {\n throw new Error('zero-call protected model reservation must disable gateway access')\n }\n return { mode: 'disabled' }\n }\n\n const source = exactRecord(value, ['mode', 'domains'], 'protected model reservation network')\n if (source.mode !== 'gateway-only') {\n throw new Error('protected model reservation must allow only its model gateway')\n }\n if (\n !Array.isArray(source.domains) ||\n source.domains.length !== 1 ||\n source.domains[0] !== gatewayDomain\n ) {\n throw new Error('protected model reservation returned an unexpected gateway domain')\n }\n return { mode: 'gateway-only', domains: [gatewayDomain] }\n}\n\nfunction validateActivation(\n value: unknown,\n expectedNames: readonly string[],\n): AgentCandidateProtectedModelActivation {\n const source = exactRecord(value, ['env'], 'protected model activation response')\n const env = record(source.env, 'protected model activation environment')\n const actualNames = Object.keys(env).sort()\n if (\n actualNames.length !== expectedNames.length ||\n actualNames.some((name, index) => name !== expectedNames[index])\n ) {\n throw new Error('protected model activation returned unexpected environment names')\n }\n const detached: Record<string, string> = Object.create(null) as Record<string, string>\n for (const name of expectedNames) {\n const value = env[name]\n if (typeof value !== 'string' || value.length < 8 || value.length > 65_536) {\n throw new Error(`protected model activation ${name} must be a non-empty protected value`)\n }\n detached[name] = value\n }\n return Object.freeze({ env: Object.freeze(detached) })\n}\n\nfunction validateResolvedModel(\n value: unknown,\n expected: Parameters<AgentCandidateModelPort['resolve']>[0],\n): AgentCandidateResolvedModel {\n const source = exactRecord(\n value,\n ['requested', 'provider', 'model', 'snapshot', 'reasoningEffort'],\n 'resolved candidate model',\n )\n if (source.requested !== expected.requested) {\n throw new Error('model resolver changed the evaluator-owned request')\n }\n if (source.reasoningEffort !== expected.reasoningEffort) {\n throw new Error('model resolver changed the evaluator-owned reasoning effort')\n }\n for (const name of ['requested', 'provider', 'model', 'snapshot'] as const) {\n if (typeof source[name] !== 'string' || source[name].length === 0) {\n throw new Error(`resolved candidate model ${name} must be non-empty`)\n }\n }\n return source as unknown as AgentCandidateResolvedModel\n}\n\nfunction assertGrantIdentity(\n expected: RememberedReservation,\n actual: AgentCandidateModelGrantActivateInput | AgentCandidateModelGrantSettleInput,\n): void {\n if (\n actual.executionId !== expected.executionId ||\n actual.preparationId !== expected.preparationId ||\n actual.grantDigest !== expected.grantDigest ||\n canonicalCandidateDigest(actual.resolved) !== canonicalCandidateDigest(expected.resolved)\n ) {\n throw new Error('protected model grant input does not match its immutable reservation')\n }\n}\n\nfunction assertWithinReservedLimits(\n usage: {\n modelCalls: number\n inputTokens: number\n outputTokens: number\n costUsdNanos: number\n },\n reservation: RememberedReservation,\n): void {\n for (const [name, actual, limit] of [\n ['model calls', usage.modelCalls, reservation.limits.maxModelCalls],\n ['input tokens', usage.inputTokens, reservation.limits.maxInputTokens],\n ['output tokens', usage.outputTokens, reservation.limits.maxOutputTokens],\n ['cost USD nanos', usage.costUsdNanos, reservation.maxCostUsdNanos],\n ] as const) {\n if (actual > limit) {\n throw new Error(`protected model settlement ${name} ${actual} exceeds reserved ${limit}`)\n }\n }\n}\n\nfunction exactEnvironmentNames(values: readonly string[]): readonly string[] {\n if (values.length === 0) {\n throw new Error('protected model activation environment names must not be empty')\n }\n const names = [...values].sort()\n if (new Set(names).size !== names.length) {\n throw new Error('protected model activation environment names must be unique')\n }\n for (const name of names) {\n if (\n !/^[A-Za-z_][A-Za-z0-9_]*$/.test(name) ||\n ['__proto__', 'constructor', 'prototype'].includes(name)\n ) {\n throw new Error(`protected model activation environment name is invalid: ${name}`)\n }\n }\n return Object.freeze(names)\n}\n\nfunction assertGatewayDomain(value: string): string {\n if (\n value.length > 253 ||\n value !== value.toLowerCase() ||\n value.endsWith('.') ||\n value.includes(':') ||\n value === 'localhost' ||\n value.endsWith('.localhost') ||\n value === 'metadata.google' ||\n value === 'metadata.google.internal'\n ) {\n throw new Error('protected model gateway must be an exact lowercase public DNS name')\n }\n const labels = value.split('.')\n if (\n labels.length < 2 ||\n !labels.every(\n (label) =>\n label.length >= 1 && label.length <= 63 && /^[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/.test(label),\n ) ||\n !/[a-z]/.test(labels.at(-1) ?? '')\n ) {\n throw new Error('protected model gateway must be an exact lowercase public DNS name')\n }\n return value\n}\n\nfunction reservationKey(executionId: string, preparationId: string): string {\n return canonicalCandidateDigest({ executionId, preparationId })\n}\n\nfunction pruneExpiredState(\n reservations: Map<string, RememberedReservation>,\n settlements: Map<string, RememberedSettlement>,\n now: number,\n): void {\n for (const [key, value] of reservations) {\n if (value.expiresAtMs <= now) reservations.delete(key)\n }\n for (const [key, value] of settlements) {\n if (value.expiresAtMs <= now) settlements.delete(key)\n }\n}\n\nfunction rememberSettlement(\n settlements: Map<string, RememberedSettlement>,\n key: string,\n value: RememberedSettlement,\n): void {\n settlements.delete(key)\n settlements.set(key, value)\n while (settlements.size > MAX_RECENT_SETTLEMENTS) {\n const oldest = settlements.keys().next().value\n if (oldest === undefined) return\n settlements.delete(oldest)\n }\n}\n\nfunction isSha256Digest(value: unknown): value is Sha256Digest {\n return typeof value === 'string' && /^sha256:[a-f0-9]{64}$/.test(value)\n}\n\nfunction exactRecord(\n value: unknown,\n keys: readonly string[],\n label: string,\n): Record<string, unknown> {\n const source = record(value, label)\n assertExactObjectKeys(source, keys, label)\n return source\n}\n\nfunction record(value: unknown, label: string): Record<string, unknown> {\n if (value === null || typeof value !== 'object' || Array.isArray(value)) {\n throw new Error(`${label} must be an object`)\n }\n const prototype = Object.getPrototypeOf(value)\n if (prototype !== Object.prototype && prototype !== null) {\n throw new Error(`${label} must be a plain object`)\n }\n return value as Record<string, unknown>\n}\n","import type { TraceStore } from '@tangle-network/agent-eval'\n\nimport type {\n AgentCandidateExecutionAttemptRef,\n AgentCandidateExecutionClaimStore,\n AgentCandidateExecutionFinishResult,\n} from './claim'\nimport {\n candidateCleanupDeadline,\n candidateCleanupTimeout,\n withinCandidateCleanupDeadline,\n} from './cleanup'\nimport { sealAgentCandidateExecutorFinalCapture } from './executor-capture'\nimport { sealAgentCandidateModelSettlement } from './model-settlement'\nimport { persistCandidateModelSettlementEvidence } from './outcome-evidence'\nimport { RecoveryAgentCandidateTraceStore } from './protected-trace-store'\nimport type {\n AgentCandidateExecutionPorts,\n AgentCandidateExecutorPort,\n AgentCandidateOutputArtifactPort,\n} from './types'\n\nexport interface RecoverExpiredAgentCandidateOptions {\n attempt: AgentCandidateExecutionAttemptRef\n claimStore: AgentCandidateExecutionClaimStore\n executor: AgentCandidateExecutorPort\n traceStore: TraceStore\n ports: Pick<AgentCandidateExecutionPorts, 'models' | 'memory'>\n outputArtifacts: AgentCandidateOutputArtifactPort\n cleanupTimeoutMs?: number\n /** Evaluator clock; must be the same clock used by the claim store. */\n now?: () => number\n}\n\n/** Close an expired crashed attempt from persisted non-secret handles, then record failure. */\nexport async function recoverExpiredAgentCandidateExecution(\n options: RecoverExpiredAgentCandidateOptions,\n): Promise<AgentCandidateExecutionFinishResult> {\n const record = await options.claimStore.getAttempt(options.attempt)\n if (!record) throw new Error('candidate execution recovery attempt is missing')\n if (record.terminal) {\n return Object.freeze({ finished: false, terminal: record.terminal, exactReplay: true })\n }\n const cleanupTimeoutMs = candidateCleanupTimeout(\n options.cleanupTimeoutMs ?? record.claim.cleanup.cleanupTimeoutMs,\n )\n if (cleanupTimeoutMs > record.claim.cleanup.cleanupTimeoutMs) {\n throw new Error('recovery cleanup timeout exceeds the frozen preparation bound')\n }\n\n const now = options.now ?? Date.now\n if (now() < record.claim.leaseExpiresAtMs) {\n throw new Error('candidate execution lease has not expired')\n }\n\n const cleanupDeadlineAtMs = candidateCleanupDeadline(cleanupTimeoutMs)\n const controller = new AbortController()\n controller.abort(new Error('recovering an expired candidate execution'))\n const recoveryTraceStore = new RecoveryAgentCandidateTraceStore(options.traceStore)\n const processClosure = withinCandidateCleanupDeadline(\n async () => {\n const stopped = await options.executor.stopAndCapture(\n {\n executionId: record.claim.executionId,\n executionPlanDigest: record.claim.executionPlanDigest,\n },\n {\n traceStore: recoveryTraceStore,\n reason: 'failed',\n signal: controller.signal,\n deadlineAtMs: record.claim.leaseExpiresAtMs,\n },\n )\n sealAgentCandidateExecutorFinalCapture(stopped)\n return { stopped: true as const }\n },\n cleanupDeadlineAtMs,\n 'expired candidate process termination',\n )\n\n const modelClosure = withinCandidateCleanupDeadline(\n async () =>\n sealAgentCandidateModelSettlement(\n await options.ports.models.settleGrant({\n executionId: record.claim.executionId,\n preparationId: record.claim.cleanup.preparationId,\n grantDigest: record.claim.cleanup.modelGrantDigest,\n resolved: record.claim.cleanup.resolvedModel,\n reason: 'failed',\n }),\n {\n preparationId: record.claim.cleanup.preparationId,\n grantDigest: record.claim.cleanup.modelGrantDigest,\n model: record.claim.cleanup.resolvedModel.model,\n },\n ),\n cleanupDeadlineAtMs,\n 'expired candidate model settlement',\n )\n\n const memoryClosure = record.claim.cleanup.memory\n ? withinCandidateCleanupDeadline(\n async () => {\n const memory = record.claim.cleanup.memory\n if (!memory) throw new Error('expired candidate memory handle is missing')\n const closed = await options.ports.memory.close({\n executionId: record.claim.executionId,\n preparationId: record.claim.cleanup.preparationId,\n accessDigest: memory.accessDigest,\n effectiveNamespace: memory.effectiveNamespace,\n reason: 'failed',\n })\n if (closed.closed !== true || Object.keys(closed).some((key) => key !== 'closed')) {\n throw new Error('expired candidate memory did not acknowledge closure')\n }\n return { closed: true as const }\n },\n cleanupDeadlineAtMs,\n 'expired candidate memory closure',\n )\n : undefined\n\n const operations = [processClosure, modelClosure, ...(memoryClosure ? [memoryClosure] : [])]\n const outcomes = await Promise.allSettled(operations)\n const failures = outcomes\n .filter((outcome): outcome is PromiseRejectedResult => outcome.status === 'rejected')\n .map((outcome) => outcome.reason)\n if (failures.length > 0) {\n throw new AggregateError(failures, 'expired candidate cleanup could not be proven')\n }\n\n const model = await modelClosure\n const modelSettlement = await withinCandidateCleanupDeadline(\n () =>\n persistCandidateModelSettlementEvidence(\n {\n executionId: record.claim.executionId,\n executionPlanDigest: record.claim.executionPlanDigest,\n resolvedModel: record.claim.cleanup.resolvedModel,\n },\n model,\n options.outputArtifacts,\n ),\n cleanupDeadlineAtMs,\n 'expired candidate model-settlement persistence',\n )\n const memory = record.claim.cleanup.memory\n return await options.claimStore.recoverExpired(options.attempt, {\n failureClass:\n record.phase === 'claimed' && model.fixedUsage.modelCalls === 0\n ? 'pre-model-infrastructure'\n : 'unknown',\n usage: model.fixedUsage,\n modelSettlement: modelSettlement.artifact,\n process: {\n stopped: true,\n executionPlanDigest: record.claim.executionPlanDigest,\n },\n model: {\n closed: true,\n preparationId: record.claim.cleanup.preparationId,\n grantDigest: record.claim.cleanup.modelGrantDigest,\n },\n ...(memory\n ? {\n memory: {\n closed: true,\n preparationId: record.claim.cleanup.preparationId,\n accessDigest: memory.accessDigest,\n effectiveNamespace: memory.effectiveNamespace,\n },\n }\n : {}),\n })\n}\n","/**\n *\n * Per-call resilience policy for participant backends: deadline, retry with\n * backoff, and a circuit breaker. Each policy is applied *around* a single\n * turn's backend invocation, not across the whole conversation — the\n * conversation-level credit cap and `maxTurns` bound the broader run.\n *\n * Deadlines abort the underlying backend stream via `AbortSignal` linkage so\n * the OpenAI/SDK clients tear down their HTTP request cleanly instead of\n * leaking sockets. Retries replay the same logical turn (same `turnId`) so\n * any caching gateway can dedupe. Circuit breakers are *per participant*: A's\n * failures don't open B's breaker.\n *\n * @stable\n */\n\n/** Pure judgment of whether an error is worth retrying. Defaults: TimeoutError, AbortError, fetch-level network errors. */\nexport type RetryableErrorPredicate = (err: unknown) => boolean\n\n/** Backoff between attempts. Constant ms, or `(attempt: 1-indexed) => ms`. */\nexport type RetryBackoff = number | ((attempt: number) => number)\n\n/** Circuit-breaker tuning. `failuresToOpen` consecutive failures opens it; closed only after `cooldownMs`. */\nexport interface CircuitBreakerConfig {\n failuresToOpen: number\n cooldownMs: number\n}\n\nexport interface BackendCallPolicy {\n /** Per-attempt wall clock limit. Exceeding fires an AbortSignal and is treated as a retryable failure. */\n perAttemptDeadlineMs?: number\n /** Number of retries after the first attempt; total attempts = 1 + maxRetries. Default 0. */\n maxRetries?: number\n /** Backoff between attempts. Default 250ms with jitter. */\n retryBackoffMs?: RetryBackoff\n /** Custom retry classifier. Defaults to {@link defaultIsRetryable}. */\n isRetryable?: RetryableErrorPredicate\n /** Circuit breaker that opens after N consecutive failures per participant. */\n circuitBreaker?: CircuitBreakerConfig\n}\n\n/** Thrown when the circuit breaker is open for a participant and no retry is allowed yet. */\nexport class CircuitOpenError extends Error {\n constructor(participant: string, retryAfterMs: number) {\n super(\n `circuit open for participant '${participant}'; ${retryAfterMs}ms remaining before retry allowed`,\n )\n this.name = 'CircuitOpenError'\n }\n}\n\n/** Thrown when a backend call exceeds its per-attempt deadline. */\nexport class DeadlineExceededError extends Error {\n constructor(deadlineMs: number) {\n super(`backend call exceeded per-attempt deadline of ${deadlineMs}ms`)\n this.name = 'DeadlineExceededError'\n }\n}\n\n/**\n * Default retryable classification — network/timeout class errors. Errors\n * a model deliberately throws (validation, refusal, 4xx) are not retried;\n * those represent real outcomes, not transient infrastructure faults.\n */\nexport const defaultIsRetryable: RetryableErrorPredicate = (err) => {\n if (err instanceof DeadlineExceededError) return true\n if (err instanceof Error) {\n const name = err.name\n const message = err.message.toLowerCase()\n if (name === 'AbortError' || name === 'TimeoutError') return true\n if (\n message.includes('econnreset') ||\n message.includes('etimedout') ||\n message.includes('econnrefused') ||\n message.includes('socket hang up') ||\n message.includes('network') ||\n message.includes('fetch failed')\n ) {\n return true\n }\n }\n return false\n}\n\n/** Live circuit-breaker state — one instance per (participant, conversation run). */\nexport class CircuitBreakerState {\n private consecutiveFailures = 0\n private openedAt: number | undefined\n\n constructor(private readonly config: CircuitBreakerConfig | undefined) {}\n\n /**\n * Check whether the next call is allowed. Throws `CircuitOpenError` when\n * the breaker is open and the cooldown hasn't elapsed.\n */\n preflight(participant: string, now: number = Date.now()): void {\n if (!this.config || this.openedAt === undefined) return\n const remaining = this.config.cooldownMs - (now - this.openedAt)\n if (remaining > 0) {\n throw new CircuitOpenError(participant, remaining)\n }\n this.openedAt = undefined\n this.consecutiveFailures = 0\n }\n\n recordSuccess(): void {\n this.consecutiveFailures = 0\n this.openedAt = undefined\n }\n\n recordFailure(now: number = Date.now()): void {\n if (!this.config) return\n this.consecutiveFailures += 1\n if (this.consecutiveFailures >= this.config.failuresToOpen) {\n this.openedAt = now\n }\n }\n}\n\n/**\n * Build a per-attempt AbortSignal linked to the parent signal AND fired when\n * the deadline elapses. The returned `dispose()` MUST be called in a\n * `finally` (clears the timer, detaches the listener) so we don't leak.\n *\n * When the deadline fires, the signal's `reason` is a `DeadlineExceededError`\n * — callers can detect timeout-vs-cancel by reading `signal.reason` after\n * the underlying operation throws.\n */\nexport function makePerAttemptSignal(\n parentSignal: AbortSignal | undefined,\n deadlineMs: number | undefined,\n): {\n signal: AbortSignal\n dispose: () => void\n getDeadlineError(): DeadlineExceededError | undefined\n} {\n const controller = new AbortController()\n let deadlineError: DeadlineExceededError | undefined\n const cleanups: Array<() => void> = []\n\n if (parentSignal) {\n if (parentSignal.aborted) controller.abort(parentSignal.reason)\n else {\n const onAbort = () => controller.abort(parentSignal.reason)\n parentSignal.addEventListener('abort', onAbort, { once: true })\n cleanups.push(() => parentSignal.removeEventListener('abort', onAbort))\n }\n }\n if (deadlineMs !== undefined) {\n const ms = deadlineMs\n const timer = setTimeout(() => {\n deadlineError = new DeadlineExceededError(ms)\n controller.abort(deadlineError)\n }, ms)\n cleanups.push(() => clearTimeout(timer))\n }\n return {\n signal: controller.signal,\n dispose() {\n for (const c of cleanups) c()\n },\n getDeadlineError() {\n return deadlineError\n },\n }\n}\n\n/** Compute the delay before the next attempt. Default: 250ms exponential with jitter. */\nexport function computeBackoff(spec: RetryBackoff | undefined, attempt: number): number {\n if (spec === undefined) {\n const base = 250\n const jitter = Math.floor(Math.random() * base)\n return base * 2 ** (attempt - 1) + jitter\n }\n if (typeof spec === 'function') return Math.max(0, spec(attempt))\n return Math.max(0, spec)\n}\n\n/** Resolve after `ms` milliseconds — used for retry backoff in conversation call policy. */\nexport function sleep(ms: number): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, ms))\n}\n","/**\n *\n * Cross-gateway forwarding headers — the wire-level contract that makes\n * agent-to-agent communication composable across organizational boundaries.\n * Every header here is read on inbound and re-emitted on outbound, so a chain\n * `caller → A's gateway → A's runtime → B's gateway → B's runtime` ends with\n * B billing the original user, the depth counter monotonically incremented,\n * and the run/turn correlation IDs preserved end-to-end.\n *\n * The actual depth refusal (HTTP 413 at MAX_DEPTH) is enforced by\n * `agent-gateway`'s middleware; this module owns the names + the propagation\n * rules so both sides agree.\n *\n * Full protocol: `docs/agent-bus-protocol.md`.\n *\n * @stable\n */\n\n/** Standard names — lowercased so Headers maps interop on every runtime. */\nexport const FORWARD_HEADERS = {\n /** Forwarded original-user identity (`Bearer sk-tan-<user>`); downstream gateways bill against this. */\n authorization: 'x-tangle-forwarded-authorization',\n /** Monotonically incremented on every gateway hop. Refused at MAX_DEPTH. */\n depth: 'x-tangle-forwarded-depth',\n /** Top-level conversation run identifier, propagated through every nested call. */\n runId: 'x-tangle-runid',\n /** This call's turn within the run; deterministic + stable across retries. */\n turnId: 'x-tangle-turnid',\n /** When the call is *inside* another turn (recursion), the parent turn's id. */\n parentTurnId: 'x-tangle-parent-turnid',\n /** Logical conversation peer label at the sending side, for trace stitching. */\n speaker: 'x-tangle-speaker',\n} as const\n\nexport type ForwardHeaderName = (typeof FORWARD_HEADERS)[keyof typeof FORWARD_HEADERS]\n\n/** Hard cap on chained gateway hops; refused beyond this. Default keeps recursion bounded. */\nexport const DEFAULT_MAX_DEPTH = 4\n\n/**\n * Lowercase a header lookup so we read the same key regardless of source\n * casing (Hono, fetch's `Headers`, raw Node IncomingMessage, …).\n */\nfunction lc(name: string): string {\n return name.toLowerCase()\n}\n\n/**\n * Read the depth counter off an inbound request. Missing → 0 (caller is the\n * origin). Non-integer → throws — silent coercion would let a bad caller\n * reset depth and bypass the limit.\n */\nexport function readDepth(\n headers: Readonly<Record<string, string | string[] | undefined>>,\n): number {\n const raw = pickHeader(headers, FORWARD_HEADERS.depth)\n if (raw === undefined || raw === '') return 0\n const n = Number(raw)\n if (!Number.isInteger(n) || n < 0) {\n throw new Error(\n `invalid ${FORWARD_HEADERS.depth} header value '${raw}' — must be a non-negative integer`,\n )\n }\n return n\n}\n\n/**\n * Refuse further forwarding when the inbound depth has reached the limit.\n * Callers (the gateway middleware) translate the boolean to an HTTP 413.\n */\nexport function isDepthExceeded(inboundDepth: number, max: number = DEFAULT_MAX_DEPTH): boolean {\n return inboundDepth >= max\n}\n\n/**\n * Build the headers to emit on an outbound participant call, given the\n * conversation's propagation context. Depth is incremented from the inbound\n * value; runId / turnId / speaker stamp the current hop; the user's\n * `Authorization` is preserved verbatim so the downstream gateway bills the\n * right wallet.\n */\nexport function buildForwardHeaders(input: {\n inboundDepth: number\n forwardedAuthorization?: string\n runId: string\n turnId: string\n parentTurnId?: string\n speaker: string\n}): Record<string, string> {\n const out: Record<string, string> = {\n [FORWARD_HEADERS.depth]: String(input.inboundDepth + 1),\n [FORWARD_HEADERS.runId]: input.runId,\n [FORWARD_HEADERS.turnId]: input.turnId,\n [FORWARD_HEADERS.speaker]: input.speaker,\n }\n if (input.forwardedAuthorization !== undefined) {\n out[FORWARD_HEADERS.authorization] = input.forwardedAuthorization\n }\n if (input.parentTurnId !== undefined) {\n out[FORWARD_HEADERS.parentTurnId] = input.parentTurnId\n }\n return out\n}\n\n/**\n * Header bag carried through `AgentBackendContext.propagatedHeaders` so\n * backends that opt in can merge them into their outbound HTTP requests.\n * Distinct from `buildForwardHeaders` so callers can attach extra\n * non-protocol headers (e.g. tracing) without colliding.\n */\nexport type PropagatedHeaders = Readonly<Record<string, string>>\n\nfunction pickHeader(\n headers: Readonly<Record<string, string | string[] | undefined>>,\n name: string,\n): string | undefined {\n const target = lc(name)\n for (const key of Object.keys(headers)) {\n if (lc(key) === target) {\n const value = headers[key]\n if (Array.isArray(value)) return value[0]\n return value\n }\n }\n return undefined\n}\n","/**\n *\n * Deterministic turn identifier. Stable across retries of the same logical\n * turn so backends (and any caching gateway in between) can dedupe on it.\n * A retry triggered by a network blip or deadline timeout MUST produce the\n * same `turn_id`; only the underlying attempt count differs.\n *\n * Shape: `${runId}.t${index}.${speakerSlug}` — readable in logs, sortable by\n * turn index, attributable to a speaker. Slugify keeps the speaker portion\n * URL-safe so it can ride in HTTP headers without escaping.\n *\n * @stable\n */\n\nexport function turnId(runId: string, index: number, speaker: string): string {\n return `${runId}.t${index}.${slugifySpeaker(speaker)}`\n}\n\n/**\n * Reduce a speaker name to ASCII alphanumerics + dashes. Preserves enough\n * substance to read in a log line; collisions between speakers within a\n * single Conversation are prevented by `defineConversation`'s\n * unique-name check, so the slug only needs to be deterministic, not unique.\n */\nexport function slugifySpeaker(speaker: string): string {\n const cleaned = speaker\n .normalize('NFKD')\n .replace(/[^\\w-]+/g, '-')\n .replace(/-+/g, '-')\n .replace(/^-|-$/g, '')\n .toLowerCase()\n return cleaned || 'anon'\n}\n","/**\n *\n * Conversation orchestrator. Drives N participants in turn through their own\n * `AgentExecutionBackend`s, aggregating per-turn text + usage, enforcing\n * `maxTurns` / `maxCreditsCents` / `haltOn`, and emitting per-event stream\n * markers so callers can plumb the run through SSE without buffering.\n *\n * `runConversation` returns the full result; `runConversationStream` returns\n * an `AsyncIterable<ConversationStreamEvent>` for callers that want to\n * forward events as they arrive. Both share one driving loop.\n *\n * Distributed-systems primitives layered on top of the loop:\n * - **Idempotent turn ids** — `turnId(runId, index, speaker)` stays stable\n * across retries so caching gateways can dedupe.\n * - **Durable journal** — optional `ConversationJournal` persists every\n * committed turn; reusing a runId against the same journal resumes\n * transparently from the last committed turn.\n * - **Per-turn call policy** — deadline, retry-with-backoff, and a\n * per-participant circuit breaker. Retries replay the same logical turn\n * (same `turnId`); the retry loop lives inside the outer generator so\n * deltas yield naturally without cross-coroutine buffering.\n * - **Header propagation** — run/turn/depth headers (+ forwarded user\n * authorization) stamped onto every outbound backend call so downstream\n * gateways can bill the right user and enforce `X-Tangle-Forwarded-Depth`.\n *\n * Credit cap is enforced *between turns*, not mid-stream: a turn that\n * overshoots the cap completes, the cap then halts the conversation before\n * the next turn.\n *\n * @stable\n */\n\nimport type { KnowledgeReadinessReport } from '@tangle-network/agent-eval'\n\nimport { BackendTransportError } from '../errors'\nimport { newRuntimeSession, nowIso, touchSession } from '../sessions'\nimport type {\n AgentBackendContext,\n AgentBackendInput,\n AgentTaskSpec,\n RuntimeSession,\n} from '../types'\nimport {\n type BackendCallPolicy,\n CircuitBreakerState,\n computeBackoff,\n defaultIsRetryable,\n makePerAttemptSignal,\n sleep,\n} from './call-policy'\nimport { buildForwardHeaders, FORWARD_HEADERS } from './headers'\nimport { turnId as deriveTurnId } from './turn-id'\nimport type {\n Conversation,\n ConversationParticipant,\n ConversationResult,\n ConversationStreamEvent,\n ConversationTurn,\n HaltContext,\n HaltReason,\n RunConversationOptions,\n TurnOrder,\n} from './types'\n\nexport async function runConversation(\n conversation: Conversation,\n options: RunConversationOptions,\n): Promise<ConversationResult> {\n let result: ConversationResult | undefined\n for await (const event of runConversationStream(conversation, options)) {\n if (options.onEvent) await options.onEvent(event)\n if (event.type === 'conversation_end') result = event.result\n }\n if (!result) {\n throw new BackendTransportError(\n 'conversation',\n 'conversation stream ended without a conversation_end event',\n )\n }\n return result\n}\n\n/** Streaming conversation orchestrator: drives N participants in turn through their own backends, enforcing `maxTurns` / `maxCreditsCents` / `haltOn`, yielding per-event stream markers. */\nexport async function* runConversationStream(\n conversation: Conversation,\n options: RunConversationOptions,\n): AsyncIterable<ConversationStreamEvent> {\n const runId = options.runId ?? `conv_${crypto.randomUUID()}`\n const inboundDepth = options.inboundDepth ?? 0\n const callerHeaders = options.propagatedHeaders ?? {}\n const forwardedAuthorization = callerHeaders[FORWARD_HEADERS.authorization]\n\n const breakers = new Map<string, CircuitBreakerState>()\n for (const participant of conversation.participants) {\n const cfg =\n participant.callPolicy?.circuitBreaker ??\n conversation.policy.defaultCallPolicy?.circuitBreaker\n breakers.set(participant.name, new CircuitBreakerState(cfg))\n }\n\n let transcript: ConversationTurn[] = []\n let spentCreditsCents = 0\n let startedAt = nowIso()\n let resumed = false\n\n if (options.journal) {\n const prior = await options.journal.loadRun(runId)\n if (prior) {\n if (prior.halted) {\n // Run already terminated — surface its final state without re-running.\n const replayResult: ConversationResult = {\n runId,\n transcript: prior.turns,\n turns: prior.turns.length,\n spentCreditsCents: prior.turns.reduce(\n (sum, t) => sum + centsFromUsd(t.usage?.costUsd ?? 0),\n 0,\n ),\n halted: prior.halted,\n durationMs: 0,\n startedAt: prior.startedAt,\n endedAt: prior.endedAt ?? prior.startedAt,\n }\n yield {\n type: 'conversation_resumed',\n runId,\n participants: conversation.participants.map((p) => p.name),\n transcript: prior.turns,\n timestamp: nowIso(),\n }\n yield { type: 'conversation_end', runId, result: replayResult, timestamp: nowIso() }\n return\n }\n transcript = [...prior.turns]\n spentCreditsCents = transcript.reduce(\n (sum, t) => sum + centsFromUsd(t.usage?.costUsd ?? 0),\n 0,\n )\n startedAt = prior.startedAt\n resumed = true\n } else {\n await options.journal.beginRun(runId, startedAt)\n }\n }\n const startedAtMs = Date.now()\n\n if (resumed) {\n yield {\n type: 'conversation_resumed',\n runId,\n participants: conversation.participants.map((p) => p.name),\n // Snapshot the resumed transcript — the live `transcript` array gets\n // pushed to as the run continues, so handing the bare reference to a\n // subscriber would leak future writes into a past event.\n transcript: [...transcript],\n timestamp: nowIso(),\n }\n } else {\n yield {\n type: 'conversation_start',\n runId,\n participants: conversation.participants.map((p) => p.name),\n seed: options.seed,\n timestamp: startedAt,\n }\n }\n\n // When resumed, the next user input is the last persisted turn's text;\n // for a fresh run, it's the caller's seed.\n let currentInput =\n transcript.length === 0\n ? options.seed\n : (transcript[transcript.length - 1]?.text ?? options.seed)\n let halt: HaltReason | undefined\n\n const initialOffset = transcript.length\n for (let turnIndex = initialOffset; turnIndex < conversation.policy.maxTurns; turnIndex++) {\n if (options.signal?.aborted) {\n halt = { kind: 'abort' }\n break\n }\n if (\n conversation.policy.maxCreditsCents !== undefined &&\n spentCreditsCents >= conversation.policy.maxCreditsCents\n ) {\n halt = {\n kind: 'max_credits',\n spentCents: spentCreditsCents,\n capCents: conversation.policy.maxCreditsCents,\n }\n break\n }\n\n const speakerIdx = selectSpeaker(\n conversation.policy.turnOrder,\n conversation.participants.length,\n { transcript, turnIndex, spentCreditsCents },\n )\n const speaker = conversation.participants[speakerIdx]\n if (!speaker) {\n throw new BackendTransportError(\n 'conversation',\n `turnOrder selector returned out-of-range index ${speakerIdx} for ${conversation.participants.length} participants`,\n )\n }\n\n const tid = deriveTurnId(runId, turnIndex, speaker.name)\n const callPolicy: BackendCallPolicy | undefined =\n speaker.callPolicy ?? conversation.policy.defaultCallPolicy\n const breaker = breakers.get(speaker.name)\n if (!breaker) {\n throw new BackendTransportError(\n 'conversation',\n `internal: no circuit-breaker state registered for participant '${speaker.name}'`,\n )\n }\n const isRetryable = callPolicy?.isRetryable ?? defaultIsRetryable\n const totalAttempts = 1 + (callPolicy?.maxRetries ?? 0)\n\n yield {\n type: 'turn_start',\n runId,\n index: turnIndex,\n speaker: speaker.name,\n turnId: tid,\n attempt: 1,\n timestamp: nowIso(),\n }\n\n let aggregator: TurnAggregator | undefined\n let attemptCount = 0\n let lastError: unknown\n let breakerOpenFailure: unknown\n\n for (let attempt = 1; attempt <= totalAttempts; attempt++) {\n attemptCount = attempt\n try {\n breaker.preflight(speaker.name)\n } catch (err) {\n // Breaker open — no point retrying; halt the conversation with this\n // participant's error rather than busy-looping until exhaustion.\n breakerOpenFailure = err\n break\n }\n\n if (attempt > 1) {\n yield {\n type: 'turn_retry',\n runId,\n index: turnIndex,\n speaker: speaker.name,\n turnId: tid,\n attempt,\n reason: lastError instanceof Error ? lastError.message : String(lastError),\n timestamp: nowIso(),\n }\n }\n\n const perAttempt = makePerAttemptSignal(options.signal, callPolicy?.perAttemptDeadlineMs)\n const localAgg = new TurnAggregator({\n index: turnIndex,\n speaker: speaker.name,\n startedAt: nowIso(),\n })\n\n try {\n for await (const delta of driveSingleAttempt({\n speaker,\n participants: conversation.participants,\n input: currentInput,\n turnIndex,\n runId,\n turnId: tid,\n transcript,\n signal: perAttempt.signal,\n aggregator: localAgg,\n propagatedHeaders: buildForwardHeaders({\n inboundDepth,\n // When the participant elects to pay for its own outbound calls,\n // drop the forwarded user identity so the downstream gateway\n // bills the participant's own credentials instead. The backend\n // brings its own `Authorization` header at construction time\n // (e.g. `createOpenAICompatibleBackend({ apiKey: sk-tan-AGENT })`);\n // omitting the forwarded header is what flips the billing target.\n forwardedAuthorization: resolveAuthForwarding(speaker, {\n transcript,\n turnIndex,\n spentCreditsCents,\n })\n ? forwardedAuthorization\n : undefined,\n runId,\n turnId: tid,\n parentTurnId: options.parentTurnId,\n speaker: speaker.name,\n }),\n })) {\n yield {\n type: 'turn_text_delta',\n runId,\n index: turnIndex,\n speaker: speaker.name,\n turnId: tid,\n text: delta.text,\n timestamp: delta.timestamp,\n }\n }\n perAttempt.dispose()\n breaker.recordSuccess()\n aggregator = localAgg\n break\n } catch (err) {\n perAttempt.dispose()\n breaker.recordFailure()\n // Surface the deadline error explicitly when timeout was the cause —\n // otherwise the upstream may throw a generic AbortError that loses\n // diagnostic info.\n lastError = perAttempt.getDeadlineError() ?? err\n if (attempt >= totalAttempts || !isRetryable(lastError)) {\n break\n }\n await sleep(computeBackoff(callPolicy?.retryBackoffMs, attempt))\n }\n }\n\n if (!aggregator) {\n const failure = breakerOpenFailure ?? lastError\n const message = failure instanceof Error ? failure.message : String(failure)\n halt = { kind: 'participant_error', participant: speaker.name, message }\n break\n }\n\n const turn = aggregator.toTurn({ turnId: tid, attempts: attemptCount })\n transcript.push(turn)\n spentCreditsCents += centsFromUsd(turn.usage?.costUsd ?? 0)\n if (options.journal) {\n await options.journal.appendTurn(runId, turn)\n }\n\n yield { type: 'turn_end', runId, turn, timestamp: nowIso() }\n\n if (conversation.policy.haltOn) {\n const haltCtx: HaltContext = {\n transcript,\n lastTurn: turn,\n turnIndex,\n spentCreditsCents,\n }\n const decision = await conversation.policy.haltOn(haltCtx)\n if (decision === true) {\n halt = { kind: 'predicate', reason: 'predicate_true' }\n break\n }\n if (typeof decision === 'object' && decision !== null && decision.halted) {\n halt = { kind: 'predicate', reason: decision.reason }\n break\n }\n }\n\n currentInput = turn.text\n }\n\n if (!halt) halt = { kind: 'max_turns', turns: transcript.length }\n\n const endedAt = nowIso()\n const result: ConversationResult = {\n runId,\n transcript,\n turns: transcript.length,\n spentCreditsCents,\n halted: halt,\n durationMs: Date.now() - startedAtMs,\n startedAt,\n endedAt,\n }\n if (options.journal) {\n await options.journal.recordHalt(runId, halt, endedAt)\n }\n\n yield { type: 'conversation_end', runId, result, timestamp: endedAt }\n}\n\n// ── Single attempt ───────────────────────────────────────────────────────\n\ninterface SingleAttemptArgs {\n speaker: ConversationParticipant\n participants: readonly ConversationParticipant[]\n input: string\n turnIndex: number\n runId: string\n turnId: string\n transcript: readonly ConversationTurn[]\n signal: AbortSignal\n aggregator: TurnAggregator\n propagatedHeaders: Record<string, string>\n}\n\nasync function* driveSingleAttempt(\n args: SingleAttemptArgs,\n): AsyncGenerator<{ text: string; timestamp?: string }> {\n const task: AgentTaskSpec = {\n id: args.turnId,\n intent: args.input,\n metadata: {\n runId: args.runId,\n turnId: args.turnId,\n turnIndex: args.turnIndex,\n speaker: args.speaker.name,\n participants: args.participants.map((p) => p.name),\n },\n }\n const knowledge = passingReadiness(task.id)\n const messages = buildMessagesFor(args.speaker.name, args.transcript, args.input)\n const backendInput: AgentBackendInput = { task, message: args.input, messages }\n\n const startCtx: Omit<AgentBackendContext, 'session'> & { requestedSessionId?: string } = {\n task,\n knowledge,\n signal: args.signal,\n runId: args.runId,\n turnId: args.turnId,\n propagatedHeaders: args.propagatedHeaders,\n }\n const session: RuntimeSession = args.speaker.backend.start\n ? touchSession(await args.speaker.backend.start(backendInput, startCtx))\n : newRuntimeSession(args.speaker.backend.kind, undefined, {\n runId: args.runId,\n turnIndex: args.turnIndex,\n turnId: args.turnId,\n speaker: args.speaker.name,\n })\n\n const streamCtx: AgentBackendContext = {\n task,\n knowledge,\n session,\n signal: args.signal,\n runId: args.runId,\n turnId: args.turnId,\n propagatedHeaders: args.propagatedHeaders,\n }\n\n for await (const event of args.speaker.backend.stream(backendInput, streamCtx)) {\n if (args.signal.aborted) {\n // Surface the abort so the outer retry/halt logic can react. The signal\n // either fires because of caller-cancel (propagate as-is) or because of\n // the per-attempt deadline timer (signal.reason is DeadlineExceededError).\n const reason = args.signal.reason\n throw reason instanceof Error ? reason : new Error('aborted')\n }\n if (event.type === 'text_delta') {\n args.aggregator.appendText(event.text)\n yield { text: event.text, timestamp: event.timestamp }\n } else if (event.type === 'llm_call') {\n args.aggregator.recordUsage(event)\n } else if (event.type === 'final') {\n args.aggregator.adoptFinalText(event.text)\n }\n }\n}\n\nclass TurnAggregator {\n private text = ''\n private adoptedFinal = false\n private usage:\n | {\n tokensIn?: number\n tokensOut?: number\n costUsd?: number\n latencyMs?: number\n model?: string\n }\n | undefined\n\n constructor(private readonly base: { index: number; speaker: string; startedAt: string }) {}\n\n appendText(text: string): void {\n if (this.adoptedFinal) return\n this.text += text\n }\n\n /**\n * Use the backend's `final.text` only when no streamed deltas were observed.\n * Some backends emit deltas AND a final summary; treating both as content\n * would double-count.\n */\n adoptFinalText(text: string | undefined): void {\n if (!text) return\n if (this.text.length > 0) return\n this.text = text\n this.adoptedFinal = true\n }\n\n recordUsage(event: {\n model?: string\n tokensIn?: number\n tokensOut?: number\n costUsd?: number\n latencyMs?: number\n }): void {\n const u = this.usage ?? {}\n if (event.tokensIn !== undefined) u.tokensIn = (u.tokensIn ?? 0) + event.tokensIn\n if (event.tokensOut !== undefined) u.tokensOut = (u.tokensOut ?? 0) + event.tokensOut\n if (event.costUsd !== undefined) u.costUsd = (u.costUsd ?? 0) + event.costUsd\n if (event.latencyMs !== undefined) u.latencyMs = event.latencyMs\n if (event.model !== undefined) u.model = event.model\n this.usage = u\n }\n\n toTurn(meta: { turnId: string; attempts: number }): ConversationTurn {\n return {\n index: this.base.index,\n speaker: this.base.speaker,\n turnId: meta.turnId,\n text: this.text.trim(),\n usage: this.usage,\n attempts: meta.attempts,\n startedAt: this.base.startedAt,\n endedAt: nowIso(),\n }\n }\n}\n\n/**\n * Build the participant's POV of the transcript so an OpenAI-compatible\n * backend sees its own turns as `assistant` and everyone else's as `user`,\n * with explicit speaker tags so 3+ party conversations stay disambiguated.\n * The seed / current input is appended as the trailing user message.\n */\nfunction buildMessagesFor(\n speakerName: string,\n transcript: readonly ConversationTurn[],\n currentInput: string,\n): Array<{ role: string; content: string }> {\n const messages: Array<{ role: string; content: string }> = []\n for (const turn of transcript) {\n if (turn.speaker === speakerName) {\n messages.push({ role: 'assistant', content: turn.text })\n } else {\n messages.push({ role: 'user', content: `[${turn.speaker}] ${turn.text}` })\n }\n }\n if (currentInput) messages.push({ role: 'user', content: currentInput })\n return messages\n}\n\n/**\n * True when this participant should forward the caller's\n * `X-Tangle-Forwarded-Authorization` on outbound calls (the \"pass-through\"\n * commercial mode). False when it elects to pay for its own outbound calls\n * (the \"reseller\" / \"bundle\" mode). See ConversationParticipant.authSource.\n */\nfunction resolveAuthForwarding(\n participant: ConversationParticipant,\n state: { transcript: readonly ConversationTurn[]; turnIndex: number; spentCreditsCents: number },\n): boolean {\n const decision =\n typeof participant.authSource === 'function'\n ? participant.authSource(state)\n : (participant.authSource ?? 'forward-user')\n return decision === 'forward-user'\n}\n\nfunction selectSpeaker(\n order: TurnOrder | undefined,\n participantCount: number,\n state: { transcript: readonly ConversationTurn[]; turnIndex: number; spentCreditsCents: number },\n): number {\n const resolved = order ?? (participantCount === 2 ? 'alternate' : 'round-robin')\n if (resolved === 'alternate' || resolved === 'round-robin') {\n return state.turnIndex % participantCount\n }\n if (typeof resolved === 'function') {\n const idx = resolved(state)\n if (!Number.isInteger(idx) || idx < 0 || idx >= participantCount) {\n throw new BackendTransportError(\n 'conversation',\n `turnOrder function returned invalid index ${String(idx)} for ${participantCount} participants`,\n )\n }\n return idx\n }\n throw new BackendTransportError('conversation', `unknown turnOrder: ${String(resolved)}`)\n}\n\nfunction centsFromUsd(usd: number): number {\n return Math.round(usd * 100)\n}\n\n/**\n * Synthesize a knowledge-readiness report that *passes* every gate, used to\n * satisfy `AgentBackendContext.knowledge` per turn. Conversations don't apply\n * task-level readiness gating per-turn — that's a `runAgentTask` concern.\n */\nfunction passingReadiness(taskId: string): KnowledgeReadinessReport {\n return {\n taskId,\n readinessScore: 1,\n blockingMissingRequirements: [],\n nonBlockingGaps: [],\n recommendedAction: 'run_agent',\n bundle: {\n taskId,\n requirements: [],\n evidenceIds: [],\n claimIds: [],\n wikiPageIds: [],\n userAnswers: {},\n missing: [],\n readinessScore: 1,\n },\n severity: 'info',\n reason: 'conversation-mode: readiness gating not applied per-turn',\n }\n}\n","/**\n *\n * Wrap a `Conversation` so it satisfies `AgentExecutionBackend`. The result is\n * an addressable \"single agent\" whose internal behavior is an N-party\n * orchestrated conversation — the recursion primitive that lets a swarm be a\n * participant inside another swarm, or be published behind a single\n * agent-gateway endpoint.\n *\n * Stream events from inner participants are NOT forwarded verbatim. Outer\n * callers see one `text_delta` per inner turn (the turn's full text), tagged\n * with `[speaker] ` prefix so the outer transcript stays attributable. The\n * conversation's `conversation_end` halt reason rides on a `final` event.\n *\n * @stable\n */\n\nimport { newRuntimeSession, nowIso } from '../sessions'\nimport type {\n AgentBackendContext,\n AgentBackendInput,\n AgentExecutionBackend,\n RuntimeSession,\n RuntimeStreamEvent,\n} from '../types'\nimport { FORWARD_HEADERS, readDepth } from './headers'\nimport { runConversationStream } from './run-conversation'\nimport type { Conversation, HaltReason } from './types'\n\nexport function createConversationBackend(options: {\n conversation: Conversation\n /** Optional backend kind label. Defaults to `'conversation'`. */\n kind?: string\n}): AgentExecutionBackend {\n const kind = options.kind ?? 'conversation'\n\n return {\n kind,\n start(_input, context): RuntimeSession {\n return newRuntimeSession(kind, context.requestedSessionId, {\n participants: options.conversation.participants.map((p) => p.name),\n })\n },\n async *stream(\n input: AgentBackendInput,\n context: AgentBackendContext,\n ): AsyncIterable<RuntimeStreamEvent> {\n const seed = input.message ?? input.messages?.at(-1)?.content ?? context.task.intent\n const task = context.task\n const session = context.session\n\n yield { type: 'backend_start', task, session, backend: kind, timestamp: nowIso() }\n\n let finalText = ''\n let totalCostUsd = 0\n let totalTokensIn = 0\n let totalTokensOut = 0\n\n // Recursion: forward this call's propagation context into the nested\n // conversation. The nested run INHERITS the parent's runId (protocol\n // invariant: runId is immutable across nesting), continues the depth\n // counter from the headers, and stamps the enclosing turn as the\n // parentTurnId so trace stitching reaches across nesting levels.\n const inboundDepth = parseInboundDepth(context.propagatedHeaders)\n for await (const event of runConversationStream(options.conversation, {\n seed,\n signal: context.signal,\n runId: context.runId,\n propagatedHeaders: context.propagatedHeaders,\n inboundDepth,\n parentTurnId: context.turnId,\n })) {\n if (event.type === 'turn_end') {\n const tagged = `[${event.turn.speaker}] ${event.turn.text}\\n`\n finalText += tagged\n yield { type: 'text_delta', task, session, text: tagged, timestamp: event.timestamp }\n if (event.turn.usage) {\n const u = event.turn.usage\n if (u.costUsd !== undefined) totalCostUsd += u.costUsd\n if (u.tokensIn !== undefined) totalTokensIn += u.tokensIn\n if (u.tokensOut !== undefined) totalTokensOut += u.tokensOut\n yield {\n type: 'llm_call',\n task,\n session,\n model: u.model ?? `${kind}/${event.turn.speaker}`,\n tokensIn: u.tokensIn,\n tokensOut: u.tokensOut,\n costUsd: u.costUsd,\n latencyMs: u.latencyMs,\n timestamp: event.timestamp,\n }\n }\n } else if (event.type === 'conversation_end') {\n const halt = event.result.halted\n yield {\n type: 'final',\n task,\n session,\n status: halt.kind === 'participant_error' ? 'failed' : 'completed',\n reason: describeHalt(halt),\n text: finalText.trim(),\n metadata: {\n conversationRunId: event.result.runId,\n turns: event.result.turns,\n spentCreditsCents: event.result.spentCreditsCents,\n halted: halt,\n durationMs: event.result.durationMs,\n tokensIn: totalTokensIn,\n tokensOut: totalTokensOut,\n costUsd: totalCostUsd,\n },\n timestamp: event.timestamp,\n }\n }\n }\n\n yield { type: 'backend_end', task, session, backend: kind, timestamp: nowIso() }\n },\n }\n}\n\nfunction parseInboundDepth(headers: Readonly<Record<string, string>> | undefined): number {\n if (!headers) return 0\n // Accept either the canonical header key OR a lookup via the keyed name.\n const raw = headers[FORWARD_HEADERS.depth]\n if (raw === undefined) return 0\n try {\n return readDepth({ [FORWARD_HEADERS.depth]: raw })\n } catch {\n return 0\n }\n}\n\nfunction describeHalt(halt: HaltReason): string {\n switch (halt.kind) {\n case 'max_turns':\n return `max_turns (${halt.turns})`\n case 'max_credits':\n return `max_credits (${halt.spentCents}/${halt.capCents}¢)`\n case 'predicate':\n return `predicate: ${halt.reason}`\n case 'abort':\n return 'abort'\n case 'participant_error':\n return `participant_error[${halt.participant}]: ${halt.message}`\n }\n}\n","/**\n *\n * Declarative constructor for a multi-agent `Conversation`. Validates inputs\n * fail-loud at definition time (duplicate participant names, alternate order\n * with ≠2 participants, non-positive `maxTurns`) so misconfiguration is caught\n * before `runConversation` is called and not buried inside a streaming run.\n *\n * @stable\n */\n\nimport { ValidationError } from '../errors'\nimport type { Conversation, ConversationParticipant, ConversationPolicy, TurnOrder } from './types'\n\nexport function defineConversation(input: {\n participants: ConversationParticipant[]\n policy: ConversationPolicy\n}): Conversation {\n if (input.participants.length < 2) {\n throw new ValidationError(\n `Conversation requires at least 2 participants; received ${input.participants.length}.`,\n )\n }\n\n const seen = new Set<string>()\n for (const p of input.participants) {\n if (!p.name || p.name.trim() === '') {\n throw new ValidationError('Conversation participant.name must be a non-empty string.')\n }\n if (seen.has(p.name)) {\n throw new ValidationError(\n `Conversation participant names must be unique within a Conversation; '${p.name}' appears more than once.`,\n )\n }\n seen.add(p.name)\n if (!p.backend || typeof p.backend.stream !== 'function') {\n throw new ValidationError(\n `Conversation participant '${p.name}' is missing a backend with a stream() method.`,\n )\n }\n }\n\n const policy = normalizePolicy(input.policy, input.participants.length)\n\n return {\n participants: input.participants,\n policy,\n }\n}\n\nfunction normalizePolicy(policy: ConversationPolicy, participantCount: number): ConversationPolicy {\n if (!Number.isInteger(policy.maxTurns) || policy.maxTurns < 1) {\n throw new ValidationError(\n `ConversationPolicy.maxTurns must be a positive integer; received ${String(policy.maxTurns)}.`,\n )\n }\n if (\n policy.maxCreditsCents !== undefined &&\n (!Number.isFinite(policy.maxCreditsCents) || policy.maxCreditsCents < 0)\n ) {\n throw new ValidationError(\n `ConversationPolicy.maxCreditsCents must be a non-negative finite number when set; received ${String(\n policy.maxCreditsCents,\n )}.`,\n )\n }\n const turnOrder = policy.turnOrder ?? (participantCount === 2 ? 'alternate' : 'round-robin')\n if (turnOrder === 'alternate' && participantCount !== 2) {\n throw new ValidationError(\n `ConversationPolicy.turnOrder 'alternate' requires exactly 2 participants; received ${participantCount}. Use 'round-robin' or a custom selector for N-party conversations.`,\n )\n }\n return { ...policy, turnOrder: turnOrder as TurnOrder }\n}\n","/**\n *\n * Durable conversation transcript — survives a driver process crash mid-run.\n * The runner journals every committed turn before yielding `turn_end`, so a\n * resumed run replays the same `runId` against the same journal and picks up\n * from the first un-recorded turn. Combined with the deterministic\n * `turnId(runId, index, speaker)`, a retried turn collides with the prior\n * attempt's id and any caching gateway can dedupe.\n *\n * The interface is small enough that a Cloudflare D1 / R2 / postgres adapter\n * is ~30 lines. The in-memory adapter is the default for tests and scratch.\n * The file adapter (JSONL on disk) is the default-durable choice when no\n * upstream store is wired.\n *\n * @stable\n */\n\nimport type { ConversationTurn, HaltReason } from './types'\n\nexport interface ConversationJournalEntry {\n runId: string\n startedAt: string\n /** Set when the run reaches a terminal state. */\n halted?: HaltReason\n endedAt?: string\n turns: ConversationTurn[]\n}\n\nexport interface ConversationJournal {\n /**\n * Load any prior state for `runId`. Returns `undefined` for a fresh run.\n * Implementations MUST NOT mutate the returned object — the runner clones\n * before continuing — but the runtime treats absence and emptiness\n * identically, so a journal with zero turns is equivalent to \"fresh.\"\n */\n loadRun(runId: string): Promise<ConversationJournalEntry | undefined>\n\n /**\n * Initialise journal state for a fresh run. Called once per run, before any\n * `appendTurn`. Idempotent: calling with an existing runId is a no-op if\n * the entry already exists with the same `startedAt`.\n */\n beginRun(runId: string, startedAt: string): Promise<void>\n\n /**\n * Append a committed turn. The runner only calls this AFTER the turn's\n * backend stream completed and the credit total has been updated, so an\n * appended turn is observed-committed and never speculative.\n */\n appendTurn(runId: string, turn: ConversationTurn): Promise<void>\n\n /**\n * Record the run's terminal halt reason + end time. Once called, the run\n * is observed-final; subsequent `loadRun` returns the same halt.\n */\n recordHalt(runId: string, halt: HaltReason, endedAt: string): Promise<void>\n}\n\n/** In-memory `ConversationJournal` — suitable for testing and single-process runs. */\nexport class InMemoryConversationJournal implements ConversationJournal {\n private readonly entries = new Map<string, ConversationJournalEntry>()\n\n async loadRun(runId: string): Promise<ConversationJournalEntry | undefined> {\n const entry = this.entries.get(runId)\n if (!entry) return undefined\n // Defensive copy — callers MUST NOT mutate journal-owned arrays.\n return {\n runId: entry.runId,\n startedAt: entry.startedAt,\n halted: entry.halted,\n endedAt: entry.endedAt,\n turns: [...entry.turns],\n }\n }\n\n async beginRun(runId: string, startedAt: string): Promise<void> {\n const existing = this.entries.get(runId)\n if (existing) {\n if (existing.startedAt !== startedAt) {\n throw new Error(\n `runId '${runId}' already exists with startedAt=${existing.startedAt}; refusing to overwrite with ${startedAt}`,\n )\n }\n return\n }\n this.entries.set(runId, { runId, startedAt, turns: [] })\n }\n\n async appendTurn(runId: string, turn: ConversationTurn): Promise<void> {\n const entry = this.entries.get(runId)\n if (!entry) {\n throw new Error(\n `appendTurn called for unknown runId '${runId}'; call beginRun first or use the runner which handles it`,\n )\n }\n if (entry.halted) {\n throw new Error(\n `cannot append turn to halted run '${runId}' (halt reason: ${JSON.stringify(entry.halted)})`,\n )\n }\n entry.turns.push(turn)\n }\n\n async recordHalt(runId: string, halt: HaltReason, endedAt: string): Promise<void> {\n const entry = this.entries.get(runId)\n if (!entry) {\n throw new Error(`recordHalt called for unknown runId '${runId}'`)\n }\n entry.halted = halt\n entry.endedAt = endedAt\n }\n}\n\n/**\n * JSONL on disk. One line per record; first line is the `begin`, subsequent\n * lines are `turn` records, terminal line is `halt`. Replays the whole file\n * on `loadRun` — cheap for the conversation sizes this is designed for\n * (thousands of turns, not millions). For huge runs, plug in a real DB\n * adapter; the interface is small.\n *\n * Each `appendTurn` / `recordHalt` calls `fsync` after the write so a\n * process crash between writes never loses an acknowledged turn.\n */\nexport class FileConversationJournal implements ConversationJournal {\n constructor(private readonly path: string) {}\n\n async loadRun(runId: string): Promise<ConversationJournalEntry | undefined> {\n const fs = await import('node:fs/promises')\n let text: string\n try {\n text = await fs.readFile(this.path, 'utf8')\n } catch (err) {\n if (isNoEntError(err)) return undefined\n throw err\n }\n const lines = text.split('\\n').filter((line) => line.length > 0)\n let entry: ConversationJournalEntry | undefined\n for (const line of lines) {\n const record = JSON.parse(line) as JournalRecord\n if (record.runId !== runId) continue\n if (record.kind === 'begin') {\n entry = { runId, startedAt: record.startedAt, turns: [] }\n } else if (record.kind === 'turn') {\n if (!entry) {\n throw new Error(\n `journal corrupted: turn record for runId '${runId}' precedes its begin record`,\n )\n }\n entry.turns.push(record.turn)\n } else if (record.kind === 'halt') {\n if (!entry) {\n throw new Error(\n `journal corrupted: halt record for runId '${runId}' precedes its begin record`,\n )\n }\n entry.halted = record.halted\n entry.endedAt = record.endedAt\n }\n }\n return entry\n }\n\n async beginRun(runId: string, startedAt: string): Promise<void> {\n const existing = await this.loadRun(runId)\n if (existing) {\n if (existing.startedAt !== startedAt) {\n throw new Error(\n `runId '${runId}' already exists in ${this.path} with startedAt=${existing.startedAt}; refusing to overwrite with ${startedAt}`,\n )\n }\n return\n }\n await this.appendRecord({ kind: 'begin', runId, startedAt })\n }\n\n async appendTurn(runId: string, turn: ConversationTurn): Promise<void> {\n await this.appendRecord({ kind: 'turn', runId, turn })\n }\n\n async recordHalt(runId: string, halt: HaltReason, endedAt: string): Promise<void> {\n await this.appendRecord({ kind: 'halt', runId, halted: halt, endedAt })\n }\n\n private async appendRecord(record: JournalRecord): Promise<void> {\n const fs = await import('node:fs/promises')\n const path = await import('node:path')\n await fs.mkdir(path.dirname(this.path), { recursive: true })\n const fh = await fs.open(this.path, 'a')\n try {\n await fh.write(`${JSON.stringify(record)}\\n`)\n await fh.sync()\n } finally {\n await fh.close()\n }\n }\n}\n\ntype JournalRecord =\n | { kind: 'begin'; runId: string; startedAt: string }\n | { kind: 'turn'; runId: string; turn: ConversationTurn }\n | { kind: 'halt'; runId: string; halted: HaltReason; endedAt: string }\n\nfunction isNoEntError(err: unknown): boolean {\n return (\n typeof err === 'object' &&\n err !== null &&\n 'code' in err &&\n (err as { code: unknown }).code === 'ENOENT'\n )\n}\n","/**\n *\n * Durable conversation journal backed by any SQL store. Adapter-agnostic by\n * design: callers wire a `SqlAdapter` against their driver of choice (D1,\n * postgres, sqlite, libSQL…) and the same journal implementation persists\n * conversation runs durably across process restarts. The schema is two\n * tables — runs (latest state) + events (append-only log) — so a partial\n * crash in the middle of a turn leaves an unambiguous \"last committed turn\"\n * to resume from.\n *\n * Why not bake in a specific driver? agent-runtime ships against multiple\n * runtimes (Cloudflare Workers, Node, Bun, Deno) and consumers' fleets have\n * already standardized on one of D1 / postgres / sqlite / libSQL. Adapter\n * indirection costs ~5 lines per driver in the consumer's code and keeps the\n * SDK free of native deps.\n *\n * @example D1 (Cloudflare Workers)\n * import { SqlConversationJournal, d1ToSqlAdapter } from '@tangle-network/agent-runtime'\n * const journal = new SqlConversationJournal(d1ToSqlAdapter(env.DB))\n * await journal.migrate() // once at deploy\n * await runConversation(conv, { seed, journal, runId: 'run_abc' })\n *\n * @example node-postgres\n * import { Pool } from 'pg'\n * const pool = new Pool({ connectionString: process.env.DATABASE_URL })\n * const pg: SqlAdapter = {\n * exec: async (sql, params = []) => {\n * const r = await pool.query(sql, params as never)\n * return { rowsAffected: r.rowCount ?? 0 }\n * },\n * query: async (sql, params = []) => (await pool.query(sql, params as never)).rows,\n * }\n * const journal = new SqlConversationJournal(pg)\n * await journal.migrate()\n *\n * @stable\n */\n\nimport type { ConversationJournal, ConversationJournalEntry } from './journal'\nimport type { ConversationTurn, HaltReason } from './types'\n\n/**\n * Minimal SQL driver shape. Implementations forward to whichever client the\n * deployment already uses; agent-runtime takes no opinion on which.\n *\n * Parameter placeholders MUST be `?` (positional). All adapters listed in the\n * file header accept this convention.\n */\nexport interface SqlAdapter {\n /** Execute a write statement (INSERT/UPDATE/DELETE/DDL). */\n exec(sql: string, params?: readonly unknown[]): Promise<{ rowsAffected: number }>\n /** Execute a read statement (SELECT). Returns rows as plain objects. */\n query<TRow = Record<string, unknown>>(sql: string, params?: readonly unknown[]): Promise<TRow[]>\n}\n\n/**\n * Adapt a Cloudflare D1 binding to the SqlAdapter shape. Lives here so D1\n * consumers don't have to write the wrapper themselves; the runtime never\n * imports `@cloudflare/workers-types` directly (peer-style typing).\n */\nexport function d1ToSqlAdapter(db: D1DatabaseLike): SqlAdapter {\n return {\n async exec(sql, params = []) {\n const stmt = db.prepare(sql)\n const bound = params.length > 0 ? stmt.bind(...params) : stmt\n const result = await bound.run()\n const meta = (result as { meta?: { rows_written?: number; changes?: number } }).meta\n return { rowsAffected: meta?.rows_written ?? meta?.changes ?? 0 }\n },\n async query<TRow>(sql: string, params: readonly unknown[] = []): Promise<TRow[]> {\n const stmt = db.prepare(sql)\n const bound = params.length > 0 ? stmt.bind(...params) : stmt\n const result = await bound.all<TRow>()\n return result.results ?? []\n },\n }\n}\n\n/**\n * Structural type matching the surface of `D1Database` we depend on, so the\n * SDK never imports `@cloudflare/workers-types`. Consumers pass their real\n * `D1Database` from `env.DB` and TS structural compatibility lines it up.\n */\nexport interface D1DatabaseLike {\n prepare(sql: string): D1StmtLike\n}\nexport interface D1StmtLike {\n bind(...params: unknown[]): D1StmtLike\n run(): Promise<unknown>\n all<TRow = unknown>(): Promise<{ results?: TRow[] }>\n}\n\nconst RUNS_TABLE_DDL = (table: string) => `\n CREATE TABLE IF NOT EXISTS ${table}_runs (\n run_id TEXT PRIMARY KEY,\n started_at TEXT NOT NULL,\n halted_kind TEXT,\n halted_payload TEXT,\n ended_at TEXT\n )\n`\nconst TURNS_TABLE_DDL = (table: string) => `\n CREATE TABLE IF NOT EXISTS ${table}_turns (\n run_id TEXT NOT NULL,\n turn_index INTEGER NOT NULL,\n payload TEXT NOT NULL,\n PRIMARY KEY (run_id, turn_index)\n )\n`\nconst TURNS_INDEX_DDL = (table: string) => `\n CREATE INDEX IF NOT EXISTS idx_${table}_turns_run ON ${table}_turns (run_id, turn_index)\n`\n\n/**\n * SQL-backed ConversationJournal. Two tables — runs (one row per runId, holds\n * start/halt timestamps + halt reason) and turns (one row per committed turn,\n * payload is the ConversationTurn JSON). Replays the turns table on\n * `loadRun` and writes append-only per `appendTurn`.\n */\nexport class SqlConversationJournal implements ConversationJournal {\n /**\n * @param db SQL adapter (D1, postgres, sqlite, libSQL — all work)\n * @param table Table-name prefix; the journal creates `${table}_runs` and\n * `${table}_turns`. Lets multiple journals share a database\n * without colliding (e.g. one per product surface).\n */\n constructor(\n private readonly db: SqlAdapter,\n private readonly table: string = 'agent_runtime_journal',\n ) {}\n\n /**\n * Create the journal's tables if absent. Idempotent. Call once at deploy\n * (or at app boot) — running on every request is harmless but adds latency.\n */\n async migrate(): Promise<void> {\n await this.db.exec(RUNS_TABLE_DDL(this.table))\n await this.db.exec(TURNS_TABLE_DDL(this.table))\n await this.db.exec(TURNS_INDEX_DDL(this.table))\n }\n\n async loadRun(runId: string): Promise<ConversationJournalEntry | undefined> {\n const runs = await this.db.query<{\n run_id: string\n started_at: string\n halted_kind: string | null\n halted_payload: string | null\n ended_at: string | null\n }>(\n `SELECT run_id, started_at, halted_kind, halted_payload, ended_at FROM ${this.table}_runs WHERE run_id = ?`,\n [runId],\n )\n const row = runs[0]\n if (!row) return undefined\n const turns = await this.db.query<{ payload: string; turn_index: number }>(\n `SELECT payload, turn_index FROM ${this.table}_turns WHERE run_id = ? ORDER BY turn_index ASC`,\n [runId],\n )\n return {\n runId: row.run_id,\n startedAt: row.started_at,\n halted: row.halted_payload ? (JSON.parse(row.halted_payload) as HaltReason) : undefined,\n endedAt: row.ended_at ?? undefined,\n turns: turns.map((t) => JSON.parse(t.payload) as ConversationTurn),\n }\n }\n\n async beginRun(runId: string, startedAt: string): Promise<void> {\n const existing = await this.db.query<{ started_at: string }>(\n `SELECT started_at FROM ${this.table}_runs WHERE run_id = ?`,\n [runId],\n )\n if (existing.length > 0) {\n if (existing[0]?.started_at !== startedAt) {\n throw new Error(\n `runId '${runId}' already exists with startedAt=${existing[0]?.started_at}; refusing to overwrite with ${startedAt}`,\n )\n }\n return\n }\n await this.db.exec(`INSERT INTO ${this.table}_runs (run_id, started_at) VALUES (?, ?)`, [\n runId,\n startedAt,\n ])\n }\n\n async appendTurn(runId: string, turn: ConversationTurn): Promise<void> {\n const halted = await this.db.query<{ halted_kind: string | null }>(\n `SELECT halted_kind FROM ${this.table}_runs WHERE run_id = ?`,\n [runId],\n )\n if (halted.length === 0) {\n throw new Error(\n `appendTurn called for unknown runId '${runId}'; call beginRun first or use the runner which handles it`,\n )\n }\n if (halted[0]?.halted_kind) {\n throw new Error(\n `cannot append turn to halted run '${runId}' (halt kind: ${halted[0]?.halted_kind})`,\n )\n }\n await this.db.exec(\n `INSERT INTO ${this.table}_turns (run_id, turn_index, payload) VALUES (?, ?, ?)`,\n [runId, turn.index, JSON.stringify(turn)],\n )\n }\n\n async recordHalt(runId: string, halt: HaltReason, endedAt: string): Promise<void> {\n const rs = await this.db.exec(\n `UPDATE ${this.table}_runs SET halted_kind = ?, halted_payload = ?, ended_at = ? WHERE run_id = ?`,\n [halt.kind, JSON.stringify(halt), endedAt, runId],\n )\n if (rs.rowsAffected === 0) {\n throw new Error(`recordHalt called for unknown runId '${runId}'`)\n }\n }\n}\n","/**\n * `runPersonaConversation` — the persona loop runner: run a WORKER `AgentProfile`\n * (the agent under test) as a multi-round conversation driven by a PERSONA (the\n * simulated user), over the persistent conversation transcript.\n *\n * It is profiles-vs-profiles: the persona is itself a driver `AgentProfile` (an\n * LLM role-playing the user from its facts) — `runConversation` runs the two\n * against each other. Scripted persona turns are kept as a deterministic\n * fast-path. Only the WORKER is metered (it is the side under test); the\n * persona-driver is the test harness, not billed against the agent.\n *\n * `runPersonaDispatch` wraps the runner as a `ProfileDispatchFn` so it drops\n * straight into `runProfileMatrix({ dispatch })` — the same loop serves a single\n * cell and the whole matrix, replacing the per-agent hand-rolled\n * `dispatchWithSurface` bridges.\n */\n\nimport type { AgentProfile } from '@tangle-network/agent-eval'\nimport type {\n DispatchContext,\n ProfileDispatchFn,\n Scenario,\n} from '@tangle-network/agent-eval/campaign'\nimport { createIterableBackend } from '../backends'\nimport type { AgentExecutionBackend, RuntimeStreamEvent } from '../types'\nimport { defineConversation } from './define-conversation'\nimport { runConversation } from './run-conversation'\nimport type { ConversationTurn, HaltPredicate, HaltReason } from './types'\n\n/** A persona that drives the conversation: either a full driver `AgentProfile`\n * (an LLM user-sim) or a deterministic script of user turns (the fast-path). */\nexport type PersonaDriver =\n | { kind: 'profile'; profile: AgentProfile }\n | { kind: 'scripted'; turns: string[] }\n\nexport interface RunPersonaConversationOptions {\n /** The agent under test. Metered; its rendered prompt leads its turns. */\n worker: AgentProfile\n /** The simulated user driving the dialogue. */\n persona: PersonaDriver\n /** Turn an `AgentProfile` into a runnable backend (router / sandbox / fake).\n * Applied to the worker and to a `profile`-kind persona. */\n backendFor: (profile: AgentProfile, role: 'worker' | 'persona') => AgentExecutionBackend\n /** Render a profile's system prompt — prepended to that profile's messages. */\n systemPromptOf: (profile: AgentProfile) => string\n /** Speaker-turn cap. Default for a scripted persona = `2 * turns.length`\n * (worker answers each user turn). REQUIRED for a `profile` persona. */\n maxTurns?: number\n /** Kickoff message routed to the first speaker (the persona). Default 'Begin.' */\n seed?: string\n /** Content-based \"until satisfied\" halt, called after every turn. `maxTurns` is the\n * hard ceiling; this is the early stop (the persona declares the goal met / unreachable). */\n haltOn?: HaltPredicate\n signal?: AbortSignal\n /** Worker participant / transcript speaker label. Default 'agent'. */\n workerName?: string\n}\n\nexport interface PersonaConversationResult {\n transcript: ConversationTurn[]\n turns: number\n halted: HaltReason\n /** Worker-only spend (the side under test). */\n costUsd: number\n tokensIn: number\n tokensOut: number\n}\n\ninterface UsageCounter {\n tokensIn: number\n tokensOut: number\n costUsd: number\n}\n\n/** Prefix a backend's requests with `systemPrompt`; when `counter` is given,\n * accumulate its `llm_call` token/cost usage (used for the metered worker). */\nfunction withProfilePrompt(\n inner: AgentExecutionBackend,\n systemPrompt: string,\n counter?: UsageCounter,\n): AgentExecutionBackend {\n return {\n kind: inner.kind,\n start: inner.start ? (input, ctx) => inner.start!(input, ctx) : undefined,\n resume: inner.resume ? (session, input, ctx) => inner.resume!(session, input, ctx) : undefined,\n stop: inner.stop ? (session, reason) => inner.stop!(session, reason) : undefined,\n async *stream(input, context) {\n const base =\n input.messages ?? (input.message ? [{ role: 'user', content: input.message }] : [])\n const messages =\n base[0]?.role === 'system' ? base : [{ role: 'system', content: systemPrompt }, ...base]\n for await (const event of inner.stream({ ...input, messages }, context)) {\n if (counter && event.type === 'llm_call') {\n counter.tokensIn += event.tokensIn ?? 0\n counter.tokensOut += event.tokensOut ?? 0\n counter.costUsd += event.costUsd ?? 0\n }\n yield event\n }\n },\n }\n}\n\n/** A persona participant that replays scripted user turns in order. */\nfunction scriptedPersonaBackend(turns: readonly string[]): AgentExecutionBackend {\n let idx = 0\n return createIterableBackend({\n kind: 'persona-user',\n async *stream(_input, context) {\n const text = turns[idx]\n if (text === undefined) {\n throw new Error(\n `persona-user: ran out of scripted turns at index ${idx} (had ${turns.length})`,\n )\n }\n idx += 1\n yield {\n type: 'text_delta',\n task: context.task,\n session: context.session,\n text,\n timestamp: new Date().toISOString(),\n } satisfies RuntimeStreamEvent\n },\n })\n}\n\n/**\n * Run one worker profile against one persona as a multi-round conversation.\n * The persona leads (participant 0): it speaks, the worker answers, repeat,\n * until `maxTurns`. Returns the persistent transcript + worker-only usage.\n */\nexport async function runPersonaConversation(\n opts: RunPersonaConversationOptions,\n): Promise<PersonaConversationResult> {\n const counter: UsageCounter = { tokensIn: 0, tokensOut: 0, costUsd: 0 }\n const workerName = opts.workerName ?? 'agent'\n const worker = withProfilePrompt(\n opts.backendFor(opts.worker, 'worker'),\n opts.systemPromptOf(opts.worker),\n counter,\n )\n\n let persona: AgentExecutionBackend\n let maxTurns: number\n if (opts.persona.kind === 'scripted') {\n if (opts.persona.turns.length === 0) {\n throw new Error('runPersonaConversation: scripted persona has no turns')\n }\n persona = scriptedPersonaBackend(opts.persona.turns)\n maxTurns = opts.maxTurns ?? 2 * opts.persona.turns.length\n } else {\n persona = withProfilePrompt(\n opts.backendFor(opts.persona.profile, 'persona'),\n opts.systemPromptOf(opts.persona.profile),\n )\n if (opts.maxTurns === undefined) {\n throw new Error('runPersonaConversation: maxTurns is required for a profile-driven persona')\n }\n maxTurns = opts.maxTurns\n }\n\n const conversation = defineConversation({\n // Persona leads (participant 0): the seed routes to it, it produces the\n // user turn, the worker answers, alternate.\n participants: [\n { name: 'user', backend: persona },\n { name: workerName, backend: worker },\n ],\n policy: { maxTurns, turnOrder: 'alternate', ...(opts.haltOn ? { haltOn: opts.haltOn } : {}) },\n })\n const result = await runConversation(conversation, {\n seed: opts.seed ?? 'Begin.',\n signal: opts.signal,\n })\n // Worker-only cost. Prefer the worker's own metered llm_call spend. Fall back\n // to the engine's aggregate spend ONLY for a scripted persona — there the\n // harness has no LLM cost so the aggregate IS the worker's. For a\n // profile-driven persona the aggregate also includes the persona-driver's\n // spend, so attributing it to the worker would over-count; report the\n // worker's metered spend (0 if its backend reported none) instead.\n const costUsd =\n counter.costUsd > 0\n ? counter.costUsd\n : opts.persona.kind === 'scripted'\n ? result.spentCreditsCents / 100\n : 0\n return {\n transcript: result.transcript,\n turns: result.turns,\n halted: result.halted,\n costUsd,\n tokensIn: counter.tokensIn,\n tokensOut: counter.tokensOut,\n }\n}\n\nexport interface RunPersonaConfig<TScenario extends Scenario, TArtifact> {\n /** Turn an `AgentProfile` into a runnable backend (router / sandbox / fake). */\n backendFor: (profile: AgentProfile, role: 'worker' | 'persona') => AgentExecutionBackend\n /** Render a profile's system prompt. */\n systemPromptOf: (profile: AgentProfile) => string\n /** The persona driving each scenario — a driver profile or scripted turns. */\n personaOf: (scenario: TScenario) => PersonaDriver\n /** Build the scored artifact from the finished transcript. */\n artifactOf: (transcript: ConversationTurn[], scenario: TScenario) => TArtifact\n /** Speaker-turn cap (required when a persona is profile-driven). */\n maxTurns?: (scenario: TScenario) => number\n seed?: (scenario: TScenario) => string\n workerName?: string\n}\n\n/**\n * Wrap {@link runPersonaConversation} as a `ProfileDispatchFn` for\n * `runProfileMatrix`: the profile axis is the worker-under-test, the scenario\n * axis is the persona, and the runner is the cell. Meters the worker through\n * `ctx.cost` so the matrix's backend-integrity guard sees real usage.\n */\nexport function runPersonaDispatch<TScenario extends Scenario, TArtifact>(\n config: RunPersonaConfig<TScenario, TArtifact>,\n): ProfileDispatchFn<TScenario, TArtifact> {\n return async (\n worker: AgentProfile,\n scenario: TScenario,\n ctx: DispatchContext,\n ): Promise<TArtifact> => {\n const result = await runPersonaConversation({\n worker,\n persona: config.personaOf(scenario),\n backendFor: config.backendFor,\n systemPromptOf: config.systemPromptOf,\n maxTurns: config.maxTurns?.(scenario),\n seed: config.seed?.(scenario),\n signal: ctx.signal,\n workerName: config.workerName,\n })\n ctx.cost.observe(result.costUsd, 'persona-conversation')\n ctx.cost.observeTokens({ input: result.tokensIn, output: result.tokensOut })\n return config.artifactOf(result.transcript, scenario)\n }\n}\n","/**\n * `handleChatTurn` — framework-neutral chat-turn HTTP orchestrator.\n * Owns the NDJSON `ChatStreamEvent` line protocol, the `session.run.*`\n * lifecycle vocabulary, and the persist / post-process / trace-flush\n * hook order. Returns a `ReadableStream` body the product hands to its\n * platform `Response`.\n *\n * Execution durability is the substrate's concern: `box.streamPrompt`\n * auto-reconnects in-call; cross-process reconnect via `X-Execution-ID`\n * is the product's job. The producer this engine wraps already speaks\n * that protocol — the engine just frames the events.\n *\n * Hooks (`ChatTurnHooks`):\n * - `produce` — build the backend event stream\n * - `persistAssistantMessage` — write the assistant turn to the product DB\n * - `onTurnComplete?` — post-process (proposals, citations, …)\n * - `onEvent?` — per-event side channel (e.g. DO broadcast)\n * - `transformFinalText?` — pre-persist transform (e.g. PII redact)\n * - `traceFlush?` — handed to waitUntil so OTLP export lands\n *\n * Framework neutrality: takes already-resolved values (`identity` tuple,\n * a `waitUntil`), never a `Request` or a `Context`. The product's thin\n * route adapter does auth + parse + access-control, then calls\n * `handleChatTurn(...)` and returns `result.body` as its platform `Response`.\n */\n\n/** The NDJSON line protocol every product chat client already speaks. */\nexport interface ChatStreamEvent {\n type: string\n data?: Record<string, unknown>\n}\n\n/** Identity of a chat turn. `tenantId` is the workspace id for workspace-\n * scoped products and the user id for session-scoped products. */\nexport interface ChatTurnIdentity {\n tenantId: string\n /** Thread / session id. */\n sessionId: string\n userId: string\n /** Monotonic 0-based turn index within the session. */\n turnIndex: number\n}\n\n/** The live side of a turn — what the product's `produce` hook returns. */\nexport interface ChatTurnProducer<TEvent extends ChatStreamEvent = ChatStreamEvent> {\n /** The turn's event stream. Forwarded verbatim to the caller. */\n stream: AsyncGenerator<TEvent, void, unknown>\n /** The turn's final assistant text. Read once, after `stream` drains. */\n finalText(): string\n}\n\nexport interface ChatTurnHooks {\n /** Build the backend stream. The engine forwards events verbatim and\n * reads `finalText()` once the stream drains. */\n produce(): ChatTurnProducer\n /** Persist the assistant message to the product's own store. Called\n * once, after drain, with the assembled (transform-applied) text. */\n persistAssistantMessage(input: { identity: ChatTurnIdentity; finalText: string }): Promise<void>\n /** Optional post-processing (proposals, citations, credit metering …).\n * Errors are swallowed + logged — post-process must never fail a turn\n * that already streamed successfully. */\n onTurnComplete?(input: { identity: ChatTurnIdentity; finalText: string }): Promise<void>\n /** Optional per-event side channel (e.g. DO broadcast). Runs for every\n * emitted event, lifecycle envelope included. Errors swallowed — a\n * broadcast failure must not break the chat stream. */\n onEvent?(event: ChatStreamEvent): void | Promise<void>\n /** Optional pre-persist transform of the final text (e.g. PII\n * redaction). Affects only what is persisted; the live stream is\n * never altered. */\n transformFinalText?(text: string): string | Promise<string>\n /** Optional trace flush — resolves when OTLP export completes. Handed\n * to `waitUntil` so the worker isolate stays alive for the POST. */\n traceFlush?(): Promise<void>\n}\n\nexport interface RunChatTurnInput {\n identity: ChatTurnIdentity\n hooks: ChatTurnHooks\n /** Worker liveness hook. When omitted, trace flush is awaited inline\n * before the stream closes. */\n waitUntil?: (p: Promise<unknown>) => void\n /** Structured logger for swallowed hook errors. Defaults to\n * `console.error` so failures surface without product wiring. */\n log?: (message: string, meta?: Record<string, unknown>) => void\n}\n\nexport interface ChatTurnResult {\n /** NDJSON body — return this as the platform `Response` body. */\n body: ReadableStream<Uint8Array>\n /** Content type for the response. */\n contentType: 'application/x-ndjson'\n}\n\nconst encoder = new TextEncoder()\n\nfunction encodeLine(event: ChatStreamEvent): Uint8Array {\n return encoder.encode(`${JSON.stringify(event)}\\n`)\n}\n\nfunction defaultLog(message: string, meta?: Record<string, unknown>): void {\n if (meta) console.error(message, meta)\n else console.error(message)\n}\n\n/**\n * Run one chat turn. Returns immediately with a `ReadableStream` body;\n * the turn executes as the body is pulled. Never rejects — backend\n * failures surface as `error` + `session.run.failed` events.\n */\nexport function handleChatTurn(input: RunChatTurnInput): ChatTurnResult {\n const log = input.log ?? defaultLog\n const { identity, hooks } = input\n\n const body = new ReadableStream<Uint8Array>({\n start: async (controller) => {\n const emit = async (event: ChatStreamEvent): Promise<void> => {\n controller.enqueue(encodeLine(event))\n if (hooks.onEvent) {\n try {\n await hooks.onEvent(event)\n } catch (err) {\n log('[chat-engine] onEvent hook threw', {\n error: err instanceof Error ? err.message : String(err),\n })\n }\n }\n }\n\n try {\n await emit({\n type: 'session.run.started',\n data: {\n sessionId: identity.sessionId,\n tenantId: identity.tenantId,\n turnIndex: identity.turnIndex,\n },\n })\n\n const producer = hooks.produce()\n for await (const event of producer.stream) {\n await emit(event)\n }\n const rawFinal = producer.finalText()\n const finalText = hooks.transformFinalText\n ? await hooks.transformFinalText(rawFinal)\n : rawFinal\n\n await hooks.persistAssistantMessage({ identity, finalText })\n if (hooks.onTurnComplete) {\n try {\n await hooks.onTurnComplete({ identity, finalText })\n } catch (err) {\n log('[chat-engine] onTurnComplete threw', {\n error: err instanceof Error ? err.message : String(err),\n })\n }\n }\n\n await emit({\n type: 'session.run.completed',\n data: { sessionId: identity.sessionId },\n })\n } catch (err) {\n const message = err instanceof Error ? err.message : String(err)\n log('[chat-engine] turn failed', { error: message })\n await emit({ type: 'error', data: { message } })\n await emit({\n type: 'session.run.failed',\n data: { sessionId: identity.sessionId, message },\n })\n } finally {\n if (hooks.traceFlush) {\n const flush = hooks.traceFlush().catch((err) =>\n log('[chat-engine] traceFlush threw', {\n error: err instanceof Error ? err.message : String(err),\n }),\n )\n if (input.waitUntil) input.waitUntil(flush)\n else await flush\n }\n controller.close()\n }\n },\n })\n\n return { body, contentType: 'application/x-ndjson' }\n}\n","/**\n * Derive a stable executionId from the run identity. The same\n * `(projectId, sessionId, turnIndex)` tuple yields the same id — so a\n * client retry of the same turn lands on the same substrate execution\n * and the orchestrator's buffer replays instead of starting a second\n * prompt.\n *\n * Format is readable, not hashed: operators grepping orchestrator logs\n * for `gtm-agent:thread-abc:3` find the run without translating an\n * opaque id. Substrate executionIds are not a secrecy boundary.\n *\n * Wire integration:\n * - Sandbox PromptOptions accepts `executionId` and `lastEventId`.\n * Products pass this id to make cross-process reconnect land on the\n * same substrate execution instead of spawning a duplicate run.\n */\nexport function deriveExecutionId(input: {\n projectId: string\n sessionId: string\n turnIndex: number\n}): string {\n return `${input.projectId}:${input.sessionId}:${input.turnIndex}`\n}\n","/**\n *\n * `improve` — the ONE public, surface-pluggable RSI verb.\n *\n * A thin facade over agent-eval's `selfImprove` (the held-out-gated closed\n * loop). It removes the two things a caller otherwise has to know to drive the\n * loop by hand: WHICH `MutableSurface` of the profile is being optimized, and\n * WHICH `SurfaceProposer` mutates that surface. You name a `surface`; the\n * facade picks the matching default proposer, extracts the baseline surface from\n * the profile, runs `selfImprove`, and (on a ship verdict) writes the promoted\n * winner back into the corresponding profile field.\n *\n * - `surface: 'prompt'` → `gepaProposer` mutates `profile.prompt.systemPrompt`.\n * - `surface: 'skills'` → `skillOptProposer` mutates a skills document string.\n * - `surface: 'rollout-policy'` → `rolloutPolicyProposer` mutates the\n * inference-time `StructuralRolloutPolicy` dials ({ k, repairRounds, testgen })\n * persisted in `profile.extensions['structural-rollout']` — deterministic\n * bounded neighbor enumeration; the held-out gate does the deciding. No-op\n * (nothing proposed, nothing shipped) when the profile has no such extension.\n * - `surface` ∈ {`tools`, `mcp`, `hooks`, `code`} → no zero-config default\n * proposer exists (a code/config proposer needs caller-supplied wiring — a\n * worktree repo root, a candidate generator, a serializer). The facade\n * requires an explicit `opts.generator` for these and throws a `ConfigError`\n * otherwise. This is a designed boundary, not a missing default: there is\n * no safe value the facade could invent for those seams.\n *\n * Everything else (`scenarios`, `judge`, `agent`, `budget`, `llm`) passes\n * straight through to `selfImprove`.\n *\n * @experimental\n */\n\nimport {\n gepaProposer,\n gitWorktreeAdapter,\n skillOptProposer,\n} from '@tangle-network/agent-eval/campaign'\nimport {\n type DispatchContext,\n type JudgeConfig,\n type MutableSurface,\n type Scenario,\n type SelfImproveBudget,\n type SelfImproveLlm,\n type SelfImproveOptions,\n type SelfImproveResult,\n type SurfaceProposer,\n selfImprove,\n} from '@tangle-network/agent-eval/contract'\nimport type { AgentProfile } from '@tangle-network/agent-interface'\nimport { ConfigError } from '../errors'\nimport type { LocalHarness } from '../mcp/local-harness'\nimport { assertModelAllowed } from '../runtime/supervise/model-policy'\nimport { agenticGenerator, type Verifier } from './agentic-generator'\nimport { type CandidateGenerator, improvementDriver } from './improvement-driver'\nimport { rawTraceDistiller } from './raw-trace-distiller'\nimport {\n applyRolloutPolicyToProfile,\n normalizeRolloutPolicy,\n rolloutPolicyProposer,\n serializeRolloutPolicy,\n structuralRolloutPolicyFromProfile,\n} from './rollout-policy'\n\n/** The agent-profile lever `improve` optimizes. Mirrors the AgentProfile-law\n * profile levers; `code` is the implementation-tier surface, `rollout-policy`\n * the inference-time structuralRollout dials\n * (`profile.extensions['structural-rollout']`). */\nexport type ImproveSurface =\n | 'prompt'\n | 'skills'\n | 'tools'\n | 'mcp'\n | 'hooks'\n | 'code'\n | 'rollout-policy'\n\nexport interface ImproveOptions<TScenario extends Scenario, TArtifact> {\n /** Which profile lever to optimize. Default `'prompt'`. Selects the default\n * generator + the baseline-surface extraction shape. */\n surface?: ImproveSurface\n /** The `SurfaceProposer` that mutates the surface. When unset, the facade\n * picks the default for `surface` (`gepaProposer` for prompt, `skillOptProposer`\n * for skills); surfaces with no default REQUIRE this (fail-loud otherwise). */\n generator?: SurfaceProposer\n /** Gate mode. `'holdout'` (default) runs the held-out promotion gate;\n * `'none'` is a baseline-only run (`budget.generations = 0`). */\n gate?: 'holdout' | 'none'\n /** Scenarios to evaluate against. Passthrough to `selfImprove`. */\n scenarios: TScenario[]\n /** Judge that scores artifacts. Passthrough to `selfImprove`. */\n judge: JudgeConfig<TArtifact, TScenario>\n /** The agent under improvement — same shape as `selfImprove.agent`: it takes\n * the current surface + scenario + ctx and returns the artifact to judge. */\n agent: (surface: MutableSurface, scenario: TScenario, ctx: DispatchContext) => Promise<TArtifact>\n /** Budget + loop shape. Passthrough; `gate: 'none'` forces `generations = 0`. */\n budget?: SelfImproveBudget\n /** LLM config. Passthrough to `selfImprove` AND used to construct the default\n * reflective proposer (`gepaProposer`/`skillOptProposer`) when `generator` is unset. */\n llm?: SelfImproveLlm\n /** Restrict the run to this subset of models. When set, the reflection model\n * (`llm.model`, or the default when unset) must be a member, or `improve()` throws\n * a `ConfigError` before the generator is built. Unset = unrestricted. */\n allowedModels?: readonly string[]\n /** Run directory passthrough to `selfImprove`. Pass a REAL path to make the loop\n * durable: campaign cells + the loop provenance record land on the filesystem as\n * they complete, so a multi-hour search survives a process/infra death instead of\n * losing every generation with it (the default `mem://` run keeps everything\n * in-process). */\n runDir?: string\n /** Per-generation findings producer passthrough (see selfImprove.analyzeGeneration).\n * DEFAULT: the built-in failure distiller — after each generation it turns the\n * worst-scoring/errored cells into structured findings ({ scenario, composite,\n * notes, error }) for the NEXT proposal round, so the proposer reasons over what\n * actually failed instead of a static seed. Pass your own producer (e.g. a\n * trace-analyst over the runDir's traces) to replace it; pass `null` to disable\n * and keep the static `findings` all the way through. */\n analyzeGeneration?: SelfImproveOptions<TScenario, TArtifact>['analyzeGeneration'] | null\n /** META-HARNESS mode: instead of the ~400-char distilled findings, feed the\n * proposer RAW-TRACE FILESYSTEM CONTEXT — the PATHS into the prior generation's\n * real run traces under `runDir` (per-cell `spans.jsonl` event logs +\n * `cached-result.json` scores + artifacts) plus a `grep`/`cat`-to-diagnose\n * instruction — so the coding agent reads the actual failures itself rather than\n * a pre-summary. Requires a REAL `runDir` (that is where the traces live).\n * Ignored when `analyzeGeneration` is set explicitly (that wins) or is `null`\n * (disabled). Equivalent to `analyzeGeneration: rawTraceDistiller()`; this flag\n * is the one-line enable. Default `false` (the distiller stays the default). */\n rawTraceContext?: boolean\n /** CODE-surface wiring with prompt-parity DX: name `surface: 'code'`, point at a\n * repo, and the facade assembles the whole candidate pipeline — git worktrees\n * (`gitWorktreeAdapter`) driven by `improvementDriver` with the full agentic\n * generator (a real coding harness edits each candidate worktree; a `verify`\n * hook gates candidates before they are ever measured). Ignored when\n * `opts.generator` is supplied. Without either, `surface: 'code'` still fails\n * loud — there is no safe zero-config repo to invent. */\n code?: ImproveCodeOptions\n /** SKILLS-surface wiring for real skill-DOCUMENT optimization. Without this,\n * `surface: 'skills'` optimizes the profile's skills REFS array (file pointers)\n * — which `skillOptProposer` (a document patcher) cannot meaningfully edit.\n * Provide the document CONTENT to optimize + a `writeBack` to persist the\n * shipped winner (the profile ref points at a file the caller owns). This is\n * what makes skillOpt reachable through improve(). */\n skills?: ImproveSkillsOptions\n /** Storage passthrough to `selfImprove`; overrides the default chosen from `runDir`. */\n storage?: SelfImproveOptions<TScenario, TArtifact>['storage']\n}\n\nexport interface ImproveSkillsOptions {\n /** The skill document's current text — the baseline `skillOptProposer` patches. */\n document: string\n /** Persist the shipped winner document (write the file the profile ref points at).\n * Called only on a ship verdict. When omitted, the winner is still returned in\n * `result.raw.winner.surface` for the caller to materialize. */\n writeBack?: (winnerDocument: string) => void\n}\n\nexport interface ImproveCodeOptions {\n /** Repo root candidate worktrees fork from. */\n repoRoot: string\n /** Base ref candidates fork from. Default `main`. */\n baseRef?: string\n /** Directory worktrees are created under. Default `<repoRoot>/.worktrees`. */\n worktreeDir?: string\n /** Coding harness the agentic generator runs in each worktree. Default `claude`. */\n harness?: LocalHarness\n /** Verify a candidate worktree before it becomes a measurable surface; failures\n * feed the next shot (see `agenticGenerator.verify` / `commandVerifier`). */\n verify?: Verifier\n /** Per-shot wall-clock timeout for the harness (ms). */\n timeoutMs?: number\n /** Byte-producer override — the test seam and the escape hatch for custom\n * candidate production. When set, `harness`/`verify`/`timeoutMs` are unused. */\n generator?: CandidateGenerator\n}\n\nexport interface ImproveResult<TScenario extends Scenario, TArtifact> {\n /** The profile after improvement: the winner surface applied back into the\n * matching field when the gate shipped, else the input profile unchanged. */\n profile: AgentProfile\n /** True when `gateDecision === 'ship'`. */\n shipped: boolean\n /** Held-out lift (`winner − baseline` composite). */\n lift: number\n /** The five-valued gate verdict from `selfImprove`. */\n gateDecision: SelfImproveResult<TScenario, TArtifact>['gateDecision']\n /** Full `selfImprove` result for advanced inspection. */\n raw: SelfImproveResult<TScenario, TArtifact>\n}\n\n/** Default model id for the reflective drivers when `llm.model` is unset — a model the Tangle\n * router actually serves (callers should pass their own `llm.model`). */\nconst defaultReflectionModel = 'deepseek-v4-flash'\n\n/** The reflective proposers (`gepaProposer`/`skillOptProposer`) take a full\n * `LlmClientOptions`; `SelfImproveLlm` is the thin user-facing subset. */\nfunction llmClientOptions(llm: SelfImproveLlm | undefined): { baseUrl?: string; apiKey?: string } {\n return { baseUrl: llm?.baseUrl, apiKey: llm?.apiKey }\n}\n\n/** The default proposer for a surface, or `undefined` when the surface has no\n * zero-config default (the caller must supply `opts.generator`). */\nfunction defaultGeneratorFor(\n surface: ImproveSurface,\n llm: SelfImproveLlm | undefined,\n): SurfaceProposer | undefined {\n const model = llm?.model ?? defaultReflectionModel\n switch (surface) {\n case 'prompt':\n return gepaProposer({ llm: llmClientOptions(llm), model, target: 'agent system prompt' })\n case 'skills':\n return skillOptProposer({ llm: llmClientOptions(llm), model, target: 'agent skill document' })\n case 'rollout-policy':\n // Deterministic bounded enumeration — no LLM, so `llm` is unused here.\n return rolloutPolicyProposer()\n default:\n return undefined\n }\n}\n\n/** Extract the baseline surface a driver mutates from the profile field that\n * backs `surface`. `prompt`/`skills` are string surfaces; the config surfaces\n * serialize the matching profile record. */\nfunction baselineSurfaceFor(\n profile: AgentProfile,\n surface: ImproveSurface,\n skills?: ImproveSkillsOptions,\n): MutableSurface {\n switch (surface) {\n case 'prompt':\n return profile.prompt?.systemPrompt ?? ''\n case 'skills':\n // With a document supplied, optimize its CONTENT (the real skillOpt path);\n // otherwise fall back to the refs-array surface for back-compat.\n return skills?.document ?? JSON.stringify(profile.resources?.skills ?? [])\n case 'tools':\n return JSON.stringify(profile.tools ?? {})\n case 'mcp':\n return JSON.stringify(profile.mcp ?? {})\n case 'hooks':\n return JSON.stringify(profile.hooks ?? {})\n case 'rollout-policy': {\n // Empty surface when the profile never opted into structural rollout: the\n // proposer reads it as \"propose nothing\", so the loop runs baseline-only and\n // holds — tuning dials nothing consumes would ship dead config.\n const policy = structuralRolloutPolicyFromProfile(profile)\n return policy ? serializeRolloutPolicy(policy) : ''\n }\n case 'code':\n // A code surface is produced by the caller's generator from a worktree;\n // the facade has no worktree ref to seed, so the baseline is the empty\n // string (the driver opens its own worktree off `baseRef`).\n return ''\n }\n}\n\n/** The default `analyzeGeneration`: distill each generation's failing cells into\n * findings for the next proposal round. Deliberately dependency-free — judge notes\n * and errors are already the domain's own diagnosis (executable gates put their\n * reasons there); a trace-analyst can replace this wholesale via\n * `opts.analyzeGeneration`. Falls back to the static seed findings when the\n * generation had no failures, so a clean round never wipes the seed context. */\nfunction generationFailureDistiller<TScenario extends Scenario, TArtifact>(\n staticFindings: unknown[],\n): NonNullable<SelfImproveOptions<TScenario, TArtifact>['analyzeGeneration']> {\n const CAP = 12\n return async (input) => {\n const failures: Array<{ scenario: string; composite: number; notes: string; error?: string }> =\n []\n for (const candidate of input.candidates) {\n for (const rawCell of candidate.campaign.cells) {\n const cell = rawCell as unknown as Record<string, unknown>\n const scenario = String(cell.scenarioId ?? 'unknown')\n const error = typeof cell.error === 'string' ? cell.error : undefined\n const judgeScores =\n cell.judgeScores && typeof cell.judgeScores === 'object'\n ? Object.values(\n cell.judgeScores as Record<string, { composite?: number; notes?: string }>,\n )\n : []\n const composite =\n judgeScores.length === 0\n ? 0\n : judgeScores.reduce((sum, j) => sum + (j.composite ?? 0), 0) / judgeScores.length\n if (!error && composite >= 0.999) continue\n const notes = judgeScores\n .map((j) => j.notes)\n .filter((n): n is string => typeof n === 'string' && n.length > 0)\n .join('; ')\n .slice(0, 400)\n failures.push({\n scenario,\n composite: Number(composite.toFixed(3)),\n notes,\n ...(error ? { error: error.slice(0, 200) } : {}),\n })\n }\n }\n if (failures.length === 0) return staticFindings\n failures.sort((a, b) => a.composite - b.composite)\n return failures.slice(0, CAP)\n }\n}\n\n/** Assemble the code-surface proposer from `opts.code`: git worktrees + the\n * improvement driver + (by default) the full agentic generator. Returns\n * `undefined` when the surface is not `code` or no code options were given —\n * the caller then falls through to the fail-loud ConfigError. */\nfunction codeProposerFor(\n surface: ImproveSurface,\n code: ImproveCodeOptions | undefined,\n): SurfaceProposer | undefined {\n if (surface !== 'code' || !code) return undefined\n const generator =\n code.generator ??\n agenticGenerator({\n ...(code.harness ? { harness: code.harness } : {}),\n ...(code.verify ? { verify: code.verify } : {}),\n ...(code.timeoutMs ? { timeoutMs: code.timeoutMs } : {}),\n })\n return improvementDriver({\n worktree: gitWorktreeAdapter({\n repoRoot: code.repoRoot,\n ...(code.worktreeDir ? { worktreeDir: code.worktreeDir } : {}),\n }),\n generator,\n ...(code.baseRef ? { baseRef: code.baseRef } : {}),\n }) as SurfaceProposer\n}\n\n/** Parse a JSON winner surface (`skills`/`tools`/`mcp`/`hooks`) with a typed,\n * contextual error. A malformed generator output must fail loud here, not throw\n * a raw `SyntaxError` to the caller after a ship verdict. */\nfunction parseWinnerJson<T>(winner: string, surface: ImproveSurface): T {\n try {\n return JSON.parse(winner) as T\n } catch (cause) {\n throw new ConfigError(\n `improve(): the shipped '${surface}' winner is not valid JSON, so it cannot be applied back to the profile: ${\n (cause as Error).message\n }`,\n )\n }\n}\n\n/** Apply a promoted winner surface back into the profile field for `surface`.\n * Returns a shallow copy; never mutates the input profile. */\nfunction applyWinnerToProfile(\n profile: AgentProfile,\n surface: ImproveSurface,\n winner: MutableSurface,\n): AgentProfile {\n // Only string surfaces map cleanly back onto a profile field. A `CodeSurface`\n // winner (the `code` lever) is a worktree ref, not a profile value — the\n // caller materializes it from `raw.winner.surface`; the returned profile is\n // unchanged for that lever.\n if (typeof winner !== 'string') return profile\n switch (surface) {\n case 'prompt':\n return { ...profile, prompt: { ...profile.prompt, systemPrompt: winner } }\n case 'skills':\n return {\n ...profile,\n resources: { ...profile.resources, skills: parseWinnerJson(winner, surface) },\n }\n case 'tools':\n return { ...profile, tools: parseWinnerJson(winner, surface) }\n case 'mcp':\n return { ...profile, mcp: parseWinnerJson(winner, surface) }\n case 'hooks':\n return { ...profile, hooks: parseWinnerJson(winner, surface) }\n case 'rollout-policy': {\n // Parse + re-validate the winner against the policy's own invariants — a\n // custom generator's malformed dial must fail loud, not persist silently.\n const policy = normalizeRolloutPolicy(parseWinnerJson(winner, surface))\n if (!policy) {\n throw new ConfigError(\n `improve(): the shipped 'rollout-policy' winner is not a valid StructuralRolloutPolicy ` +\n `(integer k >= 1, repairRounds >= 0, testgen >= 0), so it cannot be applied: ${winner}`,\n )\n }\n return applyRolloutPolicyToProfile(profile, policy)\n }\n case 'code':\n return profile\n }\n}\n\n/**\n * Run the held-out-gated self-improvement loop on ONE profile surface.\n *\n * @example Optimize the system prompt, default holdout gate:\n *\n * const out = await improve(profile, findings, {\n * surface: 'prompt',\n * scenarios,\n * judge,\n * agent: (surface, scenario, ctx) => runAgent(surface, scenario, ctx.signal),\n * })\n * if (out.shipped) deploy(out.profile)\n */\nexport async function improve<TScenario extends Scenario, TArtifact>(\n profile: AgentProfile,\n findings: unknown[],\n opts: ImproveOptions<TScenario, TArtifact>,\n): Promise<ImproveResult<TScenario, TArtifact>> {\n const surface = opts.surface ?? 'prompt'\n const gate = opts.gate ?? 'holdout'\n\n // Fail loud before the generator is built: the reflection model must be in the allowed subset\n // (no-op when allowedModels is unset).\n assertModelAllowed(opts.llm?.model ?? defaultReflectionModel, opts.allowedModels)\n\n const proposer =\n opts.generator ?? defaultGeneratorFor(surface, opts.llm) ?? codeProposerFor(surface, opts.code)\n if (!proposer) {\n throw new ConfigError(\n surface === 'code'\n ? `improve(): surface 'code' needs either opts.generator or opts.code ({ repoRoot, ... }) — there is no safe zero-config repo to invent`\n : `improve(): surface '${surface}' has no default generator — pass opts.generator (a SurfaceProposer) explicitly`,\n )\n }\n\n const budget: SelfImproveBudget =\n gate === 'none' ? { ...opts.budget, generations: 0 } : { ...opts.budget }\n\n const raw = await selfImprove<TScenario, TArtifact>({\n agent: opts.agent,\n scenarios: opts.scenarios,\n judge: opts.judge,\n baselineSurface: baselineSurfaceFor(profile, surface, opts.skills),\n proposer,\n budget,\n llm: opts.llm,\n findings,\n ...(opts.runDir !== undefined ? { runDir: opts.runDir } : {}),\n ...(opts.storage !== undefined ? { storage: opts.storage } : {}),\n ...(opts.analyzeGeneration === null\n ? {}\n : {\n analyzeGeneration:\n opts.analyzeGeneration ??\n (opts.rawTraceContext\n ? rawTraceDistiller<TScenario, TArtifact>({ fallbackFindings: findings })\n : generationFailureDistiller<TScenario, TArtifact>(findings)),\n }),\n })\n\n const shipped = raw.gateDecision === 'ship'\n // When a skill DOCUMENT was optimized, the winner is document text — persist it\n // via writeBack (the profile ref points at the caller's file, unchanged) rather\n // than parsing it as a refs array. Otherwise use the standard field write-back.\n const usedSkillDocument = surface === 'skills' && opts.skills !== undefined\n if (shipped && usedSkillDocument && typeof raw.winner.surface === 'string') {\n opts.skills?.writeBack?.(raw.winner.surface)\n }\n const nextProfile =\n shipped && !usedSkillDocument\n ? applyWinnerToProfile(profile, surface, raw.winner.surface)\n : profile\n\n return { profile: nextProfile, shipped, lift: raw.lift, gateDecision: raw.gateDecision, raw }\n}\n","/**\n *\n * `improvementDriver` — the ONE reflective/agentic improvement proposer for\n * agent-eval's improvement loop. It implements `SurfaceProposer` and owns\n * the candidate lifecycle (worktree create → generate → finalize/discard,\n * × populationSize); it delegates the only thing that genuinely varies — HOW\n * a candidate change is produced — to a pluggable `CandidateGenerator`.\n *\n * There is no separate \"analyst driver\" vs \"autoresearch driver\": those are\n * the SAME driver at two settings of a dial.\n * - cheap reflective path → `reflectiveGenerator` (shots=1, no sandbox;\n * applies pre-drafted patches)\n * - full agentic path → `agenticGenerator` (shots=N, multi-shot\n * verify-in-session loop; an agent reads code +\n * report, edits, and re-tries on verifier failure)\n * Both emit changes into a worktree the driver finalizes into a\n * `CodeSurface{ worktreeRef }` the loop measures on the holdout. See\n * agent-eval's `docs/design/self-improvement-engine.md`.\n *\n * @experimental\n */\n\nimport type { AnalystFinding } from '@tangle-network/agent-eval'\nimport type {\n CodeSurface,\n LabeledScenarioStore,\n ProposeContext,\n SurfaceProposer,\n WorktreeAdapter,\n} from '@tangle-network/agent-eval/campaign'\n\n/** The byte-producing seam — the ONE thing that differs between the cheap\n * reflective path and the full agentic path. A generator makes (uncommitted)\n * changes inside `worktreePath`; the driver commits them via the worktree\n * adapter's `finalize`. */\nexport interface CandidateGenerator {\n kind: string\n /** Whether this generator can produce a candidate from an EMPTY findings set\n * and no phase-2 report — i.e. it draws its change signal from the repo and\n * the raw-trace filesystem context on disk, not only from pre-summarized\n * findings. An agentic coder (`agenticGenerator`) sets this: the seed repo +\n * raw traces ARE the signal, so it must still run the full `populationSize`\n * when the distiller yielded nothing (this is the meta-harness contract — the\n * agent diagnoses from the raw traces itself). A patch-applier\n * (`reflectiveGenerator`) leaves it unset — with no findings there is no\n * patch to draft, so the driver short-circuits rather than spin up worktrees\n * for a guaranteed no-op. Default `false`. */\n proposesWithoutFindings?: boolean\n generate(args: {\n /** The candidate worktree — a fresh checkout of baseRef. Write changes here. */\n worktreePath: string\n /** Phase-2 research report (analyst findings + diff), opaque. */\n report: unknown\n /** Findings resolved from the report or the loop context. */\n findings: AnalystFinding[]\n /** Handle to all captured data, to ground the change. */\n dataset?: LabeledScenarioStore\n /** DEPTH: max iterations the generator may take (agentic uses this; the\n * reflective generator ignores it). */\n maxShots: number\n signal: AbortSignal\n }): Promise<{ applied: boolean; summary: string }>\n}\n\nexport interface ImprovementDriverOptions {\n worktree: WorktreeAdapter\n generator: CandidateGenerator\n /** Base ref candidate worktrees fork from. Default `main`. */\n baseRef?: string\n}\n\n/** The one reflective/agentic improvement proposer (`SurfaceProposer`): owns the candidate worktree lifecycle and delegates HOW a change is produced to a pluggable `CandidateGenerator`. */\nexport function improvementDriver(opts: ImprovementDriverOptions): SurfaceProposer<AnalystFinding> {\n const baseRef = opts.baseRef ?? 'main'\n\n return {\n kind: `improvement:${opts.generator.kind}`,\n async propose(ctx: ProposeContext<AnalystFinding>) {\n const findings = resolveFindings(ctx)\n // No findings AND no report AND a generator that can only act on findings\n // (the reflective patch-applier) — propose nothing rather than spin up\n // worktrees for a guaranteed no-op. An agentic coder draws its signal from\n // the repo + raw traces on disk, so it opts in via `proposesWithoutFindings`\n // and still runs the full populationSize even on an empty findings set —\n // otherwise the FIRST generation (whose seed findings are empty and whose\n // rawTraceDistiller has not run yet) would always generate ZERO candidates.\n if (\n findings.length === 0 &&\n ctx.report === undefined &&\n !opts.generator.proposesWithoutFindings\n ) {\n return []\n }\n\n const surfaces: CodeSurface[] = []\n for (let i = 0; i < ctx.populationSize; i++) {\n if (ctx.signal.aborted) break\n const wt = await opts.worktree.create({\n baseRef,\n label: `${opts.generator.kind}-gen${ctx.generation}-cand${i}`,\n })\n // Once a worktree exists it MUST be accounted for: finalized into a\n // surface, or discarded. A throw from generate()/finalize() must not\n // leak the worktree + branch — discard best-effort, then rethrow loud.\n try {\n const { applied, summary } = await opts.generator.generate({\n worktreePath: wt.path,\n report: ctx.report,\n findings,\n dataset: ctx.dataset,\n maxShots: ctx.maxImprovementShots ?? 1,\n signal: ctx.signal,\n })\n if (!applied) {\n await opts.worktree.discard(wt)\n continue\n }\n surfaces.push(await opts.worktree.finalize(wt, summary))\n } catch (err) {\n // Best-effort cleanup; never mask the original failure.\n await opts.worktree.discard(wt).catch(() => {})\n throw err\n }\n }\n return surfaces\n },\n }\n}\n\n/** Phase-2 report carries `findings` when present; else fall back to the\n * loop's `ctx.findings`. The report is opaque to the substrate, so probe it\n * structurally. */\nfunction resolveFindings(ctx: ProposeContext<AnalystFinding>): AnalystFinding[] {\n const report = ctx.report\n if (report && typeof report === 'object' && 'findings' in report) {\n const f = (report as { findings: unknown }).findings\n if (Array.isArray(f) && f.length > 0) return f as AnalystFinding[]\n }\n return ctx.findings\n}\n","/**\n *\n * `rawTraceDistiller` — the meta-harness `analyzeGeneration` producer.\n *\n * The default `generationFailureDistiller` (in `improve.ts`) COMPRESSES each\n * generation's failing cells into ~400-char structured findings before the next\n * proposal round. That is the ACE-style recipe: a small summary is the proposer's\n * whole view of what went wrong. This producer does the opposite — the\n * meta-harness recipe (yoonholee.com/meta-harness): it does NOT summarize. It\n * points the coding-agent proposer at the generation's RAW run traces already on\n * disk under `runDir` — the durable per-cell `spans.jsonl` event logs,\n * `cached-result.json` scores, and any artifacts the substrate persisted — and\n * instructs the agent to `grep`/`cat`/`ls` them to diagnose the failures itself\n * (up to the harness's full context, ~millions of tokens, vs a ~400-char digest).\n *\n * It emits `AnalystFinding[]` so it drops into the SAME `opts.analyzeGeneration`\n * slot the default distiller uses, and renders through the same\n * `agenticGenerator` prompt path (`claim` + `recommended_action`). The findings\n * carry ABSOLUTE paths — the coding harness runs with `cwd` = a candidate\n * worktree, so a relative `runDir` would be uncattable from there.\n *\n * Runtime layout it reads (written by agent-eval's optimization loop):\n *\n * <runDir>/gen-<N>/ ← the generation dir (input.runDir)\n * candidate-<i>/ ← one candidate campaign (campaign.runDir)\n * <sanitized cellId>/ ← one scenario×rep cell\n * spans.jsonl ← the raw trace (event/span log)\n * cached-result.json ← the cell's score + artifact ref\n * <artifacts…> ← whatever the dispatch wrote\n *\n * @experimental\n */\n\nimport { type Dirent, existsSync, readdirSync } from 'node:fs'\nimport { basename, join, resolve } from 'node:path'\nimport { type AnalystFinding, makeFinding } from '@tangle-network/agent-eval'\nimport type { Scenario, SelfImproveOptions } from '@tangle-network/agent-eval/contract'\n\nconst ANALYST_ID = 'raw-trace-distiller'\n/** A cell counts as \"failing\" below this mean composite (matches the default\n * distiller's near-perfect threshold) or when it recorded an `error`. */\nconst PASS_THRESHOLD = 0.999\n\nexport interface RawTraceDistillerOptions {\n /** Anchor the emitted paths at this run root instead of the generation `runDir`\n * the loop passes in. Normally unset — each call points at that generation's\n * own directory (`input.runDir`). Pass an absolute path when you construct the\n * producer ahead of the loop and want a fixed anchor (e.g. a test fixture). */\n runDir?: string\n /** Max candidates to surface trace paths for, worst-scoring first. Default 12. */\n maxCandidates?: number\n /** Max failing cells to enumerate per candidate before collapsing the rest into\n * an \"ls the candidate dir\" pointer. Default 8. */\n maxCellsPerCandidate?: number\n /** Max concrete file paths to list per cell (the agent can always `ls` the dir\n * for the rest). Default 24. */\n maxFilesPerCell?: number\n /** Findings to fall back to when the generation had NO failing cells, so a\n * clean round never wipes the proposer's steering context. Mirrors the default\n * distiller's static-seed fallback. Default: a single instruction finding. */\n fallbackFindings?: unknown[]\n}\n\ninterface CellTrace {\n scenarioId: string\n composite: number\n error?: string\n cellDir: string\n files: string[]\n truncatedFiles: boolean\n}\n\n/**\n * Build an `analyzeGeneration` producer that feeds the proposer RAW-TRACE\n * FILESYSTEM CONTEXT — paths into the prior generation's real run traces plus a\n * grep/cat-to-diagnose instruction — instead of a pre-summarized digest.\n *\n * Drop-in for `opts.analyzeGeneration` on `improve()` / `selfImprove()`:\n *\n * await improve(profile, seedFindings, {\n * surface: 'code',\n * code: { repoRoot },\n * runDir: '/abs/run', // MUST be a real path — the traces live here\n * analyzeGeneration: rawTraceDistiller(),\n * scenarios, judge, agent,\n * })\n */\nexport function rawTraceDistiller<TScenario extends Scenario = Scenario, TArtifact = unknown>(\n options: RawTraceDistillerOptions = {},\n): NonNullable<SelfImproveOptions<TScenario, TArtifact>['analyzeGeneration']> {\n const maxCandidates = options.maxCandidates ?? 12\n const maxCellsPerCandidate = options.maxCellsPerCandidate ?? 8\n const maxFilesPerCell = options.maxFilesPerCell ?? 24\n\n return async (input) => {\n const genRoot = absoluteRunDir(options.runDir ?? input.runDir)\n const durable = isDurable(genRoot)\n\n // Rank candidates worst-first; the worst failures are the highest-signal\n // context for the next edit. Stable sort keeps equal-composite order.\n const ranked = [...input.candidates]\n .map((c) => ({\n surfaceHash: c.surfaceHash,\n composite: c.composite,\n campaignDir: absoluteRunDir(c.campaign.runDir),\n cells: failingCells(c.campaign, maxCellsPerCandidate, maxFilesPerCell),\n }))\n .sort((a, b) => a.composite - b.composite)\n .slice(0, maxCandidates)\n\n const totalFailingCells = ranked.reduce((n, c) => n + c.cells.length, 0)\n\n // A clean generation: keep the proposer's steering context rather than\n // wiping it (parity with the default distiller's static-seed fallback). An\n // EMPTY fallback array means there is no STATIC seed to preserve — it must NOT\n // wipe the context to nothing. Fall through to the default raw-trace\n // instruction so the meta-harness discipline stays live (the agent still\n // inspects the on-disk traces next round, and the finding's `raw-trace-context`\n // area keeps the agenticGenerator's diagnosis-evidence gate armed). A bare\n // `??` would return the empty array and silently disable both.\n if (totalFailingCells === 0) {\n if (options.fallbackFindings && options.fallbackFindings.length > 0) {\n return options.fallbackFindings\n }\n return [\n makeFinding({\n analyst_id: ANALYST_ID,\n severity: 'info',\n area: 'raw-trace-context',\n confidence: 1,\n claim: `Generation ${input.generation} had no failing cells. The full raw run traces are on disk under ${genRoot}.`,\n recommended_action: `To keep improving, grep/cat the raw traces under ${genRoot} (per-cell spans.jsonl + cached-result.json) to find the weakest passing runs, then make a targeted harness-code edit.`,\n evidence_refs: [{ kind: 'artifact', uri: genRoot }],\n metadata: { generation: input.generation, runDir: genRoot, failingCells: 0 },\n }),\n ]\n }\n\n const findings: AnalystFinding[] = []\n\n // 1. The meta-harness instruction: diagnose from the RAW traces, not a digest.\n findings.push(\n makeFinding({\n analyst_id: ANALYST_ID,\n severity: 'high',\n area: 'raw-trace-context',\n confidence: 1,\n claim: `Generation ${input.generation} produced ${totalFailingCells} failing/low-scoring cell(s) across ${ranked.length} candidate(s). Their FULL RAW run traces are on disk under ${genRoot} — the actual event logs (spans.jsonl), scores (cached-result.json), and artifacts, not a summary.${\n durable\n ? ''\n : ' (WARNING: this run root does not exist on disk — it looks like an in-memory run; pass a real runDir to improve() to get raw-trace context.)'\n }`,\n recommended_action: `Do NOT rely on a pre-summarized finding. Before editing, DIAGNOSE from the raw traces: run \\`grep\\`/\\`cat\\`/\\`ls\\` over the trace files and directories named in the following findings to see exactly what each failing run did and why it scored low, then make the smallest harness-code edit that fixes the dominant failure. Start with \\`grep -rIn \"error\" ${genRoot}\\` then \\`cat\\` the spans.jsonl of the worst cell.`,\n evidence_refs: [{ kind: 'artifact', uri: genRoot }],\n metadata: {\n generation: input.generation,\n runDir: genRoot,\n failingCells: totalFailingCells,\n candidates: ranked.length,\n },\n }),\n )\n\n // 2. One finding per failing candidate: its campaign dir + the concrete raw\n // trace files to grep/cat.\n for (const cand of ranked) {\n if (cand.cells.length === 0) continue\n const scenarioList = cand.cells.map((c) => c.scenarioId).join(', ')\n const fileLines = cand.cells\n .map((c) => {\n const header = ` cell ${c.scenarioId} (composite ${c.composite.toFixed(3)}${\n c.error ? `, error: ${truncate(c.error, 160)}` : ''\n }) — dir ${c.cellDir}`\n const files = c.files.map((f) => ` - ${f}`).join('\\n')\n const more = c.truncatedFiles ? `\\n - …(ls ${c.cellDir} for the rest)` : ''\n return c.files.length > 0 ? `${header}\\n${files}${more}` : header\n })\n .join('\\n')\n\n findings.push(\n makeFinding({\n analyst_id: ANALYST_ID,\n severity: cand.composite < 0.5 ? 'critical' : 'high',\n area: 'raw-trace-context',\n confidence: 1,\n subject: cand.surfaceHash,\n claim: `Candidate ${cand.surfaceHash} scored composite ${cand.composite.toFixed(3)} with ${cand.cells.length} failing cell(s) [${scenarioList}]. Its raw traces are under ${cand.campaignDir}.`,\n recommended_action: `grep/cat these raw trace files to diagnose WHY this candidate failed before editing:\\n${fileLines}\\nOr scan the whole candidate at once: \\`grep -rIn . ${cand.campaignDir}\\` and \\`ls -R ${cand.campaignDir}\\`.`,\n evidence_refs: [\n { kind: 'artifact', uri: cand.campaignDir },\n ...cand.cells.flatMap((c) =>\n c.files.map((f) => ({ kind: 'artifact' as const, uri: f })),\n ),\n ],\n metadata: {\n surfaceHash: cand.surfaceHash,\n composite: cand.composite,\n campaignDir: cand.campaignDir,\n cells: cand.cells.map((c) => ({\n scenarioId: c.scenarioId,\n composite: c.composite,\n cellDir: c.cellDir,\n files: c.files,\n ...(c.error ? { error: c.error } : {}),\n })),\n },\n }),\n )\n }\n\n return findings\n }\n}\n\n/** The failing cells of a candidate campaign, each with its on-disk trace files.\n * Mirrors the default distiller's per-cell composite (mean of judge composites,\n * 0 when a cell produced no judge score) and its failing predicate. */\nfunction failingCells(\n campaign: {\n runDir: string\n cells: ReadonlyArray<{\n cellId: string\n scenarioId: string\n error?: string\n judgeScores: Record<string, { composite?: number }>\n }>\n artifactsByPath?: Record<string, string>\n },\n maxCells: number,\n maxFiles: number,\n): CellTrace[] {\n const campaignDir = absoluteRunDir(campaign.runDir)\n const durable = isDurable(campaignDir)\n const out: CellTrace[] = []\n for (const cell of campaign.cells) {\n const scores = Object.values(cell.judgeScores ?? {})\n const composite =\n scores.length === 0\n ? 0\n : scores.reduce((sum, s) => sum + (s.composite ?? 0), 0) / scores.length\n if (!cell.error && composite >= PASS_THRESHOLD) continue\n\n const cellDir = join(campaignDir, sanitizeCellId(cell.cellId))\n const artifactPaths = artifactPathsForCell(campaign.artifactsByPath, cell.cellId)\n const discovered = durable ? listTraceFiles(cellDir) : []\n // Canonical anchors the substrate always writes, kept even when a mem:// run\n // never flushed them to disk (so the agent still learns the expected path).\n const canonical = [join(cellDir, 'spans.jsonl'), join(cellDir, 'cached-result.json')]\n const files = dedupeSorted([...discovered, ...artifactPaths, ...canonical])\n\n out.push({\n scenarioId: cell.scenarioId,\n composite: Number(composite.toFixed(3)),\n ...(cell.error ? { error: cell.error } : {}),\n cellDir,\n files: files.slice(0, maxFiles),\n truncatedFiles: files.length > maxFiles,\n })\n if (out.length >= maxCells) break\n }\n return out\n}\n\n/** Absolute paths of artifacts the campaign recorded for a cell. `artifactsByPath`\n * is keyed `${cellId}/${relPath}` → absolute path. */\nfunction artifactPathsForCell(\n artifactsByPath: Record<string, string> | undefined,\n cellId: string,\n): string[] {\n if (!artifactsByPath) return []\n const prefix = `${cellId}/`\n return Object.entries(artifactsByPath)\n .filter(([key]) => key.startsWith(prefix))\n .map(([, absPath]) => resolve(absPath))\n}\n\n/** Real files directly under `dir` and one level of sub-directories (artifacts\n * are sometimes nested). Absolute paths, sorted. `[]` when the dir is absent,\n * stale, unreadable, or contains symlinked dirs — trace context is advisory and\n * the canonical anchors below still tell the proposer where to inspect. */\nfunction listTraceFiles(dir: string): string[] {\n const out: string[] = []\n for (const entry of safeReadDir(dir)) {\n const full = join(dir, entry.name)\n if (entry.isFile()) {\n out.push(full)\n } else if (!entry.isSymbolicLink() && entry.isDirectory()) {\n for (const sub of safeReadDir(full)) {\n if (sub.isFile()) out.push(join(full, sub.name))\n }\n }\n }\n return out\n}\n\nfunction safeReadDir(dir: string): Dirent[] {\n try {\n return readdirSync(dir, { withFileTypes: true })\n } catch {\n return []\n }\n}\n\n/** Substrate cell-dir sanitization — must match agent-eval's\n * `cellId.replace(/[^a-zA-Z0-9_-]/g, '_')` so the computed dir matches disk. */\nfunction sanitizeCellId(cellId: string): string {\n return cellId.replace(/[^a-zA-Z0-9_-]/g, '_')\n}\n\n/** A run root is durable (has real files) when it is not an in-memory sentinel\n * and exists on disk. `mem://` runs keep everything in-process — no traces. */\nfunction isDurable(runDir: string): boolean {\n return !runDir.startsWith('mem://') && existsSync(runDir)\n}\n\n/** Resolve a run dir to absolute (the coding harness runs from a worktree cwd, so\n * relative paths are uncattable there). `mem://` sentinels pass through untouched. */\nfunction absoluteRunDir(runDir: string): string {\n return runDir.startsWith('mem://') ? runDir : resolve(runDir)\n}\n\nfunction dedupeSorted(paths: string[]): string[] {\n return [...new Set(paths)].sort((a, b) => {\n // Group by directory then filename for a stable, readable listing.\n const da = a.slice(0, a.length - basename(a).length)\n const db = b.slice(0, b.length - basename(b).length)\n return da === db ? basename(a).localeCompare(basename(b)) : da.localeCompare(db)\n })\n}\n\nfunction truncate(s: string, n: number): string {\n return s.length <= n ? s : `${s.slice(0, n - 1)}…`\n}\n","/**\n * `rolloutPolicyProposer` — the `'rollout-policy'` surface for `improve()`: the\n * inference-time `StructuralRolloutPolicy` dials { k, repairRounds, testgen } as a\n * held-out-gated optimizable surface.\n *\n * Why this seam: agent-eval's loop contract is already generic — `MutableSurface`\n * admits any string, documented as \"serialized tool config\" — so the policy rides\n * the SAME serialize→propose→gate→parse-back cycle the tools/mcp/hooks surfaces\n * use. No agent-eval changes; the only net-new piece is this proposer.\n *\n * Why deterministic: prompt-wording proposals are a measured zero on this stack,\n * and the policy space is tiny and fully enumerable. The proposer emits bounded\n * single-dial neighbors (k±2 in [1,10], repairRounds±1 in [0,3], testgen±3 in\n * [0,10], ≤4 per generation) and lets the held-out gate do ALL the deciding — an\n * LLM proposer would add cost and nondeterminism with nothing to reason about.\n *\n * Persistence: the policy lives in `profile.extensions['structural-rollout']`\n * (AgentProfile's designed slot for runtime-specific config). A gated winner is\n * written back there by `improve()`, the same profile-field write-back every other\n * config surface gets; `structuralRolloutPolicyFromProfile` is the read side a\n * runtime caller feeds to `structuralRollout({ policy })`.\n *\n * @experimental\n */\n\nimport type {\n MutableSurface,\n ProposeContext,\n ProposedCandidate,\n SurfaceProposer,\n} from '@tangle-network/agent-eval/campaign'\nimport type { AgentProfile } from '@tangle-network/agent-interface'\nimport {\n defaultStructuralRolloutPolicy,\n type StructuralRolloutPolicy,\n} from '../runtime/structural-rollout'\n\n/** The profile extensions namespace the policy persists under. */\nexport const ROLLOUT_POLICY_EXTENSION = 'structural-rollout'\n\n/** Proposal bounds per dial. These are the SEARCH bounds (what the proposer may\n * explore), chosen so every reachable value is a measured-sane recipe: k=1 is the\n * low-compute preset, testgen=0 disables check authoring, repairRounds caps where\n * the measured increment flattens (+1–3pp beyond round 2). */\nexport const ROLLOUT_POLICY_BOUNDS = {\n k: { min: 1, max: 10, step: 2 },\n repairRounds: { min: 0, max: 3, step: 1 },\n testgen: { min: 0, max: 10, step: 3 },\n} as const\n\n/** Max candidates per generation — the search space is 3 dials, so a small\n * neighborhood per generation converges without burning gate budget. */\nconst MAX_CANDIDATES_PER_GENERATION = 4\n\nconst clamp = (v: number, min: number, max: number) => Math.min(max, Math.max(min, v))\n\nconst isBoundedInt = (v: unknown, min: number): v is number =>\n typeof v === 'number' && Number.isInteger(v) && v >= min\n\n/** Parse a serialized policy surface. Defensive by design — the proposer reads\n * `ctx.currentSurface`, which the loop types as `string | CodeSurface`. Returns\n * `undefined` (never throws) for non-strings, malformed JSON, or a shape that\n * violates the policy's own invariants: the no-op signal. Unknown dials are\n * dropped; `diverse`/`temperature` ride through untouched (the proposer never\n * mutates them — `diverse` is a measured paired null). */\nexport function parseRolloutPolicy(surface: MutableSurface): StructuralRolloutPolicy | undefined {\n if (typeof surface !== 'string' || surface.trim().length === 0) return undefined\n let raw: unknown\n try {\n raw = JSON.parse(surface)\n } catch {\n return undefined\n }\n return normalizeRolloutPolicy(raw)\n}\n\n/** Normalize an untyped policy bag (a parsed surface or a profile extension) into\n * a full `StructuralRolloutPolicy`, defaults merged. Returns `undefined` when any\n * present dial violates the policy invariants (mirrors `resolvePolicy`: integer\n * k ≥ 1, repairRounds ≥ 0, testgen ≥ 0) — a corrupt config must read as \"not\n * configured\", never as a fabricated recipe. */\nexport function normalizeRolloutPolicy(raw: unknown): StructuralRolloutPolicy | undefined {\n if (typeof raw !== 'object' || raw === null || Array.isArray(raw)) return undefined\n const bag = raw as Record<string, unknown>\n const k = bag.k ?? defaultStructuralRolloutPolicy.k\n const repairRounds = bag.repairRounds ?? defaultStructuralRolloutPolicy.repairRounds\n const testgen = bag.testgen ?? defaultStructuralRolloutPolicy.testgen\n if (!isBoundedInt(k, 1) || !isBoundedInt(repairRounds, 0) || !isBoundedInt(testgen, 0)) {\n return undefined\n }\n return {\n k,\n repairRounds,\n testgen,\n ...(typeof bag.diverse === 'boolean' ? { diverse: bag.diverse } : {}),\n ...(typeof bag.temperature === 'number' ? { temperature: bag.temperature } : {}),\n }\n}\n\n/** Stable serialization — dial order is fixed so identical policies produce\n * identical surfaces (the loop dedupes/hashes candidates by surface content). */\nexport function serializeRolloutPolicy(policy: StructuralRolloutPolicy): string {\n return JSON.stringify({\n k: policy.k,\n repairRounds: policy.repairRounds,\n testgen: policy.testgen,\n ...(policy.diverse !== undefined ? { diverse: policy.diverse } : {}),\n ...(policy.temperature !== undefined ? { temperature: policy.temperature } : {}),\n })\n}\n\n/** Read the persisted policy off the profile. `undefined` when the profile does\n * not opt into structural rollout — the improve() surface no-ops then, because\n * tuning dials nothing consumes would ship dead config. */\nexport function structuralRolloutPolicyFromProfile(\n profile: AgentProfile,\n): StructuralRolloutPolicy | undefined {\n const bag = profile.extensions?.[ROLLOUT_POLICY_EXTENSION]\n if (bag === undefined) return undefined\n return normalizeRolloutPolicy(bag)\n}\n\n/** Persist a policy into the profile's extensions namespace. Shallow copy; never\n * mutates the input profile (the applyWinnerToProfile contract). */\nexport function applyRolloutPolicyToProfile(\n profile: AgentProfile,\n policy: StructuralRolloutPolicy,\n): AgentProfile {\n const bag: Record<string, unknown> = {\n k: policy.k,\n repairRounds: policy.repairRounds,\n testgen: policy.testgen,\n ...(policy.diverse !== undefined ? { diverse: policy.diverse } : {}),\n ...(policy.temperature !== undefined ? { temperature: policy.temperature } : {}),\n }\n return {\n ...profile,\n extensions: { ...profile.extensions, [ROLLOUT_POLICY_EXTENSION]: bag },\n }\n}\n\n/** All bounded single-dial neighbors of `policy`, in a fixed priority order: k\n * first (selection breadth carries 85–92% of the measured effect), then\n * repairRounds, then testgen. Steps clamp to the dial's bounds; clamped-to-no-op\n * and duplicate policies are dropped. */\nexport function enumerateNeighborPolicies(\n policy: StructuralRolloutPolicy,\n): StructuralRolloutPolicy[] {\n const moves: Array<{ dial: 'k' | 'repairRounds' | 'testgen'; delta: 1 | -1 }> = [\n { dial: 'k', delta: 1 },\n { dial: 'k', delta: -1 },\n { dial: 'repairRounds', delta: 1 },\n { dial: 'repairRounds', delta: -1 },\n { dial: 'testgen', delta: 1 },\n { dial: 'testgen', delta: -1 },\n ]\n const seen = new Set<string>([serializeRolloutPolicy(policy)])\n const neighbors: StructuralRolloutPolicy[] = []\n for (const move of moves) {\n const bounds = ROLLOUT_POLICY_BOUNDS[move.dial]\n const next = clamp(policy[move.dial] + move.delta * bounds.step, bounds.min, bounds.max)\n const candidate: StructuralRolloutPolicy = { ...policy, [move.dial]: next }\n const key = serializeRolloutPolicy(candidate)\n if (seen.has(key)) continue\n seen.add(key)\n neighbors.push(candidate)\n }\n return neighbors\n}\n\nfunction candidateLabel(base: StructuralRolloutPolicy, next: StructuralRolloutPolicy): string {\n for (const dial of ['k', 'repairRounds', 'testgen'] as const) {\n if (next[dial] !== base[dial]) return `${dial} ${base[dial]}→${next[dial]}`\n }\n return 'unchanged'\n}\n\n/**\n * The deterministic `SurfaceProposer` for the `'rollout-policy'` surface.\n *\n * Each generation: parse the current policy surface, enumerate its bounded\n * single-dial neighbors, and return at most `min(populationSize, 4)` of them,\n * rotating the enumeration window by generation so successive generations explore\n * different neighbors when nothing promoted. Proposes NOTHING when the surface\n * carries no policy (the profile never opted in) — an empty proposal is the\n * loop-native no-op, mirroring `improvementDriver`'s no-findings behavior.\n */\nexport function rolloutPolicyProposer(): SurfaceProposer {\n return {\n kind: 'rollout-policy',\n async propose(ctx: ProposeContext): Promise<ProposedCandidate[]> {\n const policy = parseRolloutPolicy(ctx.currentSurface)\n if (!policy) return []\n const neighbors = enumerateNeighborPolicies(policy)\n if (neighbors.length === 0) return []\n const cap = Math.max(1, Math.min(ctx.populationSize, MAX_CANDIDATES_PER_GENERATION))\n const start = (ctx.generation * cap) % neighbors.length\n const window: StructuralRolloutPolicy[] = []\n for (let i = 0; i < Math.min(cap, neighbors.length); i += 1) {\n window.push(neighbors[(start + i) % neighbors.length] as StructuralRolloutPolicy)\n }\n return window.map((candidate) => ({\n surface: serializeRolloutPolicy(candidate),\n label: candidateLabel(policy, candidate),\n rationale:\n 'bounded single-dial neighbor of the current structuralRollout policy; ' +\n 'the held-out gate decides (deterministic enumeration — the dial space is tiny ' +\n 'and prompt-style reflective proposals are a measured zero here)',\n }))\n },\n }\n}\n","/**\n *\n * `reflectiveGenerator` — the cheap, no-sandbox `CandidateGenerator`. It drafts\n * surface edits via the existing improvement adapter (`proposeFromFindings`,\n * one LLM patch per finding) and applies them as ONE coherent improvement into\n * the candidate worktree. `maxShots` is ignored — reflection is single-shot by\n * construction (the patches are already drafted).\n *\n * This is the `shots=1, sandbox=off` setting of the one improvement driver.\n * The `agenticGenerator` (a multi-shot verify-in-session loop) is the\n * `shots=N` setting — both plug into the same `improvementDriver`.\n *\n * @experimental\n */\n\nimport { spawnSync } from 'node:child_process'\nimport type { SurfaceImprovementEdit } from '../agent/improvement-adapter'\nimport type { ImprovementAdapter } from '../analyst-loop/types'\nimport type { CandidateGenerator } from './improvement-driver'\n\nexport interface ReflectiveGeneratorOptions {\n improvementAdapter: ImprovementAdapter<SurfaceImprovementEdit>\n}\n\n/** Cheap no-sandbox `CandidateGenerator` (the `shots=1` setting): draft surface edits via the improvement adapter and apply them as one coherent candidate. */\nexport function reflectiveGenerator(opts: ReflectiveGeneratorOptions): CandidateGenerator {\n return {\n kind: 'reflective',\n async generate({ worktreePath, findings }) {\n const batch = await opts.improvementAdapter.proposeFromFindings(findings)\n if (batch.edits.length === 0) return { applied: false, summary: '' }\n\n let applied = 0\n for (const edit of batch.edits) {\n if (applyPatch(edit.patch, worktreePath)) applied++\n }\n if (applied === 0) return { applied: false, summary: '' }\n\n const summary =\n batch.edits.length === 1\n ? batch.edits[0]!.summary\n : `analyst: ${applied} surface edit${applied === 1 ? '' : 's'}`\n return { applied: true, summary }\n },\n }\n}\n\n/** Mirror the improvement adapter's proven apply invocation, run inside the\n * candidate worktree (a fresh checkout of baseRef, so `-p0` paths match). */\nfunction applyPatch(patch: string, cwd: string): boolean {\n const result = spawnSync('git', ['apply', '--whitespace=fix', '-p0', '-'], {\n cwd,\n input: patch,\n encoding: 'utf-8',\n })\n return result.status === 0\n}\n","/**\n *\n * Pure readiness-decision helper. Maps a `KnowledgeReadinessReport` from\n * `@tangle-network/agent-eval` to a three-state branch (`ready` / `blocked` /\n * `caveat`) the runtime, route handlers, and UI shells can all switch on.\n *\n * Default `minimumScore` of 0.7 mirrors the readiness scoring scale in\n * agent-eval; callers tightening or loosening this should keep it consistent\n * across all entry points for the same product so the UI / metrics agree on\n * what \"caveat\" means.\n *\n * @stable\n */\n\nimport type { KnowledgeReadinessReport } from '@tangle-network/agent-eval'\n\nimport { ValidationError } from './errors'\nimport type { KnowledgeReadinessDecision } from './types'\n\nconst DEFAULT_MINIMUM_READINESS_SCORE = 0.7\n\n/**\n * Map a `KnowledgeReadinessReport` to a three-state branch (`ready` / `blocked` / `caveat`) the runtime, route handlers, and UI shells all switch on.\n *\n * @stable\n */\nexport function decideKnowledgeReadiness(\n report: KnowledgeReadinessReport,\n options: { minimumScore?: number } = {},\n): KnowledgeReadinessDecision {\n const minimumScore = options.minimumScore ?? DEFAULT_MINIMUM_READINESS_SCORE\n if (!Number.isFinite(minimumScore) || minimumScore < 0 || minimumScore > 1) {\n throw new ValidationError(\n `minimumScore must be a finite number in [0, 1]; received ${String(minimumScore)}`,\n )\n }\n const blockingGapIds = report.blockingMissingRequirements.map((requirement) => requirement.id)\n const nonBlockingGapIds = report.nonBlockingGaps.map((requirement) => requirement.id)\n if (blockingGapIds.length > 0) {\n return {\n passed: false,\n status: 'blocked',\n reason: report.reason,\n readinessScore: report.readinessScore,\n recommendedAction: report.recommendedAction,\n severity: report.severity,\n blockingGapIds,\n nonBlockingGapIds,\n }\n }\n if (report.readinessScore < minimumScore) {\n return {\n passed: false,\n status: 'caveat',\n reason: `Knowledge readiness score ${report.readinessScore.toFixed(3)} is below minimum ${minimumScore.toFixed(3)}.`,\n readinessScore: report.readinessScore,\n recommendedAction: report.recommendedAction,\n severity: report.severity,\n blockingGapIds,\n nonBlockingGapIds,\n }\n }\n return {\n passed: true,\n status: 'ready',\n reason: report.reason,\n readinessScore: report.readinessScore,\n recommendedAction: report.recommendedAction,\n severity: report.severity,\n blockingGapIds,\n nonBlockingGapIds,\n }\n}\n","/**\n * The product-facing backend selector for `runChatThroughRuntime` /\n * `runAgentTaskStream`: one call turns a `--backend {router,tcloud,cli-bridge,\n * sandbox}` choice into the `AgentExecutionBackend` the chat leg runs on.\n *\n * It is the `AgentExecutionBackend` sibling of `resolveSandboxClient` (which\n * resolves the `SandboxClient` a `runLoop` drives). Both exist for the same\n * reason: every in-process eval product hand-rolled the identical\n * \"`backend-name` → `createOpenAICompatibleBackend`\" branch, and the copies\n * drift. This is the single generic resolver they share.\n *\n * - `router` / `tcloud` / `cli-bridge` → OpenAI-compatible chat completions.\n * All three speak `POST {baseUrl}/chat/completions` in OpenAI's SSE shape —\n * the router (a.k.a. tcloud) IS that endpoint, and cli-bridge fronts a\n * harness CLI behind the same protocol at its own `/v1`. They differ only\n * in `baseUrl` / `apiKey` and the `kind` label a product wants on its\n * traces. cli-bridge REQUIRES `model` in the request body, so it MUST route\n * through `createOpenAICompatibleBackend` (which sends it), never a\n * transport that drops the field.\n * - `sandbox` → the caller's own domain backend. The sandbox variant carries\n * product specifics (system prompt, workspace id, in-box D1 executor) that\n * do NOT belong in the substrate, so the product passes a `sandboxBackend()`\n * seam that this resolver simply invokes.\n *\n * This resolver is PURE backend selection. Product concerns — credit hard-cuts,\n * fetch-capture shims, D1 platform wiring — stay as product-side WRAPPERS\n * around the returned backend. The OpenAI-compat passthrough fields (`tools`,\n * `toolChoice`, `responseFormat`, `temperature`, `maxTokens`, `fetchImpl`,\n * `retry`) are forwarded verbatim so a product can advertise its app tools,\n * preserve generation settings, or install a capturing fetch without\n * re-opening the branch this consolidation closes.\n */\n\nimport { createOpenAICompatibleBackend } from './backends'\nimport type { AgentBackendInput, AgentExecutionBackend } from './types'\n\n/** The transport a chat backend runs on. */\nexport type AgentBackendKind = 'router' | 'tcloud' | 'cli-bridge' | 'sandbox'\n\n/**\n * OpenAI-compat passthrough forwarded to `createOpenAICompatibleBackend` for\n * the `router` / `tcloud` / `cli-bridge` kinds. Mirrors that factory's optional\n * inputs so a product keeps its tool advertising / capture-fetch without\n * re-implementing the backend branch.\n */\ntype OpenAICompatPassthrough = Pick<\n Parameters<typeof createOpenAICompatibleBackend>[0],\n 'tools' | 'toolChoice' | 'responseFormat' | 'temperature' | 'maxTokens' | 'fetchImpl' | 'retry'\n>\n\nexport interface ResolveAgentBackendOptions<TInput extends AgentBackendInput = AgentBackendInput>\n extends OpenAICompatPassthrough {\n /** The chat transport to resolve. */\n kind: AgentBackendKind\n /**\n * Bearer credential for the OpenAI-compat kinds. Empty string is valid for a\n * loopback-anonymous cli-bridge; a `router`/`tcloud` route with an empty key\n * is a caller bug the product surfaces before calling in.\n */\n apiKey: string\n /** Base URL for the OpenAI-compat kinds. cli-bridge's is its `/v1`. */\n baseUrl: string\n /** Model id sent on every request. cli-bridge rejects a request without it. */\n model: string\n /** `kind` label stamped on the resolved backend + its traces. Defaults to `kind`. */\n label?: string\n /**\n * `sandbox` kind: the product's own domain backend. Required for that kind —\n * the substrate owns no product sandbox shape, so a `sandbox` resolution with\n * no seam is a caller bug, not a silent fallback.\n */\n sandboxBackend?: () => AgentExecutionBackend<TInput>\n}\n\n/**\n * Resolve the `AgentExecutionBackend` for the chosen `kind`. Reuse this instead\n * of hand-rolling the `createOpenAICompatibleBackend` branch in each product.\n */\nexport function resolveAgentBackend<TInput extends AgentBackendInput = AgentBackendInput>(\n opts: ResolveAgentBackendOptions<TInput>,\n): AgentExecutionBackend<TInput> {\n switch (opts.kind) {\n case 'router':\n case 'tcloud':\n case 'cli-bridge': {\n const passthrough: OpenAICompatPassthrough = {}\n // Forward only the fields a caller actually set — an explicit\n // `tools: []` / `undefined` would otherwise reach the factory and change\n // its request shape (some providers reject an empty `tools` array).\n if (opts.tools !== undefined) passthrough.tools = opts.tools\n if (opts.toolChoice !== undefined) passthrough.toolChoice = opts.toolChoice\n if (opts.responseFormat !== undefined) passthrough.responseFormat = opts.responseFormat\n if (opts.temperature !== undefined) passthrough.temperature = opts.temperature\n if (opts.maxTokens !== undefined) passthrough.maxTokens = opts.maxTokens\n if (opts.fetchImpl !== undefined) passthrough.fetchImpl = opts.fetchImpl\n if (opts.retry !== undefined) passthrough.retry = opts.retry\n return createOpenAICompatibleBackend<TInput>({\n apiKey: opts.apiKey,\n baseUrl: opts.baseUrl,\n model: opts.model,\n kind: opts.label ?? opts.kind,\n ...passthrough,\n })\n }\n case 'sandbox': {\n if (!opts.sandboxBackend) {\n throw new Error(\"resolveAgentBackend: kind 'sandbox' requires opts.sandboxBackend\")\n }\n return opts.sandboxBackend()\n }\n }\n}\n","/**\n *\n * The two top-level entry points:\n *\n * - `runAgentTask` — single-shot lifecycle for adapter-driven tasks.\n * - `runAgentTaskStream` — streaming lifecycle that delegates execution to an\n * `AgentExecutionBackend` (model API, sandbox, or custom iterable).\n *\n * Both gate the run on `KnowledgeReadinessReport` from `agent-eval`, emit the\n * same lifecycle event vocabulary (under different shapes — see `types.ts`),\n * and route session lifecycle through a pluggable `RuntimeSessionStore`.\n *\n * @stable\n */\n\nimport {\n acquisitionPlansForKnowledgeGaps,\n blockingKnowledgeEval,\n type ControlContext,\n type ControlEvalResult,\n type ControlRunResult,\n type DataAcquisitionPlan,\n FAILURE_CLASSES,\n type FailureClass,\n type KnowledgeReadinessReport,\n type RunRecord,\n runAgentControlLoop,\n scoreKnowledgeReadiness,\n type UserQuestion,\n userQuestionsForKnowledgeGaps,\n} from '@tangle-network/agent-eval'\n\nconst FAILURE_CLASS_SET = new Set<string>(FAILURE_CLASSES)\n\n/** True when a free-form control failure string is a canonical taxonomy\n * class — so only real taxonomy tags are promoted to the cross-agent\n * `RunRecord.failureClass` key; novel strings stay as `failureMode` detail. */\nfunction asFailureClass(value: string | undefined): FailureClass | undefined {\n return value && FAILURE_CLASS_SET.has(value) ? (value as FailureClass) : undefined\n}\n\n/** Stamp cross-cutting defaults onto adapter-projected RunRecords without\n * overriding anything the adapter set explicitly:\n * - `scenarioId` — the run's scenario, when the record omits one.\n * - `failureClass` — the control layer's failure classification promoted\n * onto the canonical cross-agent key, but ONLY when it's a real taxonomy\n * class. This is what lets the substrate aggregate failures across every\n * agent in one vocabulary instead of per-agent ad-hoc strings. */\nexport function applyRunRecordDefaults(\n records: RunRecord[],\n scenarioId: string,\n controlFailureClass: string | undefined,\n): RunRecord[] {\n const fc = asFailureClass(controlFailureClass)\n return records.map((record) => {\n let r = record\n if (r.scenarioId === undefined) r = { ...r, scenarioId }\n if (r.failureClass === undefined && fc) r = { ...r, failureClass: fc }\n return r\n })\n}\n\nimport { normalizeBackendStreamEvent } from './backends'\nimport { BackendTransportError, SessionMismatchError } from './errors'\nimport { decideKnowledgeReadiness } from './readiness'\nimport { newRuntimeSession, nowIso, touchSession } from './sessions'\nimport type {\n AgentBackendInput,\n AgentExecutionBackend,\n AgentKnowledgeProvider,\n AgentRuntimeEventSink,\n AgentTaskContext,\n AgentTaskRunResult,\n AgentTaskSpec,\n AgentTaskStatus,\n BackendErrorDetail,\n RunAgentTaskOptions,\n RunAgentTaskStreamOptions,\n RuntimeSession,\n RuntimeStreamEvent,\n} from './types'\n\n/**\n * Single-shot task lifecycle for adapter-driven tasks: readiness-gated, emits the runtime lifecycle event vocabulary, session-store pluggable.\n *\n * @stable\n */\nexport async function runAgentTask<\n TState,\n TAction,\n TActionResult,\n TEval extends ControlEvalResult = ControlEvalResult,\n>(\n options: RunAgentTaskOptions<TState, TAction, TActionResult, TEval>,\n): Promise<AgentTaskRunResult<TState, TAction, TActionResult, TEval>> {\n const task = options.task\n await emit(options.onEvent, { type: 'task_start', task })\n await emit(options.onEvent, { type: 'readiness_start', task })\n let knowledge = await buildReadiness(task, options.knowledge)\n await emit(options.onEvent, { type: 'readiness_end', task, knowledge })\n const questions = userQuestionsForKnowledgeGaps(knowledge.blockingMissingRequirements)\n const acquisitionPlans = acquisitionPlansForKnowledgeGaps([\n ...knowledge.blockingMissingRequirements,\n ...knowledge.nonBlockingGaps,\n ])\n const preflight = await runKnowledgePreflight(\n task,\n questions,\n acquisitionPlans,\n options.knowledge,\n options.onEvent,\n )\n if (\n options.knowledge?.refreshReadiness &&\n (Object.keys(preflight.userAnswers).length > 0 || preflight.acquiredEvidenceIds.length > 0)\n ) {\n await emit(options.onEvent, { type: 'readiness_start', task })\n knowledge = await options.knowledge.refreshReadiness({\n task,\n previous: knowledge,\n userAnswers: preflight.userAnswers,\n acquiredEvidenceIds: preflight.acquiredEvidenceIds,\n })\n await emit(options.onEvent, { type: 'readiness_end', task, knowledge })\n }\n\n await emit(options.onEvent, { type: 'control_start', task, knowledge })\n const scenarioId = options.scenarioId ?? task.id\n const control = await runAgentControlLoop<TState, TAction, TActionResult, TEval>({\n intent: task.intent,\n budget: task.budget,\n signal: options.signal,\n store: options.store,\n scenarioId,\n projectId: options.projectId,\n variantId: options.variantId,\n observe: ({ history, abortSignal }) =>\n options.adapter.observe({ task, knowledge, history, abortSignal }),\n validate: async ({ state, history, abortSignal }) => {\n const readinessEval = blockingKnowledgeEval(knowledge, {\n minimumScore: options.minimumReadinessScore,\n })\n const evals = await options.adapter.validate({\n task,\n knowledge,\n state,\n history,\n abortSignal,\n })\n return [readinessEval as TEval, ...evals]\n },\n decide: (ctx) => {\n if (isKnowledgeBlocked(ctx.evals)) {\n return (\n options.adapter.onKnowledgeBlocked?.({\n task,\n knowledge,\n questions,\n acquisitionPlans,\n }) ?? {\n type: 'stop',\n pass: false,\n score: knowledge.readinessScore,\n reason: `knowledge readiness blocked: ${knowledge.reason}`,\n }\n )\n }\n return options.adapter.decide(toAgentContext(task, knowledge, ctx))\n },\n act: (action, ctx) => options.adapter.act(action, toAgentContext(task, knowledge, ctx)),\n shouldStop: options.adapter.shouldStop\n ? (ctx) => options.adapter.shouldStop!(toAgentContext(task, knowledge, ctx))\n : undefined,\n getActionCostUsd: options.adapter.getActionCostUsd\n ? ({ action, result, state, evals, history }) =>\n options.adapter.getActionCostUsd!({ action, result, task, state, evals, history })\n : undefined,\n onStep: (step) => emit(options.onEvent, { type: 'control_step', task, step }),\n })\n await emit(options.onEvent, { type: 'control_end', task, control })\n const status = statusFromControl(control)\n await emit(options.onEvent, { type: 'task_end', task, status, reason: control.reason })\n\n return {\n task,\n status,\n knowledge,\n questions,\n acquisitionPlans,\n userAnswers: preflight.userAnswers,\n acquiredEvidenceIds: preflight.acquiredEvidenceIds,\n control,\n runRecords: applyRunRecordDefaults(\n options.adapter.projectRunRecords?.(control, task) ?? [],\n scenarioId,\n control.failureClass,\n ),\n }\n}\n\n/**\n * Streaming task lifecycle: delegates execution to an `AgentExecutionBackend` (model API, sandbox, or custom iterable) and yields lifecycle events as they happen.\n *\n * @stable\n */\nexport async function* runAgentTaskStream<TInput extends AgentBackendInput = AgentBackendInput>(\n options: RunAgentTaskStreamOptions<TInput>,\n): AsyncIterable<RuntimeStreamEvent> {\n const task = options.task\n const input = { task, ...(options.input ?? {}) } as TInput\n yield streamEvent({ type: 'task_start', task })\n\n yield streamEvent({ type: 'readiness_start', task })\n let knowledge = await buildReadiness(task, options.knowledge)\n const questions = userQuestionsForKnowledgeGaps(knowledge.blockingMissingRequirements)\n const acquisitionPlans = acquisitionPlansForKnowledgeGaps([\n ...knowledge.blockingMissingRequirements,\n ...knowledge.nonBlockingGaps,\n ])\n const preflight = await runKnowledgePreflightStream(\n task,\n questions,\n acquisitionPlans,\n options.knowledge,\n )\n for (const event of preflight.events) yield event\n if (\n options.knowledge?.refreshReadiness &&\n (Object.keys(preflight.userAnswers).length > 0 || preflight.acquiredEvidenceIds.length > 0)\n ) {\n yield streamEvent({ type: 'readiness_start', task })\n knowledge = await options.knowledge.refreshReadiness({\n task,\n previous: knowledge,\n userAnswers: preflight.userAnswers,\n acquiredEvidenceIds: preflight.acquiredEvidenceIds,\n })\n }\n const decision = decideKnowledgeReadiness(knowledge, {\n minimumScore: options.minimumReadinessScore,\n })\n yield streamEvent({ type: 'readiness_end', task, knowledge, decision })\n if (!decision.passed && decision.status === 'blocked') {\n const reason = `knowledge readiness blocked: ${decision.reason}`\n yield streamEvent({ type: 'task_end', task, status: 'blocked', reason })\n yield streamEvent({ type: 'final', task, status: 'blocked', reason })\n return\n }\n\n const store = options.sessionStore\n const existing = options.sessionId ? await store?.get(options.sessionId) : undefined\n const shouldResume = Boolean(options.resume && existing)\n let session =\n shouldResume && existing\n ? await resumeBackendSession(options.backend, existing, input, {\n task,\n knowledge,\n signal: options.signal,\n })\n : await startBackendSession(\n options.backend,\n input,\n { task, knowledge, signal: options.signal },\n options.sessionId,\n )\n await store?.put(session)\n const sessionEvent = streamEvent({\n type: shouldResume ? 'session_resumed' : 'session_created',\n task,\n session,\n })\n await store?.appendEvent?.(session.id, sessionEvent)\n yield sessionEvent\n\n const backendStart = streamEvent({\n type: 'backend_start',\n task,\n session,\n backend: options.backend.kind,\n })\n await store?.appendEvent?.(session.id, backendStart)\n yield backendStart\n\n let finalText = ''\n try {\n for await (const rawEvent of options.backend.stream(input, {\n task,\n knowledge,\n session,\n signal: options.signal,\n })) {\n const event = normalizeBackendStreamEvent(rawEvent, task, session)\n if (event.type === 'text_delta') finalText += event.text\n await store?.appendEvent?.(session.id, event)\n yield event\n }\n const completedStatus: AgentTaskStatus = 'completed'\n session = touchSession({ ...session, status: completedStatus })\n await store?.put(session)\n const backendEnd = streamEvent({\n type: 'backend_end',\n task,\n session,\n backend: options.backend.kind,\n })\n await store?.appendEvent?.(session.id, backendEnd)\n yield backendEnd\n const reason = 'backend completed'\n const taskEnd = streamEvent({ type: 'task_end', task, status: completedStatus, reason })\n await store?.appendEvent?.(session.id, taskEnd)\n yield taskEnd\n const final = streamEvent({\n type: 'final',\n task,\n session,\n status: completedStatus,\n reason,\n text: finalText || undefined,\n })\n await store?.appendEvent?.(session.id, final)\n yield final\n } catch (err) {\n const message = err instanceof Error ? err.message : String(err)\n session = touchSession({ ...session, status: options.signal?.aborted ? 'aborted' : 'failed' })\n await store?.put(session)\n let stopErrorMessage: string | undefined\n try {\n await options.backend.stop?.(session, message)\n } catch (stopErr) {\n stopErrorMessage = stopErr instanceof Error ? stopErr.message : String(stopErr)\n }\n const combinedMessage = stopErrorMessage\n ? `${message}; backend stop failed: ${stopErrorMessage}`\n : message\n // Typed transport detail — preserves status code + truncated body so\n // consumers can map onto `RunRecord.error` without re-parsing the log\n // string. Required by the runtime's fail-loud contract: silent empty\n // output for a 402 / 401 / 5xx hides the real failure mode.\n const errorDetail: BackendErrorDetail =\n err instanceof BackendTransportError\n ? {\n kind: 'transport',\n message: combinedMessage,\n status: err.status,\n body: err.body,\n }\n : { kind: 'backend', message: combinedMessage }\n const backendError = streamEvent({\n type: 'backend_error',\n task,\n session,\n backend: options.backend.kind,\n message: combinedMessage,\n recoverable: !options.signal?.aborted,\n error: errorDetail,\n })\n await store?.appendEvent?.(session.id, backendError)\n yield backendError\n const status: AgentTaskStatus = options.signal?.aborted ? 'aborted' : 'failed'\n const taskEnd = streamEvent({ type: 'task_end', task, status, reason: message })\n await store?.appendEvent?.(session.id, taskEnd)\n yield taskEnd\n const final = streamEvent({\n type: 'final',\n task,\n session,\n status,\n reason: message,\n text: finalText || undefined,\n error: errorDetail,\n })\n await store?.appendEvent?.(session.id, final)\n yield final\n }\n}\n\nasync function runKnowledgePreflight<\n TState,\n TAction,\n TActionResult,\n TEval extends ControlEvalResult,\n>(\n task: AgentTaskSpec,\n questions: UserQuestion[],\n acquisitionPlans: DataAcquisitionPlan[],\n provider: AgentKnowledgeProvider | undefined,\n onEvent: AgentRuntimeEventSink<TState, TAction, TActionResult, TEval> | undefined,\n): Promise<{ userAnswers: Record<string, string>; acquiredEvidenceIds: string[] }> {\n let userAnswers: Record<string, string> = {}\n let acquiredEvidenceIds: string[] = []\n if (questions.length > 0 && provider?.answerQuestions) {\n await emit(onEvent, { type: 'questions_start', task, questions })\n userAnswers = await provider.answerQuestions(questions, task)\n await emit(onEvent, { type: 'questions_end', task, questions, userAnswers })\n }\n if (acquisitionPlans.length > 0 && provider?.executeAcquisitionPlans) {\n await emit(onEvent, { type: 'acquisition_start', task, acquisitionPlans })\n acquiredEvidenceIds = await provider.executeAcquisitionPlans(acquisitionPlans, task)\n await emit(onEvent, {\n type: 'acquisition_end',\n task,\n acquisitionPlans,\n acquiredEvidenceIds,\n })\n }\n return { userAnswers, acquiredEvidenceIds }\n}\n\nasync function runKnowledgePreflightStream(\n task: AgentTaskSpec,\n questions: UserQuestion[],\n acquisitionPlans: DataAcquisitionPlan[],\n provider: AgentKnowledgeProvider | undefined,\n): Promise<{\n userAnswers: Record<string, string>\n acquiredEvidenceIds: string[]\n events: RuntimeStreamEvent[]\n}> {\n const events: RuntimeStreamEvent[] = []\n let userAnswers: Record<string, string> = {}\n let acquiredEvidenceIds: string[] = []\n if (questions.length > 0 && provider?.answerQuestions) {\n events.push(streamEvent({ type: 'questions_start', task, questions }))\n userAnswers = await provider.answerQuestions(questions, task)\n events.push(streamEvent({ type: 'questions_end', task, questions, userAnswers }))\n }\n if (acquisitionPlans.length > 0 && provider?.executeAcquisitionPlans) {\n events.push(streamEvent({ type: 'acquisition_start', task, acquisitionPlans }))\n acquiredEvidenceIds = await provider.executeAcquisitionPlans(acquisitionPlans, task)\n events.push(\n streamEvent({ type: 'acquisition_end', task, acquisitionPlans, acquiredEvidenceIds }),\n )\n }\n return { userAnswers, acquiredEvidenceIds, events }\n}\n\nfunction streamEvent<T extends Omit<RuntimeStreamEvent, 'timestamp'>>(\n event: T,\n): T & { timestamp: string } {\n return { ...event, timestamp: nowIso() }\n}\n\nasync function startBackendSession<TInput extends AgentBackendInput>(\n backend: AgentExecutionBackend<TInput>,\n input: TInput,\n context: { task: AgentTaskSpec; knowledge: KnowledgeReadinessReport; signal?: AbortSignal },\n requestedSessionId?: string,\n): Promise<RuntimeSession> {\n if (backend.start) return backend.start(input, { ...context, requestedSessionId })\n return newRuntimeSession(backend.kind, requestedSessionId)\n}\n\nasync function resumeBackendSession<TInput extends AgentBackendInput>(\n backend: AgentExecutionBackend<TInput>,\n session: RuntimeSession,\n input: TInput,\n context: { task: AgentTaskSpec; knowledge: KnowledgeReadinessReport; signal?: AbortSignal },\n): Promise<RuntimeSession> {\n if (session.backend !== backend.kind) {\n throw new SessionMismatchError(session.backend, backend.kind)\n }\n if (backend.resume) return backend.resume(session, input, context)\n return touchSession({ ...session, status: 'active' })\n}\n\nfunction buildReadiness(\n task: AgentTaskSpec,\n provider: AgentKnowledgeProvider | undefined,\n): Promise<KnowledgeReadinessReport> | KnowledgeReadinessReport {\n if (provider?.buildReadiness) return provider.buildReadiness(task)\n return scoreKnowledgeReadiness({\n taskId: task.id,\n requirements: task.requiredKnowledge ?? [],\n metadata: { domain: task.domain, ...task.metadata },\n })\n}\n\nfunction isKnowledgeBlocked(evals: ControlEvalResult[]): boolean {\n return evals.some((evalResult) => evalResult.id === 'knowledge-ready' && !evalResult.passed)\n}\n\nfunction statusFromControl(\n control: ControlRunResult<unknown, unknown, unknown, ControlEvalResult>,\n): AgentTaskStatus {\n if (control.stoppedBy === 'abort') return 'aborted'\n if (control.reason.includes('knowledge readiness blocked')) return 'blocked'\n if (control.pass) return 'completed'\n return 'failed'\n}\n\nasync function emit<TState, TAction, TActionResult, TEval extends ControlEvalResult>(\n sink: AgentRuntimeEventSink<TState, TAction, TActionResult, TEval> | undefined,\n event: Parameters<AgentRuntimeEventSink<TState, TAction, TActionResult, TEval>>[0],\n): Promise<void> {\n await sink?.(event)\n}\n\nfunction toAgentContext<TState, TAction, TActionResult, TEval extends ControlEvalResult>(\n task: AgentTaskSpec,\n knowledge: KnowledgeReadinessReport,\n ctx: ControlContext<TState, TAction, TActionResult, TEval>,\n): AgentTaskContext<TState, TAction, TActionResult, TEval> {\n return {\n task,\n knowledge,\n state: ctx.state,\n evals: ctx.evals,\n history: ctx.history,\n budget: ctx.budget,\n stepIndex: ctx.stepIndex,\n wallMs: ctx.wallMs,\n spentCostUsd: ctx.spentCostUsd,\n remainingCostUsd: ctx.remainingCostUsd,\n abortSignal: ctx.abortSignal,\n }\n}\n","/**\n *\n * Production-run lifecycle: record what the agent did on behalf of a customer,\n * what it cost, and how it ended.\n *\n * Three concerns live in this module:\n *\n * 1. **Lifecycle state machine** — `running` -> `completed | failed | cancelled`,\n * enforced by `RuntimeRunStateError`. Completion is idempotent for the same\n * status (a second `complete()` call is a no-op so retries / cleanup paths\n * don't double-fire side effects). A different terminal status is a state\n * error.\n *\n * 2. **Cost ledger** — every `llm_call` event the handle observes contributes\n * `tokensIn`, `tokensOut`, `costUsd`, and bumps `llmCalls`. Wall time is\n * measured from `startRuntimeRun()` to `complete()`. Surface via\n * `handle.cost()` for cost-per-task dashboards.\n *\n * 3. **Persistence adapter** — `RuntimeRunPersistenceAdapter` is the seam\n * consumers plug in to write a `RuntimeRunRow` to their D1 / postgres /\n * KV store. The adapter receives a sanitized row shape; no telemetry\n * payload bytes flow through it unless the consumer opts in via\n * `RuntimeRunOptions.telemetryEvents`.\n *\n * @stable\n */\n\nimport { RuntimeRunStateError, ValidationError } from './errors'\nimport type { AgentTaskSpec, RuntimeStreamEvent } from './types'\n\n/** @stable */\nexport type RuntimeRunStatus = 'running' | 'completed' | 'failed' | 'cancelled'\n\n/** @stable */\nexport interface RuntimeRunCost {\n /** Cumulative input tokens across every observed `llm_call` event. */\n tokensIn: number\n /** Cumulative output tokens across every observed `llm_call` event. */\n tokensOut: number\n /** Sum of `costUsd` from every observed `llm_call` event. */\n costUsd: number\n /** Wall time from `startRuntimeRun()` to `complete()` (or `now()` if not yet completed). */\n wallMs: number\n /** Count of `llm_call` events observed during the run. */\n llmCalls: number\n}\n\n/** @stable */\nexport interface RuntimeRunCompleteInput {\n status: Exclude<RuntimeRunStatus, 'running'>\n resultSummary?: string\n /** Optional explicit cost override; if omitted, the accumulated ledger is used. */\n cost?: Partial<RuntimeRunCost>\n /** Stable error message when `status === 'failed'`. */\n error?: string\n /** Additional adapter-specific fields merged into the persisted row. */\n metadata?: Record<string, unknown>\n}\n\n/** @stable */\nexport interface RuntimeRunRow {\n /** Stable runtime-side identifier. Adapters may translate to their own primary key. */\n id: string\n workspaceId: string\n sessionId?: string\n agentId?: string\n domain?: string\n taskId: string\n scenarioId?: string\n status: RuntimeRunStatus\n resultSummary?: string\n error?: string\n cost: RuntimeRunCost\n startedAt: string\n completedAt?: string\n metadata?: Record<string, unknown>\n}\n\n/** @stable */\nexport interface RuntimeRunPersistenceAdapter {\n /**\n * Called once when `handle.persist()` runs. Implementations write `row` to\n * their durable store (D1, postgres, KV) and return whatever the consumer\n * wants the caller to see (often the storage-side row id). Errors thrown\n * here propagate out of `persist()` so the caller can decide whether to\n * retry or log-and-continue.\n */\n upsert(row: RuntimeRunRow): Promise<void> | void\n}\n\n/** @stable */\nexport interface RuntimeRunOptions {\n workspaceId: string\n sessionId?: string\n agentId?: string\n taskSpec: AgentTaskSpec\n scenarioId?: string\n /** Optional persistence adapter; if omitted, `persist()` is a no-op. */\n adapter?: RuntimeRunPersistenceAdapter\n /** Override the row id; default = `${taskSpec.id}:${random suffix}`. */\n id?: string\n /** Override the clock; default = `Date.now()`. Useful for deterministic tests. */\n now?: () => number\n}\n\n/** @stable */\nexport interface RuntimeRunHandle {\n /** Stable id assigned at start. */\n readonly id: string\n readonly workspaceId: string\n readonly sessionId: string | undefined\n readonly taskSpec: AgentTaskSpec\n readonly status: RuntimeRunStatus\n\n /**\n * Observe a single `RuntimeStreamEvent`. The handle ignores non-cost events\n * (text deltas, tool calls) silently so consumers can pipe the whole stream\n * through `handle.observe`. `llm_call` events update the ledger.\n */\n observe(event: RuntimeStreamEvent): void\n\n /** Snapshot of the current cost ledger. Safe to call at any time. */\n cost(): RuntimeRunCost\n\n /**\n * Transition to a terminal state. Idempotent for the same status; throws\n * `RuntimeRunStateError` for a different terminal status (state machines\n * don't time-travel).\n */\n complete(input: RuntimeRunCompleteInput): void\n\n /** Build the current row without writing it. Useful for tests + dry runs. */\n toRow(metadata?: Record<string, unknown>): RuntimeRunRow\n\n /**\n * Persist the current row via the configured adapter. Must be called after\n * `complete()`. Idempotent for the same terminal state (the adapter sees\n * the same row on retry).\n */\n persist(metadata?: Record<string, unknown>): Promise<void>\n}\n\n/**\n *\n * Construct a runtime-run handle. The returned handle is mutable across its\n * lifetime; consumers should not share it across requests.\n *\n * @stable\n */\nexport function startRuntimeRun(options: RuntimeRunOptions): RuntimeRunHandle {\n if (!options.workspaceId) {\n throw new ValidationError('startRuntimeRun: workspaceId is required')\n }\n if (!options.taskSpec?.id) {\n throw new ValidationError('startRuntimeRun: taskSpec.id is required')\n }\n const now = options.now ?? Date.now\n const startedAtMs = now()\n const startedAt = new Date(startedAtMs).toISOString()\n const id = options.id ?? `${options.taskSpec.id}:${randomSuffix()}`\n\n let status: RuntimeRunStatus = 'running'\n let completedAtMs: number | undefined\n let resultSummary: string | undefined\n let error: string | undefined\n let completionMetadata: Record<string, unknown> | undefined\n\n const ledger: RuntimeRunCost = {\n tokensIn: 0,\n tokensOut: 0,\n costUsd: 0,\n wallMs: 0,\n llmCalls: 0,\n }\n\n const snapshotCost = (): RuntimeRunCost => ({\n tokensIn: ledger.tokensIn,\n tokensOut: ledger.tokensOut,\n costUsd: ledger.costUsd,\n wallMs: (completedAtMs ?? now()) - startedAtMs,\n llmCalls: ledger.llmCalls,\n })\n\n const buildRow = (extraMetadata?: Record<string, unknown>): RuntimeRunRow => ({\n id,\n workspaceId: options.workspaceId,\n sessionId: options.sessionId,\n agentId: options.agentId,\n domain: options.taskSpec.domain,\n taskId: options.taskSpec.id,\n scenarioId: options.scenarioId,\n status,\n resultSummary,\n error,\n cost: snapshotCost(),\n startedAt,\n completedAt: completedAtMs !== undefined ? new Date(completedAtMs).toISOString() : undefined,\n metadata: mergeMetadata(completionMetadata, extraMetadata),\n })\n\n return {\n id,\n workspaceId: options.workspaceId,\n sessionId: options.sessionId,\n taskSpec: options.taskSpec,\n get status() {\n return status\n },\n observe(event) {\n if (event.type !== 'llm_call') return\n ledger.llmCalls += 1\n if (typeof event.tokensIn === 'number' && Number.isFinite(event.tokensIn)) {\n ledger.tokensIn += event.tokensIn\n }\n if (typeof event.tokensOut === 'number' && Number.isFinite(event.tokensOut)) {\n ledger.tokensOut += event.tokensOut\n }\n if (typeof event.costUsd === 'number' && Number.isFinite(event.costUsd)) {\n ledger.costUsd += event.costUsd\n }\n },\n cost: snapshotCost,\n complete(input) {\n // JS callers can bypass the `Exclude<…, 'running'>` type; enforce the\n // state machine at runtime as well.\n if ((input.status as RuntimeRunStatus) === 'running') {\n throw new ValidationError('complete() requires a terminal status, got \"running\"')\n }\n if (status !== 'running') {\n if (status === input.status) return\n throw new RuntimeRunStateError(\n `Cannot transition runtime run from \"${status}\" to \"${input.status}\"`,\n )\n }\n status = input.status\n completedAtMs = now()\n resultSummary = input.resultSummary\n error = input.error\n completionMetadata = input.metadata\n if (input.cost) {\n if (typeof input.cost.tokensIn === 'number' && Number.isFinite(input.cost.tokensIn)) {\n ledger.tokensIn = input.cost.tokensIn\n }\n if (typeof input.cost.tokensOut === 'number' && Number.isFinite(input.cost.tokensOut)) {\n ledger.tokensOut = input.cost.tokensOut\n }\n if (typeof input.cost.costUsd === 'number' && Number.isFinite(input.cost.costUsd)) {\n ledger.costUsd = input.cost.costUsd\n }\n if (typeof input.cost.llmCalls === 'number' && Number.isFinite(input.cost.llmCalls)) {\n ledger.llmCalls = input.cost.llmCalls\n }\n }\n },\n toRow(metadata) {\n return buildRow(metadata)\n },\n async persist(metadata) {\n if (status === 'running') {\n throw new RuntimeRunStateError('Cannot persist a runtime run before complete() is called')\n }\n if (!options.adapter) return\n await options.adapter.upsert(buildRow(metadata))\n },\n }\n}\n\nfunction mergeMetadata(\n base: Record<string, unknown> | undefined,\n extra: Record<string, unknown> | undefined,\n): Record<string, unknown> | undefined {\n if (!base && !extra) return undefined\n return { ...(base ?? {}), ...(extra ?? {}) }\n}\n\nfunction randomSuffix(): string {\n // 8 chars of base36 — sufficient for in-process uniqueness. Callers needing\n // stronger guarantees pass `options.id` explicitly.\n return Math.random().toString(36).slice(2, 10)\n}\n","/**\n *\n * Sanitization for runtime telemetry. The rule: nothing user-controlled leaks\n * unless the caller opts in with a `RuntimeTelemetryOptions` flag. This is the\n * envelope that ends up in `agent_run.metadata.runtimeEvents` on every\n * consumer, so the default must be safe.\n *\n * @stable\n */\n\nimport type {\n ControlEvalResult,\n ControlRunResult,\n ControlStep,\n DataAcquisitionPlan,\n KnowledgeReadinessReport,\n KnowledgeRequirement,\n UserQuestion,\n} from '@tangle-network/agent-eval'\n\nimport type {\n AgentRuntimeEvent,\n AgentTaskSpec,\n AgentTaskStatus,\n RuntimeSession,\n RuntimeStreamEvent,\n} from './types'\n\n/** @stable */\nexport interface RuntimeTelemetryOptions {\n /**\n * Include raw task inputs. Off by default because task inputs often contain\n * customer facts, credentials, source text, or internal IDs.\n */\n includeInputs?: boolean\n /** Include requirement descriptions. Secret requirements are always redacted. */\n includeRequirementDescriptions?: boolean\n /** Include evidence IDs. Off by default; counts are safer for shared reports. */\n includeEvidenceIds?: boolean\n /** Include user answers from question preflight. Off by default. */\n includeUserAnswers?: boolean\n /** Include action payloads and action results for control steps. Off by default. */\n includeControlPayloads?: boolean\n /** Include task metadata. Off by default because metadata may carry IDs or policy internals. */\n includeMetadata?: boolean\n /** Include eval detail/evidence strings. Off by default because validators may echo private input. */\n includeEvalDetails?: boolean\n}\n\n/** @stable */\nexport interface SanitizedKnowledgeRequirement {\n id: string\n description?: string\n requiredFor: string[]\n category: KnowledgeRequirement['category']\n acquisitionMode: KnowledgeRequirement['acquisitionMode']\n importance: KnowledgeRequirement['importance']\n freshness: KnowledgeRequirement['freshness']\n sensitivity: KnowledgeRequirement['sensitivity']\n confidenceNeeded: number\n currentConfidence: number\n evidenceCount: number\n evidenceIds?: string[]\n fallbackPolicy: KnowledgeRequirement['fallbackPolicy']\n}\n\n/** @stable */\nexport interface SanitizedKnowledgeReadinessReport {\n taskId: string\n readinessScore: number\n recommendedAction: KnowledgeReadinessReport['recommendedAction']\n severity: KnowledgeReadinessReport['severity']\n reason: string\n blockingMissingRequirements: SanitizedKnowledgeRequirement[]\n nonBlockingGaps: SanitizedKnowledgeRequirement[]\n evidenceCount: number\n evidenceIds?: string[]\n missingRequirementIds: string[]\n}\n\n/** Strip PII and large blobs from a `KnowledgeReadinessReport` for safe telemetry emission. @stable */\nexport function sanitizeKnowledgeReadinessReport(\n report: KnowledgeReadinessReport,\n options: RuntimeTelemetryOptions = {},\n): SanitizedKnowledgeReadinessReport {\n return {\n taskId: report.taskId,\n readinessScore: report.readinessScore,\n recommendedAction: report.recommendedAction,\n severity: report.severity,\n reason: report.reason,\n blockingMissingRequirements: report.blockingMissingRequirements.map((requirement) =>\n sanitizeKnowledgeRequirement(requirement, options),\n ),\n nonBlockingGaps: report.nonBlockingGaps.map((requirement) =>\n sanitizeKnowledgeRequirement(requirement, options),\n ),\n evidenceCount: report.bundle.evidenceIds.length,\n evidenceIds: options.includeEvidenceIds ? report.bundle.evidenceIds : undefined,\n missingRequirementIds: report.bundle.missing.map((requirement) => requirement.id),\n }\n}\n\n/** Reduce an `AgentRuntimeEvent` to a PII-safe, serializable plain object for telemetry. @stable */\nexport function sanitizeAgentRuntimeEvent<\n TState,\n TAction,\n TActionResult,\n TEval extends ControlEvalResult,\n>(\n event: AgentRuntimeEvent<TState, TAction, TActionResult, TEval>,\n options: RuntimeTelemetryOptions = {},\n): Record<string, unknown> {\n const base = { type: event.type, task: sanitizeTask(event.task, options) }\n if (\n event.type === 'readiness_start' ||\n event.type === 'task_start' ||\n event.type === 'control_start'\n ) {\n return event.type === 'control_start'\n ? { ...base, knowledge: sanitizeKnowledgeReadinessReport(event.knowledge, options) }\n : base\n }\n if (event.type === 'readiness_end') {\n return { ...base, knowledge: sanitizeKnowledgeReadinessReport(event.knowledge, options) }\n }\n if (event.type === 'questions_start') {\n return {\n ...base,\n questions: event.questions.map((question) => sanitizeQuestion(question, options)),\n }\n }\n if (event.type === 'questions_end') {\n return {\n ...base,\n questions: event.questions.map((question) => sanitizeQuestion(question, options)),\n userAnswers: options.includeUserAnswers ? event.userAnswers : redactRecord(event.userAnswers),\n }\n }\n if (event.type === 'acquisition_start') {\n return { ...base, acquisitionPlans: event.acquisitionPlans.map(sanitizeAcquisitionPlan) }\n }\n if (event.type === 'acquisition_end') {\n return {\n ...base,\n acquisitionPlans: event.acquisitionPlans.map(sanitizeAcquisitionPlan),\n acquiredEvidenceCount: event.acquiredEvidenceIds.length,\n acquiredEvidenceIds: options.includeEvidenceIds ? event.acquiredEvidenceIds : undefined,\n }\n }\n if (event.type === 'control_step') {\n return { ...base, step: sanitizeControlStep(event.step, options) }\n }\n if (event.type === 'control_end') {\n return { ...base, control: sanitizeControlRun(event.control, options) }\n }\n return { ...base, status: event.status, reason: event.reason }\n}\n\n/** Reduce a `RuntimeStreamEvent` to a PII-safe, serializable plain object for telemetry. @stable */\nexport function sanitizeRuntimeStreamEvent(\n event: RuntimeStreamEvent,\n options: RuntimeTelemetryOptions = {},\n): Record<string, unknown> {\n const withTask = 'task' in event && event.task ? { task: sanitizeTask(event.task, options) } : {}\n const withSession =\n 'session' in event && event.session\n ? { session: sanitizeRuntimeSession(event.session, options) }\n : {}\n\n if (event.type === 'readiness_end') {\n return {\n type: event.type,\n ...withTask,\n timestamp: event.timestamp,\n decision: event.decision,\n knowledge: sanitizeKnowledgeReadinessReport(event.knowledge, options),\n }\n }\n if (event.type === 'questions_start') {\n return {\n type: event.type,\n ...withTask,\n timestamp: event.timestamp,\n questions: event.questions.map((question) => sanitizeQuestion(question, options)),\n }\n }\n if (event.type === 'questions_end') {\n return {\n type: event.type,\n ...withTask,\n timestamp: event.timestamp,\n questions: event.questions.map((question) => sanitizeQuestion(question, options)),\n userAnswers: options.includeUserAnswers ? event.userAnswers : redactRecord(event.userAnswers),\n }\n }\n if (event.type === 'acquisition_start') {\n return {\n type: event.type,\n ...withTask,\n timestamp: event.timestamp,\n acquisitionPlans: event.acquisitionPlans.map(sanitizeAcquisitionPlan),\n }\n }\n if (event.type === 'acquisition_end') {\n return {\n type: event.type,\n ...withTask,\n timestamp: event.timestamp,\n acquisitionPlans: event.acquisitionPlans.map(sanitizeAcquisitionPlan),\n acquiredEvidenceCount: event.acquiredEvidenceIds.length,\n acquiredEvidenceIds: options.includeEvidenceIds ? event.acquiredEvidenceIds : undefined,\n }\n }\n if (event.type === 'tool_call') {\n return {\n type: event.type,\n ...withTask,\n ...withSession,\n timestamp: event.timestamp,\n toolName: event.toolName,\n toolCallId: event.toolCallId,\n args: options.includeControlPayloads ? event.args : undefined,\n }\n }\n if (event.type === 'tool_result') {\n return {\n type: event.type,\n ...withTask,\n ...withSession,\n timestamp: event.timestamp,\n toolName: event.toolName,\n toolCallId: event.toolCallId,\n result: options.includeControlPayloads ? event.result : undefined,\n }\n }\n if (event.type === 'llm_call') {\n return {\n type: event.type,\n ...withTask,\n ...withSession,\n timestamp: event.timestamp,\n model: event.model,\n tokensIn: event.tokensIn,\n tokensOut: event.tokensOut,\n costUsd: event.costUsd,\n latencyMs: event.latencyMs,\n finishReason: event.finishReason,\n }\n }\n if (event.type === 'artifact') {\n return {\n type: event.type,\n ...withTask,\n ...withSession,\n timestamp: event.timestamp,\n artifactId: event.artifactId,\n name: event.name,\n mimeType: event.mimeType,\n uri: options.includeEvidenceIds ? event.uri : undefined,\n content: options.includeControlPayloads ? event.content : undefined,\n metadata: options.includeMetadata ? event.metadata : undefined,\n }\n }\n if (event.type === 'proposal_created') {\n return {\n type: event.type,\n ...withTask,\n ...withSession,\n timestamp: event.timestamp,\n proposalId: event.proposalId,\n title: options.includeControlPayloads ? event.title : undefined,\n content: options.includeControlPayloads ? event.content : undefined,\n status: event.status,\n }\n }\n if (event.type === 'final') {\n // Surface error `kind` + `status` always — operators need failure\n // classification regardless of telemetry payload opt-in. `body` follows\n // the same gating as raw payloads (`includeControlPayloads`) because it\n // can echo user-visible text from the upstream provider's error page.\n const sanitizedError =\n event.error !== undefined\n ? {\n kind: event.error.kind,\n message: event.error.message,\n status: event.error.status,\n body: options.includeControlPayloads ? event.error.body : undefined,\n }\n : undefined\n return {\n type: event.type,\n ...withTask,\n ...withSession,\n timestamp: event.timestamp,\n status: event.status,\n reason: event.reason,\n text: options.includeControlPayloads ? event.text : undefined,\n metadata: options.includeMetadata ? event.metadata : undefined,\n ...(sanitizedError !== undefined ? { error: sanitizedError } : {}),\n }\n }\n return {\n type: event.type,\n ...withTask,\n ...withSession,\n timestamp: 'timestamp' in event ? event.timestamp : undefined,\n ...pickPublicStreamFields(event),\n }\n}\n\nfunction sanitizeTask(\n task: AgentTaskSpec,\n options: RuntimeTelemetryOptions,\n): Record<string, unknown> {\n return {\n id: task.id,\n intent: task.intent,\n domain: task.domain,\n inputs: options.includeInputs ? task.inputs : task.inputs ? '[redacted]' : undefined,\n requiredKnowledge: task.requiredKnowledge?.map((requirement) =>\n sanitizeKnowledgeRequirement(requirement, options),\n ),\n metadata: options.includeMetadata ? task.metadata : task.metadata ? '[redacted]' : undefined,\n }\n}\n\nfunction sanitizeRuntimeSession(\n session: RuntimeSession,\n options: RuntimeTelemetryOptions,\n): Record<string, unknown> {\n return {\n id: session.id,\n backend: session.backend,\n status: session.status,\n hasResumeToken: Boolean(session.resumeToken),\n createdAt: session.createdAt,\n updatedAt: session.updatedAt,\n metadata: options.includeMetadata\n ? session.metadata\n : session.metadata\n ? '[redacted]'\n : undefined,\n }\n}\n\nfunction sanitizeKnowledgeRequirement(\n requirement: KnowledgeRequirement,\n options: RuntimeTelemetryOptions,\n): SanitizedKnowledgeRequirement {\n const includeDescription =\n options.includeRequirementDescriptions && requirement.sensitivity !== 'secret'\n return {\n id: requirement.id,\n description: includeDescription ? requirement.description : undefined,\n requiredFor: requirement.requiredFor,\n category: requirement.category,\n acquisitionMode: requirement.acquisitionMode,\n importance: requirement.importance,\n freshness: requirement.freshness,\n sensitivity: requirement.sensitivity,\n confidenceNeeded: requirement.confidenceNeeded,\n currentConfidence: requirement.currentConfidence,\n evidenceCount: requirement.evidenceIds.length,\n evidenceIds: options.includeEvidenceIds ? requirement.evidenceIds : undefined,\n fallbackPolicy: requirement.fallbackPolicy,\n }\n}\n\nfunction sanitizeQuestion(\n question: UserQuestion,\n options: RuntimeTelemetryOptions,\n): Record<string, unknown> {\n return {\n id: question.id,\n question:\n options.includeRequirementDescriptions && question.answerType !== 'credential'\n ? question.question\n : undefined,\n reason: options.includeRequirementDescriptions ? question.reason : undefined,\n requirementId: question.requirementId,\n importance: question.importance,\n answerType: question.answerType,\n impactIfUnknown: options.includeRequirementDescriptions ? question.impactIfUnknown : undefined,\n optionCount: question.options?.length ?? 0,\n }\n}\n\nfunction sanitizeAcquisitionPlan(plan: DataAcquisitionPlan): Record<string, unknown> {\n return {\n id: plan.id,\n requirementIds: plan.requirementIds,\n mode: plan.mode,\n priority: plan.priority,\n expectedEvidenceCount: plan.expectedEvidenceIds?.length ?? 0,\n questionCount: plan.questions?.length ?? 0,\n }\n}\n\nfunction sanitizeControlStep<TState, TAction, TActionResult, TEval extends ControlEvalResult>(\n step: ControlStep<TState, TAction, TActionResult, TEval>,\n options: RuntimeTelemetryOptions,\n): Record<string, unknown> {\n const actionOutcome = step.actionOutcome\n return {\n index: step.index,\n decisionType: step.decision.type,\n reason: step.decision.reason,\n action:\n options.includeControlPayloads && step.decision.type === 'continue'\n ? step.decision.action\n : undefined,\n result: options.includeControlPayloads && actionOutcome?.ok ? actionOutcome.result : undefined,\n actionOk: actionOutcome?.ok,\n actionError: actionOutcome?.ok === false ? actionOutcome.error : undefined,\n durationMs: actionOutcome?.durationMs,\n evalsBefore: summarizeEvals(step.evalsBefore, options),\n evalsAfter: summarizeEvals(step.evalsAfter, options),\n startedAt: step.startedAt,\n endedAt: step.endedAt,\n }\n}\n\nfunction sanitizeControlRun<TState, TAction, TActionResult, TEval extends ControlEvalResult>(\n control: ControlRunResult<TState, TAction, TActionResult, TEval>,\n options: RuntimeTelemetryOptions,\n): Record<string, unknown> {\n return {\n pass: control.pass,\n completed: control.completed,\n reason: control.reason,\n score: control.score,\n stepCount: control.steps.length,\n wallMs: control.wallMs,\n spentCostUsd: control.spentCostUsd,\n failureClass: control.failureClass,\n stoppedBy: control.stoppedBy,\n runId: control.runId,\n runtimeErrorCount: control.runtimeErrors.length,\n finalEvals: summarizeEvals(control.finalEvals, options),\n }\n}\n\nfunction summarizeEvals(\n evals: ControlEvalResult[],\n options: RuntimeTelemetryOptions,\n): Array<Record<string, unknown>> {\n return evals.map((evalResult) => ({\n id: evalResult.id,\n passed: evalResult.passed,\n score: evalResult.score,\n severity: evalResult.severity,\n objective: evalResult.objective,\n detail: options.includeEvalDetails ? evalResult.detail : undefined,\n evidence: options.includeEvalDetails ? evalResult.evidence : undefined,\n }))\n}\n\nfunction redactRecord(record: Record<string, string>): Record<string, string> {\n return Object.fromEntries(Object.keys(record).map((key) => [key, '[redacted]']))\n}\n\nfunction pickPublicStreamFields(event: RuntimeStreamEvent): Record<string, unknown> {\n if (event.type === 'session_created' || event.type === 'session_resumed') return {}\n if (event.type === 'backend_start' || event.type === 'backend_end')\n return { backend: event.backend }\n if (event.type === 'backend_error') {\n // `error.body` is the truncated upstream response — it can carry\n // user-visible text (a `free_tier_limit` envelope is safe, but an HTML\n // error page from a misconfigured proxy may echo the request URL with\n // query string). Redact body by default; surface `kind` + `status` so\n // operators can still classify the failure without raw text.\n const sanitizedError =\n event.error !== undefined\n ? {\n kind: event.error.kind,\n status: event.error.status,\n }\n : undefined\n return {\n backend: event.backend,\n message: event.message,\n recoverable: event.recoverable,\n ...(sanitizedError !== undefined ? { error: sanitizedError } : {}),\n }\n }\n if (event.type === 'task_end') return { status: event.status, reason: event.reason }\n if (event.type === 'text_delta' || event.type === 'reasoning_delta') return { text: event.text }\n return {}\n}\n\n/** @stable */\nexport interface RuntimeEventCollector<\n TState = unknown,\n TAction = unknown,\n TActionResult = unknown,\n TEval extends ControlEvalResult = ControlEvalResult,\n> {\n onEvent: (event: AgentRuntimeEvent<TState, TAction, TActionResult, TEval>) => void\n events: Array<Record<string, unknown>>\n}\n\n/** @stable */\nexport type RuntimeStreamEventSink = (event: RuntimeStreamEvent) => void\n\n/** @stable */\nexport interface RuntimeStreamEventSummary {\n /** Total count of sanitized events collected. */\n eventCount: number\n /** Count of events per `type`. Useful for log-line summaries. */\n eventCountsByType: Record<string, number>\n /** First session id observed in a `session_created` / `session_resumed` event, if any. */\n firstSessionId?: string\n /** Last `final` event's status, if a final event was observed. */\n finalStatus?: AgentTaskStatus\n /** Last `final` event's reason, if a final event was observed. */\n finalReason?: string\n /** Concatenated `text_delta.text` across the stream, even when payloads are redacted. */\n finalText: string\n}\n\n/** @stable */\nexport interface RuntimeStreamEventCollector {\n onEvent: RuntimeStreamEventSink\n events: Array<Record<string, unknown>>\n /** Snapshot of a small streaming-flavored summary derived from collected events. */\n summary(): RuntimeStreamEventSummary\n}\n\n/** Build an in-memory collector that sanitizes and accumulates `AgentRuntimeEvent`s for inspection. @stable */\nexport function createRuntimeEventCollector<\n TState = unknown,\n TAction = unknown,\n TActionResult = unknown,\n TEval extends ControlEvalResult = ControlEvalResult,\n>(\n options: RuntimeTelemetryOptions = {},\n): RuntimeEventCollector<TState, TAction, TActionResult, TEval> {\n const events: Array<Record<string, unknown>> = []\n return {\n events,\n onEvent: (event) => {\n events.push(sanitizeAgentRuntimeEvent(event, options))\n },\n }\n}\n\n/**\n *\n * Streaming-event counterpart of `createRuntimeEventCollector`. Pass each\n * event yielded by `runAgentTaskStream` through `onEvent` and read the\n * sanitized copies off `events`; the same `RuntimeTelemetryOptions` redaction\n * flags apply. Kept distinct from `createRuntimeEventCollector` because the\n * stream and non-stream event shapes overlap on `type` literals — dispatching\n * on `type` alone would misroute events.\n *\n * @stable\n */\nexport function createRuntimeStreamEventCollector(\n options: RuntimeTelemetryOptions = {},\n): RuntimeStreamEventCollector {\n const events: Array<Record<string, unknown>> = []\n const eventCountsByType: Record<string, number> = {}\n let firstSessionId: string | undefined\n let finalStatus: AgentTaskStatus | undefined\n let finalReason: string | undefined\n let finalText = ''\n return {\n events,\n onEvent: (event) => {\n events.push(sanitizeRuntimeStreamEvent(event, options))\n eventCountsByType[event.type] = (eventCountsByType[event.type] ?? 0) + 1\n if (event.type === 'text_delta') finalText += event.text\n if (\n !firstSessionId &&\n (event.type === 'session_created' || event.type === 'session_resumed')\n ) {\n firstSessionId = event.session.id\n }\n if (event.type === 'final') {\n finalStatus = event.status\n finalReason = event.reason\n }\n },\n summary() {\n return {\n eventCount: events.length,\n eventCountsByType: { ...eventCountsByType },\n firstSessionId,\n finalStatus,\n finalReason,\n finalText,\n }\n },\n }\n}\n","/**\n *\n * Server-Sent Events serialization for runtime telemetry streams.\n *\n * Newline-safe by construction: any newline in `id` or `event` is collapsed to\n * a space (browsers terminate fields on newline), and multi-line `data`\n * payloads are split into one `data:` line per source line so JSON.stringify\n * output transports cleanly.\n *\n * @stable\n */\n\nimport type { KnowledgeReadinessReport } from '@tangle-network/agent-eval'\nimport type { RuntimeTelemetryOptions } from './sanitize'\nimport { sanitizeKnowledgeReadinessReport, sanitizeRuntimeStreamEvent } from './sanitize'\nimport type { RuntimeStreamEvent } from './types'\n\n/** @stable */\nexport interface ServerSentEventOptions {\n event?: string\n id?: string\n retry?: number\n}\n\n/** @stable */\nexport function encodeServerSentEvent(data: unknown, options: ServerSentEventOptions = {}): string {\n const lines: string[] = []\n if (options.id) lines.push(`id: ${stripNewlines(options.id)}`)\n if (options.event) lines.push(`event: ${stripNewlines(options.event)}`)\n if (typeof options.retry === 'number' && Number.isFinite(options.retry) && options.retry >= 0) {\n lines.push(`retry: ${Math.floor(options.retry)}`)\n }\n\n const payload = typeof data === 'string' ? data : JSON.stringify(data)\n for (const line of payload.split(/\\r?\\n/)) {\n lines.push(`data: ${line}`)\n }\n return `${lines.join('\\n')}\\n\\n`\n}\n\n/** Serialize a `KnowledgeReadinessReport` as a Server-Sent Event string. @stable */\nexport function readinessServerSentEvent(\n report: KnowledgeReadinessReport,\n options: RuntimeTelemetryOptions & ServerSentEventOptions = {},\n): string {\n const { event, id, retry, ...telemetryOptions } = options\n return encodeServerSentEvent(\n {\n type: 'readiness',\n readiness: sanitizeKnowledgeReadinessReport(report, telemetryOptions),\n },\n { event, id, retry },\n )\n}\n\n/** Serialize a `RuntimeStreamEvent` as a Server-Sent Event string. @stable */\nexport function runtimeStreamServerSentEvent(\n event: RuntimeStreamEvent,\n options: RuntimeTelemetryOptions & ServerSentEventOptions = {},\n): string {\n const { event: sseEvent, id, retry, ...telemetryOptions } = options\n return encodeServerSentEvent(sanitizeRuntimeStreamEvent(event, telemetryOptions), {\n event: sseEvent,\n id,\n retry,\n })\n}\n\nfunction stripNewlines(value: string): string {\n return value.replace(/[\\r\\n]/g, ' ')\n}\n","/**\n * Bounded turn-level tool-dispatch loop.\n *\n * `runAgentTaskStream` runs ONE model turn; `runLoop` orchestrates DELEGATED\n * multi-agent topologies (refine / fanout-vote). Neither is the everyday\n * interactive shape: a chat turn where the model may emit tool calls, each is\n * executed, the results are folded back, and the turn re-runs until the model\n * stops (or a turn cap). Every agent app hand-rolls that loop — this is it,\n * as a reusable primitive.\n *\n * Substrate-neutral by design: the caller supplies `streamTurn` (wrapping\n * whatever backend / `runAgentTaskStream` it uses) and `executeToolCall`\n * (routing to its executors). This module owns the LOOP; the caller owns the\n * model and the executors. `Raw` (streaming variant) is the caller's own\n * event type. The only imported contract is the runtime hook type: hooks are\n * execution-scoped observers, not part of the agent profile.\n */\n\nimport type { RuntimeDecisionEvidenceRef, RuntimeHooks } from './runtime-hooks'\nimport { notifyRuntimeDecisionPoint, notifyRuntimeHookEvent } from './runtime-hooks'\n\nexport interface ToolLoopCall {\n toolCallId?: string\n toolName: string\n args: Record<string, unknown>\n}\n\n/** Outcome of one tool dispatch — structurally compatible with a hub/integration\n * tool-outcome union, so callers can fold either through the loop. */\nexport type ToolCallOutcome =\n | { ok: true; result: unknown }\n | { ok: false; code: string; message: string; status?: number }\n\n/** Runaway-backstop: stops an infinite tool loop where cost is unmetered. Set\n * far above any legitimate workflow — this is a watchdog, not a policy cap.\n * Legitimate per-call budgets come from `maxCostUsd` + `costOf`. */\nconst RUNAWAY_BACKSTOP_TURNS = 200\nconst DEFAULT_DECISION_CONTEXT_CHARS = 12_000\nconst FAILURE_RECOVERY_ACTIONS = ['retry', 'verify', 'continue', 'stop']\n/** Consecutive identical calls (same tool + canonical-JSON args) that trigger\n * stuck-loop detection. The window resets on any different call. */\nconst STUCK_LOOP_THRESHOLD = 3\n\n/** One OpenAI-shaped tool-call entry carried on an assistant message. */\nexport interface ToolLoopAssistantToolCall {\n id: string\n type: 'function'\n function: { name: string; arguments: string }\n}\n\n/**\n * A message in the running conversation the loop sends to `streamTurn`.\n *\n * The base `{ role, content }` covers `system` / `user` / plain `assistant`\n * turns. Two optional fields carry the OpenAI function-calling contract so a\n * strict model (Claude, and any OpenAI-compatible provider that validates tool\n * history) reads its own tool use back instead of re-issuing the same call:\n *\n * - an assistant turn that emitted tool calls carries `tool_calls`, and its\n * `content` is `null` when the turn was tool-only;\n * - each tool result is its own `{ role: 'tool', tool_call_id, content }`\n * message keyed to the call that produced it.\n *\n * Widening is additive: a `streamTurn` that reads only `role` + `content` still\n * works; one that forwards the whole message to an OpenAI-compatible endpoint\n * now sends correct tool history.\n */\nexport type ToolLoopMessage = {\n role: string\n content: string | null\n tool_calls?: ToolLoopAssistantToolCall[]\n tool_call_id?: string\n}\n\n/** A tool-call id is required to key a `role: 'tool'` result back to its call.\n * When the model omitted one, derive a stable id from the tool name so the\n * assistant `tool_calls` entry and its `tool` result still match. */\nfunction toolCallId(call: ToolLoopCall): string {\n return call.toolCallId ?? `call_${call.toolName}`\n}\n\n/** The assistant turn that emitted `pending`, in OpenAI shape: text content\n * (null when the turn was tool-only) plus its `tool_calls` array. */\nfunction assistantToolCallMessage(turnText: string, pending: ToolLoopCall[]): ToolLoopMessage {\n return {\n role: 'assistant',\n content: turnText.trim() || null,\n tool_calls: pending.map((call) => ({\n id: toolCallId(call),\n type: 'function',\n function: { name: call.toolName, arguments: JSON.stringify(call.args) },\n })),\n }\n}\n\n/** One `role: 'tool'` result message keyed to its call by `tool_call_id`. */\nfunction toolResultMessage(call: ToolLoopCall, content: string): ToolLoopMessage {\n return { role: 'tool', tool_call_id: toolCallId(call), content }\n}\n\nfunction defaultRender(label: string, outcome: ToolCallOutcome): string {\n if (outcome.ok) return `- ${label} → ok: ${JSON.stringify(outcome.result)}`\n return `- ${label} → failed (${outcome.code}): ${outcome.message}`\n}\n\n// ── Awaitable variant (drain-only callers, tests) ──────────────────────────\n\nexport type ToolLoopEvent =\n | { type: 'text'; text: string }\n | { type: 'tool_call'; call: ToolLoopCall }\n | { type: 'other'; event: unknown }\n\n/** Why the loop stopped. `completed` = model finished naturally; `stuck-loop` =\n * ≥3 consecutive identical tool calls (same tool + args); `backstop` = hit the\n * runaway-backstop cap (200 by default); `deadline` = wall-clock deadlineMs\n * exceeded; `budget` = maxCostUsd exhausted. Non-`completed` stops are infra /\n * resource outcomes — eval scoring must distinguish them from capability failure. */\nexport type ToolLoopStopReason = 'completed' | 'stuck-loop' | 'backstop' | 'deadline' | 'budget'\n\nexport interface ToolLoopResult {\n finalText: string\n toolResults: Array<{ call: ToolLoopCall; label: string; outcome: ToolCallOutcome }>\n turns: number\n stopReason: ToolLoopStopReason\n /** @deprecated Use `stopReason !== 'completed'` instead. */\n cappedOut: boolean\n}\n\nexport interface RunToolLoopOptions {\n systemPrompt: string\n userMessage: string\n priorMessages?: ToolLoopMessage[]\n streamTurn: (messages: ToolLoopMessage[]) => AsyncIterable<ToolLoopEvent>\n executeToolCall: (call: ToolLoopCall) => Promise<ToolCallOutcome>\n isExecutableTool: (toolName: string) => boolean\n /** Runaway-backstop cap. Default 200 — set far above any legitimate workflow.\n * For per-workflow limits, use `maxCostUsd` or `deadlineMs` instead. */\n maxToolTurns?: number\n /** Wall-clock deadline in ms since epoch (Date.now()-based). When exceeded the\n * loop stops with stopReason `deadline`. */\n deadlineMs?: number\n /** Maximum total cost in USD. Requires `costOf` to meter each tool call. */\n maxCostUsd?: number\n /** Return the USD cost of one outcome. Required for `maxCostUsd` to work. */\n costOf?: (call: ToolLoopCall, outcome: ToolCallOutcome) => number\n renderResult?: (label: string, outcome: ToolCallOutcome) => string\n labelFor?: (call: ToolLoopCall) => string\n runId?: string\n scenarioId?: string\n hooks?: RuntimeHooks\n}\n\n/** Run the bounded tool loop and return the final text + every executed tool\n * outcome. Awaitable — callers needing to stream events to a UI use\n * {@link streamToolLoop}. */\nexport async function runToolLoop(opts: RunToolLoopOptions): Promise<ToolLoopResult> {\n const backstop = opts.maxToolTurns ?? RUNAWAY_BACKSTOP_TURNS\n const render = opts.renderResult ?? defaultRender\n const labelFor = opts.labelFor ?? ((c: ToolLoopCall) => c.toolName)\n const runId = opts.runId ?? `agent-run-${randomSuffix()}`\n const messages: ToolLoopMessage[] = [\n { role: 'system', content: opts.systemPrompt },\n ...(opts.priorMessages ?? []),\n { role: 'user', content: opts.userMessage },\n ]\n const observer = createToolLoopObserver(opts.hooks, runId, opts.scenarioId)\n const toolResults: ToolLoopResult['toolResults'] = []\n let finalText = ''\n let turns = 0\n let accumulatedCostUsd = 0\n // Stuck-loop detection: track the last canonical-JSON call signature and how\n // many consecutive times we've seen it.\n let lastCallHash: string | null = null\n let consecutiveCount = 0\n\n observer.loopBefore(backstop, messages.length)\n\n for (let toolTurn = 0; ; toolTurn++) {\n turns++\n\n // Wall-clock deadline check — before every new turn.\n if (opts.deadlineMs !== undefined && Date.now() >= opts.deadlineMs) {\n observer.loopAfter({ turns, toolResults: toolResults.length, stopReason: 'deadline' })\n return { finalText, toolResults, turns, stopReason: 'deadline', cappedOut: true }\n }\n\n let turnText = ''\n const pending: ToolLoopCall[] = []\n const turnEventId = observer.turnBefore(toolTurn, messages.length)\n for await (const ev of opts.streamTurn([...messages])) {\n if (ev.type === 'text') {\n turnText += ev.text\n finalText += ev.text\n } else if (ev.type === 'tool_call' && opts.isExecutableTool(ev.call.toolName)) {\n pending.push(ev.call)\n }\n }\n if (pending.length === 0) {\n observer.turnAfter(toolTurn, turnEventId, {\n pendingToolCalls: 0,\n finalTextChars: finalText.length,\n })\n break\n }\n\n // Runaway backstop — the model keeps emitting calls past the safety ceiling.\n if (toolTurn >= backstop) {\n observer.turnAfter(toolTurn, turnEventId, {\n pendingToolCalls: pending.length,\n stopReason: 'backstop',\n })\n observer.loopAfter({ turns, toolResults: toolResults.length, stopReason: 'backstop' })\n return { finalText, toolResults, turns, stopReason: 'backstop', cappedOut: true }\n }\n\n // The assistant turn that emitted the calls, carrying its tool_calls array,\n // so a strict model reads its own tool use back in OpenAI shape.\n messages.push(assistantToolCallMessage(turnText, pending))\n const outcomes: ExecutedToolCall[] = []\n for (const [callIndex, call] of pending.entries()) {\n // Stuck-loop detection: hash the first pending call each turn (a model\n // stuck in a loop re-issues the same call repeatedly, not alternating calls).\n const callHash = canonicalCallHash(call)\n if (callHash === lastCallHash) {\n consecutiveCount++\n } else {\n lastCallHash = callHash\n consecutiveCount = 1\n }\n if (consecutiveCount >= STUCK_LOOP_THRESHOLD) {\n observer.turnAfter(toolTurn, turnEventId, {\n pendingToolCalls: pending.length,\n stopReason: 'stuck-loop',\n })\n observer.loopAfter({ turns, toolResults: toolResults.length, stopReason: 'stuck-loop' })\n return { finalText, toolResults, turns, stopReason: 'stuck-loop', cappedOut: true }\n }\n\n const callEventId = observer.toolCallBefore(toolTurn, turnEventId, callIndex, call)\n let outcome: ToolCallOutcome\n try {\n outcome = await opts.executeToolCall(call)\n } catch (err) {\n outcome = {\n ok: false,\n code: 'executor_error',\n message: err instanceof Error ? err.message : String(err),\n }\n }\n\n // Budget check after each tool call.\n if (opts.maxCostUsd !== undefined && opts.costOf !== undefined) {\n accumulatedCostUsd += opts.costOf(call, outcome)\n if (accumulatedCostUsd >= opts.maxCostUsd) {\n const label = labelFor(call)\n toolResults.push({ call, label, outcome })\n messages.push(toolResultMessage(call, render(label, outcome)))\n observer.toolCallAfter(toolTurn, callEventId, call, outcome)\n observer.turnAfter(toolTurn, turnEventId, {\n pendingToolCalls: pending.length,\n stopReason: 'budget',\n })\n observer.loopAfter({ turns, toolResults: toolResults.length, stopReason: 'budget' })\n return { finalText, toolResults, turns, stopReason: 'budget', cappedOut: true }\n }\n }\n\n const label = labelFor(call)\n const rendered = render(label, outcome)\n toolResults.push({ call, label, outcome })\n outcomes.push({ call, label, outcome, rendered })\n // One role:'tool' message per result, keyed to its call by tool_call_id.\n messages.push(toolResultMessage(call, rendered))\n observer.toolCallAfter(toolTurn, callEventId, call, outcome)\n }\n observer.failureRecovery({\n toolTurn,\n messages,\n turnText,\n outcomes,\n })\n observer.turnAfter(toolTurn, turnEventId, {\n pendingToolCalls: pending.length,\n toolResults: outcomes.map((item) => ({\n toolName: item.call.toolName,\n toolCallId: item.call.toolCallId,\n ok: item.outcome.ok,\n })),\n failedToolCalls: outcomes.filter((item) => !item.outcome.ok).length,\n })\n }\n observer.loopAfter({ turns, toolResults: toolResults.length, stopReason: 'completed' })\n return { finalText, toolResults, turns, stopReason: 'completed', cappedOut: false }\n}\n\n// ── Streaming variant (SSE chat runtimes + per-event telemetry) ────────────\n\nexport type StreamToolLoopYield<Raw> =\n | { kind: 'event'; event: Raw }\n | {\n kind: 'tool_result'\n toolName: string\n toolCallId?: string\n label: string\n outcome: ToolCallOutcome\n }\n | { kind: 'capped'; pending: number; stopReason: Exclude<ToolLoopStopReason, 'completed'> }\n\nexport interface StreamToolLoopOptions<Raw> {\n systemPrompt: string\n userMessage: string\n priorMessages?: ToolLoopMessage[]\n streamTurn: (messages: ToolLoopMessage[]) => AsyncIterable<Raw>\n extractText: (event: Raw) => string\n extractToolCall: (event: Raw) => ToolLoopCall | null\n isExecutableTool: (toolName: string) => boolean\n executeToolCall: (call: ToolLoopCall) => Promise<ToolCallOutcome>\n /** Runaway-backstop cap. Default 200 — set far above any legitimate workflow. */\n maxToolTurns?: number\n /** Wall-clock deadline in ms since epoch (Date.now()-based). */\n deadlineMs?: number\n /** Maximum total cost in USD. Requires `costOf` to meter each tool call. */\n maxCostUsd?: number\n /** Return the USD cost of one outcome. Required for `maxCostUsd` to work. */\n costOf?: (call: ToolLoopCall, outcome: ToolCallOutcome) => number\n renderResult?: (label: string, outcome: ToolCallOutcome) => string\n labelFor?: (call: ToolLoopCall) => string\n runId?: string\n scenarioId?: string\n hooks?: RuntimeHooks\n}\n\n/** Streaming bounded tool loop: yields each raw turn event (the caller maps +\n * telemetries + re-emits it) and each executed `tool_result`; emits one\n * `capped` if it stops for any non-completed reason with calls still pending. */\nexport async function* streamToolLoop<Raw>(\n opts: StreamToolLoopOptions<Raw>,\n): AsyncGenerator<StreamToolLoopYield<Raw>, void, unknown> {\n const backstop = opts.maxToolTurns ?? RUNAWAY_BACKSTOP_TURNS\n const render = opts.renderResult ?? defaultRender\n const labelFor = opts.labelFor ?? ((c: ToolLoopCall) => c.toolName)\n const runId = opts.runId ?? `agent-run-${randomSuffix()}`\n const messages: ToolLoopMessage[] = [\n { role: 'system', content: opts.systemPrompt },\n ...(opts.priorMessages ?? []),\n { role: 'user', content: opts.userMessage },\n ]\n const observer = createToolLoopObserver(opts.hooks, runId, opts.scenarioId)\n let accumulatedCostUsd = 0\n let lastCallHash: string | null = null\n let consecutiveCount = 0\n\n observer.loopBefore(backstop, messages.length)\n\n for (let toolTurn = 0; ; toolTurn++) {\n // Wall-clock deadline check before every new turn.\n if (opts.deadlineMs !== undefined && Date.now() >= opts.deadlineMs) {\n observer.loopAfter({ turns: toolTurn + 1, stopReason: 'deadline' })\n yield { kind: 'capped', pending: 0, stopReason: 'deadline' }\n return\n }\n\n let turnText = ''\n const pending: ToolLoopCall[] = []\n const turnEventId = observer.turnBefore(toolTurn, messages.length)\n for await (const event of opts.streamTurn([...messages])) {\n yield { kind: 'event', event }\n turnText += opts.extractText(event)\n const call = opts.extractToolCall(event)\n if (call && opts.isExecutableTool(call.toolName)) pending.push(call)\n }\n if (pending.length === 0) {\n observer.turnAfter(toolTurn, turnEventId, { pendingToolCalls: 0 })\n observer.loopAfter({ turns: toolTurn + 1, stopReason: 'completed' })\n return\n }\n\n // Runaway backstop.\n if (toolTurn >= backstop) {\n observer.turnAfter(toolTurn, turnEventId, {\n pendingToolCalls: pending.length,\n stopReason: 'backstop',\n })\n observer.loopAfter({ turns: toolTurn + 1, stopReason: 'backstop' })\n yield { kind: 'capped', pending: pending.length, stopReason: 'backstop' }\n return\n }\n\n // The assistant turn that emitted the calls, carrying its tool_calls array,\n // so a strict model reads its own tool use back in OpenAI shape.\n messages.push(assistantToolCallMessage(turnText, pending))\n const outcomes: ExecutedToolCall[] = []\n for (const [callIndex, call] of pending.entries()) {\n // Stuck-loop detection.\n const callHash = canonicalCallHash(call)\n if (callHash === lastCallHash) {\n consecutiveCount++\n } else {\n lastCallHash = callHash\n consecutiveCount = 1\n }\n if (consecutiveCount >= STUCK_LOOP_THRESHOLD) {\n observer.turnAfter(toolTurn, turnEventId, {\n pendingToolCalls: pending.length,\n stopReason: 'stuck-loop',\n })\n observer.loopAfter({ turns: toolTurn + 1, stopReason: 'stuck-loop' })\n yield { kind: 'capped', pending: pending.length, stopReason: 'stuck-loop' }\n return\n }\n\n const callEventId = observer.toolCallBefore(toolTurn, turnEventId, callIndex, call)\n let outcome: ToolCallOutcome\n try {\n outcome = await opts.executeToolCall(call)\n } catch (err) {\n outcome = {\n ok: false,\n code: 'executor_error',\n message: err instanceof Error ? err.message : String(err),\n }\n }\n\n // Budget check after each tool call.\n if (opts.maxCostUsd !== undefined && opts.costOf !== undefined) {\n accumulatedCostUsd += opts.costOf(call, outcome)\n if (accumulatedCostUsd >= opts.maxCostUsd) {\n const label = labelFor(call)\n yield {\n kind: 'tool_result',\n toolName: call.toolName,\n toolCallId: call.toolCallId,\n label,\n outcome,\n }\n messages.push(toolResultMessage(call, render(label, outcome)))\n observer.toolCallAfter(toolTurn, callEventId, call, outcome)\n observer.turnAfter(toolTurn, turnEventId, {\n pendingToolCalls: pending.length,\n stopReason: 'budget',\n })\n observer.loopAfter({ turns: toolTurn + 1, stopReason: 'budget' })\n yield { kind: 'capped', pending: pending.length, stopReason: 'budget' }\n return\n }\n }\n\n const label = labelFor(call)\n yield {\n kind: 'tool_result',\n toolName: call.toolName,\n toolCallId: call.toolCallId,\n label,\n outcome,\n }\n const rendered = render(label, outcome)\n outcomes.push({ call, label, outcome, rendered })\n // One role:'tool' message per result, keyed to its call by tool_call_id.\n messages.push(toolResultMessage(call, rendered))\n observer.toolCallAfter(toolTurn, callEventId, call, outcome)\n }\n observer.failureRecovery({\n toolTurn,\n messages,\n turnText,\n outcomes,\n })\n observer.turnAfter(toolTurn, turnEventId, {\n pendingToolCalls: pending.length,\n toolResults: outcomes.map((item) => ({\n toolName: item.call.toolName,\n toolCallId: item.call.toolCallId,\n ok: item.outcome.ok,\n })),\n failedToolCalls: outcomes.filter((item) => !item.outcome.ok).length,\n })\n }\n}\n\ninterface ExecutedToolCall {\n call: ToolLoopCall\n label: string\n outcome: ToolCallOutcome\n rendered: string\n}\n\ninterface NotifyToolFailureRecoveryOptions {\n hooks?: RuntimeHooks\n runId: string\n scenarioId?: string\n stepIndex: number\n messages: ToolLoopMessage[]\n turnText: string\n outcomes: ExecutedToolCall[]\n}\n\ninterface NotifyToolLoopEventOptions {\n hooks?: RuntimeHooks\n runId: string\n scenarioId?: string\n target: 'agent.run' | 'agent.turn' | 'agent.tool_call'\n phase: 'before' | 'after' | 'error' | 'event'\n id?: string\n stepIndex?: number\n parentId?: string\n payload?: Record<string, unknown>\n metadata?: Record<string, unknown>\n}\n\ninterface ToolLoopObserver {\n loopBefore(maxToolTurns: number, messageCount: number): void\n loopAfter(payload: Record<string, unknown>): void\n turnBefore(toolTurn: number, messageCount: number): string\n turnAfter(toolTurn: number, turnEventId: string, payload: Record<string, unknown>): void\n toolCallBefore(\n toolTurn: number,\n turnEventId: string,\n callIndex: number,\n call: ToolLoopCall,\n ): string\n toolCallAfter(\n toolTurn: number,\n callEventId: string,\n call: ToolLoopCall,\n outcome: ToolCallOutcome,\n ): void\n failureRecovery(options: {\n toolTurn: number\n messages: ToolLoopMessage[]\n turnText: string\n outcomes: ExecutedToolCall[]\n }): void\n}\n\nfunction createToolLoopObserver(\n hooks: RuntimeHooks | undefined,\n runId: string,\n scenarioId: string | undefined,\n): ToolLoopObserver {\n const loopEventId = `${runId}:agent.run`\n return {\n loopBefore: (maxToolTurns, messageCount) => {\n notifyToolLoopEvent({\n hooks,\n runId,\n scenarioId,\n target: 'agent.run',\n phase: 'before',\n id: `${loopEventId}:before`,\n payload: { maxToolTurns, messageCount },\n })\n },\n loopAfter: (payload) => {\n notifyToolLoopEvent({\n hooks,\n runId,\n scenarioId,\n target: 'agent.run',\n phase: 'after',\n id: `${loopEventId}:after`,\n payload,\n })\n },\n turnBefore: (toolTurn, messageCount) => {\n const turnEventId = `${loopEventId}:${toolTurn}`\n notifyToolLoopEvent({\n hooks,\n runId,\n scenarioId,\n target: 'agent.turn',\n phase: 'before',\n id: turnEventId,\n stepIndex: toolTurn,\n parentId: loopEventId,\n payload: { messageCount },\n })\n return turnEventId\n },\n turnAfter: (toolTurn, turnEventId, payload) => {\n notifyToolLoopEvent({\n hooks,\n runId,\n scenarioId,\n target: 'agent.turn',\n phase: 'after',\n id: `${turnEventId}:after`,\n stepIndex: toolTurn,\n parentId: turnEventId,\n payload,\n })\n },\n toolCallBefore: (toolTurn, turnEventId, callIndex, call) => {\n const callEventId = `${turnEventId}:tool-call:${callIndex}`\n notifyToolLoopEvent({\n hooks,\n runId,\n scenarioId,\n target: 'agent.tool_call',\n phase: 'before',\n id: callEventId,\n stepIndex: toolTurn,\n parentId: turnEventId,\n payload: toolCallPayload(call),\n })\n return callEventId\n },\n toolCallAfter: (toolTurn, callEventId, call, outcome) => {\n notifyToolLoopEvent({\n hooks,\n runId,\n scenarioId,\n target: 'agent.tool_call',\n phase: 'after',\n id: `${callEventId}:after`,\n stepIndex: toolTurn,\n parentId: callEventId,\n payload: { ...toolCallPayload(call), outcome: outcomePayload(outcome) },\n })\n },\n failureRecovery: (options) => {\n notifyToolFailureRecovery({\n hooks,\n runId,\n scenarioId,\n stepIndex: options.toolTurn,\n messages: options.messages,\n turnText: options.turnText,\n outcomes: options.outcomes,\n })\n },\n }\n}\n\nfunction notifyToolLoopEvent(options: NotifyToolLoopEventOptions): void {\n notifyRuntimeHookEvent(options.hooks, {\n id: options.id ?? `${options.runId}:${options.target}:${options.phase}`,\n runId: options.runId,\n scenarioId: options.scenarioId,\n target: options.target,\n phase: options.phase,\n timestamp: Date.now(),\n stepIndex: options.stepIndex,\n parentId: options.parentId,\n payload: options.payload,\n metadata: { producer: 'tool-loop', ...options.metadata },\n })\n}\n\nfunction notifyToolFailureRecovery(options: NotifyToolFailureRecoveryOptions): void {\n const failed = options.outcomes.filter((item) => !item.outcome.ok)\n if (failed.length === 0) return\n\n const evidence: RuntimeDecisionEvidenceRef[] = []\n for (const item of failed) {\n const id = item.call.toolCallId ?? `${options.stepIndex}:${item.label}`\n evidence.push({\n source: 'tool_call',\n id,\n detail: `${item.call.toolName} ${stringifySafe(item.call.args, 2_000)}`,\n metadata: { toolName: item.call.toolName, label: item.label },\n })\n evidence.push({\n source: 'tool_result',\n id: `${id}:result`,\n detail: item.rendered,\n metadata: failureMetadata(item.outcome),\n })\n }\n\n notifyRuntimeDecisionPoint(options.hooks, {\n id: `${options.runId}:agent.turn:${options.stepIndex}:failure-recovery`,\n runId: options.runId,\n scenarioId: options.scenarioId,\n stepIndex: options.stepIndex,\n kind: 'retry',\n candidateActions: [...FAILURE_RECOVERY_ACTIONS],\n context: renderDecisionContext(options.messages, options.turnText, options.outcomes),\n evidence,\n metadata: {\n target: 'failure-recovery',\n source: 'agent.turn',\n failedToolCount: failed.length,\n toolNames: failed.map((item) => item.call.toolName),\n },\n })\n}\n\nfunction toolCallPayload(call: ToolLoopCall): Record<string, unknown> {\n return {\n toolName: call.toolName,\n toolCallId: call.toolCallId,\n argsPreview: stringifySafe(call.args, 2_000),\n }\n}\n\nfunction outcomePayload(outcome: ToolCallOutcome): Record<string, unknown> {\n if (!outcome.ok) {\n return {\n ok: false,\n code: outcome.code,\n message: trimText(outcome.message, 2_000),\n status: outcome.status,\n }\n }\n return {\n ok: true,\n resultPreview: stringifySafe(outcome.result, 2_000),\n }\n}\n\nfunction failureMetadata(outcome: ToolCallOutcome): Record<string, unknown> | undefined {\n if (outcome.ok) return undefined\n return {\n code: outcome.code,\n message: outcome.message,\n status: outcome.status,\n }\n}\n\nfunction renderDecisionContext(\n messages: ToolLoopMessage[],\n turnText: string,\n outcomes: ExecutedToolCall[],\n): string {\n const recent = messages.slice(-6).map((message) => `[${message.role}]\\n${message.content ?? ''}`)\n const assistant = turnText.trim() ? [`[assistant]\\n${turnText}`] : []\n const toolResults = [`[tool results]\\n${outcomes.map((item) => item.rendered).join('\\n')}`]\n return trimText(\n [...recent, ...assistant, ...toolResults].join('\\n\\n'),\n DEFAULT_DECISION_CONTEXT_CHARS,\n )\n}\n\n/** Canonical identifier for a tool call used by stuck-loop detection.\n * Keys are sorted so `{b:1,a:2}` and `{a:2,b:1}` produce the same hash. */\nfunction canonicalCallHash(call: ToolLoopCall): string {\n const sortedArgs = Object.fromEntries(\n Object.entries(call.args).sort(([a], [b]) => a.localeCompare(b)),\n )\n return `${call.toolName}:${JSON.stringify(sortedArgs)}`\n}\n\nfunction stringifySafe(value: unknown, max: number): string {\n let text: string\n try {\n text = JSON.stringify(value) ?? String(value)\n } catch {\n text = String(value)\n }\n return trimText(text, max)\n}\n\nfunction trimText(text: string, max: number): string {\n if (text.length <= max) return text\n return `${text.slice(0, max)}…`\n}\n\nfunction randomSuffix(len = 8): string {\n return Math.random()\n .toString(36)\n .slice(2, 2 + len)\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAEA,SAAS,cAAAA,aAAY,aAAa,uBAAuB;AACzD,SAAS,YAAAC,iBAAgB;AACzB;AAAA,EAIE;AAAA,OAEK;;;ACNA,IAAM,uBAAuB;AAC7B,IAAM,yBAAyB;AAC/B,IAAM,0BAA0B;AAChC,IAAM,uBAAuB;;;ACNpC,SAAS,uCAAuC;;;ACDhD,SAAS,kBAAkB;AAC3B,SAAS,qBAAqB;AAMvB,SAAS,YAAY,OAAiC;AAC3D,SAAO,UAAU,WAAW,QAAQ,EAAE,OAAO,KAAK,EAAE,OAAO,KAAK,CAAC;AACnE;AAEO,SAAS,wBAAwB,OAA4B;AAClE,SAAO,OAAO,KAAK,cAAc,KAAK,GAAG,MAAM;AACjD;AAEO,SAAS,yBAAyB,OAA8B;AACrE,SAAO,eAAe,KAAK;AAC7B;AAGO,SAAS,wBAA2B,OAAa;A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KAAK,KAAK,OAAO,KAAK;AAAA,EAC9C,QAAQ;AACN,WAAO,OAAO,KAAK;AAAA,EACrB;AACA,SAAO,SAAS,MAAM,GAAG;AAC3B;AAEA,SAAS,SAAS,MAAc,KAAqB;AACnD,MAAI,KAAK,UAAU,IAAK,QAAO;AAC/B,SAAO,GAAG,KAAK,MAAM,GAAG,GAAG,CAAC;AAC9B;AAEA,SAASD,cAAa,MAAM,GAAW;AACrC,SAAO,KAAK,OAAO,EAChB,SAAS,EAAE,EACX,MAAM,GAAG,IAAI,GAAG;AACrB;","names":["createHash","readFile","sha256","realpath","resolve","resolve","realpath","retryRejection","SHA256_PATTERN","assertExecutionId","assertSha256Digest","createHash","record","requireString","requireNumber","requireObject","readFile","hasControlCharacter","mkdir","open","join","assertExpiredLease","assertLease","assertSameSlot","assertUnexpiredLease","attemptRecord","claimSlot","leaseDigest","newLease","readClaim","readClaimIfPresent","readTerminal","readTerminalIfPresent","readTransitionIfPresent","rejectedExistingClaim","rejectedRetry","retryRejection","sealAttemptRef","sealClaim","sealLease","mkdir","record","winner","join","open","isNodeError","assertCount","mkdtemp","rm","tmpdir","join","isLlmSpan","REDACTION_VERSION","agentCandidateArtifactRefSchema","agentCandidateArtifactRefSchema","isLlmSpan","REDACTION_VERSION","mkdtemp","join","tmpdir","rm","mkdtemp","rm","tmpdir","join","agentCandidateWorkspaceSnapshotEvidenceSchema","agentCandidateWorkspaceSnapshotEvidenceSchema","mkdtemp","join","tmpdir","rm","REDACTION_VERSION","REDACTION_VERSION","randomBytes","lstat","readdir","relative","agentCandidateExecutionPlanEvidenceSchema","agentCandidateMaterializationReceiptSchema","agentCandidateWorkspaceSnapshotEvidenceSchema","randomBytes","modelLimits","agentCandidateExecutionPlanEvidenceSchema","agentCandidateMaterializationReceiptSchema","errorMessage","agentCandidateWorkspaceSnapshotEvidenceSchema","relative","lstat","readdir","record","source","value","record","memory","resolve","record","emit","join","resolve","record","record","randomSuffix","label"]}