@tangle-network/agent-runtime 0.94.10 → 0.94.12

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.
Files changed (59) hide show
  1. package/README.md +65 -1
  2. package/dist/agent.d.ts +2 -1
  3. package/dist/agent.js +2 -1
  4. package/dist/agent.js.map +1 -1
  5. package/dist/{agentic-generator-1g7GDba7.d.ts → agentic-generator-DDMM45kZ.d.ts} +46 -6
  6. package/dist/analyst-loop.d.ts +2 -1
  7. package/dist/backends-BO4Jqoe2.d.ts +134 -0
  8. package/dist/chunk-AEG3NGJ2.js +639 -0
  9. package/dist/chunk-AEG3NGJ2.js.map +1 -0
  10. package/dist/{chunk-GHXW56PO.js → chunk-D3H7F6L2.js} +136 -36
  11. package/dist/chunk-D3H7F6L2.js.map +1 -0
  12. package/dist/{chunk-7NCP74SL.js → chunk-PCURO3DL.js} +4 -4
  13. package/dist/chunk-PCURO3DL.js.map +1 -0
  14. package/dist/{chunk-YP6B7RZ2.js → chunk-U33YZ7B2.js} +6 -635
  15. package/dist/chunk-U33YZ7B2.js.map +1 -0
  16. package/dist/chunk-VYA2YEKA.js +1187 -0
  17. package/dist/chunk-VYA2YEKA.js.map +1 -0
  18. package/dist/{chunk-MXBQNVFE.js → chunk-XP5KDM3R.js} +5 -5
  19. package/dist/{completion-gate-BB4IZwyh.d.ts → completion-gate-D1gX1-hg.d.ts} +2 -2
  20. package/dist/conversation.d.ts +793 -0
  21. package/dist/conversation.js +56 -0
  22. package/dist/conversation.js.map +1 -0
  23. package/dist/{coordination-CyVQ61My.d.ts → coordination-Dr_axlAf.d.ts} +6 -5
  24. package/dist/environment-provider.d.ts +3 -2
  25. package/dist/{improve-DZeatcs7.d.ts → improve-BN3HyXIO.d.ts} +2 -2
  26. package/dist/index.d.ts +29 -943
  27. package/dist/index.js +58 -1159
  28. package/dist/index.js.map +1 -1
  29. package/dist/intelligence.d.ts +6 -5
  30. package/dist/intelligence.js +5 -5
  31. package/dist/knowledge.d.ts +8 -7
  32. package/dist/lifecycle.d.ts +3 -3
  33. package/dist/lifecycle.js +1 -1
  34. package/dist/{local-harness-ZLMkKdZc.d.ts → local-harness-ZqCx51u7.d.ts} +1 -1
  35. package/dist/{loop-runner-bin-DA3ccCAs.d.ts → loop-runner-bin-BRQSQdHa.d.ts} +2 -2
  36. package/dist/loop-runner-bin.d.ts +7 -6
  37. package/dist/loop-runner-bin.js +4 -3
  38. package/dist/loops.d.ts +16 -15
  39. package/dist/loops.js +2 -1
  40. package/dist/mcp/index.d.ts +11 -10
  41. package/dist/mcp/index.js +2 -1
  42. package/dist/mcp/index.js.map +1 -1
  43. package/dist/{mcp-serve-verifier-BO4MEsR3.d.ts → mcp-serve-verifier-DQQDbuyz.d.ts} +1 -1
  44. package/dist/{openai-tools-0wACz8f8.d.ts → openai-tools-fnj6SRVg.d.ts} +1 -1
  45. package/dist/primeintellect/index.d.ts +214 -0
  46. package/dist/primeintellect/index.js +1120 -0
  47. package/dist/primeintellect/index.js.map +1 -0
  48. package/dist/profiles.d.ts +2 -1
  49. package/dist/{sanitize-Dcbjp0tU.d.ts → sanitize-BTSsdBXw.d.ts} +1 -1
  50. package/dist/{supervise-BaEsCHNh.d.ts → supervise-DmYOug5f.d.ts} +4 -4
  51. package/dist/{types-CogNCaw7.d.ts → types-1d5QGK3t.d.ts} +1 -1
  52. package/dist/types-BwoZWq-i.d.ts +510 -0
  53. package/dist/{types-CKmyZ9TP.d.ts → types-ByAYqlVb.d.ts} +3 -509
  54. package/dist/{worktree-fanout-Do2YbtFD.d.ts → worktree-fanout-CPprU-qI.d.ts} +4 -4
  55. package/package.json +15 -3
  56. package/dist/chunk-7NCP74SL.js.map +0 -1
  57. package/dist/chunk-GHXW56PO.js.map +0 -1
  58. package/dist/chunk-YP6B7RZ2.js.map +0 -1
  59. /package/dist/{chunk-MXBQNVFE.js.map → chunk-XP5KDM3R.js.map} +0 -0
