@tangle-network/agent-runtime 0.106.0 → 0.107.1
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/README.md +2 -2
- package/dist/{activation-CRjVfOiy.js → activation-Ck5ksFWg.js} +5 -4
- package/dist/{activation-CRjVfOiy.js.map → activation-Ck5ksFWg.js.map} +1 -1
- package/dist/agent.d.ts +2 -2
- package/dist/agent.js +1 -1
- package/dist/{analyst-loop-DGdtVENg.js → analyst-loop-C8cGThTW.js} +12 -4
- package/dist/{analyst-loop-DGdtVENg.js.map → analyst-loop-C8cGThTW.js.map} +1 -1
- package/dist/analyst-loop.d.ts +1 -1
- package/dist/analyst-loop.js +1 -1
- package/dist/{backends-Dy8NujB4.js → backends-CiOCyRHb.js} +33 -3
- package/dist/{backends-Dy8NujB4.js.map → backends-CiOCyRHb.js.map} +1 -1
- package/dist/candidate-execution/index.js +4 -4
- package/dist/{candidate-execution-DqMbv1rU.js → candidate-execution-BUpR0mSD.js} +4 -4
- package/dist/{candidate-execution-DqMbv1rU.js.map → candidate-execution-BUpR0mSD.js.map} +1 -1
- package/dist/{conversation-XucG_K3l.js → conversation-BpLQZGPH.js} +2 -2
- package/dist/{conversation-XucG_K3l.js.map → conversation-BpLQZGPH.js.map} +1 -1
- package/dist/conversation.js +1 -1
- package/dist/{improvement-adapter-Cr5TBSji.d.ts → improvement-adapter-BaAdfJKT.d.ts} +2 -2
- package/dist/{improvement-cycle-C095kS_g.js → improvement-cycle-Ulvvbg5p.js} +367 -34
- package/dist/improvement-cycle-Ulvvbg5p.js.map +1 -0
- package/dist/{index-DruSKs3Z.d.ts → index-CeawCSEg.d.ts} +2 -2
- package/dist/{index-BGdxAwfO.d.ts → index-D6MwUzvB.d.ts} +7 -7
- package/dist/{index-CbNM40xG.d.ts → index-jmFVBIHo.d.ts} +2 -2
- package/dist/index.d.ts +6 -6
- package/dist/index.js +10 -10
- package/dist/intelligence.d.ts +145 -66
- package/dist/intelligence.js +5 -5
- package/dist/intelligence.js.map +1 -1
- package/dist/{knowledge-Ku-mPP4f.js → knowledge-Dizh_AtL.js} +4 -4
- package/dist/{knowledge-Ku-mPP4f.js.map → knowledge-Dizh_AtL.js.map} +1 -1
- package/dist/knowledge.d.ts +1 -1
- package/dist/knowledge.js +1 -1
- package/dist/{loop-runner-bin-BXsFEUcf.d.ts → loop-runner-bin-BbYG9CeA.d.ts} +3 -3
- package/dist/{loop-runner-bin-BwjQ1NfH.js → loop-runner-bin-CvdKZkE4.js} +3 -3
- package/dist/{loop-runner-bin-BwjQ1NfH.js.map → loop-runner-bin-CvdKZkE4.js.map} +1 -1
- package/dist/loop-runner-bin.d.ts +1 -1
- package/dist/loop-runner-bin.js +1 -1
- package/dist/loops.d.ts +1 -1
- package/dist/loops.js +1 -1
- package/dist/mcp/index.d.ts +1 -1
- package/dist/mcp/index.js +1 -1
- package/dist/{prepare-B53sPV7M.js → prepare-_WTTffkz.js} +25 -8
- package/dist/prepare-_WTTffkz.js.map +1 -0
- package/dist/primeintellect/index.d.ts +1 -1
- package/dist/primeintellect/index.js +1 -1
- package/dist/{protected-model-port-BLPH5VVv.js → protected-model-port-ZUwVuftA.js} +2 -2
- package/dist/{protected-model-port-BLPH5VVv.js.map → protected-model-port-ZUwVuftA.js.map} +1 -1
- package/dist/{redact-kbIOjfjM.d.ts → redact-C5xOm8cu.d.ts} +23 -3
- package/dist/{runtime-BG0BziaP.js → runtime-5zM5XxLr.js} +2 -2
- package/dist/{runtime-BG0BziaP.js.map → runtime-5zM5XxLr.js.map} +1 -1
- package/dist/testing.js +222 -194
- package/dist/testing.js.map +1 -1
- package/dist/{types-Cja5OTGh.d.ts → types-CfGKhIuj.d.ts} +10 -2
- package/dist/{workspace-archive-BosQiotA.js → workspace-archive-CIG1VNCj.js} +2 -2
- package/dist/{workspace-archive-BosQiotA.js.map → workspace-archive-CIG1VNCj.js.map} +1 -1
- package/package.json +7 -6
- package/dist/improvement-cycle-C095kS_g.js.map +0 -1
- package/dist/prepare-B53sPV7M.js.map +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"backends-Dy8NujB4.js","names":[],"sources":["../src/sessions.ts","../src/backends.ts"],"sourcesContent":["/**\n *\n * Session helpers + an in-memory `RuntimeSessionStore` implementation suitable\n * for tests, scratch processes, and per-request scratch storage in serverless\n * runtimes. Durable stores (D1, postgres, Durable Objects) implement the same\n * interface from `./types`.\n *\n * @stable\n */\n\nimport { SessionMismatchError } from './errors'\nimport type {\n AgentBackendContext,\n AgentBackendInput,\n AgentExecutionBackend,\n RuntimeSession,\n RuntimeSessionStore,\n RuntimeStreamEvent,\n} from './types'\n\n/** @internal */\nexport function newRuntimeSession(\n backend: string,\n requestedId?: string,\n metadata?: Record<string, unknown>,\n): RuntimeSession {\n const now = nowIso()\n return {\n id: requestedId || crypto.randomUUID(),\n backend,\n status: 'active',\n createdAt: now,\n updatedAt: now,\n metadata,\n }\n}\n\n/** @internal */\nexport function touchSession(session: RuntimeSession): RuntimeSession {\n return { ...session, updatedAt: nowIso() }\n}\n\n/** @internal */\nexport function nowIso(): string {\n return new Date().toISOString()\n}\n\ninterface StartOrResumeRuntimeSessionOptions<TInput extends AgentBackendInput> {\n backend: AgentExecutionBackend<TInput>\n input: TInput | (() => TInput)\n /** Smaller input used only when the backend can continue its native session. */\n continuationInput?: TInput | (() => TInput)\n context: Omit<AgentBackendContext, 'session'>\n store?: RuntimeSessionStore\n sessionId?: string\n resume?: boolean\n validateSession?: (session: RuntimeSession) => void\n}\n\ninterface RuntimeSessionCall<TInput extends AgentBackendInput> {\n session: RuntimeSession\n input: TInput\n resumed: boolean\n}\n\n/** Start or resume one backend session and persist its current identity. @internal */\nexport async function startOrResumeRuntimeSession<TInput extends AgentBackendInput>(\n options: StartOrResumeRuntimeSessionOptions<TInput>,\n): Promise<RuntimeSessionCall<TInput>> {\n const existing =\n options.resume && options.sessionId ? await options.store?.get(options.sessionId) : undefined\n if (!existing) {\n const input = resolveSessionInput(options.input)\n const session = options.backend.start\n ? await options.backend.start(input, {\n ...options.context,\n requestedSessionId: options.sessionId,\n })\n : newRuntimeSession(options.backend.kind, options.sessionId)\n assertSessionBackend(session, options.backend.kind)\n options.validateSession?.(session)\n await options.store?.put(session)\n return { session, input, resumed: false }\n }\n\n assertSessionBackend(existing, options.backend.kind)\n const continued = options.backend.resume !== undefined\n const input = resolveSessionInput(\n continued ? (options.continuationInput ?? options.input) : options.input,\n )\n const session = options.backend.resume\n ? await options.backend.resume(existing, input, options.context)\n : touchSession({ ...existing, status: 'active' })\n assertSessionBackend(session, options.backend.kind)\n options.validateSession?.(session)\n await options.store?.put(session)\n return { session, input, resumed: true }\n}\n\nfunction resolveSessionInput<TInput extends AgentBackendInput>(\n input: TInput | (() => TInput),\n): TInput {\n return typeof input === 'function' ? input() : input\n}\n\nfunction assertSessionBackend(session: RuntimeSession, backend: string): void {\n if (session.backend !== backend) throw new SessionMismatchError(session.backend, backend)\n}\n\n/** In-memory `RuntimeSessionStore` for single-process use and tests. @stable */\nexport class InMemoryRuntimeSessionStore implements RuntimeSessionStore {\n private readonly sessions = new Map<string, RuntimeSession>()\n private readonly events = new Map<string, RuntimeStreamEvent[]>()\n\n get(sessionId: string): RuntimeSession | undefined {\n return this.sessions.get(sessionId)\n }\n\n put(session: RuntimeSession): void {\n this.sessions.set(session.id, session)\n }\n\n appendEvent(sessionId: string, event: RuntimeStreamEvent): void {\n const existing = this.events.get(sessionId) ?? []\n existing.push(event)\n this.events.set(sessionId, existing)\n }\n\n listEvents(sessionId: string): RuntimeStreamEvent[] {\n return [...(this.events.get(sessionId) ?? [])]\n }\n}\n","/**\n *\n * Backend factories for `runAgentTaskStream`. Three shapes ship in core:\n *\n * - `createIterableBackend` — wrap any custom async iterable into a backend\n * - `createSandboxPromptBackend` — sandbox / sidecar `streamPrompt` clients\n * - `createOpenAICompatibleBackend` — OpenAI-style chat completions endpoints\n *\n * Adapters stay thin: domain repos own auth, model selection, and the concrete\n * tool surface. The factories handle session creation, stream normalization,\n * and graceful end-of-stream signalling.\n *\n * @stable\n */\n\nimport { BackendTransportError } from './errors'\nimport { newRuntimeSession, nowIso, touchSession } from './sessions'\nimport type {\n AgentBackendContext,\n AgentBackendInput,\n AgentExecutionBackend,\n OpenAIChatResponseFormat,\n OpenAIChatTool,\n OpenAIChatToolChoice,\n RuntimeSession,\n RuntimeStreamEvent,\n} from './types'\n\n/** Wrap any custom async-iterable stream into a typed `AgentExecutionBackend`. @stable */\nexport function createIterableBackend<TInput extends AgentBackendInput>(options: {\n kind: string\n start?: AgentExecutionBackend<TInput>['start']\n resume?: AgentExecutionBackend<TInput>['resume']\n stream: AgentExecutionBackend<TInput>['stream']\n stop?: AgentExecutionBackend<TInput>['stop']\n}): AgentExecutionBackend<TInput> {\n return options\n}\n\n/** Build an `AgentExecutionBackend` backed by a sandbox/sidecar `streamPrompt` call. @stable */\nexport function createSandboxPromptBackend<\n TBox,\n TInput extends AgentBackendInput = AgentBackendInput,\n>(options: {\n kind?: string\n getBox(input: TInput, context: Omit<AgentBackendContext, 'session'>): Promise<TBox> | TBox\n streamPrompt(box: TBox, message: string, context: AgentBackendContext): AsyncIterable<unknown>\n mapEvent?: (event: unknown, context: AgentBackendContext) => RuntimeStreamEvent | undefined\n getSessionId?: (box: TBox, input: TInput) => string | undefined\n}): AgentExecutionBackend<TInput> {\n const kind = options.kind ?? 'sandbox'\n return {\n kind,\n async start(input, context) {\n const box = await options.getBox(input, context)\n return newRuntimeSession(\n kind,\n options.getSessionId?.(box, input) ?? context.requestedSessionId,\n { resumable: true },\n )\n },\n resume(session) {\n return touchSession({ ...session, status: 'active' })\n },\n async *stream(input, context) {\n const box = await options.getBox(input, context)\n const message = input.message ?? input.messages?.at(-1)?.content ?? context.task.intent\n for await (const event of options.streamPrompt(box, message, context)) {\n const mapped = options.mapEvent?.(event, context) ?? mapCommonBackendEvent(event, context)\n if (mapped) yield mapped\n }\n },\n }\n}\n\n/** @stable */\n/**\n * Retry policy for transient transport errors (rate limits, upstream\n * timeouts). Defaults to 5 attempts with exponential backoff starting at\n * 1s, ±25% jitter, capped at 30s. Set `maxAttempts: 1` to disable retries.\n *\n * Retried status codes:\n * - 408 Request Timeout\n * - 425 Too Early\n * - 429 Too Many Requests\n * - 500 / 502 / 503 / 504 — upstream transient failures\n *\n * Hard failures (401, 403, 4xx other than the above) propagate immediately.\n */\nexport interface BackendRetryPolicy {\n /** Total attempts including the first try. Default 5. */\n maxAttempts?: number\n /** Initial backoff in ms before the second attempt. Default 1000. */\n initialBackoffMs?: number\n /** Hard ceiling on backoff in ms. Default 30000. */\n maxBackoffMs?: number\n /** Jitter fraction in [0, 1]. Default 0.25 (±25%). */\n jitter?: number\n /** Status codes that trigger a retry. Default: 408, 425, 429, 500, 502, 503, 504. */\n retryStatuses?: ReadonlyArray<number>\n /**\n * Per-attempt wall-clock deadline in ms. If a single fetch attempt does\n * not return headers within this window the attempt is aborted and\n * retried. Default 120000 (2 min). Without this a hung upstream blocks\n * the attempt indefinitely — observed in production as a 15-minute\n * `fetch failed` that burned an entire eval persona. Set to 0 to disable.\n */\n requestTimeoutMs?: number\n}\n\nconst DEFAULT_RETRY_STATUSES = [408, 425, 429, 500, 502, 503, 504] as const\n\nfunction pickRetryDelayMs(attempt: number, policy: Required<BackendRetryPolicy>): number {\n const exp = policy.initialBackoffMs * 2 ** (attempt - 1)\n const capped = Math.min(exp, policy.maxBackoffMs)\n const jitter = capped * policy.jitter * (Math.random() * 2 - 1)\n return Math.max(0, Math.round(capped + jitter))\n}\n\n/**\n * Derive a per-attempt AbortSignal that fires when EITHER the caller's\n * signal aborts OR `timeoutMs` elapses. `dispose()` clears the timer so a\n * completed attempt doesn't leak a pending timeout. `timeoutMs <= 0`\n * disables the deadline (caller signal still propagates).\n */\nfunction withTimeout(\n callerSignal: AbortSignal | undefined,\n timeoutMs: number,\n): { signal: AbortSignal; dispose: () => void } {\n if (timeoutMs <= 0) {\n return { signal: callerSignal ?? new AbortController().signal, dispose: () => undefined }\n }\n const controller = new AbortController()\n const timer = setTimeout(\n () => controller.abort(new Error(`request timed out after ${timeoutMs}ms`)),\n timeoutMs,\n )\n if (typeof (timer as { unref?: () => void }).unref === 'function') {\n ;(timer as { unref: () => void }).unref()\n }\n const onCallerAbort = () => controller.abort(callerSignal?.reason ?? new Error('aborted'))\n if (callerSignal) {\n if (callerSignal.aborted) onCallerAbort()\n else callerSignal.addEventListener('abort', onCallerAbort, { once: true })\n }\n return {\n signal: controller.signal,\n dispose: () => {\n clearTimeout(timer)\n callerSignal?.removeEventListener('abort', onCallerAbort)\n },\n }\n}\n\nfunction sleep(ms: number, signal?: AbortSignal): Promise<void> {\n return new Promise((resolve, reject) => {\n if (signal?.aborted) {\n reject(signal.reason ?? new Error('aborted'))\n return\n }\n const t = setTimeout(() => {\n signal?.removeEventListener('abort', onAbort)\n resolve()\n }, ms)\n const onAbort = () => {\n clearTimeout(t)\n reject(signal?.reason ?? new Error('aborted'))\n }\n signal?.addEventListener('abort', onAbort, { once: true })\n })\n}\n\n/**\n *\n * OpenAI-compat streaming backend. Routes `runAgentTaskStream` through any\n * `POST /chat/completions` endpoint that speaks OpenAI's SSE protocol —\n * Tangle Router, OpenAI direct, OpenRouter, Groq, DeepSeek, Together. The\n * router also fronts Anthropic models in Anthropic-native SSE shape; this\n * backend handles both.\n *\n * ### Tool calls\n *\n * Pass `tools` (and optionally `toolChoice`) to forward an OpenAI Chat\n * Completions `tools[]` array on every request. Streamed `tool_call` chunks\n * are buffered until the model finalizes them (either `finish_reason:\n * 'tool_calls'` for OpenAI shape or a `content_block_stop` for Anthropic\n * `tool_use` blocks proxied through the router), then emitted as a single\n * `tool_call` RuntimeStreamEvent with the assembled `args`.\n *\n * The backend does NOT execute tools — it surfaces calls for the caller's\n * own dispatcher (typically the product's MCP / sandbox runtime) to fulfill\n * and feed back as a subsequent `messages` turn. This keeps the transport\n * thin and lets the agent host own tool dispatch policy.\n *\n * ### Fail-loud errors\n *\n * Non-success HTTP responses (4xx/5xx) and exhausted retry budgets throw\n * `BackendTransportError` from inside the `stream()` generator. The runtime\n * catches the throw, yields a `backend_error` with a typed `error` field\n * (`kind`, `status`, truncated `body`) and a terminal `final` event with\n * `status: 'failed'` carrying the same detail. Consumers MUST map\n * `final.error` onto their `RunRecord.error` — silently treating an empty\n * `finalText` as \"agent produced nothing\" hides credit exhaustion, auth\n * failure, and upstream outages.\n *\n * @stable\n */\nexport function createOpenAICompatibleBackend<\n TInput extends AgentBackendInput = AgentBackendInput,\n>(options: {\n apiKey: string\n baseUrl: string\n model: string\n kind?: string\n /**\n * OpenAI Chat Completions `tools[]` definitions surfaced to the model on\n * every request. Omit to send a tool-free request (existing behavior).\n * The runtime makes no assumption about the dispatcher — calls stream out\n * as `tool_call` events and the caller is responsible for executing them\n * and feeding `tool_result` messages back on a follow-up turn.\n */\n tools?: ReadonlyArray<OpenAIChatTool>\n /**\n * OpenAI Chat Completions `tool_choice`. Default `undefined` (request\n * omits the field; provider falls back to its own default — typically\n * `'auto'`).\n */\n toolChoice?: OpenAIChatToolChoice\n /**\n * OpenAI Chat Completions `response_format`. Omit for provider default text.\n */\n responseFormat?: OpenAIChatResponseFormat\n /** OpenAI Chat Completions `temperature`. Omit for provider default. */\n temperature?: number\n /** Maximum completion tokens, sent as OpenAI-compatible `max_tokens`. Omit for provider default. */\n maxTokens?: number\n fetchImpl?: typeof fetch\n retry?: BackendRetryPolicy\n}): AgentExecutionBackend<TInput> {\n const fetcher = options.fetchImpl ?? fetch\n const kind = options.kind ?? 'tcloud'\n const retryPolicy: Required<BackendRetryPolicy> = {\n maxAttempts: options.retry?.maxAttempts ?? 5,\n initialBackoffMs: options.retry?.initialBackoffMs ?? 1000,\n maxBackoffMs: options.retry?.maxBackoffMs ?? 30000,\n jitter: options.retry?.jitter ?? 0.25,\n retryStatuses: options.retry?.retryStatuses ?? DEFAULT_RETRY_STATUSES,\n requestTimeoutMs: options.retry?.requestTimeoutMs ?? 120_000,\n }\n return {\n kind,\n start(_input, context) {\n return newRuntimeSession(kind, context.requestedSessionId)\n },\n async *stream(input, context) {\n const url = `${options.baseUrl.replace(/\\/$/, '')}/chat/completions`\n // `stream_options.include_usage` instructs OpenAI-compatible providers\n // (and the Tangle Router) to emit a final usage chunk in the SSE stream.\n // Without this the response carries no token counts and every downstream\n // ledger reads zero. Providers that don't recognize the field ignore it.\n const bodyPayload: Record<string, unknown> = {\n model: options.model,\n stream: true,\n stream_options: { include_usage: true },\n messages: input.messages ?? [\n { role: 'user', content: input.message ?? context.task.intent },\n ],\n }\n if (options.tools && options.tools.length > 0) {\n bodyPayload.tools = options.tools\n if (options.toolChoice !== undefined) bodyPayload.tool_choice = options.toolChoice\n }\n if (options.responseFormat !== undefined) {\n bodyPayload.response_format = options.responseFormat\n }\n if (options.temperature !== undefined) {\n bodyPayload.temperature = options.temperature\n }\n if (options.maxTokens !== undefined) {\n bodyPayload.max_tokens = options.maxTokens\n }\n const requestBody = JSON.stringify(bodyPayload)\n let response: Response | undefined\n let lastStatus = 0\n // The last thrown transport error (timeout abort, DNS / connection\n // failure). Network throws are retryable just like 5xx — without this\n // a `fetch failed` propagated immediately and burned the attempt.\n let lastThrown: unknown\n for (let attempt = 1; attempt <= retryPolicy.maxAttempts; attempt++) {\n lastThrown = undefined\n // Per-attempt deadline: abort a hung upstream instead of waiting\n // forever. Linked to context.signal so a caller cancel still wins.\n const attemptSignal = withTimeout(context.signal, retryPolicy.requestTimeoutMs)\n try {\n response = await fetcher(url, {\n method: 'POST',\n headers: {\n Authorization: `Bearer ${options.apiKey}`,\n 'Content-Type': 'application/json',\n // Cross-gateway forwarding: when this call is part of a\n // multi-agent conversation, the runner stamps run/turn/\n // depth/forwarded-auth headers onto the context. They flow\n // through to the downstream gateway verbatim so the original\n // user gets billed, the recursion depth stays bounded, and\n // the trace correlates across hops.\n ...(context.propagatedHeaders ?? {}),\n },\n body: requestBody,\n signal: attemptSignal.signal,\n })\n } catch (err) {\n attemptSignal.dispose()\n // A caller-initiated abort is terminal — do not retry it.\n if (context.signal?.aborted) throw err\n lastThrown = err\n response = undefined\n if (attempt === retryPolicy.maxAttempts) break\n await sleep(pickRetryDelayMs(attempt, retryPolicy), context.signal)\n continue\n }\n attemptSignal.dispose()\n if (response.ok) break\n lastStatus = response.status\n if (!retryPolicy.retryStatuses.includes(response.status)) break\n if (attempt === retryPolicy.maxAttempts) break\n // Drain the failed body so the connection can be reused.\n try {\n await response.body?.cancel()\n } catch {\n // Best-effort — some runtimes don't expose cancel.\n }\n const delayMs = pickRetryDelayMs(attempt, retryPolicy)\n await sleep(delayMs, context.signal)\n }\n if (!response) {\n const reason = lastThrown instanceof Error ? lastThrown.message : String(lastThrown)\n throw new BackendTransportError(\n kind,\n `chat backend unreachable after ${retryPolicy.maxAttempts} attempts: ${reason}`,\n { status: 0 },\n )\n }\n if (!response.ok) {\n // Capture the upstream body so the operator sees *why* the call\n // failed (e.g. `free_tier_limit`, `invalid_api_key`,\n // `model_not_found`). Truncate aggressively — HTML error pages from a\n // misconfigured proxy can be megabytes and would otherwise bloat\n // every persisted event. Best-effort: if body reading throws we\n // still surface the status code.\n let body: string | undefined\n try {\n const raw = await response.text()\n body = raw.length > MAX_ERROR_BODY_BYTES ? `${raw.slice(0, MAX_ERROR_BODY_BYTES)}…` : raw\n } catch {\n body = undefined\n }\n throw new BackendTransportError(kind, `chat backend returned ${lastStatus || 'unknown'}`, {\n status: lastStatus || 0,\n body,\n })\n }\n yield* streamResponseEvents(response, context, options.model)\n },\n }\n}\n\n/**\n * Cap the captured error body. 2 KiB is enough to carry a JSON error envelope\n * with a structured `code`/`message` payload (the router returns ~150 bytes\n * for a free-tier denial; OpenAI returns ~300 bytes for invalid auth) without\n * letting an HTML error page balloon persisted events.\n */\nconst MAX_ERROR_BODY_BYTES = 2048\n\n/**\n * Token usage accumulated across an SSE stream. OpenAI emits a single final\n * `usage` chunk; Anthropic emits `input_tokens` on `message_start` and\n * `output_tokens` on the terminal `message_delta`. We accept both — and the\n * router proxy may forward either shape depending on which upstream answered.\n */\ninterface StreamUsageAccumulator {\n tokensIn?: number\n tokensOut?: number\n model?: string\n finishReason?: string\n saw: boolean\n}\n\n/** @internal */\nexport function normalizeBackendStreamEvent(\n event: RuntimeStreamEvent,\n task: AgentBackendContext['task'],\n session: RuntimeSession,\n): RuntimeStreamEvent {\n if (\n 'task' in event &&\n event.task &&\n 'session' in event &&\n event.session &&\n 'timestamp' in event &&\n event.timestamp\n ) {\n return event\n }\n return {\n ...event,\n task: 'task' in event && event.task ? event.task : task,\n session: 'session' in event && event.session ? event.session : session,\n timestamp: 'timestamp' in event && event.timestamp ? event.timestamp : nowIso(),\n } as RuntimeStreamEvent\n}\n\nfunction mapCommonBackendEvent(\n event: unknown,\n context: AgentBackendContext,\n): RuntimeStreamEvent | undefined {\n if (!event || typeof event !== 'object') return undefined\n const record = event as Record<string, unknown>\n const type = String(record.type ?? '')\n const data =\n record.data && typeof record.data === 'object'\n ? (record.data as Record<string, unknown>)\n : record\n if (type === 'message.part.updated' || type === 'text_delta' || type === 'delta') {\n // `@tangle-network/sandbox` `box.streamPrompt` emits `message.part.updated`\n // with a nested part: `{ type: 'message.part.updated', data: { part:\n // { type: 'text', text: '…' } } }`. Walk into `data.part.text` so the\n // canonical sandbox-SDK shape produces a `text_delta` natively — no\n // per-product `mapEvent` shim required. Tool parts are picked up by\n // the `tool_call` / `tool_result` branches below; non-text parts here\n // fall through to `undefined` (the consumer can opt in via `mapEvent`).\n const part = data.part as Record<string, unknown> | undefined\n const partText =\n part !== undefined &&\n typeof part === 'object' &&\n (part.type === 'text' || part.type === undefined)\n ? stringValue(part.text)\n : undefined\n const text =\n stringValue(data.text) ?? stringValue(data.delta) ?? stringValue(record.text) ?? partText\n return text\n ? {\n type: 'text_delta',\n task: context.task,\n session: context.session,\n text,\n timestamp: nowIso(),\n }\n : undefined\n }\n if (type === 'reasoning_delta') {\n const text = stringValue(data.text) ?? stringValue(record.text)\n return text\n ? {\n type: 'reasoning_delta',\n task: context.task,\n session: context.session,\n text,\n timestamp: nowIso(),\n }\n : undefined\n }\n if (type === 'tool_call') {\n return {\n type: 'tool_call',\n task: context.task,\n session: context.session,\n toolName: stringValue(data.name) ?? stringValue(record.toolName) ?? 'tool',\n toolCallId: stringValue(data.id) ?? stringValue(record.toolCallId),\n args: data.args ?? data.input ?? record.args,\n timestamp: nowIso(),\n }\n }\n if (type === 'tool_result') {\n return {\n type: 'tool_result',\n task: context.task,\n session: context.session,\n toolName: stringValue(data.name) ?? stringValue(record.toolName) ?? 'tool',\n toolCallId: stringValue(data.id) ?? stringValue(record.toolCallId),\n result: data.result ?? data.output ?? record.result,\n timestamp: nowIso(),\n }\n }\n if (type === 'artifact') {\n const artifactId =\n stringValue(data.artifactId) ?? stringValue(data.id) ?? stringValue(record.artifactId)\n if (!artifactId) return undefined\n return {\n type: 'artifact',\n task: context.task,\n session: context.session,\n artifactId,\n name: stringValue(data.name) ?? stringValue(record.name),\n mimeType: stringValue(data.mimeType) ?? stringValue(record.mimeType),\n uri: stringValue(data.uri) ?? stringValue(record.uri),\n content: stringValue(data.content) ?? stringValue(data.body) ?? stringValue(record.content),\n metadata:\n data.metadata && typeof data.metadata === 'object'\n ? (data.metadata as Record<string, unknown>)\n : undefined,\n timestamp: nowIso(),\n }\n }\n if (type === 'proposal_created' || type === 'proposal' || type === 'filing') {\n const proposalId =\n stringValue(data.proposalId) ?? stringValue(data.id) ?? stringValue(record.proposalId)\n if (!proposalId) return undefined\n const status = stringValue(data.status) ?? stringValue(record.status)\n return {\n type: 'proposal_created',\n task: context.task,\n session: context.session,\n proposalId,\n title: stringValue(data.title) ?? stringValue(record.title) ?? proposalId,\n status:\n status === 'pending' || status === 'approved' || status === 'rejected' ? status : undefined,\n content: stringValue(data.content) ?? stringValue(data.body) ?? stringValue(record.content),\n timestamp: nowIso(),\n }\n }\n if (type === 'result' || type === 'final') {\n const text = stringValue(data.finalText) ?? stringValue(data.text) ?? stringValue(record.text)\n return text\n ? {\n type: 'text_delta',\n task: context.task,\n session: context.session,\n text,\n timestamp: nowIso(),\n }\n : undefined\n }\n return undefined\n}\n\nasync function* streamResponseEvents(\n response: Response,\n context: AgentBackendContext,\n requestedModel: string,\n): AsyncIterable<RuntimeStreamEvent> {\n const body = response.body\n if (!body) return\n const reader = body.getReader()\n const decoder = new TextDecoder()\n let buffer = ''\n const usage: StreamUsageAccumulator = { saw: false }\n // Tool-call assembly is stateful across SSE chunks: both OpenAI and\n // Anthropic streamed `arguments`/`partial_json` incrementally and the\n // final event is only safe to emit once we see a `finish_reason:\n // 'tool_calls'` or `content_block_stop` for the relevant index.\n const toolCalls: ToolCallAccumulator = new Map()\n const startedAt = Date.now()\n for (;;) {\n const { done, value } = await reader.read()\n if (done) break\n buffer += decoder.decode(value, { stream: true }).replace(/\\r\\n/g, '\\n')\n for (const event of drainStreamBuffer(false)) yield event\n }\n buffer += decoder.decode().replace(/\\r\\n/g, '\\n')\n for (const event of drainStreamBuffer(true)) yield event\n if (buffer.trim()) {\n for (const event of parseStreamChunk(buffer, context, usage, toolCalls)) yield event\n }\n // Flush any tool calls the model never closed via `finish_reason` — the\n // upstream may have terminated the stream without a terminal chunk (e.g.\n // when the proxy proactively forwards `[DONE]`). Emitting these here is\n // strictly safer than silently dropping a tool call the agent intended.\n for (const event of flushPendingToolCalls(toolCalls, context)) yield event\n // Synthesize a single `llm_call` event from accumulated usage. We only emit\n // when the upstream actually reported tokens — silent zeros would corrupt\n // every cost ledger that observes the stream. Consumers that need to detect\n // missing usage can check `tokensIn === undefined`.\n if (usage.saw) {\n yield {\n type: 'llm_call',\n task: context.task,\n session: context.session,\n model: usage.model ?? requestedModel,\n tokensIn: usage.tokensIn,\n tokensOut: usage.tokensOut,\n // `costUsd` is intentionally absent — pricing tables live in consumers\n // (agent-eval's `estimateCost`, MetricsCollector). Emitting a wrong\n // number here is worse than emitting none.\n latencyMs: Date.now() - startedAt,\n finishReason: usage.finishReason,\n timestamp: nowIso(),\n }\n }\n\n function* drainStreamBuffer(flush: boolean): Iterable<RuntimeStreamEvent> {\n for (;;) {\n const sseBoundary = buffer.indexOf('\\n\\n')\n if (sseBoundary >= 0) {\n const chunk = buffer.slice(0, sseBoundary)\n buffer = buffer.slice(sseBoundary + 2)\n for (const event of parseStreamChunk(chunk, context, usage, toolCalls)) yield event\n continue\n }\n\n const newline = buffer.indexOf('\\n')\n if (newline >= 0 && !buffer.slice(0, newline).startsWith('data:')) {\n const line = buffer.slice(0, newline)\n buffer = buffer.slice(newline + 1)\n for (const event of parseStreamChunk(line, context, usage, toolCalls)) yield event\n continue\n }\n\n if (flush && buffer.trim() && !buffer.trimStart().startsWith('data:')) {\n const line = buffer\n buffer = ''\n for (const event of parseStreamChunk(line, context, usage, toolCalls)) yield event\n continue\n }\n\n break\n }\n }\n}\n\n/**\n * Per-tool-call accumulator. Keyed by either OpenAI `index` (cast to string)\n * or Anthropic `content_block` `index`. Holds the streamed identifier, name,\n * and string-form `arguments` so we can emit a single typed `tool_call`\n * event once the stream signals the call is finalized.\n */\ntype ToolCallAccumulator = Map<\n string,\n {\n id?: string\n name?: string\n /** Accumulated JSON-string `arguments` / `input` payload. */\n argsRaw: string\n /** Source format: OpenAI delta vs Anthropic `tool_use` block. */\n source: 'openai' | 'anthropic'\n /** Set true once the model signals this call is complete. */\n finalized: boolean\n }\n>\n\nfunction* parseStreamChunk(\n chunk: string,\n context: AgentBackendContext,\n usage: StreamUsageAccumulator,\n toolCalls: ToolCallAccumulator,\n): Iterable<RuntimeStreamEvent> {\n const lines = chunk.split(/\\r?\\n/)\n const dataLines = lines.filter((line) => line.startsWith('data:'))\n if (\n dataLines.length === 0 &&\n lines.every((line) => {\n const trimmed = line.trim()\n return trimmed.length === 0 || trimmed.startsWith(':')\n })\n ) {\n return\n }\n const data =\n dataLines.length > 0\n ? dataLines.map((line) => line.slice(5).trimStart()).join('\\n')\n : chunk.trim()\n if (!data || data === '[DONE]') return\n let parsed: Record<string, unknown>\n try {\n parsed = JSON.parse(data) as Record<string, unknown>\n } catch {\n yield {\n type: 'text_delta',\n task: context.task,\n session: context.session,\n text: data,\n timestamp: nowIso(),\n }\n return\n }\n captureStreamUsage(parsed, usage)\n const choices = parsed.choices\n const choice = Array.isArray(choices)\n ? (choices[0] as Record<string, unknown> | undefined)\n : undefined\n const delta = choice?.delta as Record<string, unknown> | undefined\n const message = choice?.message as Record<string, unknown> | undefined\n\n // ── OpenAI streamed `tool_calls` deltas ─────────────────────────────\n const deltaToolCalls = delta?.tool_calls\n if (Array.isArray(deltaToolCalls)) {\n for (const tc of deltaToolCalls) {\n if (!tc || typeof tc !== 'object') continue\n const rec = tc as Record<string, unknown>\n const idx = numberValue(rec.index) ?? 0\n const key = `openai:${idx}`\n const acc = toolCalls.get(key) ?? { argsRaw: '', source: 'openai' as const, finalized: false }\n const id = stringValue(rec.id)\n if (id) acc.id = id\n const fn = rec.function as Record<string, unknown> | undefined\n const name = stringValue(fn?.name)\n if (name) acc.name = name\n const args = stringValue(fn?.arguments)\n if (args) acc.argsRaw += args\n toolCalls.set(key, acc)\n }\n }\n // `message.tool_calls` is the non-streamed shape — the model returned a\n // complete tool call in one chunk. Treat the whole array as terminal.\n const messageToolCalls = message?.tool_calls\n if (Array.isArray(messageToolCalls)) {\n for (const tc of messageToolCalls) {\n if (!tc || typeof tc !== 'object') continue\n const rec = tc as Record<string, unknown>\n const fn = rec.function as Record<string, unknown> | undefined\n const idx = numberValue(rec.index) ?? messageToolCalls.indexOf(tc)\n const key = `openai:${idx}`\n const acc = toolCalls.get(key) ?? { argsRaw: '', source: 'openai' as const, finalized: false }\n const id = stringValue(rec.id)\n if (id) acc.id = id\n const name = stringValue(fn?.name)\n if (name) acc.name = name\n const args = stringValue(fn?.arguments)\n if (args) acc.argsRaw += args\n acc.finalized = true\n toolCalls.set(key, acc)\n }\n }\n\n const finishReason = stringValue(choice?.finish_reason)\n if (finishReason === 'tool_calls') {\n // Model signaled it's done streaming tool calls — flush every OpenAI-\n // sourced pending entry. Subsequent chunks (usage, [DONE]) won't add\n // more.\n for (const [key, acc] of toolCalls) {\n if (acc.source === 'openai' && !acc.finalized) acc.finalized = true\n toolCalls.set(key, acc)\n }\n }\n\n // ── Anthropic shape (proxied through router) ────────────────────────\n const eventType = stringValue(parsed.type)\n if (eventType === 'content_block_start') {\n const block = parsed.content_block as Record<string, unknown> | undefined\n if (block && stringValue(block.type) === 'tool_use') {\n const idx = numberValue(parsed.index) ?? 0\n const key = `anthropic:${idx}`\n toolCalls.set(key, {\n id: stringValue(block.id),\n name: stringValue(block.name),\n argsRaw: '',\n source: 'anthropic',\n finalized: false,\n })\n }\n }\n if (eventType === 'content_block_delta') {\n const d = parsed.delta as Record<string, unknown> | undefined\n const dType = stringValue(d?.type)\n if (dType === 'input_json_delta') {\n const idx = numberValue(parsed.index) ?? 0\n const key = `anthropic:${idx}`\n const acc = toolCalls.get(key)\n if (acc) {\n const partial = stringValue(d?.partial_json) ?? ''\n acc.argsRaw += partial\n toolCalls.set(key, acc)\n }\n } else {\n const text = stringValue(d?.text)\n if (text) {\n yield {\n type: 'text_delta',\n task: context.task,\n session: context.session,\n text,\n timestamp: nowIso(),\n }\n }\n }\n }\n if (eventType === 'content_block_stop') {\n const idx = numberValue(parsed.index) ?? 0\n const key = `anthropic:${idx}`\n const acc = toolCalls.get(key)\n if (acc) {\n acc.finalized = true\n toolCalls.set(key, acc)\n }\n }\n\n // Emit any tool calls that just became finalized. Done eagerly per-chunk so\n // consumers see the call as soon as it's safe — the analyst loop watches\n // `tool_call` events for delegation-pattern detection.\n for (const event of drainFinalizedToolCalls(toolCalls, context)) yield event\n\n // ── Text deltas ──────────────────────────────────────────────────────\n const text =\n stringValue(delta?.content) ?? stringValue(message?.content) ?? stringValue(parsed.text)\n if (text) {\n yield {\n type: 'text_delta',\n task: context.task,\n session: context.session,\n text,\n timestamp: nowIso(),\n }\n return\n }\n const mapped = mapCommonBackendEvent(parsed, context)\n if (mapped) yield mapped\n}\n\nfunction* drainFinalizedToolCalls(\n toolCalls: ToolCallAccumulator,\n context: AgentBackendContext,\n): Iterable<RuntimeStreamEvent> {\n for (const [key, acc] of toolCalls) {\n if (!acc.finalized) continue\n toolCalls.delete(key)\n yield buildToolCallEvent(acc, context)\n }\n}\n\nfunction* flushPendingToolCalls(\n toolCalls: ToolCallAccumulator,\n context: AgentBackendContext,\n): Iterable<RuntimeStreamEvent> {\n for (const [key, acc] of toolCalls) {\n toolCalls.delete(key)\n yield buildToolCallEvent(acc, context)\n }\n}\n\nfunction buildToolCallEvent(\n acc: { id?: string; name?: string; argsRaw: string; source: 'openai' | 'anthropic' },\n context: AgentBackendContext,\n): RuntimeStreamEvent {\n // `argsRaw` is JSON-string by the provider contract (OpenAI streams an\n // escaped JSON string; Anthropic streams `partial_json` chunks). Parse\n // best-effort — surface the raw string if parsing fails so downstream\n // doesn't lose the call entirely.\n let args: unknown = acc.argsRaw\n if (acc.argsRaw.length > 0) {\n try {\n args = JSON.parse(acc.argsRaw)\n } catch {\n args = acc.argsRaw\n }\n } else {\n args = {}\n }\n return {\n type: 'tool_call',\n task: context.task,\n session: context.session,\n toolName: acc.name ?? 'tool',\n toolCallId: acc.id,\n args,\n timestamp: nowIso(),\n }\n}\n\n/**\n * Accumulate token usage from any SSE chunk shape the router may emit.\n *\n * - OpenAI: a final chunk before `[DONE]` with `{ usage: { prompt_tokens,\n * completion_tokens, total_tokens } }` and (often) empty `choices`. The\n * `model` field is on every chunk and the last `choices[0].finish_reason`\n * carries the stop reason.\n * - Anthropic: `message_start` carries `message.model` and\n * `message.usage.input_tokens`. The terminal `message_delta` carries\n * `usage.output_tokens` and `delta.stop_reason`.\n */\nfunction captureStreamUsage(parsed: Record<string, unknown>, usage: StreamUsageAccumulator): void {\n const model = stringValue(parsed.model)\n if (model && !usage.model) usage.model = model\n\n const openAiUsage = parsed.usage as Record<string, unknown> | undefined\n if (openAiUsage && typeof openAiUsage === 'object') {\n const promptTokens = numberValue(openAiUsage.prompt_tokens)\n const completionTokens = numberValue(openAiUsage.completion_tokens)\n const inputTokens = numberValue(openAiUsage.input_tokens)\n const outputTokens = numberValue(openAiUsage.output_tokens)\n if (promptTokens !== undefined) {\n usage.tokensIn = promptTokens\n usage.saw = true\n } else if (inputTokens !== undefined) {\n usage.tokensIn = (usage.tokensIn ?? 0) + inputTokens\n usage.saw = true\n }\n if (completionTokens !== undefined) {\n usage.tokensOut = completionTokens\n usage.saw = true\n } else if (outputTokens !== undefined) {\n usage.tokensOut = (usage.tokensOut ?? 0) + outputTokens\n usage.saw = true\n }\n }\n\n const type = stringValue(parsed.type)\n if (type === 'message_start') {\n const message = parsed.message as Record<string, unknown> | undefined\n const messageModel = stringValue(message?.model)\n if (messageModel && !usage.model) usage.model = messageModel\n const messageUsage = message?.usage as Record<string, unknown> | undefined\n const inputTokens = numberValue(messageUsage?.input_tokens)\n if (inputTokens !== undefined) {\n usage.tokensIn = inputTokens\n usage.saw = true\n }\n const outputTokens = numberValue(messageUsage?.output_tokens)\n if (outputTokens !== undefined) {\n usage.tokensOut = (usage.tokensOut ?? 0) + outputTokens\n usage.saw = true\n }\n }\n if (type === 'message_delta') {\n const delta = parsed.delta as Record<string, unknown> | undefined\n const stopReason = stringValue(delta?.stop_reason)\n if (stopReason) usage.finishReason = stopReason\n }\n\n const choices = parsed.choices\n if (Array.isArray(choices)) {\n const finishReason = stringValue(\n (choices[0] as Record<string, unknown> | undefined)?.finish_reason,\n )\n if (finishReason) usage.finishReason = finishReason\n }\n}\n\nfunction numberValue(value: unknown): number | undefined {\n return typeof value === 'number' && Number.isFinite(value) ? value : undefined\n}\n\nfunction stringValue(value: unknown): string | undefined {\n return typeof value === 'string' && value.length > 0 ? value : undefined\n}\n"],"mappings":";;;;;;;;;;;;AAqBA,SAAgB,kBACd,SACA,aACA,UACgB;CAChB,MAAM,MAAM,OAAO;CACnB,OAAO;EACL,IAAI,eAAe,OAAO,WAAW;EACrC;EACA,QAAQ;EACR,WAAW;EACX,WAAW;EACX;CACF;AACF;;AAGA,SAAgB,aAAa,SAAyC;CACpE,OAAO;EAA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AW;GAC9B,MAAM,aAAa,MAAM,aAAa,KAAK;GAC3C,MAAM,MAAM;EACd;CACF;CACA,IAAI,SAAS,iBAAiB;EAC5B,MAAM,QAAQ,OAAO;EACrB,MAAM,aAAa,YAAY,OAAO,WAAW;EACjD,IAAI,YAAY,MAAM,eAAe;CACvC;CAEA,MAAM,UAAU,OAAO;CACvB,IAAI,MAAM,QAAQ,OAAO,GAAG;EAC1B,MAAM,eAAe,YAClB,QAAQ,EAAE,EAA0C,aACvD;EACA,IAAI,cAAc,MAAM,eAAe;CACzC;AACF;AAEA,SAAS,YAAY,OAAoC;CACvD,OAAO,OAAO,UAAU,YAAY,OAAO,SAAS,KAAK,IAAI,QAAQ,KAAA;AACvE;AAEA,SAAS,YAAY,OAAoC;CACvD,OAAO,OAAO,UAAU,YAAY,MAAM,SAAS,IAAI,QAAQ,KAAA;AACjE"}
|
|
1
|
+
{"version":3,"file":"backends-CiOCyRHb.js","names":[],"sources":["../src/sessions.ts","../src/backends.ts"],"sourcesContent":["/**\n *\n * Session helpers + an in-memory `RuntimeSessionStore` implementation suitable\n * for tests, scratch processes, and per-request scratch storage in serverless\n * runtimes. Durable stores (D1, postgres, Durable Objects) implement the same\n * interface from `./types`.\n *\n * @stable\n */\n\nimport { SessionMismatchError } from './errors'\nimport type {\n AgentBackendContext,\n AgentBackendInput,\n AgentExecutionBackend,\n RuntimeSession,\n RuntimeSessionStore,\n RuntimeStreamEvent,\n} from './types'\n\n/** @internal */\nexport function newRuntimeSession(\n backend: string,\n requestedId?: string,\n metadata?: Record<string, unknown>,\n): RuntimeSession {\n const now = nowIso()\n return {\n id: requestedId || crypto.randomUUID(),\n backend,\n status: 'active',\n createdAt: now,\n updatedAt: now,\n metadata,\n }\n}\n\n/** @internal */\nexport function touchSession(session: RuntimeSession): RuntimeSession {\n return { ...session, updatedAt: nowIso() }\n}\n\n/** @internal */\nexport function nowIso(): string {\n return new Date().toISOString()\n}\n\ninterface StartOrResumeRuntimeSessionOptions<TInput extends AgentBackendInput> {\n backend: AgentExecutionBackend<TInput>\n input: TInput | (() => TInput)\n /** Smaller input used only when the backend can continue its native session. */\n continuationInput?: TInput | (() => TInput)\n context: Omit<AgentBackendContext, 'session'>\n store?: RuntimeSessionStore\n sessionId?: string\n resume?: boolean\n validateSession?: (session: RuntimeSession) => void\n}\n\ninterface RuntimeSessionCall<TInput extends AgentBackendInput> {\n session: RuntimeSession\n input: TInput\n resumed: boolean\n}\n\n/** Start or resume one backend session and persist its current identity. @internal */\nexport async function startOrResumeRuntimeSession<TInput extends AgentBackendInput>(\n options: StartOrResumeRuntimeSessionOptions<TInput>,\n): Promise<RuntimeSessionCall<TInput>> {\n const existing =\n options.resume && options.sessionId ? await options.store?.get(options.sessionId) : undefined\n if (!existing) {\n const input = resolveSessionInput(options.input)\n const session = options.backend.start\n ? await options.backend.start(input, {\n ...options.context,\n requestedSessionId: options.sessionId,\n })\n : newRuntimeSession(options.backend.kind, options.sessionId)\n assertSessionBackend(session, options.backend.kind)\n options.validateSession?.(session)\n await options.store?.put(session)\n return { session, input, resumed: false }\n }\n\n assertSessionBackend(existing, options.backend.kind)\n const continued = options.backend.resume !== undefined\n const input = resolveSessionInput(\n continued ? (options.continuationInput ?? options.input) : options.input,\n )\n const session = options.backend.resume\n ? await options.backend.resume(existing, input, options.context)\n : touchSession({ ...existing, status: 'active' })\n assertSessionBackend(session, options.backend.kind)\n options.validateSession?.(session)\n await options.store?.put(session)\n return { session, input, resumed: true }\n}\n\nfunction resolveSessionInput<TInput extends AgentBackendInput>(\n input: TInput | (() => TInput),\n): TInput {\n return typeof input === 'function' ? input() : input\n}\n\nfunction assertSessionBackend(session: RuntimeSession, backend: string): void {\n if (session.backend !== backend) throw new SessionMismatchError(session.backend, backend)\n}\n\n/** In-memory `RuntimeSessionStore` for single-process use and tests. @stable */\nexport class InMemoryRuntimeSessionStore implements RuntimeSessionStore {\n private readonly sessions = new Map<string, RuntimeSession>()\n private readonly events = new Map<string, RuntimeStreamEvent[]>()\n\n get(sessionId: string): RuntimeSession | undefined {\n return this.sessions.get(sessionId)\n }\n\n put(session: RuntimeSession): void {\n this.sessions.set(session.id, session)\n }\n\n appendEvent(sessionId: string, event: RuntimeStreamEvent): void {\n const existing = this.events.get(sessionId) ?? []\n existing.push(event)\n this.events.set(sessionId, existing)\n }\n\n listEvents(sessionId: string): RuntimeStreamEvent[] {\n return [...(this.events.get(sessionId) ?? [])]\n }\n}\n","/**\n *\n * Backend factories for `runAgentTaskStream`. Three shapes ship in core:\n *\n * - `createIterableBackend` — wrap any custom async iterable into a backend\n * - `createSandboxPromptBackend` — sandbox / sidecar `streamPrompt` clients\n * - `createOpenAICompatibleBackend` — OpenAI-style chat completions endpoints\n *\n * Adapters stay thin: domain repos own auth, model selection, and the concrete\n * tool surface. The factories handle session creation, stream normalization,\n * and graceful end-of-stream signalling.\n *\n * @stable\n */\n\nimport { BackendTransportError } from './errors'\nimport { newRuntimeSession, nowIso, touchSession } from './sessions'\nimport type {\n AgentBackendContext,\n AgentBackendInput,\n AgentExecutionBackend,\n OpenAIChatResponseFormat,\n OpenAIChatTool,\n OpenAIChatToolChoice,\n RuntimeSession,\n RuntimeStreamEvent,\n} from './types'\n\n/** Wrap any custom async-iterable stream into a typed `AgentExecutionBackend`. @stable */\nexport function createIterableBackend<TInput extends AgentBackendInput>(options: {\n kind: string\n start?: AgentExecutionBackend<TInput>['start']\n resume?: AgentExecutionBackend<TInput>['resume']\n stream: AgentExecutionBackend<TInput>['stream']\n stop?: AgentExecutionBackend<TInput>['stop']\n}): AgentExecutionBackend<TInput> {\n return options\n}\n\n/** Build an `AgentExecutionBackend` backed by a sandbox/sidecar `streamPrompt` call. @stable */\nexport function createSandboxPromptBackend<\n TBox,\n TInput extends AgentBackendInput = AgentBackendInput,\n>(options: {\n kind?: string\n getBox(input: TInput, context: Omit<AgentBackendContext, 'session'>): Promise<TBox> | TBox\n streamPrompt(box: TBox, message: string, context: AgentBackendContext): AsyncIterable<unknown>\n mapEvent?: (event: unknown, context: AgentBackendContext) => RuntimeStreamEvent | undefined\n getSessionId?: (box: TBox, input: TInput) => string | undefined\n}): AgentExecutionBackend<TInput> {\n const kind = options.kind ?? 'sandbox'\n return {\n kind,\n async start(input, context) {\n const box = await options.getBox(input, context)\n return newRuntimeSession(\n kind,\n options.getSessionId?.(box, input) ?? context.requestedSessionId,\n { resumable: true },\n )\n },\n resume(session) {\n return touchSession({ ...session, status: 'active' })\n },\n async *stream(input, context) {\n const box = await options.getBox(input, context)\n const message = input.message ?? input.messages?.at(-1)?.content ?? context.task.intent\n for await (const event of options.streamPrompt(box, message, context)) {\n const mapped = options.mapEvent?.(event, context) ?? mapCommonBackendEvent(event, context)\n if (mapped) yield mapped\n }\n },\n }\n}\n\n/** @stable */\n/**\n * Retry policy for transient transport errors (rate limits, upstream\n * timeouts). Defaults to 5 attempts with exponential backoff starting at\n * 1s, ±25% jitter, capped at 30s. Set `maxAttempts: 1` to disable retries.\n *\n * Retried status codes:\n * - 408 Request Timeout\n * - 425 Too Early\n * - 429 Too Many Requests\n * - 500 / 502 / 503 / 504 — upstream transient failures\n *\n * Hard failures (401, 403, 4xx other than the above) propagate immediately.\n */\nexport interface BackendRetryPolicy {\n /** Total attempts including the first try. Default 5. */\n maxAttempts?: number\n /** Initial backoff in ms before the second attempt. Default 1000. */\n initialBackoffMs?: number\n /** Hard ceiling on backoff in ms. Default 30000. */\n maxBackoffMs?: number\n /** Jitter fraction in [0, 1]. Default 0.25 (±25%). */\n jitter?: number\n /** Status codes that trigger a retry. Default: 408, 425, 429, 500, 502, 503, 504. */\n retryStatuses?: ReadonlyArray<number>\n /**\n * Per-attempt wall-clock deadline in ms. If a single fetch attempt does\n * not return headers within this window the attempt is aborted and\n * retried. Default 120000 (2 min). Without this a hung upstream blocks\n * the attempt indefinitely — observed in production as a 15-minute\n * `fetch failed` that burned an entire eval persona. Set to 0 to disable.\n */\n requestTimeoutMs?: number\n}\n\nconst DEFAULT_RETRY_STATUSES = [408, 425, 429, 500, 502, 503, 504] as const\n\nfunction pickRetryDelayMs(attempt: number, policy: Required<BackendRetryPolicy>): number {\n const exp = policy.initialBackoffMs * 2 ** (attempt - 1)\n const capped = Math.min(exp, policy.maxBackoffMs)\n const jitter = capped * policy.jitter * (Math.random() * 2 - 1)\n return Math.max(0, Math.round(capped + jitter))\n}\n\n/**\n * Derive a per-attempt AbortSignal that fires when EITHER the caller's\n * signal aborts OR `timeoutMs` elapses. `dispose()` clears the timer so a\n * completed attempt doesn't leak a pending timeout. `timeoutMs <= 0`\n * disables the deadline (caller signal still propagates).\n */\nfunction withTimeout(\n callerSignal: AbortSignal | undefined,\n timeoutMs: number,\n): { signal: AbortSignal; dispose: () => void } {\n if (timeoutMs <= 0) {\n return { signal: callerSignal ?? new AbortController().signal, dispose: () => undefined }\n }\n const controller = new AbortController()\n const timer = setTimeout(\n () => controller.abort(new Error(`request timed out after ${timeoutMs}ms`)),\n timeoutMs,\n )\n if (typeof (timer as { unref?: () => void }).unref === 'function') {\n ;(timer as { unref: () => void }).unref()\n }\n const onCallerAbort = () => controller.abort(callerSignal?.reason ?? new Error('aborted'))\n if (callerSignal) {\n if (callerSignal.aborted) onCallerAbort()\n else callerSignal.addEventListener('abort', onCallerAbort, { once: true })\n }\n return {\n signal: controller.signal,\n dispose: () => {\n clearTimeout(timer)\n callerSignal?.removeEventListener('abort', onCallerAbort)\n },\n }\n}\n\nfunction sleep(ms: number, signal?: AbortSignal): Promise<void> {\n return new Promise((resolve, reject) => {\n if (signal?.aborted) {\n reject(signal.reason ?? new Error('aborted'))\n return\n }\n const t = setTimeout(() => {\n signal?.removeEventListener('abort', onAbort)\n resolve()\n }, ms)\n const onAbort = () => {\n clearTimeout(t)\n reject(signal?.reason ?? new Error('aborted'))\n }\n signal?.addEventListener('abort', onAbort, { once: true })\n })\n}\n\n/**\n *\n * OpenAI-compat streaming backend. Routes `runAgentTaskStream` through any\n * `POST /chat/completions` endpoint that speaks OpenAI's SSE protocol —\n * Tangle Router, OpenAI direct, OpenRouter, Groq, DeepSeek, Together. The\n * router also fronts Anthropic models in Anthropic-native SSE shape; this\n * backend handles both.\n *\n * ### Tool calls\n *\n * Pass `tools` (and optionally `toolChoice`) to forward an OpenAI Chat\n * Completions `tools[]` array on every request. Streamed `tool_call` chunks\n * are buffered until the model finalizes them (either `finish_reason:\n * 'tool_calls'` for OpenAI shape or a `content_block_stop` for Anthropic\n * `tool_use` blocks proxied through the router), then emitted as a single\n * `tool_call` RuntimeStreamEvent with the assembled `args`.\n *\n * The backend does NOT execute tools — it surfaces calls for the caller's\n * own dispatcher (typically the product's MCP / sandbox runtime) to fulfill\n * and feed back as a subsequent `messages` turn. This keeps the transport\n * thin and lets the agent host own tool dispatch policy.\n *\n * ### Fail-loud errors\n *\n * Non-success HTTP responses (4xx/5xx) and exhausted retry budgets throw\n * `BackendTransportError` from inside the `stream()` generator. The runtime\n * catches the throw, yields a `backend_error` with a typed `error` field\n * (`kind`, `status`, truncated `body`) and a terminal `final` event with\n * `status: 'failed'` carrying the same detail. Consumers MUST map\n * `final.error` onto their `RunRecord.error` — silently treating an empty\n * `finalText` as \"agent produced nothing\" hides credit exhaustion, auth\n * failure, and upstream outages.\n *\n * @stable\n */\nexport function createOpenAICompatibleBackend<\n TInput extends AgentBackendInput = AgentBackendInput,\n>(options: {\n apiKey: string\n baseUrl: string\n model: string\n kind?: string\n /**\n * OpenAI Chat Completions `tools[]` definitions surfaced to the model on\n * every request. Omit to send a tool-free request (existing behavior).\n * The runtime makes no assumption about the dispatcher — calls stream out\n * as `tool_call` events and the caller is responsible for executing them\n * and feeding `tool_result` messages back on a follow-up turn.\n */\n tools?: ReadonlyArray<OpenAIChatTool>\n /**\n * OpenAI Chat Completions `tool_choice`. Default `undefined` (request\n * omits the field; provider falls back to its own default — typically\n * `'auto'`).\n */\n toolChoice?: OpenAIChatToolChoice\n /**\n * OpenAI Chat Completions `response_format`. Omit for provider default text.\n */\n responseFormat?: OpenAIChatResponseFormat\n /** OpenAI Chat Completions `temperature`. Omit for provider default. */\n temperature?: number\n /** Maximum completion tokens, sent as OpenAI-compatible `max_tokens`. Omit for provider default. */\n maxTokens?: number\n fetchImpl?: typeof fetch\n retry?: BackendRetryPolicy\n}): AgentExecutionBackend<TInput> {\n const fetcher = options.fetchImpl ?? fetch\n const kind = options.kind ?? 'tcloud'\n const retryPolicy: Required<BackendRetryPolicy> = {\n maxAttempts: options.retry?.maxAttempts ?? 5,\n initialBackoffMs: options.retry?.initialBackoffMs ?? 1000,\n maxBackoffMs: options.retry?.maxBackoffMs ?? 30000,\n jitter: options.retry?.jitter ?? 0.25,\n retryStatuses: options.retry?.retryStatuses ?? DEFAULT_RETRY_STATUSES,\n requestTimeoutMs: options.retry?.requestTimeoutMs ?? 120_000,\n }\n return {\n kind,\n start(_input, context) {\n return newRuntimeSession(kind, context.requestedSessionId)\n },\n async *stream(input, context) {\n const url = `${options.baseUrl.replace(/\\/$/, '')}/chat/completions`\n // `stream_options.include_usage` instructs OpenAI-compatible providers\n // (and the Tangle Router) to emit a final usage chunk in the SSE stream.\n // Without this the response carries no token counts and every downstream\n // ledger reads zero. Providers that don't recognize the field ignore it.\n const bodyPayload: Record<string, unknown> = {\n model: options.model,\n stream: true,\n stream_options: { include_usage: true },\n messages: input.messages ?? [\n { role: 'user', content: input.message ?? context.task.intent },\n ],\n }\n if (options.tools && options.tools.length > 0) {\n bodyPayload.tools = options.tools\n if (options.toolChoice !== undefined) bodyPayload.tool_choice = options.toolChoice\n }\n if (options.responseFormat !== undefined) {\n bodyPayload.response_format = options.responseFormat\n }\n if (options.temperature !== undefined) {\n bodyPayload.temperature = options.temperature\n }\n if (options.maxTokens !== undefined) {\n bodyPayload.max_tokens = options.maxTokens\n }\n const requestBody = JSON.stringify(bodyPayload)\n let response: Response | undefined\n let lastStatus = 0\n // The last thrown transport error (timeout abort, DNS / connection\n // failure). Network throws are retryable just like 5xx — without this\n // a `fetch failed` propagated immediately and burned the attempt.\n let lastThrown: unknown\n for (let attempt = 1; attempt <= retryPolicy.maxAttempts; attempt++) {\n lastThrown = undefined\n // Per-attempt deadline: abort a hung upstream instead of waiting\n // forever. Linked to context.signal so a caller cancel still wins.\n const attemptSignal = withTimeout(context.signal, retryPolicy.requestTimeoutMs)\n try {\n response = await fetcher(url, {\n method: 'POST',\n headers: {\n Authorization: `Bearer ${options.apiKey}`,\n 'Content-Type': 'application/json',\n // Cross-gateway forwarding: when this call is part of a\n // multi-agent conversation, the runner stamps run/turn/\n // depth/forwarded-auth headers onto the context. They flow\n // through to the downstream gateway verbatim so the original\n // user gets billed, the recursion depth stays bounded, and\n // the trace correlates across hops.\n ...(context.propagatedHeaders ?? {}),\n },\n body: requestBody,\n signal: attemptSignal.signal,\n })\n } catch (err) {\n attemptSignal.dispose()\n // A caller-initiated abort is terminal — do not retry it.\n if (context.signal?.aborted) throw err\n lastThrown = err\n response = undefined\n if (attempt === retryPolicy.maxAttempts) break\n await sleep(pickRetryDelayMs(attempt, retryPolicy), context.signal)\n continue\n }\n attemptSignal.dispose()\n if (response.ok) break\n lastStatus = response.status\n if (!retryPolicy.retryStatuses.includes(response.status)) break\n if (attempt === retryPolicy.maxAttempts) break\n // Drain the failed body so the connection can be reused.\n try {\n await response.body?.cancel()\n } catch {\n // Best-effort — some runtimes don't expose cancel.\n }\n const delayMs = pickRetryDelayMs(attempt, retryPolicy)\n await sleep(delayMs, context.signal)\n }\n if (!response) {\n const reason = lastThrown instanceof Error ? lastThrown.message : String(lastThrown)\n throw new BackendTransportError(\n kind,\n `chat backend unreachable after ${retryPolicy.maxAttempts} attempts: ${reason}`,\n { status: 0 },\n )\n }\n if (!response.ok) {\n // Capture the upstream body so the operator sees *why* the call\n // failed (e.g. `free_tier_limit`, `invalid_api_key`,\n // `model_not_found`). Truncate aggressively — HTML error pages from a\n // misconfigured proxy can be megabytes and would otherwise bloat\n // every persisted event. Best-effort: if body reading throws we\n // still surface the status code.\n let body: string | undefined\n try {\n const raw = await response.text()\n body = raw.length > MAX_ERROR_BODY_BYTES ? `${raw.slice(0, MAX_ERROR_BODY_BYTES)}…` : raw\n } catch {\n body = undefined\n }\n throw new BackendTransportError(kind, `chat backend returned ${lastStatus || 'unknown'}`, {\n status: lastStatus || 0,\n body,\n })\n }\n yield* streamResponseEvents(response, context, options.model)\n },\n }\n}\n\n/**\n * Cap the captured error body. 2 KiB is enough to carry a JSON error envelope\n * with a structured `code`/`message` payload (the router returns ~150 bytes\n * for a free-tier denial; OpenAI returns ~300 bytes for invalid auth) without\n * letting an HTML error page balloon persisted events.\n */\nconst MAX_ERROR_BODY_BYTES = 2048\n\n/**\n * Token usage accumulated across an SSE stream. OpenAI emits a single final\n * `usage` chunk; Anthropic emits `input_tokens` on `message_start` and\n * `output_tokens` on the terminal `message_delta`. We accept both — and the\n * router proxy may forward either shape depending on which upstream answered.\n */\ninterface StreamUsageAccumulator {\n tokensIn?: number\n tokensOut?: number\n model?: string\n finishReason?: string\n saw: boolean\n}\n\n/** @internal */\nexport function normalizeBackendStreamEvent(\n event: RuntimeStreamEvent,\n task: AgentBackendContext['task'],\n session: RuntimeSession,\n): RuntimeStreamEvent {\n if (\n 'task' in event &&\n event.task &&\n 'session' in event &&\n event.session &&\n 'timestamp' in event &&\n event.timestamp\n ) {\n return event\n }\n return {\n ...event,\n task: 'task' in event && event.task ? event.task : task,\n session: 'session' in event && event.session ? event.session : session,\n timestamp: 'timestamp' in event && event.timestamp ? event.timestamp : nowIso(),\n } as RuntimeStreamEvent\n}\n\nfunction mapCommonBackendEvent(\n event: unknown,\n context: AgentBackendContext,\n): RuntimeStreamEvent | undefined {\n if (!event || typeof event !== 'object') return undefined\n const record = event as Record<string, unknown>\n const type = String(record.type ?? '')\n const data =\n record.data && typeof record.data === 'object'\n ? (record.data as Record<string, unknown>)\n : record\n if (type === 'message.part.updated' || type === 'text_delta' || type === 'delta') {\n // `@tangle-network/sandbox` `box.streamPrompt` emits `message.part.updated`\n // with a nested part: `{ type: 'message.part.updated', data: { part:\n // { type: 'text', text: '…' } } }`. Walk into `data.part.text` so the\n // canonical sandbox-SDK shape produces a `text_delta` natively — no\n // per-product `mapEvent` shim required. Tool parts are picked up by\n // the `tool_call` / `tool_result` branches below; non-text parts here\n // fall through to `undefined` (the consumer can opt in via `mapEvent`).\n const part = data.part as Record<string, unknown> | undefined\n const partText =\n part !== undefined &&\n typeof part === 'object' &&\n (part.type === 'text' || part.type === undefined)\n ? stringValue(part.text)\n : undefined\n const text =\n stringValue(data.text) ?? stringValue(data.delta) ?? stringValue(record.text) ?? partText\n return text\n ? {\n type: 'text_delta',\n task: context.task,\n session: context.session,\n text,\n timestamp: nowIso(),\n }\n : undefined\n }\n if (type === 'reasoning_delta') {\n const text = stringValue(data.text) ?? stringValue(record.text)\n return text\n ? {\n type: 'reasoning_delta',\n task: context.task,\n session: context.session,\n text,\n timestamp: nowIso(),\n }\n : undefined\n }\n if (type === 'tool_call') {\n return {\n type: 'tool_call',\n task: context.task,\n session: context.session,\n toolName: stringValue(data.name) ?? stringValue(record.toolName) ?? 'tool',\n toolCallId: stringValue(data.id) ?? stringValue(record.toolCallId),\n args: data.args ?? data.input ?? record.args,\n timestamp: nowIso(),\n }\n }\n if (type === 'tool_result') {\n return {\n type: 'tool_result',\n task: context.task,\n session: context.session,\n toolName: stringValue(data.name) ?? stringValue(record.toolName) ?? 'tool',\n toolCallId: stringValue(data.id) ?? stringValue(record.toolCallId),\n result: data.result ?? data.output ?? record.result,\n timestamp: nowIso(),\n }\n }\n if (type === 'artifact') {\n const artifactId =\n stringValue(data.artifactId) ?? stringValue(data.id) ?? stringValue(record.artifactId)\n if (!artifactId) return undefined\n return {\n type: 'artifact',\n task: context.task,\n session: context.session,\n artifactId,\n name: stringValue(data.name) ?? stringValue(record.name),\n mimeType: stringValue(data.mimeType) ?? stringValue(record.mimeType),\n uri: stringValue(data.uri) ?? stringValue(record.uri),\n content: stringValue(data.content) ?? stringValue(data.body) ?? stringValue(record.content),\n metadata:\n data.metadata && typeof data.metadata === 'object'\n ? (data.metadata as Record<string, unknown>)\n : undefined,\n timestamp: nowIso(),\n }\n }\n if (type === 'proposal_created' || type === 'proposal' || type === 'filing') {\n const proposalId =\n stringValue(data.proposalId) ?? stringValue(data.id) ?? stringValue(record.proposalId)\n if (!proposalId) return undefined\n const status = stringValue(data.status) ?? stringValue(record.status)\n return {\n type: 'proposal_created',\n task: context.task,\n session: context.session,\n proposalId,\n title: stringValue(data.title) ?? stringValue(record.title) ?? proposalId,\n status:\n status === 'pending' || status === 'approved' || status === 'rejected' ? status : undefined,\n content: stringValue(data.content) ?? stringValue(data.body) ?? stringValue(record.content),\n timestamp: nowIso(),\n }\n }\n if (type === 'result' || type === 'final') {\n const text = stringValue(data.finalText) ?? stringValue(data.text) ?? stringValue(record.text)\n return text\n ? {\n type: 'text_delta',\n task: context.task,\n session: context.session,\n text,\n timestamp: nowIso(),\n }\n : undefined\n }\n return undefined\n}\n\nasync function* streamResponseEvents(\n response: Response,\n context: AgentBackendContext,\n requestedModel: string,\n): AsyncIterable<RuntimeStreamEvent> {\n const body = response.body\n if (!body) return\n const reader = body.getReader()\n const decoder = new TextDecoder()\n let buffer = ''\n const usage: StreamUsageAccumulator = { saw: false }\n // Tool-call assembly is stateful across SSE chunks: both OpenAI and\n // Anthropic streamed `arguments`/`partial_json` incrementally and the\n // final event is only safe to emit once we see a `finish_reason:\n // 'tool_calls'` or `content_block_stop` for the relevant index.\n const toolCalls: ToolCallAccumulator = new Map()\n const startedAt = Date.now()\n for (;;) {\n const { done, value } = await reader.read()\n if (done) break\n buffer += decoder.decode(value, { stream: true }).replace(/\\r\\n/g, '\\n')\n for (const event of drainStreamBuffer(false)) yield event\n }\n buffer += decoder.decode().replace(/\\r\\n/g, '\\n')\n for (const event of drainStreamBuffer(true)) yield event\n if (buffer.trim()) {\n for (const event of parseStreamChunk(buffer, context, usage, toolCalls)) yield event\n }\n // Flush any tool calls the model never closed via `finish_reason` — the\n // upstream may have terminated the stream without a terminal chunk (e.g.\n // when the proxy proactively forwards `[DONE]`). Emitting these here is\n // strictly safer than silently dropping a tool call the agent intended.\n for (const event of flushPendingToolCalls(toolCalls, context)) yield event\n // Synthesize a single `llm_call` event from accumulated usage. We only emit\n // when the upstream actually reported tokens — silent zeros would corrupt\n // every cost ledger that observes the stream. Consumers that need to detect\n // missing usage can check `tokensIn === undefined`.\n if (usage.saw) {\n yield {\n type: 'llm_call',\n task: context.task,\n session: context.session,\n model: usage.model ?? requestedModel,\n tokensIn: usage.tokensIn,\n tokensOut: usage.tokensOut,\n // `costUsd` is intentionally absent — pricing tables live in consumers\n // (agent-eval's `estimateCost`, MetricsCollector). Emitting a wrong\n // number here is worse than emitting none.\n latencyMs: Date.now() - startedAt,\n finishReason: usage.finishReason,\n timestamp: nowIso(),\n }\n }\n\n function* drainStreamBuffer(flush: boolean): Iterable<RuntimeStreamEvent> {\n for (;;) {\n const sseBoundary = buffer.indexOf('\\n\\n')\n if (sseBoundary >= 0) {\n const chunk = buffer.slice(0, sseBoundary)\n buffer = buffer.slice(sseBoundary + 2)\n for (const event of parseStreamChunk(chunk, context, usage, toolCalls)) yield event\n continue\n }\n\n const newline = buffer.indexOf('\\n')\n if (newline >= 0 && !buffer.slice(0, newline).startsWith('data:')) {\n const line = buffer.slice(0, newline)\n buffer = buffer.slice(newline + 1)\n for (const event of parseStreamChunk(line, context, usage, toolCalls)) yield event\n continue\n }\n\n if (flush && buffer.trim() && !buffer.trimStart().startsWith('data:')) {\n const line = buffer\n buffer = ''\n for (const event of parseStreamChunk(line, context, usage, toolCalls)) yield event\n continue\n }\n\n break\n }\n }\n}\n\n/**\n * Per-tool-call accumulator. Keyed by either OpenAI `index` (cast to string)\n * or Anthropic `content_block` `index`. Holds the streamed identifier, name,\n * and string-form `arguments` so we can emit a single typed `tool_call`\n * event once the stream signals the call is finalized.\n */\ntype ToolCallAccumulator = Map<\n string,\n {\n id?: string\n name?: string\n /** Accumulated JSON-string `arguments` / `input` payload. */\n argsRaw: string\n /** Source format: OpenAI delta vs Anthropic `tool_use` block. */\n source: 'openai' | 'anthropic'\n /** Set true once the model signals this call is complete. */\n finalized: boolean\n }\n>\n\nfunction* parseStreamChunk(\n chunk: string,\n context: AgentBackendContext,\n usage: StreamUsageAccumulator,\n toolCalls: ToolCallAccumulator,\n): Iterable<RuntimeStreamEvent> {\n const lines = chunk.split(/\\r?\\n/)\n const dataLines = lines.filter((line) => line.startsWith('data:'))\n if (\n dataLines.length === 0 &&\n lines.every((line) => {\n const trimmed = line.trim()\n return trimmed.length === 0 || trimmed.startsWith(':')\n })\n ) {\n return\n }\n const data =\n dataLines.length > 0\n ? dataLines.map((line) => line.slice(5).trimStart()).join('\\n')\n : chunk.trim()\n if (!data || data === '[DONE]') return\n let parsed: Record<string, unknown>\n try {\n parsed = JSON.parse(data) as Record<string, unknown>\n } catch {\n yield {\n type: 'text_delta',\n task: context.task,\n session: context.session,\n text: data,\n timestamp: nowIso(),\n }\n return\n }\n captureStreamUsage(parsed, usage)\n const choices = parsed.choices\n const choice = Array.isArray(choices)\n ? (choices[0] as Record<string, unknown> | undefined)\n : undefined\n const delta = choice?.delta as Record<string, unknown> | undefined\n const message = choice?.message as Record<string, unknown> | undefined\n\n // ── OpenAI streamed `tool_calls` deltas ─────────────────────────────\n const deltaToolCalls = delta?.tool_calls\n if (Array.isArray(deltaToolCalls)) {\n for (const tc of deltaToolCalls) {\n if (!tc || typeof tc !== 'object') continue\n const rec = tc as Record<string, unknown>\n const id = stringValue(rec.id)\n const key = deltaToolCallKey(rec, id, toolCalls)\n const acc = toolCalls.get(key) ?? { argsRaw: '', source: 'openai' as const, finalized: false }\n if (id) acc.id = id\n const fn = rec.function as Record<string, unknown> | undefined\n const name = stringValue(fn?.name)\n if (name) acc.name = name\n const args = stringValue(fn?.arguments)\n if (args) acc.argsRaw += args\n toolCalls.set(key, acc)\n }\n }\n // `message.tool_calls` is the non-streamed shape — the model returned a\n // complete tool call in one chunk. Treat the whole array as terminal.\n const messageToolCalls = message?.tool_calls\n if (Array.isArray(messageToolCalls)) {\n for (const tc of messageToolCalls) {\n if (!tc || typeof tc !== 'object') continue\n const rec = tc as Record<string, unknown>\n const fn = rec.function as Record<string, unknown> | undefined\n const idx = numberValue(rec.index) ?? messageToolCalls.indexOf(tc)\n const key = `openai:${idx}`\n const acc = toolCalls.get(key) ?? { argsRaw: '', source: 'openai' as const, finalized: false }\n const id = stringValue(rec.id)\n if (id) acc.id = id\n const name = stringValue(fn?.name)\n if (name) acc.name = name\n const args = stringValue(fn?.arguments)\n if (args) acc.argsRaw += args\n acc.finalized = true\n toolCalls.set(key, acc)\n }\n }\n\n const finishReason = stringValue(choice?.finish_reason)\n if (finishReason === 'tool_calls') {\n // Model signaled it's done streaming tool calls — flush every OpenAI-\n // sourced pending entry. Subsequent chunks (usage, [DONE]) won't add\n // more.\n for (const [key, acc] of toolCalls) {\n if (acc.source === 'openai' && !acc.finalized) acc.finalized = true\n toolCalls.set(key, acc)\n }\n }\n\n // ── Anthropic shape (proxied through router) ────────────────────────\n const eventType = stringValue(parsed.type)\n if (eventType === 'content_block_start') {\n const block = parsed.content_block as Record<string, unknown> | undefined\n if (block && stringValue(block.type) === 'tool_use') {\n const idx = numberValue(parsed.index) ?? 0\n const key = `anthropic:${idx}`\n toolCalls.set(key, {\n id: stringValue(block.id),\n name: stringValue(block.name),\n argsRaw: '',\n source: 'anthropic',\n finalized: false,\n })\n }\n }\n if (eventType === 'content_block_delta') {\n const d = parsed.delta as Record<string, unknown> | undefined\n const dType = stringValue(d?.type)\n if (dType === 'input_json_delta') {\n const idx = numberValue(parsed.index) ?? 0\n const key = `anthropic:${idx}`\n const acc = toolCalls.get(key)\n if (acc) {\n const partial = stringValue(d?.partial_json) ?? ''\n acc.argsRaw += partial\n toolCalls.set(key, acc)\n }\n } else {\n const text = stringValue(d?.text)\n if (text) {\n yield {\n type: 'text_delta',\n task: context.task,\n session: context.session,\n text,\n timestamp: nowIso(),\n }\n }\n }\n }\n if (eventType === 'content_block_stop') {\n const idx = numberValue(parsed.index) ?? 0\n const key = `anthropic:${idx}`\n const acc = toolCalls.get(key)\n if (acc) {\n acc.finalized = true\n toolCalls.set(key, acc)\n }\n }\n\n // Emit any tool calls that just became finalized. Done eagerly per-chunk so\n // consumers see the call as soon as it's safe — the analyst loop watches\n // `tool_call` events for delegation-pattern detection.\n for (const event of drainFinalizedToolCalls(toolCalls, context)) yield event\n\n // ── Text deltas ──────────────────────────────────────────────────────\n const text =\n stringValue(delta?.content) ?? stringValue(message?.content) ?? stringValue(parsed.text)\n if (text) {\n yield {\n type: 'text_delta',\n task: context.task,\n session: context.session,\n text,\n timestamp: nowIso(),\n }\n return\n }\n const mapped = mapCommonBackendEvent(parsed, context)\n if (mapped) yield mapped\n}\n\nfunction* drainFinalizedToolCalls(\n toolCalls: ToolCallAccumulator,\n context: AgentBackendContext,\n): Iterable<RuntimeStreamEvent> {\n for (const [key, acc] of toolCalls) {\n if (!acc.finalized) continue\n toolCalls.delete(key)\n yield buildToolCallEvent(acc, context)\n }\n}\n\nfunction* flushPendingToolCalls(\n toolCalls: ToolCallAccumulator,\n context: AgentBackendContext,\n): Iterable<RuntimeStreamEvent> {\n for (const [key, acc] of toolCalls) {\n toolCalls.delete(key)\n yield buildToolCallEvent(acc, context)\n }\n}\n\n/**\n * The accumulator key one streamed `delta.tool_calls[]` entry belongs to.\n *\n * OpenAI's streaming contract puts `index` on every fragment, so fragments of\n * the same call concatenate under `openai:<index>`. Some OpenAI-COMPATIBLE\n * gateways do not: the Tangle router's Gemini lane emits N COMPLETE tool calls\n * inside a single delta, each with a distinct `id` and no `index` at all.\n * Defaulting those to index 0 concatenated every call's `arguments` into one\n * string, which then failed `JSON.parse` and was surfaced as a raw string — so\n * a turn that asked for six deliverables silently produced none.\n *\n * Resolution order:\n * 1. `index` present → spec path, key by index (cross-delta fragments join).\n * 2. `id` present → key by id; distinct ids are distinct calls, and a\n * repeated id still concatenates correctly.\n * 3. neither → an argument-only continuation fragment; append to the\n * last-OPENED unfinalized OpenAI entry. `Map` iteration\n * is insertion-ordered and `set` on an existing key does\n * not reorder, so this is the most recently STARTED call\n * still taking arguments — which is the one a gateway\n * streaming calls sequentially is continuing.\n */\nfunction deltaToolCallKey(\n rec: Record<string, unknown>,\n id: string | undefined,\n toolCalls: ToolCallAccumulator,\n): string {\n const idx = numberValue(rec.index)\n if (idx !== undefined) return `openai:${idx}`\n if (id) return `openai:id:${id}`\n let last: string | undefined\n for (const [key, acc] of toolCalls) {\n if (acc.source === 'openai' && !acc.finalized) last = key\n }\n return last ?? 'openai:0'\n}\n\nfunction buildToolCallEvent(\n acc: { id?: string; name?: string; argsRaw: string; source: 'openai' | 'anthropic' },\n context: AgentBackendContext,\n): RuntimeStreamEvent {\n // `argsRaw` is JSON-string by the provider contract (OpenAI streams an\n // escaped JSON string; Anthropic streams `partial_json` chunks). Parse\n // best-effort — surface the raw string if parsing fails so downstream\n // doesn't lose the call entirely.\n let args: unknown = acc.argsRaw\n if (acc.argsRaw.length > 0) {\n try {\n args = JSON.parse(acc.argsRaw)\n } catch {\n args = acc.argsRaw\n }\n } else {\n args = {}\n }\n return {\n type: 'tool_call',\n task: context.task,\n session: context.session,\n toolName: acc.name ?? 'tool',\n toolCallId: acc.id,\n args,\n timestamp: nowIso(),\n }\n}\n\n/**\n * Accumulate token usage from any SSE chunk shape the router may emit.\n *\n * - OpenAI: a final chunk before `[DONE]` with `{ usage: { prompt_tokens,\n * completion_tokens, total_tokens } }` and (often) empty `choices`. The\n * `model` field is on every chunk and the last `choices[0].finish_reason`\n * carries the stop reason.\n * - Anthropic: `message_start` carries `message.model` and\n * `message.usage.input_tokens`. The terminal `message_delta` carries\n * `usage.output_tokens` and `delta.stop_reason`.\n */\nfunction captureStreamUsage(parsed: Record<string, unknown>, usage: StreamUsageAccumulator): void {\n const model = stringValue(parsed.model)\n if (model && !usage.model) usage.model = model\n\n const openAiUsage = parsed.usage as Record<string, unknown> | undefined\n if (openAiUsage && typeof openAiUsage === 'object') {\n const promptTokens = numberValue(openAiUsage.prompt_tokens)\n const completionTokens = numberValue(openAiUsage.completion_tokens)\n const inputTokens = numberValue(openAiUsage.input_tokens)\n const outputTokens = numberValue(openAiUsage.output_tokens)\n if (promptTokens !== undefined) {\n usage.tokensIn = promptTokens\n usage.saw = true\n } else if (inputTokens !== undefined) {\n usage.tokensIn = (usage.tokensIn ?? 0) + inputTokens\n usage.saw = true\n }\n if (completionTokens !== undefined) {\n usage.tokensOut = completionTokens\n usage.saw = true\n } else if (outputTokens !== undefined) {\n usage.tokensOut = (usage.tokensOut ?? 0) + outputTokens\n usage.saw = true\n }\n }\n\n const type = stringValue(parsed.type)\n if (type === 'message_start') {\n const message = parsed.message as Record<string, unknown> | undefined\n const messageModel = stringValue(message?.model)\n if (messageModel && !usage.model) usage.model = messageModel\n const messageUsage = message?.usage as Record<string, unknown> | undefined\n const inputTokens = numberValue(messageUsage?.input_tokens)\n if (inputTokens !== undefined) {\n usage.tokensIn = inputTokens\n usage.saw = true\n }\n const outputTokens = numberValue(messageUsage?.output_tokens)\n if (outputTokens !== undefined) {\n usage.tokensOut = (usage.tokensOut ?? 0) + outputTokens\n usage.saw = true\n }\n }\n if (type === 'message_delta') {\n const delta = parsed.delta as Record<string, unknown> | undefined\n const stopReason = stringValue(delta?.stop_reason)\n if (stopReason) usage.finishReason = stopReason\n }\n\n const choices = parsed.choices\n if (Array.isArray(choices)) {\n const finishReason = stringValue(\n (choices[0] as Record<string, unknown> | undefined)?.finish_reason,\n )\n if (finishReason) usage.finishReason = finishReason\n }\n}\n\nfunction numberValue(value: unknown): number | undefined {\n return typeof value === 'number' && Number.isFinite(value) ? value : undefined\n}\n\nfunction stringValue(value: unknown): string | undefined {\n return typeof value === 'string' && value.length > 0 ? value : undefined\n}\n"],"mappings":";;;;;;;;;;;;AAqBA,SAAgB,kBACd,SACA,aACA,UACgB;CAChB,MAAM,MAAM,OAAO;CACnB,OAAO;EACL,IAAI,eAAe,OAAO,WAAW;EACrC;EACA,QAAQ;EACR,WAAW;EACX,WAAW;EACX;CACF;AACF;;AAGA,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,SAAS,iBAAiB;EAC5B,MAAM,UAAU,OAAO;EACvB,MAAM,eAAe,YAAY,SAAS,KAAK;EAC/C,IAAI,gBAAgB,CAAC,MAAM,OAAO,MAAM,QAAQ;EAChD,MAAM,eAAe,SAAS;EAC9B,MAAM,cAAc,YAAY,cAAc,YAAY;EAC1D,IAAI,gBAAgB,KAAA,GAAW;GAC7B,MAAM,WAAW;GACjB,MAAM,MAAM;EACd;EACA,MAAM,eAAe,YAAY,cAAc,aAAa;EAC5D,IAAI,iBAAiB,KAAA,GAAW;GAC9B,MAAM,aAAa,MAAM,aAAa,KAAK;GAC3C,MAAM,MAAM;EACd;CACF;CACA,IAAI,SAAS,iBAAiB;EAC5B,MAAM,QAAQ,OAAO;EACrB,MAAM,aAAa,YAAY,OAAO,WAAW;EACjD,IAAI,YAAY,MAAM,eAAe;CACvC;CAEA,MAAM,UAAU,OAAO;CACvB,IAAI,MAAM,QAAQ,OAAO,GAAG;EAC1B,MAAM,eAAe,YAClB,QAAQ,EAAE,EAA0C,aACvD;EACA,IAAI,cAAc,MAAM,eAAe;CACzC;AACF;AAEA,SAAS,YAAY,OAAoC;CACvD,OAAO,OAAO,UAAU,YAAY,OAAO,SAAS,KAAK,IAAI,QAAQ,KAAA;AACvE;AAEA,SAAS,YAAY,OAAoC;CACvD,OAAO,OAAO,UAAU,YAAY,MAAM,SAAS,IAAI,QAAQ,KAAA;AACjE"}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { $ as parseExactAgentProfile, K as applyExactAgentProfileDiff, S as CANDIDATE_TRACE_TAGS, _ as candidateExecutionClaim, a as persistCandidateOutputArtifact, c as CANDIDATE_KNOWLEDGE_ROOT_ENV, et as parseExactAgentProfileDiff, f as verifyAgentCandidateBundle, h as InMemoryAgentCandidateExecutionClaimStore, l as candidateKnowledgeExecutionPaths, n as executePreparedAgentCandidate, q as assertCandidateProfileBinding, s as CANDIDATE_KNOWLEDGE_RETRIEVAL_CONFIG_ENV, t as prepareAgentCandidateExecution, u as AGENT_CANDIDATE_EXECUTION_SUPPORT, x as CANDIDATE_TRACE_ENV } from "../prepare-
|
|
2
|
-
import { i as sealAgentCandidateBundle, n as captureAgentCandidateWorkspaceFiles, r as createAgentCandidateWorkspacePort, t as captureAgentCandidateWorkspace } from "../workspace-archive-
|
|
3
|
-
import { i as buildAgentCandidateBundle, n as disposePreparedAgentCandidateExecution, r as FileAgentCandidateExecutionClaimStore, t as recoverExpiredAgentCandidateExecution } from "../candidate-execution-
|
|
4
|
-
import { n as exactProcessProviderAsCandidateExecutor, t as createProtectedAgentCandidateModelPort } from "../protected-model-port-
|
|
1
|
+
import { $ as parseExactAgentProfile, K as applyExactAgentProfileDiff, S as CANDIDATE_TRACE_TAGS, _ as candidateExecutionClaim, a as persistCandidateOutputArtifact, c as CANDIDATE_KNOWLEDGE_ROOT_ENV, et as parseExactAgentProfileDiff, f as verifyAgentCandidateBundle, h as InMemoryAgentCandidateExecutionClaimStore, l as candidateKnowledgeExecutionPaths, n as executePreparedAgentCandidate, q as assertCandidateProfileBinding, s as CANDIDATE_KNOWLEDGE_RETRIEVAL_CONFIG_ENV, t as prepareAgentCandidateExecution, u as AGENT_CANDIDATE_EXECUTION_SUPPORT, x as CANDIDATE_TRACE_ENV } from "../prepare-_WTTffkz.js";
|
|
2
|
+
import { i as sealAgentCandidateBundle, n as captureAgentCandidateWorkspaceFiles, r as createAgentCandidateWorkspacePort, t as captureAgentCandidateWorkspace } from "../workspace-archive-CIG1VNCj.js";
|
|
3
|
+
import { i as buildAgentCandidateBundle, n as disposePreparedAgentCandidateExecution, r as FileAgentCandidateExecutionClaimStore, t as recoverExpiredAgentCandidateExecution } from "../candidate-execution-BUpR0mSD.js";
|
|
4
|
+
import { n as exactProcessProviderAsCandidateExecutor, t as createProtectedAgentCandidateModelPort } from "../protected-model-port-ZUwVuftA.js";
|
|
5
5
|
export { AGENT_CANDIDATE_EXECUTION_SUPPORT, CANDIDATE_KNOWLEDGE_RETRIEVAL_CONFIG_ENV, CANDIDATE_KNOWLEDGE_ROOT_ENV, CANDIDATE_TRACE_ENV, CANDIDATE_TRACE_TAGS, FileAgentCandidateExecutionClaimStore, InMemoryAgentCandidateExecutionClaimStore, applyExactAgentProfileDiff, assertCandidateProfileBinding, buildAgentCandidateBundle, candidateExecutionClaim, candidateKnowledgeExecutionPaths, captureAgentCandidateWorkspace, captureAgentCandidateWorkspaceFiles, createAgentCandidateWorkspacePort, createProtectedAgentCandidateModelPort, disposePreparedAgentCandidateExecution, exactProcessProviderAsCandidateExecutor, executePreparedAgentCandidate, parseExactAgentProfile, parseExactAgentProfileDiff, persistCandidateOutputArtifact, prepareAgentCandidateExecution, recoverExpiredAgentCandidateExecution, sealAgentCandidateBundle, verifyAgentCandidateBundle };
|
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import { $ as parseExactAgentProfile, B as rejectedStage, F as assertTerminalAllowedInPhase, H as sealTerminalDigest, I as assertTerminalMatchesClaim, K as applyExactAgentProfileDiff, L as assertTerminalMatchesStaged, M as candidateCleanupTimeout, N as withinCandidateCleanupDeadline, O as readVerifiedArtifact, P as assertRecoveryMatchesStaged, R as recoveredTerminalRecord, U as terminalRecord, V as requireStagedTerminal, X as freezeGenericAgentCandidateProfile, a as persistCandidateOutputArtifact, b as consumePreparedCandidateExecution, et as parseExactAgentProfileDiff, g as candidateClaimFileInternals, i as persistCandidateModelSettlementEvidence, j as candidateCleanupDeadline, nt as canonicalCandidateBytes, o as sealAgentCandidateExecutorStopAcknowledgement, ot as embeddedCandidateArtifact, p as sealAgentCandidateModelSettlement, r as RecoveryAgentCandidateTraceStore, tt as parseExactCandidateProfile, v as assertPreparedCandidateIntegrity, y as beginPreparedCandidateDisposal, z as rejectedFinish } from "./prepare-
|
|
2
|
-
import { i as sealAgentCandidateBundle } from "./workspace-archive-
|
|
3
|
-
import "./protected-model-port-
|
|
1
|
+
import { $ as parseExactAgentProfile, B as rejectedStage, F as assertTerminalAllowedInPhase, H as sealTerminalDigest, I as assertTerminalMatchesClaim, K as applyExactAgentProfileDiff, L as assertTerminalMatchesStaged, M as candidateCleanupTimeout, N as withinCandidateCleanupDeadline, O as readVerifiedArtifact, P as assertRecoveryMatchesStaged, R as recoveredTerminalRecord, U as terminalRecord, V as requireStagedTerminal, X as freezeGenericAgentCandidateProfile, a as persistCandidateOutputArtifact, b as consumePreparedCandidateExecution, et as parseExactAgentProfileDiff, g as candidateClaimFileInternals, i as persistCandidateModelSettlementEvidence, j as candidateCleanupDeadline, nt as canonicalCandidateBytes, o as sealAgentCandidateExecutorStopAcknowledgement, ot as embeddedCandidateArtifact, p as sealAgentCandidateModelSettlement, r as RecoveryAgentCandidateTraceStore, tt as parseExactCandidateProfile, v as assertPreparedCandidateIntegrity, y as beginPreparedCandidateDisposal, z as rejectedFinish } from "./prepare-_WTTffkz.js";
|
|
2
|
+
import { i as sealAgentCandidateBundle } from "./workspace-archive-CIG1VNCj.js";
|
|
3
|
+
import "./protected-model-port-ZUwVuftA.js";
|
|
4
4
|
import { verifyCodeSurface } from "@tangle-network/agent-eval/campaign";
|
|
5
5
|
import { agentCandidateExecutionPlanMaterialSchema, agentCandidateMaterializationReceiptSchema } from "@tangle-network/agent-interface";
|
|
6
6
|
import { randomUUID } from "node:crypto";
|
|
@@ -485,4 +485,4 @@ function parseCanonicalBytes(bytes, label) {
|
|
|
485
485
|
//#endregion
|
|
486
486
|
export { buildAgentCandidateBundle as i, disposePreparedAgentCandidateExecution as n, FileAgentCandidateExecutionClaimStore as r, recoverExpiredAgentCandidateExecution as t };
|
|
487
487
|
|
|
488
|
-
//# sourceMappingURL=candidate-execution-
|
|
488
|
+
//# sourceMappingURL=candidate-execution-BUpR0mSD.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"candidate-execution-DqMbv1rU.js","names":[],"sources":["../src/candidate-execution/builder.ts","../src/candidate-execution/claim-file-store.ts","../src/candidate-execution/dispose.ts","../src/candidate-execution/recover.ts"],"sourcesContent":["import type { CodeSurface } from '@tangle-network/agent-eval/campaign'\nimport { verifyCodeSurface } from '@tangle-network/agent-eval/campaign'\nimport type {\n AgentCandidateCodeDisabled,\n AgentCandidateCodeNoOp,\n AgentCandidateExecution,\n AgentCandidateGitHubRepository,\n AgentCandidateKnowledge,\n AgentCandidateMemoryPolicy,\n AgentCandidateProfile,\n AgentProfile,\n AgentProfileDiff,\n} from '@tangle-network/agent-interface'\nimport { type AgentCandidateBundleInput, sealAgentCandidateBundle } from './bundle'\nimport { embeddedCandidateArtifact } from './digest'\nimport {\n applyExactAgentProfileDiff,\n freezeGenericAgentCandidateProfile,\n parseExactAgentProfile,\n parseExactAgentProfileDiff,\n parseExactCandidateProfile,\n} from './profile'\n\n/** A complete profile that can be frozen without losing behavior. */\nexport type AgentCandidateProfileSource =\n | {\n kind: 'profile'\n profile: AgentProfile\n }\n | {\n kind: 'profile-diffs'\n base: AgentProfile\n /** Applied in order before the resulting profile is frozen into the bundle. */\n diffs: readonly AgentProfileDiff[]\n }\n | {\n kind: 'candidate-profile'\n /** Already converted to the closed, secret-free candidate profile contract. */\n profile: AgentCandidateProfile\n }\n\n/** The only accepted path from an agent-eval code candidate to executable bytes. */\nexport interface AgentCandidateCodeSurfaceSource {\n kind: 'code-surface'\n surface: CodeSurface\n repository: AgentCandidateGitHubRepository\n /** Optional parent directory used to resolve a relative `surface.worktreeRef`. */\n worktreeDir?: string\n}\n\n/** Explicit control/no-op code or one finalized CodeSurface whose bytes must still verify. */\nexport type AgentCandidateCodeSource =\n | AgentCandidateCodeDisabled\n | AgentCandidateCodeNoOp\n | AgentCandidateCodeSurfaceSource\n\n/** Complete measured surfaces and execution policy compiled into one candidate bundle. */\nexport interface BuildAgentCandidateBundleInput {\n profile: AgentCandidateProfileSource\n code: AgentCandidateCodeSource\n execution: AgentCandidateExecution\n knowledge?: AgentCandidateKnowledge\n memory: AgentCandidateMemoryPolicy\n}\n\n/**\n * Compile one measured profile/code candidate into the immutable execution\n * contract. Code bytes are re-read and verified by agent-eval before they are\n * embedded. The returned bundle is schema-validated, canonically digested, and\n * deeply immutable; call `verifyAgentCandidateBundle` at the execution boundary\n * to re-read external memory, repository, and workspace artifacts.\n */\nexport function buildAgentCandidateBundle(\n input: BuildAgentCandidateBundleInput,\n): ReturnType<typeof sealAgentCandidateBundle> {\n const bundle: AgentCandidateBundleInput = {\n kind: 'agent-candidate-bundle',\n digestAlgorithm: 'rfc8785-sha256',\n profile: compileCandidateProfile(input.profile),\n code: compileCandidateCode(input.code),\n execution: input.execution,\n ...(input.knowledge !== undefined ? { knowledge: input.knowledge } : {}),\n memory: input.memory,\n }\n return sealAgentCandidateBundle(bundle)\n}\n\nfunction compileCandidateProfile(source: AgentCandidateProfileSource): AgentCandidateProfile {\n if (source.kind === 'candidate-profile') {\n return parseExactCandidateProfile(source.profile)\n }\n\n if (source.kind === 'profile') {\n return freezeGenericAgentCandidateProfile(source.profile)\n }\n\n if (source.kind !== 'profile-diffs') {\n throw new Error(\n `unsupported candidate profile source: ${String((source as { kind?: unknown }).kind)}`,\n )\n }\n if (source.diffs.length === 0) {\n throw new Error('profile-diffs source requires at least one AgentProfileDiff')\n }\n let profile = parseExactAgentProfile(source.base, 'base profile')\n for (const [index, inputDiff] of source.diffs.entries()) {\n const diff = parseExactAgentProfileDiff(inputDiff, `profile diff ${index}`)\n profile = applyExactAgentProfileDiff(profile, diff, `profile diff ${index}`)\n }\n return freezeGenericAgentCandidateProfile(profile)\n}\n\nfunction compileCandidateCode(source: AgentCandidateCodeSource): AgentCandidateBundleInput['code'] {\n if (source.kind === 'disabled' || source.kind === 'no-op') return source\n if (source.kind !== 'code-surface') {\n throw new Error(\n `unsupported candidate code source: ${String((source as { kind?: unknown }).kind)}`,\n )\n }\n\n const verified = verifyCodeSurface(source.surface, source.worktreeDir)\n const patch = embeddedCandidateArtifact(verified.patchBytes)\n if (\n patch.sha256 !== source.surface.patch.sha256 ||\n patch.byteLength !== source.surface.patch.byteLength\n ) {\n throw new Error('verified CodeSurface patch bytes do not match its content identity')\n }\n return {\n kind: 'git-patch',\n repository: source.repository,\n baseCommit: source.surface.baseCommit,\n baseTree: source.surface.baseTree,\n candidateTree: source.surface.candidateTree,\n patch: { format: 'git-diff-binary', artifact: patch },\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 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 ...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 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 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 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 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 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 { 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 type { TraceStore } from '@tangle-network/agent-eval'\nimport type {\n AgentCandidateExecutionPlanMaterial,\n AgentCandidateMaterializationReceipt,\n} from '@tangle-network/agent-interface'\nimport {\n agentCandidateExecutionPlanMaterialSchema,\n agentCandidateMaterializationReceiptSchema,\n} from '@tangle-network/agent-interface'\n\nimport { readVerifiedArtifact } from './artifacts'\nimport type {\n AgentCandidateExecutionAttemptRef,\n AgentCandidateExecutionClaim,\n AgentCandidateExecutionClaimStore,\n AgentCandidateExecutionFinishResult,\n} from './claim'\nimport {\n candidateCleanupDeadline,\n candidateCleanupTimeout,\n withinCandidateCleanupDeadline,\n} from './cleanup'\nimport { canonicalCandidateBytes } from './digest'\nimport { sealAgentCandidateExecutorStopAcknowledgement } from './executor-capture'\nimport { sealAgentCandidateModelSettlement } from './model-settlement'\nimport { persistCandidateModelSettlementEvidence } from './outcome-evidence'\nimport { persistCandidateOutputArtifact } from './output-artifacts'\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 recoveryTraceStore = new RecoveryAgentCandidateTraceStore(options.traceStore)\n const preparation = withinCandidateCleanupDeadline(\n () => readRecoveryPreparation(record.claim, options.outputArtifacts),\n cleanupDeadlineAtMs,\n 'expired candidate preparation evidence read',\n )\n const processClosure = withinCandidateCleanupDeadline(\n async (cleanupSignal) => {\n const stopped = await options.executor.stop(\n {\n executionId: record.claim.executionId,\n executionPlanDigest: record.claim.executionPlanDigest,\n },\n {\n traceStore: recoveryTraceStore,\n reason: 'failed',\n signal: cleanupSignal,\n deadlineAtMs: cleanupDeadlineAtMs,\n },\n )\n sealAgentCandidateExecutorStopAcknowledgement(stopped)\n if (options.executor.dispose) {\n const disposed = await options.executor.dispose(\n {\n executionId: record.claim.executionId,\n executionPlanDigest: record.claim.executionPlanDigest,\n },\n { signal: cleanupSignal },\n )\n if (disposed.disposed !== true || Object.keys(disposed).some((key) => key !== 'disposed')) {\n throw new Error('expired candidate executor did not acknowledge resource disposal')\n }\n }\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 closureOutcomes = Promise.allSettled([\n modelClosure,\n memoryClosure ?? Promise.resolve(undefined),\n ] as const)\n const [preparationOutcome, processOutcome] = await Promise.allSettled([\n preparation,\n processClosure,\n ] as const)\n const failures: unknown[] = [preparationOutcome, processOutcome]\n .filter((outcome): outcome is PromiseRejectedResult => outcome.status === 'rejected')\n .map((outcome) => outcome.reason)\n const [modelOutcome, memoryOutcome] = await closureOutcomes\n for (const outcome of [modelOutcome, memoryOutcome]) {\n if (outcome.status === 'rejected') failures.push(outcome.reason)\n }\n if (failures.length > 0) {\n throw new AggregateError(failures, 'expired candidate cleanup could not be proven')\n }\n\n if (modelOutcome.status !== 'fulfilled') {\n throw new Error('expired candidate model settlement was not recovered')\n }\n const model = modelOutcome.value\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 failureClass =\n record.phase === 'claimed' && model.usage.modelCalls === 0\n ? 'pre-model-infrastructure'\n : 'unknown'\n const failureEvidence = await withinCandidateCleanupDeadline(\n () =>\n persistCandidateOutputArtifact(options.outputArtifacts, {\n executionId: record.claim.executionId,\n purpose: 'failure-evidence',\n bytes: canonicalCandidateBytes({\n kind: 'agent-candidate-recovery-failure',\n executionId: record.claim.executionId,\n attempt: record.claim.attempt,\n bundleDigest: record.claim.bundleDigest,\n executionPlanDigest: record.claim.executionPlanDigest,\n materializationReceiptDigest:\n record.claim.preparationEvidence.materializationReceipt.sha256,\n failureClass,\n processStopped: true,\n modelSettlementDigest: modelSettlement.digest,\n memoryClosed: record.claim.cleanup.memory !== undefined,\n }),\n }),\n cleanupDeadlineAtMs,\n 'expired candidate failure-evidence persistence',\n )\n const memory = record.claim.cleanup.memory\n return await options.claimStore.recoverExpired(options.attempt, {\n failureClass,\n usage: model.usage,\n modelSettlement: modelSettlement.artifact,\n failureEvidence,\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\nasync function readRecoveryPreparation(\n claim: AgentCandidateExecutionClaim,\n artifacts: AgentCandidateOutputArtifactPort,\n): Promise<{\n plan: AgentCandidateExecutionPlanMaterial\n receipt: AgentCandidateMaterializationReceipt\n}> {\n const [planBytes, receiptBytes] = await Promise.all([\n readVerifiedArtifact(claim.preparationEvidence.executionPlan, artifacts),\n readVerifiedArtifact(claim.preparationEvidence.materializationReceipt, artifacts),\n ])\n const plan = agentCandidateExecutionPlanMaterialSchema.parse(\n parseCanonicalBytes(planBytes, 'plan'),\n )\n if (claim.preparationEvidence.executionPlan.sha256 !== claim.executionPlanDigest) {\n throw new Error('recovery execution plan artifact does not match the claimed digest')\n }\n const receiptMaterial = parseCanonicalBytes(receiptBytes, 'materialization receipt')\n const receipt = agentCandidateMaterializationReceiptSchema.parse({\n ...receiptMaterial,\n digest: claim.preparationEvidence.materializationReceipt.sha256,\n })\n if (\n receipt.bundleDigest !== claim.bundleDigest ||\n receipt.executionPlan.digest !== claim.executionPlanDigest ||\n plan.runCell.bundleDigest !== claim.bundleDigest ||\n plan.executionId !== claim.executionId\n ) {\n throw new Error('recovery preparation evidence does not match the durable claim')\n }\n return { plan, receipt }\n}\n\nfunction parseCanonicalBytes(bytes: Uint8Array, label: string): Record<string, unknown> {\n let parsed: unknown\n try {\n parsed = JSON.parse(Buffer.from(bytes).toString('utf8'))\n } catch (error) {\n throw new Error(`candidate recovery ${label} is not JSON`, { cause: error })\n }\n if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) {\n throw new Error(`candidate recovery ${label} must be an object`)\n }\n if (!Buffer.from(canonicalCandidateBytes(parsed)).equals(Buffer.from(bytes))) {\n throw new Error(`candidate recovery ${label} bytes are not canonical`)\n }\n return pars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AS,KAAK,MAAM,OAAO,KAAK,KAAK,CAAC,CAAC,SAAS,MAAM,CAAC;CACzD,SAAS,OAAO;EACd,MAAM,IAAI,MAAM,sBAAsB,MAAM,eAAe,EAAE,OAAO,MAAM,CAAC;CAC7E;CACA,IAAI,CAAC,UAAU,OAAO,WAAW,YAAY,MAAM,QAAQ,MAAM,GAC/D,MAAM,IAAI,MAAM,sBAAsB,MAAM,mBAAmB;CAEjE,IAAI,CAAC,OAAO,KAAK,wBAAwB,MAAM,CAAC,CAAC,CAAC,OAAO,OAAO,KAAK,KAAK,CAAC,GACzE,MAAM,IAAI,MAAM,sBAAsB,MAAM,yBAAyB;CAEvE,OAAO;AACT"}
|
|
1
|
+
{"version":3,"file":"candidate-execution-BUpR0mSD.js","names":[],"sources":["../src/candidate-execution/builder.ts","../src/candidate-execution/claim-file-store.ts","../src/candidate-execution/dispose.ts","../src/candidate-execution/recover.ts"],"sourcesContent":["import type { CodeSurface } from '@tangle-network/agent-eval/campaign'\nimport { verifyCodeSurface } from '@tangle-network/agent-eval/campaign'\nimport type {\n AgentCandidateCodeDisabled,\n AgentCandidateCodeNoOp,\n AgentCandidateExecution,\n AgentCandidateGitHubRepository,\n AgentCandidateKnowledge,\n AgentCandidateMemoryPolicy,\n AgentCandidateProfile,\n AgentProfile,\n AgentProfileDiff,\n} from '@tangle-network/agent-interface'\nimport { type AgentCandidateBundleInput, sealAgentCandidateBundle } from './bundle'\nimport { embeddedCandidateArtifact } from './digest'\nimport {\n applyExactAgentProfileDiff,\n freezeGenericAgentCandidateProfile,\n parseExactAgentProfile,\n parseExactAgentProfileDiff,\n parseExactCandidateProfile,\n} from './profile'\n\n/** A complete profile that can be frozen without losing behavior. */\nexport type AgentCandidateProfileSource =\n | {\n kind: 'profile'\n profile: AgentProfile\n }\n | {\n kind: 'profile-diffs'\n base: AgentProfile\n /** Applied in order before the resulting profile is frozen into the bundle. */\n diffs: readonly AgentProfileDiff[]\n }\n | {\n kind: 'candidate-profile'\n /** Already converted to the closed, secret-free candidate profile contract. */\n profile: AgentCandidateProfile\n }\n\n/** The only accepted path from an agent-eval code candidate to executable bytes. */\nexport interface AgentCandidateCodeSurfaceSource {\n kind: 'code-surface'\n surface: CodeSurface\n repository: AgentCandidateGitHubRepository\n /** Optional parent directory used to resolve a relative `surface.worktreeRef`. */\n worktreeDir?: string\n}\n\n/** Explicit control/no-op code or one finalized CodeSurface whose bytes must still verify. */\nexport type AgentCandidateCodeSource =\n | AgentCandidateCodeDisabled\n | AgentCandidateCodeNoOp\n | AgentCandidateCodeSurfaceSource\n\n/** Complete measured surfaces and execution policy compiled into one candidate bundle. */\nexport interface BuildAgentCandidateBundleInput {\n profile: AgentCandidateProfileSource\n code: AgentCandidateCodeSource\n execution: AgentCandidateExecution\n knowledge?: AgentCandidateKnowledge\n memory: AgentCandidateMemoryPolicy\n}\n\n/**\n * Compile one measured profile/code candidate into the immutable execution\n * contract. Code bytes are re-read and verified by agent-eval before they are\n * embedded. The returned bundle is schema-validated, canonically digested, and\n * deeply immutable; call `verifyAgentCandidateBundle` at the execution boundary\n * to re-read external memory, repository, and workspace artifacts.\n */\nexport function buildAgentCandidateBundle(\n input: BuildAgentCandidateBundleInput,\n): ReturnType<typeof sealAgentCandidateBundle> {\n const bundle: AgentCandidateBundleInput = {\n kind: 'agent-candidate-bundle',\n digestAlgorithm: 'rfc8785-sha256',\n profile: compileCandidateProfile(input.profile),\n code: compileCandidateCode(input.code),\n execution: input.execution,\n ...(input.knowledge !== undefined ? { knowledge: input.knowledge } : {}),\n memory: input.memory,\n }\n return sealAgentCandidateBundle(bundle)\n}\n\nfunction compileCandidateProfile(source: AgentCandidateProfileSource): AgentCandidateProfile {\n if (source.kind === 'candidate-profile') {\n return parseExactCandidateProfile(source.profile)\n }\n\n if (source.kind === 'profile') {\n return freezeGenericAgentCandidateProfile(source.profile)\n }\n\n if (source.kind !== 'profile-diffs') {\n throw new Error(\n `unsupported candidate profile source: ${String((source as { kind?: unknown }).kind)}`,\n )\n }\n if (source.diffs.length === 0) {\n throw new Error('profile-diffs source requires at least one AgentProfileDiff')\n }\n let profile = parseExactAgentProfile(source.base, 'base profile')\n for (const [index, inputDiff] of source.diffs.entries()) {\n const diff = parseExactAgentProfileDiff(inputDiff, `profile diff ${index}`)\n profile = applyExactAgentProfileDiff(profile, diff, `profile diff ${index}`)\n }\n return freezeGenericAgentCandidateProfile(profile)\n}\n\nfunction compileCandidateCode(source: AgentCandidateCodeSource): AgentCandidateBundleInput['code'] {\n if (source.kind === 'disabled' || source.kind === 'no-op') return source\n if (source.kind !== 'code-surface') {\n throw new Error(\n `unsupported candidate code source: ${String((source as { kind?: unknown }).kind)}`,\n )\n }\n\n const verified = verifyCodeSurface(source.surface, source.worktreeDir)\n const patch = embeddedCandidateArtifact(verified.patchBytes)\n if (\n patch.sha256 !== source.surface.patch.sha256 ||\n patch.byteLength !== source.surface.patch.byteLength\n ) {\n throw new Error('verified CodeSurface patch bytes do not match its content identity')\n }\n return {\n kind: 'git-patch',\n repository: source.repository,\n baseCommit: source.surface.baseCommit,\n baseTree: source.surface.baseTree,\n candidateTree: source.surface.candidateTree,\n patch: { format: 'git-diff-binary', artifact: patch },\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 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 ...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 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 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 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 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 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 { 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 type { TraceStore } from '@tangle-network/agent-eval'\nimport type {\n AgentCandidateExecutionPlanMaterial,\n AgentCandidateMaterializationReceipt,\n} from '@tangle-network/agent-interface'\nimport {\n agentCandidateExecutionPlanMaterialSchema,\n agentCandidateMaterializationReceiptSchema,\n} from '@tangle-network/agent-interface'\n\nimport { readVerifiedArtifact } from './artifacts'\nimport type {\n AgentCandidateExecutionAttemptRef,\n AgentCandidateExecutionClaim,\n AgentCandidateExecutionClaimStore,\n AgentCandidateExecutionFinishResult,\n} from './claim'\nimport {\n candidateCleanupDeadline,\n candidateCleanupTimeout,\n withinCandidateCleanupDeadline,\n} from './cleanup'\nimport { canonicalCandidateBytes } from './digest'\nimport { sealAgentCandidateExecutorStopAcknowledgement } from './executor-capture'\nimport { sealAgentCandidateModelSettlement } from './model-settlement'\nimport { persistCandidateModelSettlementEvidence } from './outcome-evidence'\nimport { persistCandidateOutputArtifact } from './output-artifacts'\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 recoveryTraceStore = new RecoveryAgentCandidateTraceStore(options.traceStore)\n const preparation = withinCandidateCleanupDeadline(\n () => readRecoveryPreparation(record.claim, options.outputArtifacts),\n cleanupDeadlineAtMs,\n 'expired candidate preparation evidence read',\n )\n const processClosure = withinCandidateCleanupDeadline(\n async (cleanupSignal) => {\n const stopped = await options.executor.stop(\n {\n executionId: record.claim.executionId,\n executionPlanDigest: record.claim.executionPlanDigest,\n },\n {\n traceStore: recoveryTraceStore,\n reason: 'failed',\n signal: cleanupSignal,\n deadlineAtMs: cleanupDeadlineAtMs,\n },\n )\n sealAgentCandidateExecutorStopAcknowledgement(stopped)\n if (options.executor.dispose) {\n const disposed = await options.executor.dispose(\n {\n executionId: record.claim.executionId,\n executionPlanDigest: record.claim.executionPlanDigest,\n },\n { signal: cleanupSignal },\n )\n if (disposed.disposed !== true || Object.keys(disposed).some((key) => key !== 'disposed')) {\n throw new Error('expired candidate executor did not acknowledge resource disposal')\n }\n }\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 closureOutcomes = Promise.allSettled([\n modelClosure,\n memoryClosure ?? Promise.resolve(undefined),\n ] as const)\n const [preparationOutcome, processOutcome] = await Promise.allSettled([\n preparation,\n processClosure,\n ] as const)\n const failures: unknown[] = [preparationOutcome, processOutcome]\n .filter((outcome): outcome is PromiseRejectedResult => outcome.status === 'rejected')\n .map((outcome) => outcome.reason)\n const [modelOutcome, memoryOutcome] = await closureOutcomes\n for (const outcome of [modelOutcome, memoryOutcome]) {\n if (outcome.status === 'rejected') failures.push(outcome.reason)\n }\n if (failures.length > 0) {\n throw new AggregateError(failures, 'expired candidate cleanup could not be proven')\n }\n\n if (modelOutcome.status !== 'fulfilled') {\n throw new Error('expired candidate model settlement was not recovered')\n }\n const model = modelOutcome.value\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 failureClass =\n record.phase === 'claimed' && model.usage.modelCalls === 0\n ? 'pre-model-infrastructure'\n : 'unknown'\n const failureEvidence = await withinCandidateCleanupDeadline(\n () =>\n persistCandidateOutputArtifact(options.outputArtifacts, {\n executionId: record.claim.executionId,\n purpose: 'failure-evidence',\n bytes: canonicalCandidateBytes({\n kind: 'agent-candidate-recovery-failure',\n executionId: record.claim.executionId,\n attempt: record.claim.attempt,\n bundleDigest: record.claim.bundleDigest,\n executionPlanDigest: record.claim.executionPlanDigest,\n materializationReceiptDigest:\n record.claim.preparationEvidence.materializationReceipt.sha256,\n failureClass,\n processStopped: true,\n modelSettlementDigest: modelSettlement.digest,\n memoryClosed: record.claim.cleanup.memory !== undefined,\n }),\n }),\n cleanupDeadlineAtMs,\n 'expired candidate failure-evidence persistence',\n )\n const memory = record.claim.cleanup.memory\n return await options.claimStore.recoverExpired(options.attempt, {\n failureClass,\n usage: model.usage,\n modelSettlement: modelSettlement.artifact,\n failureEvidence,\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\nasync function readRecoveryPreparation(\n claim: AgentCandidateExecutionClaim,\n artifacts: AgentCandidateOutputArtifactPort,\n): Promise<{\n plan: AgentCandidateExecutionPlanMaterial\n receipt: AgentCandidateMaterializationReceipt\n}> {\n const [planBytes, receiptBytes] = await Promise.all([\n readVerifiedArtifact(claim.preparationEvidence.executionPlan, artifacts),\n readVerifiedArtifact(claim.preparationEvidence.materializationReceipt, artifacts),\n ])\n const plan = agentCandidateExecutionPlanMaterialSchema.parse(\n parseCanonicalBytes(planBytes, 'plan'),\n )\n if (claim.preparationEvidence.executionPlan.sha256 !== claim.executionPlanDigest) {\n throw new Error('recovery execution plan artifact does not match the claimed digest')\n }\n const receiptMaterial = parseCanonicalBytes(receiptBytes, 'materialization receipt')\n const receipt = agentCandidateMaterializationReceiptSchema.parse({\n ...receiptMaterial,\n digest: claim.preparationEvidence.materializationReceipt.sha256,\n })\n if (\n receipt.bundleDigest !== claim.bundleDigest ||\n receipt.executionPlan.digest !== claim.executionPlanDigest ||\n plan.runCell.bundleDigest !== claim.bundleDigest ||\n plan.executionId !== claim.executionId\n ) {\n throw new Error('recovery preparation evidence does not match the durable claim')\n }\n return { plan, receipt }\n}\n\nfunction parseCanonicalBytes(bytes: Uint8Array, label: string): Record<string, unknown> {\n let parsed: unknown\n try {\n parsed = JSON.parse(Buffer.from(bytes).toString('utf8'))\n } catch (error) {\n throw new Error(`candidate recovery ${label} is not JSON`, { cause: error })\n }\n if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) {\n throw new Error(`candidate recovery ${label} must be an object`)\n }\n if (!Buffer.from(canonicalCandidateBytes(parsed)).equals(Buffer.from(bytes))) {\n throw new Error(`candidate recovery ${label} bytes are not canonical`)\n }\n return parsed as Record<string, unknown>\n}\n"],"mappings":";;;;;;;;;;;;;;;;;AAwEA,SAAgB,0BACd,OAC6C;CAU7C,OAAO,yBAAyB;EAR9B,MAAM;EACN,iBAAiB;EACjB,SAAS,wBAAwB,MAAM,OAAO;EAC9C,MAAM,qBAAqB,MAAM,IAAI;EACrC,WAAW,MAAM;EACjB,GAAI,MAAM,cAAc,KAAA,IAAY,EAAE,WAAW,MAAM,UAAU,IAAI,CAAC;EACtE,QAAQ,MAAM;CAEqB,CAAC;AACxC;AAEA,SAAS,wBAAwB,QAA4D;CAC3F,IAAI,OAAO,SAAS,qBAClB,OAAO,2BAA2B,OAAO,OAAO;CAGlD,IAAI,OAAO,SAAS,WAClB,OAAO,mCAAmC,OAAO,OAAO;CAG1D,IAAI,OAAO,SAAS,iBAClB,MAAM,IAAI,MACR,yCAAyC,OAAQ,OAA8B,IAAI,GACrF;CAEF,IAAI,OAAO,MAAM,WAAW,GAC1B,MAAM,IAAI,MAAM,6DAA6D;CAE/E,IAAI,UAAU,uBAAuB,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ACvE,qBAAqB,MAAM,oBAAoB,wBAAwB,SAAS,CAClF,CAAC;CACD,MAAM,OAAO,0CAA0C,MACrD,oBAAoB,WAAW,MAAM,CACvC;CACA,IAAI,MAAM,oBAAoB,cAAc,WAAW,MAAM,qBAC3D,MAAM,IAAI,MAAM,oEAAoE;CAEtF,MAAM,kBAAkB,oBAAoB,cAAc,yBAAyB;CACnF,MAAM,UAAU,2CAA2C,MAAM;EAC/D,GAAG;EACH,QAAQ,MAAM,oBAAoB,uBAAuB;CAC3D,CAAC;CACD,IACE,QAAQ,iBAAiB,MAAM,gBAC/B,QAAQ,cAAc,WAAW,MAAM,uBACvC,KAAK,QAAQ,iBAAiB,MAAM,gBACpC,KAAK,gBAAgB,MAAM,aAE3B,MAAM,IAAI,MAAM,gEAAgE;CAElF,OAAO;EAAE;EAAM;CAAQ;AACzB;AAEA,SAAS,oBAAoB,OAAmB,OAAwC;CACtF,IAAI;CACJ,IAAI;EACF,SAAS,KAAK,MAAM,OAAO,KAAK,KAAK,CAAC,CAAC,SAAS,MAAM,CAAC;CACzD,SAAS,OAAO;EACd,MAAM,IAAI,MAAM,sBAAsB,MAAM,eAAe,EAAE,OAAO,MAAM,CAAC;CAC7E;CACA,IAAI,CAAC,UAAU,OAAO,WAAW,YAAY,MAAM,QAAQ,MAAM,GAC/D,MAAM,IAAI,MAAM,sBAAsB,MAAM,mBAAmB;CAEjE,IAAI,CAAC,OAAO,KAAK,wBAAwB,MAAM,CAAC,CAAC,CAAC,OAAO,OAAO,KAAK,KAAK,CAAC,GACzE,MAAM,IAAI,MAAM,sBAAsB,MAAM,yBAAyB;CAEvE,OAAO;AACT"}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { r as BackendTransportError, u as ValidationError } from "./errors-DEAvWQPy.js";
|
|
2
|
-
import { a as InMemoryRuntimeSessionStore, c as startOrResumeRuntimeSession, o as newRuntimeSession, s as nowIso, t as createIterableBackend } from "./backends-
|
|
2
|
+
import { a as InMemoryRuntimeSessionStore, c as startOrResumeRuntimeSession, o as newRuntimeSession, s as nowIso, t as createIterableBackend } from "./backends-CiOCyRHb.js";
|
|
3
3
|
//#region src/conversation/call-policy.ts
|
|
4
4
|
/** Thrown when the circuit breaker is open for a participant and no retry is allowed yet. */
|
|
5
5
|
var CircuitOpenError = class extends Error {
|
|
@@ -1262,4 +1262,4 @@ function runPersonaDispatch(config) {
|
|
|
1262
1262
|
//#endregion
|
|
1263
1263
|
export { makePerAttemptSignal as C, defaultIsRetryable as S, readDepth as _, FileConversationJournal as a, DeadlineExceededError as b, createConversationBackend as c, slugifySpeaker as d, turnId as f, isDepthExceeded as g, buildForwardHeaders as h, d1ToSqlAdapter as i, runConversation as l, FORWARD_HEADERS as m, runPersonaDispatch as n, InMemoryConversationJournal as o, DEFAULT_MAX_DEPTH as p, SqlConversationJournal as r, defineConversation as s, runPersonaConversation as t, runConversationStream as u, CircuitBreakerState as v, sleep as w, computeBackoff as x, CircuitOpenError as y };
|
|
1264
1264
|
|
|
1265
|
-
//# sourceMappingURL=conversation-
|
|
1265
|
+
//# sourceMappingURL=conversation-BpLQZGPH.js.map
|