@@ -0,0 +1 @@
1
+ {"version":3,"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 type { RuntimeSession, RuntimeSessionStore, RuntimeStreamEvent } 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\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.streamTask` 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":";;;;;AAaO,SAAS,kBACd,SACA,aACA,UACgB;AAChB,QAAM,MAAM,OAAO;AACnB,SAAO;AAAA,IACL,IAAI,eAAe,OAAO,WAAW;AAAA,IACrC;AAAA,IACA,QAAQ;AAAA,IACR,WAAW;AAAA,IACX,WAAW;AAAA,IACX;AAAA,EACF;AACF;AAGO,SAAS,aAAa,SAAyC;AACpE,SAAO,EAAE,GAAG,SAAS,WAAW,OAAO,EAAE;AAC3C;AAGO,SAAS,S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,IACd;AAAA,EACF;AAEA,QAAM,OAAO,YAAY,OAAO,IAAI;AACpC,MAAI,SAAS,iBAAiB;AAC5B,UAAM,UAAU,OAAO;AACvB,UAAM,eAAe,YAAY,SAAS,KAAK;AAC/C,QAAI,gBAAgB,CAAC,MAAM,MAAO,OAAM,QAAQ;AAChD,UAAM,eAAe,SAAS;AAC9B,UAAM,cAAc,YAAY,cAAc,YAAY;AAC1D,QAAI,gBAAgB,QAAW;AAC7B,YAAM,WAAW;AACjB,YAAM,MAAM;AAAA,IACd;AACA,UAAM,eAAe,YAAY,cAAc,aAAa;AAC5D,QAAI,iBAAiB,QAAW;AAC9B,YAAM,aAAa,MAAM,aAAa,KAAK;AAC3C,YAAM,MAAM;AAAA,IACd;AAAA,EACF;AACA,MAAI,SAAS,iBAAiB;AAC5B,UAAM,QAAQ,OAAO;AACrB,UAAM,aAAa,YAAY,OAAO,WAAW;AACjD,QAAI,WAAY,OAAM,eAAe;AAAA,EACvC;AAEA,QAAM,UAAU,OAAO;AACvB,MAAI,MAAM,QAAQ,OAAO,GAAG;AAC1B,UAAM,eAAe;AAAA,MAClB,QAAQ,CAAC,GAA2C;AAAA,IACvD;AACA,QAAI,aAAc,OAAM,eAAe;AAAA,EACzC;AACF;AAEA,SAAS,YAAY,OAAoC;AACvD,SAAO,OAAO,UAAU,YAAY,OAAO,SAAS,KAAK,IAAI,QAAQ;AACvE;AAEA,SAAS,YAAY,OAAoC;AACvD,SAAO,OAAO,UAAU,YAAY,MAAM,SAAS,IAAI,QAAQ;AACjE;","names":["text"]}
@@ -54,10 +54,14 @@ function agenticGenerator(opts = {}) {
54
54
  costLedger,
55
55
  costPhase
56
56
  }) {
57
- if (opts.codexReproducible && !costLedger) {
58
- throw new Error(
59
- "agenticGenerator: reproducible Codex requires the run-wide CostLedger supplied by agent-eval 0.117+"
60
- );
57
+ let reproducibleCostLedger;
58
+ if (opts.codexReproducible) {
59
+ if (!costLedger) {
60
+ throw new Error(
61
+ "agenticGenerator: reproducible Codex requires the run-wide CostLedger supplied by agent-eval 0.117+"
62
+ );
63
+ }
64
+ reproducibleCostLedger = costLedger;
61
65
  }
62
66
  const basePrompt = appendProfileResourcePaths(
63
67
  buildPrompt({ report, findings }),
@@ -88,8 +92,8 @@ ${attemptNote}` : basePrompt;
88
92
  harnessResult = await withAuthorProfileResources(
89
93
  profileResourcePlan,
90
94
  worktreePath,
91
- async (receipt) => {
92
- profileWorkspaceReceipt = receipt;
95
+ async (receipt2) => {
96
+ profileWorkspaceReceipt = receipt2;
93
97
  const result2 = await run({
94
98
  harness,
95
99
  cwd: worktreePath,
@@ -112,13 +116,12 @@ ${attemptNote}` : basePrompt;
112
116
  if (failure) throw failure;
113
117
  return harnessResult;
114
118
  };
115
- if (opts.codexReproducible) {
116
- const ledger = costLedger;
119
+ if (reproducibleCostLedger) {
117
120
  const model = opts.profile?.model?.default;
118
121
  if (!model) {
119
122
  throw new Error("agenticGenerator: reproducible Codex requires profile.model.default");
120
123
  }
121
- const paid = await ledger.runPaidCall({
124
+ const paid = await reproducibleCostLedger.runPaidCall({
122
125
  channel: "driver",
123
126
  phase: costPhase ?? "search.proposal",
124
127
  actor: `agentic-generator:${harness}`,
@@ -144,47 +147,105 @@ ${attemptNote}` : basePrompt;
144
147
  } catch (cause) {
145
148
  shotError = cause instanceof Error ? cause : new Error(String(cause));
146
149
  }
147
- await emitShotReceipt(
148
- opts.onShotCompleted,
149
- shotReceipt({
150
- generation,
151
- candidateIndex,
152
- shot,
153
- maxShots: shots,
154
- harness,
155
- profile: opts.profile,
156
- prompt: exactPrompt,
157
- startedAt,
158
- completedAt: /* @__PURE__ */ new Date(),
159
- result: harnessResult,
160
- profileWorkspaceReceipt,
161
- costCallId,
162
- costReceipt,
163
- error: shotError
164
- }),
165
- shotError
166
- );
167
- if (!harnessResult) {
150
+ const execution = shotExecutionSnapshot(harnessResult);
151
+ const receipt = shotReceipt({
152
+ generation,
153
+ candidateIndex,
154
+ shot,
155
+ maxShots: shots,
156
+ harness,
157
+ profile: opts.profile,
158
+ prompt: exactPrompt,
159
+ startedAt,
160
+ completedAt: /* @__PURE__ */ new Date(),
161
+ result: execution,
162
+ profileWorkspaceReceipt,
163
+ costCallId,
164
+ costReceipt,
165
+ error: shotError
166
+ });
167
+ await emitShotReceipt(opts.onShotCompleted, receipt, execution, shotError);
168
+ if (!execution) {
168
169
  throw new Error("agenticGenerator: author shot completed without a harness result");
169
170
  }
170
- if (!dirty(worktreePath)) {
171
+ let worktreeChanged;
172
+ try {
173
+ worktreeChanged = dirty(worktreePath);
174
+ } catch (cause) {
175
+ return rethrowShotSetupError(
176
+ opts.onShotDisposition,
177
+ receipt,
178
+ worktreePath,
179
+ "worktree-inspection",
180
+ cause
181
+ );
182
+ }
183
+ if (!worktreeChanged) {
184
+ await emitShotDisposition(opts.onShotDisposition, receipt, {
185
+ kind: "clean",
186
+ worktreePath
187
+ });
171
188
  attemptNote = EMPTY_TREE_NOTE;
172
189
  continue;
173
190
  }
174
191
  if (needsRawTraceEvidence) {
175
- const problem = rawTraceEvidenceProblem(worktreePath, findings);
192
+ let problem;
193
+ try {
194
+ problem = rawTraceEvidenceProblem(worktreePath, findings);
195
+ } catch (cause) {
196
+ return rethrowShotSetupError(
197
+ opts.onShotDisposition,
198
+ receipt,
199
+ worktreePath,
200
+ "raw-trace-evidence",
201
+ cause
202
+ );
203
+ }
176
204
  if (problem) {
205
+ await emitShotDisposition(opts.onShotDisposition, receipt, {
206
+ kind: "rejected",
207
+ worktreePath,
208
+ stage: "raw-trace-evidence",
209
+ feedback: problem
210
+ });
177
211
  attemptNote = problem;
178
212
  continue;
179
213
  }
180
214
  }
181
215
  if (!verify) {
216
+ await emitShotDisposition(opts.onShotDisposition, receipt, {
217
+ kind: "accepted",
218
+ worktreePath,
219
+ verified: false
220
+ });
182
221
  return { applied: true, summary: summarize(findings) };
183
222
  }
184
- const result = await verify(worktreePath);
223
+ let result;
224
+ try {
225
+ result = await verify(worktreePath);
226
+ } catch (cause) {
227
+ return rethrowShotSetupError(
228
+ opts.onShotDisposition,
229
+ receipt,
230
+ worktreePath,
231
+ "verification",
232
+ cause
233
+ );
234
+ }
185
235
  if (result.ok) {
236
+ await emitShotDisposition(opts.onShotDisposition, receipt, {
237
+ kind: "accepted",
238
+ worktreePath,
239
+ verified: true
240
+ });
186
241
  return { applied: true, summary: summarize(findings) };
187
242
  }
243
+ await emitShotDisposition(opts.onShotDisposition, receipt, {
244
+ kind: "rejected",
245
+ worktreePath,
246
+ stage: "verification",
247
+ feedback: result.feedback ?? null
248
+ });
188
249
  attemptNote = failureNote(result.feedback);
189
250
  }
190
251
  return { applied: false, summary: "" };
@@ -284,9 +345,9 @@ async function withAuthorProfileResources(plan, worktreePath, run) {
284
345
  if (cleanupError !== void 0) throw cleanupError;
285
346
  return value;
286
347
  }
287
- async function emitShotReceipt(callback, receipt, primaryError) {
348
+ async function emitShotReceipt(callback, receipt, execution, primaryError) {
288
349
  try {
289
- await callback?.(receipt);
350
+ await callback?.(receipt, execution);
290
351
  } catch (callbackError) {
291
352
  if (primaryError !== null) {
292
353
  throw new AggregateError(
@@ -298,6 +359,45 @@ async function emitShotReceipt(callback, receipt, primaryError) {
298
359
  }
299
360
  if (primaryError !== null) throw primaryError;
300
361
  }
362
+ async function emitShotDisposition(callback, receipt, disposition) {
363
+ await callback?.(receipt, disposition);
364
+ }
365
+ async function rethrowShotSetupError(callback, receipt, worktreePath, stage, cause) {
366
+ const error = cause instanceof Error ? cause : new Error(String(cause));
367
+ try {
368
+ await emitShotDisposition(callback, receipt, {
369
+ kind: "setup-error",
370
+ worktreePath,
371
+ stage,
372
+ error: { name: error.name, message: error.message }
373
+ });
374
+ } catch (callbackError) {
375
+ throw new AggregateError(
376
+ [cause, callbackError],
377
+ "agenticGenerator: shot processing failed and its worktree disposition could not be persisted"
378
+ );
379
+ }
380
+ throw cause;
381
+ }
382
+ function shotExecutionSnapshot(result) {
383
+ if (result === null) return null;
384
+ const usage = result.usage ? Object.freeze({ ...result.usage }) : void 0;
385
+ const evidence = result.evidence ? Object.freeze({
386
+ ...result.evidence,
387
+ readDeniedPaths: Object.freeze([...result.evidence.readDeniedPaths]),
388
+ policy: Object.freeze({ ...result.evidence.policy })
389
+ }) : void 0;
390
+ return Object.freeze({
391
+ exitCode: result.exitCode,
392
+ stdout: result.stdout,
393
+ stderr: result.stderr,
394
+ killedBySignal: result.killedBySignal,
395
+ durationMs: result.durationMs,
396
+ timedOut: result.timedOut,
397
+ ...usage ? { usage } : {},
398
+ ...evidence ? { evidence } : {}
399
+ });
400
+ }
301
401
  function shotReceipt(input) {
302
402
  const error = input.error ? {
303
403
  name: input.error instanceof Error ? input.error.name : "Error",
@@ -523,4 +623,4 @@ export {
523
623
  agenticGenerator,
524
624
  commandVerifier
525
625
  };
526
- //# sourceMappingURL=chunk-GHXW56PO.js.map
626
+ //# sourceMappingURL=chunk-D3H7F6L2.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/improvement/agentic-generator.ts"],"sourcesContent":["/**\n *\n * `agenticGenerator` — the full-agentic `CandidateGenerator`: the\n * `shots=N, sandbox=on` setting of the one `improvementDriver`. It runs a real\n * coding harness (claude / codex / opencode) inside the candidate worktree the\n * driver already created, letting the agent read the codebase + the research\n * report and make the change in place. The driver then commits the worktree\n * into a `CodeSurface`.\n *\n * Mechanism: identical to the proven Phase-2.8 in-process executor — spawn the\n * harness as a subprocess with `cwd` = the worktree, on the same filesystem,\n * so edits land in place (no sandbox-mount round-trip). `runLocalHarness` is\n * the verified primitive. The OUTER sandbox is the improvement loop's own\n * execution context; the generator does not nest a second sandbox per\n * candidate (which would reintroduce a host↔sandbox worktree-transport\n * problem that does not need solving here).\n *\n * `maxShots` is the DEPTH dial — a multi-shot verify-in-session loop, NOT the\n * kernel `runLoop`. Each shot runs one full harness session in the (persistent)\n * worktree; between shots the loop refines based on what the last shot produced:\n * - empty tree → \"you changed nothing, make the edits\" → retry\n * - dirty + `verify` fails → feed the verifier's failure into the next shot\n * (the worktree persists, so the harness RESUMES atop its own failing\n * edits with the error in hand — no `--resume` session plumbing needed,\n * and harness-agnostic across claude/codex/opencode)\n * - dirty + `verify` ok (or no verifier configured) → return the candidate\n * A candidate that never verifies within `maxShots` is discarded (`applied:\n * false`), never shipped — if you configured a verifier, a non-passing tree is\n * not a candidate. With no verifier the legacy behavior holds: first dirty shot\n * is the candidate.\n *\n * @experimental\n */\n\nimport { spawnSync } from 'node:child_process'\nimport { createHash } from 'node:crypto'\nimport { existsSync, readFileSync, rmSync } from 'node:fs'\nimport { join, resolve, sep } from 'node:path'\nimport type {\n AnalystFinding,\n CostLedgerHandle,\n CostReceipt,\n CostReceiptInput,\n MaximumCharge,\n} from '@tangle-network/agent-eval'\nimport type { AgentProfile, ReasoningEffort } from '@tangle-network/agent-interface'\nimport {\n applyWorkspacePlan,\n materializeProfile,\n type WorkspacePlan,\n type WorkspacePlanReceipt,\n} from '@tangle-network/agent-profile-materialize'\nimport {\n type CodexExecutionEvidence,\n type CodexTokenUsage,\n harnessInvocation,\n type LocalHarness,\n type LocalHarnessResult,\n runLocalHarness,\n} from '../mcp/local-harness'\nimport type { CandidateGenerator } from './improvement-driver'\n\nconst RAW_TRACE_ANALYST_ID = 'raw-trace-distiller'\nconst RAW_TRACE_AREA = 'raw-trace-context'\nconst RAW_TRACE_DIAGNOSIS_PATH = '.improve/raw-trace-diagnosis.md'\n\n/** Dedicated ephemeral root for generic author-profile files. Every declared\n * file must live below this root so cleanup cannot alter candidate-owned files. */\nexport const AGENTIC_PROFILE_RESOURCE_ROOT = '.agent-runtime-profile-resources'\n\n/** Outcome of verifying a candidate worktree. `feedback` (compiler errors,\n * failing test output) is fed into the next shot when `ok` is false. */\nexport interface VerifyResult {\n ok: boolean\n feedback?: string\n}\n\n/** Verifies the edited worktree. Sync or async; throws only on a setup fault\n * (a candidate that fails verification returns `{ok:false}`, it does not\n * throw). */\nexport type Verifier = (worktreePath: string) => Promise<VerifyResult> | VerifyResult\n\nexport interface AgenticGeneratorShotReceipt {\n readonly schemaVersion: 1\n readonly generation: number | null\n readonly candidateIndex: number | null\n /** One-based shot number within this candidate. */\n readonly shot: number\n readonly maxShots: number\n readonly harness: LocalHarness\n readonly model: string | null\n readonly reasoningEffort: ReasoningEffort | null\n readonly promptSha256: `sha256:${string}`\n readonly startedAt: string\n readonly completedAt: string\n readonly durationMs: number\n readonly exitCode: number | null\n readonly timedOut: boolean\n readonly killedBySignal: NodeJS.Signals | null\n readonly stdoutBytes: number | null\n readonly stdoutSha256: `sha256:${string}` | null\n readonly stderrBytes: number | null\n readonly stderrSha256: `sha256:${string}` | null\n readonly usage: CodexTokenUsage | null\n /** Digest of the exact profile-file workspace plan applied for this shot. */\n readonly profileWorkspacePlanDigest: string | null\n readonly profileWorkspaceFileCount: number\n /** Shared run-ledger call id for this exact shot. */\n readonly costCallId: string | null\n /** Whether dollars came from the provider, the pricing table, or are unknown. */\n readonly costBasis: 'provider-reported' | 'estimated-pricing' | 'unknown'\n readonly costUsd: number | null\n /** True only for a provider-reported amount, never for a pricing estimate. */\n readonly costUsdKnown: boolean\n readonly evidence: CodexExecutionEvidence | null\n readonly error: { readonly name: string; readonly message: string } | null\n}\n\n/** Frozen exact harness result for an author shot: full streams, process state,\n * token usage, and execution-policy evidence.\n * The `onShotCompleted` callback receives `null` when execution failed before\n * the harness returned. */\nexport type AgenticGeneratorShotExecution = Readonly<\n Omit<LocalHarnessResult, 'usage' | 'evidence'> & {\n readonly usage?: Readonly<CodexTokenUsage>\n readonly evidence?: Readonly<Omit<CodexExecutionEvidence, 'readDeniedPaths' | 'policy'>> & {\n readonly readDeniedPaths: ReadonlyArray<string>\n readonly policy: Readonly<CodexExecutionEvidence['policy']>\n }\n }\n>\n\n/** Worktree decision emitted before a completed shot is retried, accepted, or\n * discarded. The callback runs while `worktreePath` is still available, so\n * callers can persist the exact diff. */\nexport type AgenticGeneratorShotDisposition =\n | {\n readonly kind: 'clean'\n readonly worktreePath: string\n }\n | {\n readonly kind: 'rejected'\n readonly worktreePath: string\n readonly stage: 'raw-trace-evidence' | 'verification'\n readonly feedback: string | null\n }\n | {\n readonly kind: 'accepted'\n readonly worktreePath: string\n readonly verified: boolean\n }\n | {\n readonly kind: 'setup-error'\n readonly worktreePath: string\n readonly stage: 'worktree-inspection' | 'raw-trace-evidence' | 'verification'\n readonly error: { readonly name: string; readonly message: string }\n }\n\nexport interface AgenticGeneratorOptions {\n /** Local coding harness to run in the worktree. Default `claude`. */\n harness?: LocalHarness\n /** Author profile rendered through the canonical harness mapper. Required\n * for reproducible Codex so model and reasoning settings are explicit. */\n profile?: AgentProfile\n /** Run Codex with isolated configuration, exact prompt evidence, and required\n * terminal token usage. Requires `harness: 'codex'` and `profile`. */\n codexReproducible?: boolean\n /** Absolute paths reproducible Codex must not read. A function can derive\n * candidate-specific paths after the driver creates its worktree. */\n codexReadDeniedPaths?: ReadonlyArray<string> | ((worktreePath: string) => ReadonlyArray<string>)\n /** Awaited once for every attempted author shot, including process failures.\n * The second argument preserves the exact harness result, including stdout\n * and stderr, before worktree inspection or verification can reject the\n * shot. Throwing aborts the candidate so evidence persistence fails closed. */\n onShotCompleted?: (\n receipt: AgenticGeneratorShotReceipt,\n execution: AgenticGeneratorShotExecution | null,\n ) => void | Promise<void>\n /** Awaited after worktree inspection and before the shot is accepted,\n * retried, or discarded. Throwing aborts the candidate. */\n onShotDisposition?: (\n receipt: AgenticGeneratorShotReceipt,\n disposition: AgenticGeneratorShotDisposition,\n ) => void | Promise<void>\n /** Optional hard upper bound passed to the run-wide CostLedger before each\n * author shot. This MUST be enforced by the provider or executor; a planning\n * estimate is not an admissible bound. Omit for an uncapped ledger. A capped\n * ledger rejects before model dispatch when this is absent. */\n maximumCharge?: MaximumCharge\n /** Per-shot wall-clock timeout (ms). Default = `runLocalHarness` default (5m). */\n timeoutMs?: number\n /** Build the harness task prompt from the report + findings. Override for\n * domain phrasing; the default turns findings into a concrete coder task. */\n buildPrompt?: (args: { report: unknown; findings: AnalystFinding[] }) => string\n /** Verify the worktree after each dirtying shot. When set, a candidate that\n * fails verification is NOT returned — the failure feeds the next shot\n * (verify-in-session), up to `maxShots`; a candidate that never verifies is\n * discarded (`applied:false`), never shipped. Omitted ⇒ legacy behavior:\n * the first dirty shot is the candidate. See `commandVerifier`. */\n verify?: Verifier\n /** Test seam — inject the harness runner (defaults to `runLocalHarness`). */\n runHarness?: typeof runLocalHarness\n /** Test seam — inject the worktree-dirty check (defaults to `git status`). */\n isDirty?: (worktreePath: string) => boolean\n}\n\n/** Full-agentic `CandidateGenerator` (the `shots=N, sandbox=on` setting): run a real coding harness inside the candidate worktree so the agent makes the change in place. */\nexport function agenticGenerator(opts: AgenticGeneratorOptions = {}): CandidateGenerator {\n const harness = opts.harness ?? 'claude'\n if (opts.codexReproducible && harness !== 'codex') {\n throw new Error(\"agenticGenerator: codexReproducible requires harness 'codex'\")\n }\n if (opts.codexReproducible && !opts.profile) {\n throw new Error('agenticGenerator: codexReproducible requires an explicit author profile')\n }\n if (opts.codexReadDeniedPaths && !opts.codexReproducible) {\n throw new Error('agenticGenerator: codexReadDeniedPaths requires codexReproducible')\n }\n if (opts.maximumCharge && !opts.codexReproducible) {\n throw new Error('agenticGenerator: maximumCharge requires codexReproducible')\n }\n const profileResourcePlan = opts.codexReproducible\n ? authorProfileResourcePlan(opts.profile as AgentProfile)\n : null\n const buildPrompt = opts.buildPrompt ?? defaultBuildPrompt\n const run = opts.runHarness ?? runLocalHarness\n const dirty = opts.isDirty ?? worktreeDirty\n const verify = opts.verify\n\n return {\n kind: `agentic:${harness}`,\n // The seed repo + (in rawTraceContext mode) the raw-trace filesystem context\n // are the change signal — an agentic coder proposes from them even when the\n // distiller yielded zero findings. Without this, the improvementDriver's\n // empty-findings guard short-circuits and generates ZERO candidates on the\n // first (and, for a single-generation run, only) proposal round.\n proposesWithoutFindings: true,\n async generate({\n worktreePath,\n report,\n findings,\n maxShots,\n signal,\n generation,\n candidateIndex,\n costLedger,\n costPhase,\n }) {\n let reproducibleCostLedger: CostLedgerHandle | undefined\n if (opts.codexReproducible) {\n if (!costLedger) {\n throw new Error(\n 'agenticGenerator: reproducible Codex requires the run-wide CostLedger supplied by agent-eval 0.117+',\n )\n }\n reproducibleCostLedger = costLedger\n }\n const basePrompt = appendProfileResourcePaths(\n buildPrompt({ report, findings }),\n profileResourcePlan,\n )\n const needsRawTraceEvidence = requiresRawTraceEvidence(findings)\n const shots = Math.max(1, maxShots)\n // Feedback appended to the base prompt for the NEXT shot — empty on shot 0.\n let attemptNote = ''\n\n for (let shot = 0; shot < shots; shot++) {\n if (signal.aborted) break\n const taskPrompt = attemptNote ? `${basePrompt}\\n\\n${attemptNote}` : basePrompt\n const invocation = opts.profile\n ? harnessInvocation(harness, opts.profile, taskPrompt, {\n dangerouslySkipPermissions: harness === 'claude',\n ...(opts.codexReproducible ? { codexReproducible: true } : {}),\n })\n : undefined\n const exactPrompt = invocation?.prompt ?? taskPrompt\n const readDeniedPaths =\n typeof opts.codexReadDeniedPaths === 'function'\n ? opts.codexReadDeniedPaths(worktreePath)\n : opts.codexReadDeniedPaths\n const startedAt = new Date()\n let harnessResult: LocalHarnessResult | null = null\n let profileWorkspaceReceipt: WorkspacePlanReceipt | null = null\n let costReceipt: CostReceipt | null = null\n let costCallId: string | null = null\n let shotError: Error | null = null\n try {\n const execute = async (executionSignal: AbortSignal): Promise<LocalHarnessResult> => {\n harnessResult = await withAuthorProfileResources(\n profileResourcePlan,\n worktreePath,\n async (receipt) => {\n profileWorkspaceReceipt = receipt\n const result = await run({\n harness,\n cwd: worktreePath,\n taskPrompt,\n ...(invocation\n ? { invocation: { command: invocation.command, args: invocation.args } }\n : {}),\n // The candidate worktree is isolated and must be editable without an\n // interactive permission prompt. Other runLocalHarness callers remain\n // permission-safe by default.\n dangerouslySkipPermissions: harness === 'claude',\n ...(opts.codexReproducible ? { codexReproducible: true } : {}),\n ...(readDeniedPaths ? { codexReadDeniedPaths: readDeniedPaths } : {}),\n timeoutMs: opts.timeoutMs,\n signal: executionSignal,\n })\n // Assign before profile cleanup so a cleanup failure still\n // settles the model usage already returned by the harness.\n harnessResult = result\n return result\n },\n )\n const failure = shotFailure(harnessResult, exactPrompt, opts.codexReproducible === true)\n if (failure) throw failure\n return harnessResult\n }\n\n if (reproducibleCostLedger) {\n const model = opts.profile?.model?.default\n if (!model) {\n throw new Error('agenticGenerator: reproducible Codex requires profile.model.default')\n }\n const paid = await reproducibleCostLedger.runPaidCall({\n channel: 'driver',\n phase: costPhase ?? 'search.proposal',\n actor: `agentic-generator:${harness}`,\n model,\n tags: {\n generation: String(generation ?? -1),\n candidateIndex: String(candidateIndex ?? -1),\n shot: String(shot + 1),\n },\n signal,\n ...(opts.maximumCharge ? { maximumCharge: opts.maximumCharge } : {}),\n execute,\n receipt: (result) => costReceiptFromHarness(result, model),\n receiptFromError: () =>\n harnessResult?.usage ? costReceiptFromHarness(harnessResult, model) : undefined,\n })\n costCallId = paid.callId ?? null\n costReceipt = paid.receipt ?? null\n if (!paid.succeeded) throw paid.error\n harnessResult = paid.value\n } else {\n harnessResult = await execute(signal)\n }\n } catch (cause) {\n shotError = cause instanceof Error ? cause : new Error(String(cause))\n }\n const execution = shotExecutionSnapshot(harnessResult)\n const receipt = shotReceipt({\n generation,\n candidateIndex,\n shot,\n maxShots: shots,\n harness,\n profile: opts.profile,\n prompt: exactPrompt,\n startedAt,\n completedAt: new Date(),\n result: execution,\n profileWorkspaceReceipt,\n costCallId,\n costReceipt,\n error: shotError,\n })\n await emitShotReceipt(opts.onShotCompleted, receipt, execution, shotError)\n\n if (!execution) {\n throw new Error('agenticGenerator: author shot completed without a harness result')\n }\n\n let worktreeChanged: boolean\n try {\n worktreeChanged = dirty(worktreePath)\n } catch (cause) {\n return rethrowShotSetupError(\n opts.onShotDisposition,\n receipt,\n worktreePath,\n 'worktree-inspection',\n cause,\n )\n }\n\n // The worktree IS the signal: no edits ⇒ tell the next shot to act.\n if (!worktreeChanged) {\n await emitShotDisposition(opts.onShotDisposition, receipt, {\n kind: 'clean',\n worktreePath,\n })\n attemptNote = EMPTY_TREE_NOTE\n continue\n }\n\n if (needsRawTraceEvidence) {\n let problem: string | null\n try {\n problem = rawTraceEvidenceProblem(worktreePath, findings)\n } catch (cause) {\n return rethrowShotSetupError(\n opts.onShotDisposition,\n receipt,\n worktreePath,\n 'raw-trace-evidence',\n cause,\n )\n }\n if (problem) {\n await emitShotDisposition(opts.onShotDisposition, receipt, {\n kind: 'rejected',\n worktreePath,\n stage: 'raw-trace-evidence',\n feedback: problem,\n })\n attemptNote = problem\n continue\n }\n }\n\n // Dirty: with no verifier the diff IS the candidate (we trust the diff,\n // not the harness's stdout). With a verifier the candidate must pass it.\n if (!verify) {\n await emitShotDisposition(opts.onShotDisposition, receipt, {\n kind: 'accepted',\n worktreePath,\n verified: false,\n })\n return { applied: true, summary: summarize(findings) }\n }\n let result: VerifyResult\n try {\n result = await verify(worktreePath)\n } catch (cause) {\n return rethrowShotSetupError(\n opts.onShotDisposition,\n receipt,\n worktreePath,\n 'verification',\n cause,\n )\n }\n if (result.ok) {\n await emitShotDisposition(opts.onShotDisposition, receipt, {\n kind: 'accepted',\n worktreePath,\n verified: true,\n })\n return { applied: true, summary: summarize(findings) }\n }\n await emitShotDisposition(opts.onShotDisposition, receipt, {\n kind: 'rejected',\n worktreePath,\n stage: 'verification',\n feedback: result.feedback ?? null,\n })\n // Dirty but failing — resume next shot atop these edits with the error.\n attemptNote = failureNote(result.feedback)\n }\n\n // Shots exhausted: no verified candidate (or, sans verifier, no edits).\n return { applied: false, summary: '' }\n },\n }\n}\n\nfunction authorProfileResourcePlan(profile: AgentProfile): WorkspacePlan | null {\n const resources = profile.resources\n if (!resources) return null\n const unsupportedKinds = [\n resources.tools?.length ? 'tools' : null,\n resources.skills?.length ? 'skills' : null,\n resources.agents?.length ? 'agents' : null,\n ].filter((kind): kind is string => kind !== null)\n if (unsupportedKinds.length > 0) {\n throw new Error(\n `agenticGenerator: reproducible Codex author resources support files only; unsupported: ${unsupportedKinds.join(', ')}`,\n )\n }\n if (!resources.files || resources.files.length === 0) return null\n\n const plan = materializeProfile(\n {\n name: profile.name,\n resources: { files: resources.files },\n },\n 'codex',\n )\n if (plan.unsupported.length > 0) {\n throw new Error(\n `agenticGenerator: author profile files could not be materialized: ${plan.unsupported.map((item) => item.reason).join('; ')}`,\n )\n }\n if (Object.keys(plan.env).length > 0 || plan.flags.length > 0) {\n throw new Error(\n 'agenticGenerator: generic author profile files unexpectedly changed spawn values',\n )\n }\n\n const virtualRoot = resolve('/', AGENTIC_PROFILE_RESOURCE_ROOT)\n const seen = new Set<string>()\n for (const file of plan.files) {\n const target = resolve('/', file.relPath)\n if (!target.startsWith(`${virtualRoot}${sep}`)) {\n throw new Error(\n `agenticGenerator: author profile file must be below ${AGENTIC_PROFILE_RESOURCE_ROOT}: ${file.relPath}`,\n )\n }\n if (seen.has(target)) {\n throw new Error(`agenticGenerator: duplicate author profile file path: ${file.relPath}`)\n }\n seen.add(target)\n }\n return plan\n}\n\nfunction appendProfileResourcePaths(prompt: string, plan: WorkspacePlan | null): string {\n if (!plan) return prompt\n return [\n prompt,\n '',\n 'Profile resource files available for this shot:',\n ...plan.files.map((file) => `- ${file.relPath}`),\n ].join('\\n')\n}\n\nasync function withAuthorProfileResources<T>(\n plan: WorkspacePlan | null,\n worktreePath: string,\n run: (receipt: WorkspacePlanReceipt | null) => Promise<T>,\n): Promise<T> {\n if (!plan) return run(null)\n\n const rootPath = resolve(worktreePath, AGENTIC_PROFILE_RESOURCE_ROOT)\n if (existsSync(rootPath)) {\n throw new Error(\n `agenticGenerator: ephemeral author profile root already exists: ${AGENTIC_PROFILE_RESOURCE_ROOT}`,\n )\n }\n\n let value: T | undefined\n let primaryError: unknown\n try {\n const receipt = applyWorkspacePlan(plan, worktreePath)\n value = await run(receipt)\n } catch (cause) {\n primaryError = cause\n }\n\n let cleanupError: unknown\n try {\n rmSync(rootPath, { recursive: true, force: true })\n if (existsSync(rootPath)) {\n throw new Error(\n `agenticGenerator: ephemeral author profile root survived cleanup: ${AGENTIC_PROFILE_RESOURCE_ROOT}`,\n )\n }\n } catch (cause) {\n cleanupError = cause\n }\n\n if (primaryError !== undefined && cleanupError !== undefined) {\n throw new AggregateError(\n [primaryError, cleanupError],\n 'agenticGenerator: author shot and profile resource cleanup both failed',\n )\n }\n if (primaryError !== undefined) throw primaryError\n if (cleanupError !== undefined) throw cleanupError\n return value as T\n}\n\nasync function emitShotReceipt(\n callback: AgenticGeneratorOptions['onShotCompleted'],\n receipt: AgenticGeneratorShotReceipt,\n execution: AgenticGeneratorShotExecution | null,\n primaryError: Error | null,\n): Promise<void> {\n try {\n await callback?.(receipt, execution)\n } catch (callbackError) {\n if (primaryError !== null) {\n throw new AggregateError(\n [primaryError, callbackError],\n 'agenticGenerator: author shot failed and its receipt could not be persisted',\n )\n }\n throw callbackError\n }\n if (primaryError !== null) throw primaryError\n}\n\nasync function emitShotDisposition(\n callback: AgenticGeneratorOptions['onShotDisposition'],\n receipt: AgenticGeneratorShotReceipt,\n disposition: AgenticGeneratorShotDisposition,\n): Promise<void> {\n await callback?.(receipt, disposition)\n}\n\nasync function rethrowShotSetupError(\n callback: AgenticGeneratorOptions['onShotDisposition'],\n receipt: AgenticGeneratorShotReceipt,\n worktreePath: string,\n stage: Extract<AgenticGeneratorShotDisposition, { kind: 'setup-error' }>['stage'],\n cause: unknown,\n): Promise<never> {\n const error = cause instanceof Error ? cause : new Error(String(cause))\n try {\n await emitShotDisposition(callback, receipt, {\n kind: 'setup-error',\n worktreePath,\n stage,\n error: { name: error.name, message: error.message },\n })\n } catch (callbackError) {\n throw new AggregateError(\n [cause, callbackError],\n 'agenticGenerator: shot processing failed and its worktree disposition could not be persisted',\n )\n }\n throw cause\n}\n\nfunction shotExecutionSnapshot(\n result: LocalHarnessResult | null,\n): AgenticGeneratorShotExecution | null {\n if (result === null) return null\n const usage = result.usage ? Object.freeze({ ...result.usage }) : undefined\n const evidence = result.evidence\n ? Object.freeze({\n ...result.evidence,\n readDeniedPaths: Object.freeze([...result.evidence.readDeniedPaths]),\n policy: Object.freeze({ ...result.evidence.policy }),\n })\n : undefined\n return Object.freeze({\n exitCode: result.exitCode,\n stdout: result.stdout,\n stderr: result.stderr,\n killedBySignal: result.killedBySignal,\n durationMs: result.durationMs,\n timedOut: result.timedOut,\n ...(usage ? { usage } : {}),\n ...(evidence ? { evidence } : {}),\n })\n}\n\nfunction shotReceipt(input: {\n readonly generation: number | undefined\n readonly candidateIndex: number | undefined\n readonly shot: number\n readonly maxShots: number\n readonly harness: LocalHarness\n readonly profile: AgentProfile | undefined\n readonly prompt: string\n readonly startedAt: Date\n readonly completedAt: Date\n readonly result: AgenticGeneratorShotExecution | null\n readonly profileWorkspaceReceipt: WorkspacePlanReceipt | null\n readonly costCallId: string | null\n readonly costReceipt: CostReceipt | null\n readonly error: unknown\n}): AgenticGeneratorShotReceipt {\n const error = input.error\n ? {\n name: input.error instanceof Error ? input.error.name : 'Error',\n message: input.error instanceof Error ? input.error.message : String(input.error),\n }\n : null\n const result = input.result\n const costBasis = costBasisFor(input.costReceipt)\n return {\n schemaVersion: 1,\n generation: input.generation ?? null,\n candidateIndex: input.candidateIndex ?? null,\n shot: input.shot + 1,\n maxShots: input.maxShots,\n harness: input.harness,\n model: input.profile?.model?.default ?? null,\n reasoningEffort: input.profile?.model?.reasoningEffort ?? null,\n promptSha256: sha256(input.prompt),\n startedAt: input.startedAt.toISOString(),\n completedAt: input.completedAt.toISOString(),\n durationMs: result?.durationMs ?? input.completedAt.getTime() - input.startedAt.getTime(),\n exitCode: result?.exitCode ?? null,\n timedOut: result?.timedOut ?? false,\n killedBySignal: result?.killedBySignal ?? null,\n stdoutBytes: result ? Buffer.byteLength(result.stdout) : null,\n stdoutSha256: result ? sha256(result.stdout) : null,\n stderrBytes: result ? Buffer.byteLength(result.stderr) : null,\n stderrSha256: result ? sha256(result.stderr) : null,\n usage: result?.usage ? { ...result.usage } : null,\n profileWorkspacePlanDigest: input.profileWorkspaceReceipt?.workspacePlanDigest ?? null,\n profileWorkspaceFileCount: input.profileWorkspaceReceipt?.written.length ?? 0,\n costCallId: input.costCallId,\n costBasis,\n costUsd: costBasis === 'unknown' ? null : (input.costReceipt?.costUsd ?? null),\n costUsdKnown: costBasis === 'provider-reported',\n evidence: result?.evidence\n ? {\n ...result.evidence,\n readDeniedPaths: [...result.evidence.readDeniedPaths],\n policy: { ...result.evidence.policy },\n }\n : null,\n error,\n }\n}\n\nfunction costBasisFor(receipt: CostReceipt | null): AgenticGeneratorShotReceipt['costBasis'] {\n if (receipt === null || receipt.costUnknown) return 'unknown'\n return receipt.actualCostUsd === undefined ? 'estimated-pricing' : 'provider-reported'\n}\n\nfunction shotFailure(\n result: LocalHarnessResult,\n exactPrompt: string,\n codexReproducible: boolean,\n): Error | null {\n if (result.timedOut) {\n return new Error('agenticGenerator: author shot timed out')\n }\n if (result.killedBySignal) {\n return new Error(`agenticGenerator: author shot was killed by ${result.killedBySignal}`)\n }\n if (result.exitCode !== 0) {\n return new Error(`agenticGenerator: author shot exited with code ${String(result.exitCode)}`)\n }\n if (!codexReproducible) return null\n if (!result.usage || !result.evidence) {\n return new Error(\n 'agenticGenerator: reproducible Codex shot completed without usage or execution evidence',\n )\n }\n const expectedPromptSha256 = sha256(exactPrompt).slice('sha256:'.length)\n if (result.evidence.requestedPromptSha256 !== expectedPromptSha256) {\n return new Error(\n 'agenticGenerator: reproducible Codex prompt evidence does not match the exact authored prompt',\n )\n }\n return null\n}\n\nfunction costReceiptFromHarness(result: LocalHarnessResult, model: string): CostReceiptInput {\n if (!result.usage) {\n throw new Error('agenticGenerator: author shot did not report terminal token usage')\n }\n return {\n model,\n inputTokens: result.usage.inputTokens - result.usage.cachedInputTokens,\n outputTokens: result.usage.outputTokens,\n ...(result.usage.cachedInputTokens > 0 ? { cachedTokens: result.usage.cachedInputTokens } : {}),\n }\n}\n\nfunction sha256(value: string): `sha256:${string}` {\n return `sha256:${createHash('sha256').update(value).digest('hex')}`\n}\n\n/** Turn the analyst's findings (+ optional report) into a concrete coder task. */\nfunction defaultBuildPrompt(args: { report: unknown; findings: AnalystFinding[] }): string {\n const lines: string[] = [\n 'You are improving this codebase based on an evaluation analysis.',\n 'Make the smallest set of edits that addresses the findings below, then stop.',\n 'Do not change unrelated code. Do not commit — leave changes in the working tree.',\n '',\n 'Findings:',\n ]\n for (const f of args.findings) {\n const where = f.subject ? ` [${f.subject}]` : ''\n lines.push(`- (${f.severity})${where} ${f.claim}`)\n if (f.recommended_action) lines.push(` → ${f.recommended_action}`)\n }\n if (requiresRawTraceEvidence(args.findings)) {\n lines.push(\n '',\n 'Raw trace evidence requirement:',\n `- Inspect at least one raw trace path named above before editing.`,\n `- Write ${RAW_TRACE_DIAGNOSIS_PATH} in this worktree.`,\n '- Include the exact trace path(s) inspected, the failure mechanism, and the code change made.',\n '- A candidate without this file, or with only this file changed, is discarded.',\n )\n }\n return lines.join('\\n')\n}\n\nconst EMPTY_TREE_NOTE =\n 'NOTE: your previous attempt left the working tree unchanged. Make the concrete file edits now.'\n\n/** Next-shot feedback when the worktree is dirty but failed verification. The\n * edits persist on disk, so the harness resumes atop them — tell it to fix in\n * place, not start over. Verifier detail is truncated to keep the prompt bounded. */\nfunction failureNote(feedback?: string): string {\n const detail = feedback?.trim()\n return [\n 'NOTE: your edits are in the working tree but verification FAILED.',\n 'Fix the problem in place — build on your existing edits, do not revert them.',\n detail ? `Verifier output:\\n${truncate(detail, 4000)}` : 'No verifier detail was captured.',\n ].join('\\n')\n}\n\nfunction rawTraceEvidenceProblem(worktreePath: string, findings: AnalystFinding[]): string | null {\n const changedPaths = worktreeChangedPaths(worktreePath)\n const substantive = changedPaths.filter((path) => path !== RAW_TRACE_DIAGNOSIS_PATH)\n if (substantive.length === 0) {\n return [\n `NOTE: raw-trace mode requires a real code/config edit in addition to ${RAW_TRACE_DIAGNOSIS_PATH}.`,\n 'Your previous attempt only changed the diagnosis artifact. Inspect the cited traces and make the causal code change.',\n ].join('\\n')\n }\n\n const diagnosisPath = join(worktreePath, RAW_TRACE_DIAGNOSIS_PATH)\n if (!existsSync(diagnosisPath)) {\n return [\n `NOTE: raw-trace mode requires ${RAW_TRACE_DIAGNOSIS_PATH}.`,\n 'Before retrying, inspect at least one cited spans.jsonl/cached-result.json/artifact path, then write the diagnosis file with the exact path, failure mechanism, and code change.',\n ].join('\\n')\n }\n\n const body = readFileSync(diagnosisPath, 'utf8')\n const evidencePaths = traceEvidencePaths(findings)\n if (evidencePaths.length > 0 && !evidencePaths.some((path) => body.includes(path))) {\n return [\n `${RAW_TRACE_DIAGNOSIS_PATH} exists, but it does not cite any exact raw trace path from the findings.`,\n `Cite at least one of these inspected paths exactly: ${evidencePaths.slice(0, 5).join(', ')}`,\n ].join('\\n')\n }\n\n return null\n}\n\nfunction requiresRawTraceEvidence(findings: AnalystFinding[]): boolean {\n return findings.some((finding) => {\n const f = finding as unknown as Record<string, unknown>\n return f.analyst_id === RAW_TRACE_ANALYST_ID || f.area === RAW_TRACE_AREA\n })\n}\n\nfunction traceEvidencePaths(findings: AnalystFinding[]): string[] {\n const out: string[] = []\n for (const finding of findings) {\n const refs = (finding as unknown as { evidence_refs?: unknown }).evidence_refs\n if (!Array.isArray(refs)) continue\n for (const ref of refs) {\n if (!ref || typeof ref !== 'object') continue\n const uri = (ref as { uri?: unknown }).uri\n if (typeof uri === 'string' && uri.length > 0) out.push(uri)\n }\n }\n return [...new Set(out)]\n}\n\n/** A `Verifier` that runs a command in the worktree: exit 0 ⇒ ok, any other\n * exit ⇒ failed with stdout+stderr as feedback. The common case — verify by\n * `tsc --noEmit`, `pnpm build`, or a test command. A timeout is treated as a\n * FAILED candidate (a change that hangs the build is a bad change); a missing\n * binary or spawn fault throws (a setup bug, not a failed candidate — no\n * silent fallback). */\nexport function commandVerifier(\n command: string,\n args: string[] = [],\n timeoutMs = 300_000,\n): Verifier {\n return (worktreePath: string): VerifyResult => {\n const result = spawnSync(command, args, {\n cwd: worktreePath,\n encoding: 'utf-8',\n timeout: timeoutMs,\n })\n if (result.signal) {\n return {\n ok: false,\n feedback: `verifier '${command}' killed by ${result.signal} (likely timeout after ${timeoutMs}ms)`,\n }\n }\n if (result.error) {\n const code = (result.error as NodeJS.ErrnoException).code\n if (code === 'ENOENT') {\n throw new Error(\n `commandVerifier: '${command}' not found in PATH (setup bug, not a failed candidate)`,\n )\n }\n throw new Error(`commandVerifier: '${command}' failed to spawn: ${result.error.message}`)\n }\n if (result.status === 0) return { ok: true }\n const out = `${result.stdout ?? ''}${result.stderr ?? ''}`.trim()\n return { ok: false, feedback: out.length > 0 ? out : `exit ${result.status}` }\n }\n}\n\n/** A one-line summary for the commit message, derived from the findings. */\nfunction summarize(findings: AnalystFinding[]): string {\n if (findings.length === 0) return 'agentic improvement'\n if (findings.length === 1) return `agentic: ${truncate(findings[0]!.claim, 64)}`\n return `agentic: ${findings.length} findings addressed`\n}\n\nfunction truncate(s: string, n: number): string {\n return s.length <= n ? s : `${s.slice(0, n - 1)}…`\n}\n\n/** Non-empty `git status --porcelain` ⇒ the harness changed the worktree.\n * Fails loud: the worktree is a fresh checkout, so a git error here means\n * something is genuinely broken (git missing, corrupt index, killed mid-run).\n * Folding that into `false` would silently discard a candidate and mask the\n * real failure — forbidden by the no-silent-fallbacks doctrine. */\nfunction worktreeDirty(worktreePath: string): boolean {\n return worktreeChangedPaths(worktreePath).length > 0\n}\n\nfunction worktreeChangedPaths(worktreePath: string): string[] {\n const result = spawnSync('git', ['status', '--porcelain', '--untracked-files=all'], {\n cwd: worktreePath,\n encoding: 'utf-8',\n })\n if (result.error) {\n throw new Error(\n `agenticGenerator: git status failed to spawn in ${worktreePath}: ${result.error.message}`,\n )\n }\n if (result.status !== 0) {\n throw new Error(\n `agenticGenerator: git status exited ${result.status} in ${worktreePath}: ${result.stderr.trim()}`,\n )\n }\n return result.stdout\n .split('\\n')\n .map((line) => line.trim())\n .filter((line) => line.length > 0)\n .map((line) => line.slice(3).trim())\n}\n"],"mappings":";;;;;;AAkCA,SAAS,iBAAiB;AAC1B,SAA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9C,SAAO,EAAE,UAAU,IAAI,IAAI,GAAG,EAAE,MAAM,GAAG,IAAI,CAAC,CAAC;AACjD;AAOA,SAAS,cAAc,cAA+B;AACpD,SAAO,qBAAqB,YAAY,EAAE,SAAS;AACrD;AAEA,SAAS,qBAAqB,cAAgC;AAC5D,QAAM,SAAS,UAAU,OAAO,CAAC,UAAU,eAAe,uBAAuB,GAAG;AAAA,IAClF,KAAK;AAAA,IACL,UAAU;AAAA,EACZ,CAAC;AACD,MAAI,OAAO,OAAO;AAChB,UAAM,IAAI;AAAA,MACR,mDAAmD,YAAY,KAAK,OAAO,MAAM,OAAO;AAAA,IAC1F;AAAA,EACF;AACA,MAAI,OAAO,WAAW,GAAG;AACvB,UAAM,IAAI;AAAA,MACR,uCAAuC,OAAO,MAAM,OAAO,YAAY,KAAK,OAAO,OAAO,KAAK,CAAC;AAAA,IAClG;AAAA,EACF;AACA,SAAO,OAAO,OACX,MAAM,IAAI,EACV,IAAI,CAAC,SAAS,KAAK,KAAK,CAAC,EACzB,OAAO,CAAC,SAAS,KAAK,SAAS,CAAC,EAChC,IAAI,CAAC,SAAS,KAAK,MAAM,CAAC,EAAE,KAAK,CAAC;AACvC;","names":["receipt","result"]}
@@ -1,9 +1,9 @@
1
- import {
2
- agenticGenerator
3
- } from "./chunk-GHXW56PO.js";
4
1
  import {
5
2
  assertModelAllowed
6
3
  } from "./chunk-ISTDY47H.js";
4
+ import {
5
+ agenticGenerator
6
+ } from "./chunk-D3H7F6L2.js";
7
7
  import {
8
8
  ConfigError
9
9
  } from "./chunk-YEJR7IXO.js";
@@ -658,4 +658,4 @@ export {
658
658
  applyImprovementWinnerToProfile,
659
659
  improve
660
660
  };
661
- //# sourceMappingURL=chunk-7NCP74SL.js.map
661
+ //# sourceMappingURL=chunk-PCURO3DL.js.map