@tangle-network/agent-runtime 0.94.6 → 0.94.8

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 (63) hide show
  1. package/dist/agent.d.ts +1 -1
  2. package/dist/agent.js +4 -4
  3. package/dist/{agentic-generator-CL1q0H91.d.ts → agentic-generator-1g7GDba7.d.ts} +73 -6
  4. package/dist/analyst-loop.d.ts +1 -1
  5. package/dist/analyst-loop.js +2 -2
  6. package/dist/{chunk-GKZ6DFDN.js → chunk-7HH22XN4.js} +105 -27
  7. package/dist/chunk-7HH22XN4.js.map +1 -0
  8. package/dist/{chunk-JMT5VYY3.js → chunk-7NCP74SL.js} +174 -48
  9. package/dist/chunk-7NCP74SL.js.map +1 -0
  10. package/dist/{chunk-WQA5Y6PD.js → chunk-EP6RVHMX.js} +3 -3
  11. package/dist/chunk-EP6RVHMX.js.map +1 -0
  12. package/dist/{chunk-LWNMCOEA.js → chunk-FRXDOBFP.js} +3 -3
  13. package/dist/chunk-GHXW56PO.js +526 -0
  14. package/dist/chunk-GHXW56PO.js.map +1 -0
  15. package/dist/{chunk-63TIZHMI.js → chunk-KYPVUEJ4.js} +4 -4
  16. package/dist/{chunk-FVJ7M3DA.js → chunk-M22PL4GH.js} +1 -1
  17. package/dist/chunk-M22PL4GH.js.map +1 -0
  18. package/dist/{chunk-4VMRCEI6.js → chunk-MSUWXCHD.js} +2 -2
  19. package/dist/{chunk-ZQZX77MM.js → chunk-QDSOD7RC.js} +2 -2
  20. package/dist/{chunk-RNWDH5Z3.js → chunk-TNUBPPZA.js} +2 -2
  21. package/dist/{completion-gate-CfX2thvL.d.ts → completion-gate-tzwyyD-E.d.ts} +2 -2
  22. package/dist/{coordination-pOGZuYS7.d.ts → coordination-o0TzS7Ms.d.ts} +5 -5
  23. package/dist/environment-provider.d.ts +2 -2
  24. package/dist/{improve-Ciuvu2jh.d.ts → improve-DZeatcs7.d.ts} +19 -8
  25. package/dist/index.d.ts +20 -17
  26. package/dist/index.js +37 -20
  27. package/dist/index.js.map +1 -1
  28. package/dist/intelligence.d.ts +6 -6
  29. package/dist/intelligence.js +41 -17
  30. package/dist/intelligence.js.map +1 -1
  31. package/dist/knowledge.d.ts +7 -7
  32. package/dist/knowledge.js +4 -4
  33. package/dist/lifecycle.d.ts +3 -3
  34. package/dist/lifecycle.js +2 -2
  35. package/dist/{local-harness-CePtFrwu.d.ts → local-harness-ZLMkKdZc.d.ts} +1 -1
  36. package/dist/{loop-runner-bin-B4PwjVaF.d.ts → loop-runner-bin-iTSxSmpv.d.ts} +2 -2
  37. package/dist/loop-runner-bin.d.ts +6 -6
  38. package/dist/loop-runner-bin.js +6 -6
  39. package/dist/loops.d.ts +36 -23
  40. package/dist/loops.js +4 -4
  41. package/dist/mcp/bin.js +3 -3
  42. package/dist/mcp/index.d.ts +10 -10
  43. package/dist/mcp/index.js +5 -5
  44. package/dist/{mcp-serve-verifier-D7hCZIkT.d.ts → mcp-serve-verifier-BO4MEsR3.d.ts} +1 -1
  45. package/dist/{openai-tools-BMOu1t3A.d.ts → openai-tools-0wACz8f8.d.ts} +1 -1
  46. package/dist/profiles.d.ts +1 -1
  47. package/dist/{sanitize-Dr3SliRC.d.ts → sanitize-Dcbjp0tU.d.ts} +1 -1
  48. package/dist/{supervise-Y3w878fN.d.ts → supervise-CRwaJIkd.d.ts} +4 -4
  49. package/dist/{types-Kjr5W6OF.d.ts → types-CKmyZ9TP.d.ts} +4 -7
  50. package/dist/{types-DHLXdLVN.d.ts → types-CogNCaw7.d.ts} +1 -1
  51. package/dist/{worktree-fanout-DmBvR-_O.d.ts → worktree-fanout-BJy24LYe.d.ts} +4 -4
  52. package/package.json +4 -4
  53. package/dist/chunk-4WWSICFY.js +0 -210
  54. package/dist/chunk-4WWSICFY.js.map +0 -1
  55. package/dist/chunk-FVJ7M3DA.js.map +0 -1
  56. package/dist/chunk-GKZ6DFDN.js.map +0 -1
  57. package/dist/chunk-JMT5VYY3.js.map +0 -1
  58. package/dist/chunk-WQA5Y6PD.js.map +0 -1
  59. /package/dist/{chunk-LWNMCOEA.js.map → chunk-FRXDOBFP.js.map} +0 -0
  60. /package/dist/{chunk-63TIZHMI.js.map → chunk-KYPVUEJ4.js.map} +0 -0
  61. /package/dist/{chunk-4VMRCEI6.js.map → chunk-MSUWXCHD.js.map} +0 -0
  62. /package/dist/{chunk-ZQZX77MM.js.map → chunk-QDSOD7RC.js.map} +0 -0
  63. /package/dist/{chunk-RNWDH5Z3.js.map → chunk-TNUBPPZA.js.map} +0 -0
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/runtime/sandbox-events.ts"],"sourcesContent":["/**\n * Sandbox-event → runtime-event mapping.\n *\n * The sandbox SDK emits a polymorphic `SandboxEvent = { type, data, id? }`\n * whose `type` vocabulary is backend-determined (opencode, etc.) rather than\n * enumerated by the SDK. Two consumers project it:\n * - the loop kernel's cost ledger (`extractLlmCallEvent`) — sums usage off\n * every cost-bearing event, regardless of stream shape;\n * - the `AgentRuntime.act` streaming contract (`mapSandboxEvent`) — projects\n * incremental events to the `RuntimeStreamEvent` chat-UX vocabulary.\n *\n * Both live here so the empirically-observed `type` vocabulary has one home.\n */\n\nimport type { SandboxEvent } from '@tangle-network/sandbox'\nimport type { RuntimeStreamEvent } from '../types'\n\n/**\n * Extract a `RuntimeStreamEvent`-shaped `llm_call` from a sandbox event when\n * the event carries usage/cost data. Returns `undefined` for non-cost events\n * so the kernel can iterate the full stream without branching.\n *\n * Canonical cost-carrying types observed in the wild:\n * - `llm_call` — `data: { model, tokensIn, tokensOut, costUsd, ... }`\n * - `message.completed` / `result` — `data: { usage: { inputTokens,\n * outputTokens, totalCostUsd? } }`\n * - `cost.usage` / `usage` — same shape under a dedicated type\n *\n * Numeric coercion is strict: `Number.isFinite` gates every accumulator write\n * so a sentinel `NaN` from a misbehaving backend cannot poison the ledger.\n */\nexport function extractLlmCallEvent(\n event: SandboxEvent,\n agentRunName: string,\n): (RuntimeStreamEvent & { type: 'llm_call' }) | undefined {\n if (!event || typeof event !== 'object') return undefined\n const type = String(event.type ?? '')\n const data =\n event.data && typeof event.data === 'object'\n ? (event.data as Record<string, unknown>)\n : ({} as Record<string, unknown>)\n\n if (type === 'llm_call' || type === 'cost.usage' || type === 'usage') {\n return buildLlmCall(data, agentRunName)\n }\n if (type === 'message.completed' || type === 'result' || type === 'final') {\n const usage = data.usage as Record<string, unknown> | undefined\n if (!usage || typeof usage !== 'object') return undefined\n return buildLlmCall({ ...usage, model: data.model ?? usage.model }, agentRunName)\n }\n // sandbox 0.4.0 terminal event: `data = { tokenUsage: { inputTokens, outputTokens,\n // reasoningTokens, cacheReadInputTokens }, totalCostUsd }`. Usage lives under\n // `tokenUsage` (not `usage`) and the cost is top-level — neither matched the\n // branches above, so an in-process loopDispatch run reported {0,0} and the\n // backend-integrity guard misread a real run as a stub. Reasoning tokens are\n // billed output (reasoning models), so they fold into the output count.\n if (type === 'done') {\n const usage = data.tokenUsage as Record<string, unknown> | undefined\n if (!usage || typeof usage !== 'object') return undefined\n const out = pickFiniteNumber(usage, ['outputTokens', 'completion_tokens', 'tokensOut'])\n const reasoning = pickFiniteNumber(usage, ['reasoningTokens'])\n const mergedOut =\n out !== undefined || reasoning !== undefined ? (out ?? 0) + (reasoning ?? 0) : undefined\n return buildLlmCall(\n {\n inputTokens: usage.inputTokens,\n outputTokens: mergedOut,\n totalCostUsd: data.totalCostUsd,\n model: data.model ?? usage.model,\n },\n agentRunName,\n )\n }\n return undefined\n}\n\n/**\n * Sum the token usage + USD cost of a sandbox turn's events — the one honest way to meter an\n * `openSandboxRun` cell. Folds `extractLlmCallEvent` over the stream (which reads usage off EVERY backend\n * event shape), so a `runProfileMatrix` dispatch can report it to `ctx.cost`:\n *\n * receipt: (turn) => {\n * const u = sumSandboxUsage(turn.events)\n * return { model, inputTokens: u.input, outputTokens: u.output,\n * ...(u.costUsd > 0 ? { actualCostUsd: u.costUsd } : {}) }\n * }\n *\n * Without this a cell reads `{tokens:0, cost:0}` and the backend-integrity guard correctly aborts the\n * matrix as a stub. `agentRunName` is the fallback model label for cost-only events (default `'agent'`).\n */\nexport function sumSandboxUsage(\n events: readonly SandboxEvent[],\n agentRunName = 'agent',\n): { input: number; output: number; costUsd: number } {\n let input = 0\n let output = 0\n let costUsd = 0\n for (const ev of events) {\n const call = extractLlmCallEvent(ev, agentRunName)\n if (!call) continue\n input += call.tokensIn ?? 0\n output += call.tokensOut ?? 0\n costUsd += call.costUsd ?? 0\n }\n return { input, output, costUsd }\n}\n\nfunction buildLlmCall(\n data: Record<string, unknown>,\n agentRunName: string,\n): (RuntimeStreamEvent & { type: 'llm_call' }) | undefined {\n const tokensIn = pickFiniteNumber(data, ['tokensIn', 'inputTokens', 'prompt_tokens'])\n const tokensOut = pickFiniteNumber(data, ['tokensOut', 'outputTokens', 'completion_tokens'])\n const costUsd = pickFiniteNumber(data, ['costUsd', 'totalCostUsd', 'cost_usd', 'cost'])\n if (tokensIn === undefined && tokensOut === undefined && costUsd === undefined) {\n return undefined\n }\n const model = typeof data.model === 'string' && data.model.length > 0 ? data.model : agentRunName\n const event: RuntimeStreamEvent & { type: 'llm_call' } = {\n type: 'llm_call',\n model,\n }\n if (tokensIn !== undefined) event.tokensIn = tokensIn\n if (tokensOut !== undefined) event.tokensOut = tokensOut\n if (costUsd !== undefined) event.costUsd = costUsd\n return event\n}\n\nfunction pickFiniteNumber(data: Record<string, unknown>, keys: string[]): number | undefined {\n for (const key of keys) {\n const value = data[key]\n if (typeof value === 'number' && Number.isFinite(value)) return value\n }\n return undefined\n}\n\n/**\n * Cross-event state for {@link mapSandboxToolEvent}. Sandbox backends emit a\n * tool invocation as MANY `message.part.updated` frames on the same call id\n * (pending → running → completed), so faithful projection needs per-call\n * status memory: one `tool_call` on first sighting, at most one `tool_result`\n * on the terminal transition, nothing on intermediate re-frames. Create one\n * state per turn via {@link createSandboxToolPartState}.\n *\n * @experimental\n */\nexport interface SandboxToolPartState {\n /** Last seen status per tool call id. A terminal status is sticky — later\n * frames on a settled call project to nothing. */\n statusByCall: Map<string, string>\n /** Sequence for synthesized call ids when an event carries none. */\n seq: number\n}\n\n/**\n * Fresh per-turn {@link SandboxToolPartState} for {@link mapSandboxToolEvent} — an\n * empty call-status map so each turn projects tool frames independently.\n *\n * @experimental\n */\nexport function createSandboxToolPartState(): SandboxToolPartState {\n return { statusByCall: new Map(), seq: 0 }\n}\n\n/** Terminal tool statuses that are failures (everything here settles the call). */\nconst TERMINAL_TOOL_FAILURE =\n /^(error|errored|failed|failure|cancelled|canceled|timeout|timed_out)$/i\n\n/**\n * Project one `SandboxEvent` onto the `tool_call` / `tool_result` variants of\n * `RuntimeStreamEvent` — the tool-part projection `mapSandboxEvent`\n * deliberately does NOT perform. Opt-in and additive: `mapSandboxEvent`'s\n * default vocabulary (text/reasoning deltas + `llm_call`) is unchanged;\n * consumers that need the tool surface (chat UIs rendering tool activity)\n * compose this projector alongside it — `streamAgentTurn` does exactly that\n * under its `preserveToolParts` option.\n *\n * Handled shapes (observed on the opencode / claude-code sandbox backends):\n * - `message.part.updated` with `part.type === 'tool'` — stateful: a\n * `tool_call` on the call id's first frame (args from `state.input` or\n * `state.metadata.input`), a `tool_result` when the status transitions to\n * `completed` (result from `state.output` / `metadata.output`) or to a\n * terminal failure (result is `{ error, status, output? }` — the error\n * surfaced in-band, never dropped).\n * - bare `tool*` event types (`tool.call`, `tool_result`, …) — stateless:\n * `*result*` types project to `tool_result`, the rest to `tool_call`.\n *\n * Returns `[]` for every non-tool event.\n *\n * @experimental\n */\nexport function mapSandboxToolEvent(\n event: SandboxEvent,\n state: SandboxToolPartState,\n): (RuntimeStreamEvent & { type: 'tool_call' | 'tool_result' })[] {\n if (!event || typeof event !== 'object') return []\n const type = String(event.type ?? '')\n const data =\n event.data && typeof event.data === 'object'\n ? (event.data as Record<string, unknown>)\n : ({} as Record<string, unknown>)\n\n if (type === 'message.part.updated') {\n const part =\n data.part && typeof data.part === 'object' ? (data.part as Record<string, unknown>) : {}\n if (String(part.type ?? '') !== 'tool') return []\n return projectToolPart(part, state, typeof event.id === 'string' ? event.id : undefined)\n }\n\n if (type.includes('tool')) {\n const callId =\n pickString(data, ['toolCallId', 'tool_use_id', 'id']) ??\n (typeof event.id === 'string' ? event.id : undefined) ??\n `sandbox-tool-${++state.seq}`\n const toolName = pickString(data, ['name', 'toolName', 'tool']) ?? 'sandbox_tool'\n if (type.includes('result')) {\n return [\n {\n type: 'tool_result',\n toolName,\n toolCallId: callId,\n result: data.output ?? data.result ?? data.content ?? data,\n },\n ]\n }\n return [\n { type: 'tool_call', toolName, toolCallId: callId, args: data.input ?? data.args ?? {} },\n ]\n }\n\n return []\n}\n\nfunction projectToolPart(\n part: Record<string, unknown>,\n state: SandboxToolPartState,\n eventId: string | undefined,\n): (RuntimeStreamEvent & { type: 'tool_call' | 'tool_result' })[] {\n const callId =\n pickString(part, ['callID', 'callId', 'toolCallId', 'id']) ??\n eventId ??\n `sandbox-tool-${++state.seq}`\n const toolName = pickString(part, ['tool', 'toolName', 'name']) ?? 'sandbox_tool'\n const toolState =\n part.state && typeof part.state === 'object' ? (part.state as Record<string, unknown>) : {}\n const metadata =\n toolState.metadata && typeof toolState.metadata === 'object'\n ? (toolState.metadata as Record<string, unknown>)\n : {}\n const status = pickString(toolState, ['status']) ?? 'updated'\n\n const previous = state.statusByCall.get(callId)\n const settled =\n previous === 'completed' || (previous !== undefined && TERMINAL_TOOL_FAILURE.test(previous))\n if (settled) return []\n\n const out: (RuntimeStreamEvent & { type: 'tool_call' | 'tool_result' })[] = []\n if (previous === undefined) {\n out.push({\n type: 'tool_call',\n toolName,\n toolCallId: callId,\n args: toolState.input ?? metadata.input ?? {},\n })\n }\n state.statusByCall.set(callId, status)\n\n if (status === 'completed') {\n out.push({\n type: 'tool_result',\n toolName,\n toolCallId: callId,\n result: toolState.output ?? metadata.output ?? '',\n })\n } else if (TERMINAL_TOOL_FAILURE.test(status)) {\n const message =\n pickString(toolState, ['error', 'message']) ??\n pickString(metadata, ['error', 'message']) ??\n `sandbox tool ended with status ${status}`\n const output = toolState.output ?? metadata.output\n out.push({\n type: 'tool_result',\n toolName,\n toolCallId: callId,\n result: { error: message, status, ...(output !== undefined ? { output } : {}) },\n })\n }\n return out\n}\n\nfunction pickString(data: Record<string, unknown>, keys: string[]): string | undefined {\n for (const key of keys) {\n const value = data[key]\n if (typeof value === 'string' && value.length > 0) return value\n }\n return undefined\n}\n\n/**\n * Project one `SandboxEvent` onto the `RuntimeStreamEvent` chat-UX vocabulary,\n * for runtimes that bridge a sandbox `streamPrompt` into the\n * `AgentRuntime.act` streaming contract. Returns `undefined` for events that\n * have no faithful projection — the raw stream is preserved separately for the\n * `OutputAdapter`, so an unmapped event never loses data.\n *\n * Mapped (the task-optional incremental variants — no synthesized task\n * lifecycle, no guessed tool-part shapes):\n * - `message.part.updated` text part → `text_delta`\n * - `message.part.updated` reasoning/thinking part → `reasoning_delta`\n * - cost-bearing events → `llm_call` (shared with the ledger extractor)\n *\n * Tool parts are deliberately NOT mapped here (unchanged default) — compose\n * {@link mapSandboxToolEvent} alongside when a consumer needs them.\n *\n * The opencode backend emits incremental text as\n * `{ type: 'message.part.updated', data: { part: { type, text }, delta } }`;\n * `delta` is the increment, `part.text` the running accumulation.\n */\nexport function mapSandboxEvent(\n event: SandboxEvent,\n opts: { agentRunName?: string } = {},\n): RuntimeStreamEvent | undefined {\n if (!event || typeof event !== 'object') return undefined\n const type = String(event.type ?? '')\n const data =\n event.data && typeof event.data === 'object'\n ? (event.data as Record<string, unknown>)\n : ({} as Record<string, unknown>)\n\n if (type === 'message.part.updated') {\n const part =\n data.part && typeof data.part === 'object' ? (data.part as Record<string, unknown>) : {}\n const partType = String(part.type ?? '')\n const delta = typeof data.delta === 'string' ? data.delta : undefined\n const text = delta ?? (typeof part.text === 'string' ? part.text : undefined)\n if (text === undefined) return undefined\n if (partType === 'text') return { type: 'text_delta', text }\n if (partType === 'reasoning' || partType === 'thinking')\n return { type: 'reasoning_delta', text }\n return undefined\n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MAAI,SAAS,wBAAwB;AACnC,UAAM,OACJ,KAAK,QAAQ,OAAO,KAAK,SAAS,WAAY,KAAK,OAAmC,CAAC;AACzF,UAAM,WAAW,OAAO,KAAK,QAAQ,EAAE;AACvC,UAAM,QAAQ,OAAO,KAAK,UAAU,WAAW,KAAK,QAAQ;AAC5D,UAAM,OAAO,UAAU,OAAO,KAAK,SAAS,WAAW,KAAK,OAAO;AACnE,QAAI,SAAS,OAAW,QAAO;AAC/B,QAAI,aAAa,OAAQ,QAAO,EAAE,MAAM,cAAc,KAAK;AAC3D,QAAI,aAAa,eAAe,aAAa;AAC3C,aAAO,EAAE,MAAM,mBAAmB,KAAK;AACzC,WAAO;AAAA,EACT;AAEA,SAAO,oBAAoB,OAAO,KAAK,gBAAgB,OAAO;AAChE;","names":[]}
@@ -8,7 +8,7 @@ import {
8
8
  DELEGATION_STATUS_DESCRIPTION,
9
9
  DELEGATION_STATUS_INPUT_SCHEMA,
10
10
  DELEGATION_STATUS_TOOL_NAME
11
- } from "./chunk-LWNMCOEA.js";
11
+ } from "./chunk-FRXDOBFP.js";
12
12
 
13
13
  // src/mcp/openai-tools.ts
14
14
  function buildTool(name, description, parameters) {
@@ -45,4 +45,4 @@ export {
45
45
  mcpToolsForRuntimeMcp,
46
46
  mcpToolsForRuntimeMcpSubset
47
47
  };
48
- //# sourceMappingURL=chunk-4VMRCEI6.js.map
48
+ //# sourceMappingURL=chunk-MSUWXCHD.js.map
@@ -1,6 +1,6 @@
1
1
  import {
2
2
  extractLlmCallEvent
3
- } from "./chunk-FVJ7M3DA.js";
3
+ } from "./chunk-M22PL4GH.js";
4
4
  import {
5
5
  AnalystError
6
6
  } from "./chunk-YEJR7IXO.js";
@@ -579,4 +579,4 @@ export {
579
579
  iterationsToTraceStore,
580
580
  runAnalystLoop
581
581
  };
582
- //# sourceMappingURL=chunk-ZQZX77MM.js.map
582
+ //# sourceMappingURL=chunk-QDSOD7RC.js.map
@@ -3,7 +3,7 @@ import {
3
3
  } from "./chunk-5QOB7H74.js";
4
4
  import {
5
5
  supervise
6
- } from "./chunk-LWNMCOEA.js";
6
+ } from "./chunk-FRXDOBFP.js";
7
7
 
8
8
  // src/knowledge/improvement-job.ts
9
9
  import {
@@ -211,4 +211,4 @@ export {
211
211
  createAgentKnowledgeReadinessCheck,
212
212
  runKnowledgeImprovementJob
213
213
  };
214
- //# sourceMappingURL=chunk-RNWDH5Z3.js.map
214
+ //# sourceMappingURL=chunk-TNUBPPZA.js.map
@@ -1,5 +1,5 @@
1
- import { L as LocalHarness, C as CodexTokenUsage, a as CodexExecutionPolicy } from './local-harness-CePtFrwu.js';
2
- import { c as Executor } from './types-DHLXdLVN.js';
1
+ import { L as LocalHarness, C as CodexTokenUsage, b as CodexExecutionPolicy } from './local-harness-ZLMkKdZc.js';
2
+ import { c as Executor } from './types-CogNCaw7.js';
3
3
 
4
4
  /**
5
5
  *
@@ -1,12 +1,12 @@
1
- import { E as ExecutorFactory, e as ExecutorRegistry, i as Spend, A as Agent, S as Scope, a as ResultBlobStore, B as Budget } from './types-DHLXdLVN.js';
1
+ import { E as ExecutorFactory, e as ExecutorRegistry, i as Spend, A as Agent, S as Scope, a as ResultBlobStore, B as Budget } from './types-CogNCaw7.js';
2
2
  import { AgentProfile } from '@tangle-network/agent-interface';
3
3
  import { U as UiLens, a as UiFinding, C as CoderTask } from './substrate-DO2GHNg2.js';
4
- import { S as SandboxClient, E as ExecCtx, g as LoopTraceEmitter, e as LoopTraceEvent, a as RuntimeStreamEvent, d as AgentRunSpec } from './types-Kjr5W6OF.js';
4
+ import { S as SandboxClient, E as ExecCtx, g as LoopTraceEmitter, e as LoopTraceEvent, a as RuntimeStreamEvent, d as AgentRunSpec } from './types-CKmyZ9TP.js';
5
5
  import { BackendType, SandboxEvent, SandboxInstance } from '@tangle-network/sandbox';
6
6
  import { AgentEvalError } from '@tangle-network/agent-eval';
7
- import { b as ToolSpec, c as RuntimeTelemetryOptions, R as RouterConfig } from './sanitize-Dr3SliRC.js';
8
- import { G as GitRunner, a as WorktreeCheckRunner, D as DeliverableSpec } from './completion-gate-CfX2thvL.js';
9
- import { L as LocalHarness } from './local-harness-CePtFrwu.js';
7
+ import { b as ToolSpec, c as RuntimeTelemetryOptions, R as RouterConfig } from './sanitize-Dcbjp0tU.js';
8
+ import { G as GitRunner, a as WorktreeCheckRunner, D as DeliverableSpec } from './completion-gate-tzwyyD-E.js';
9
+ import { L as LocalHarness } from './local-harness-ZLMkKdZc.js';
10
10
  import { ProviderExecutorOptions, AgentEnvironmentProviderRegistry } from './environment-provider.js';
11
11
  import { AgentEnvironmentProvider } from '@tangle-network/agent-interface/environment-provider';
12
12
 
@@ -2,8 +2,8 @@ import { AgentProfile, AgentProfileValidationResult } from '@tangle-network/agen
2
2
  import { CreateAgentEnvironmentInput, AgentTurnInput, AgentEnvironmentProvider, AgentEnvironmentCapabilities, AgentProfileRef } from '@tangle-network/agent-interface/environment-provider';
3
3
  export { AgentEnvironment, AgentEnvironmentCapabilities, AgentEnvironmentEvent, AgentEnvironmentProvider, AgentEnvironmentQuery, AgentEnvironmentStatus, AgentEnvironmentSummary, AgentProfileRef, AgentSession, AgentSessionRef, AgentSessionStatus, AgentTurnInput, AgentTurnResult, CheckpointRef, CheckpointRequest, CreateAgentEnvironmentInput, ExecRequest, ExecResult, ForkRequest, PlacementInfo, ResourceRequest, WorkspaceRequest } from '@tangle-network/agent-interface/environment-provider';
4
4
  import { CreateSandboxOptions, BackendType } from '@tangle-network/sandbox';
5
- import { R as Runtime, E as ExecutorFactory } from './types-DHLXdLVN.js';
6
- import { S as SandboxClient } from './types-Kjr5W6OF.js';
5
+ import { R as Runtime, E as ExecutorFactory } from './types-CogNCaw7.js';
6
+ import { S as SandboxClient } from './types-CKmyZ9TP.js';
7
7
  import '@tangle-network/agent-eval';
8
8
 
9
9
  /** Provider object or registry name accepted by runtime provider adapters.
@@ -1,7 +1,8 @@
1
+ import { WorktreeAdapter } from '@tangle-network/agent-eval/campaign';
1
2
  import { Scenario, SelfImproveOptions, SurfaceProposer, SelfImproveResult, MutableSurface } from '@tangle-network/agent-eval/contract';
2
3
  import { AgentProfile } from '@tangle-network/agent-interface';
3
- import { L as LocalHarness } from './local-harness-CePtFrwu.js';
4
- import { V as Verifier, C as CandidateGenerator } from './agentic-generator-CL1q0H91.js';
4
+ import { L as LocalHarness } from './local-harness-ZLMkKdZc.js';
5
+ import { V as Verifier, C as CandidateGenerator } from './agentic-generator-1g7GDba7.js';
5
6
 
6
7
  /**
7
8
  *
@@ -21,13 +22,14 @@ import { V as Verifier, C as CandidateGenerator } from './agentic-generator-CL1q
21
22
  * lesson document supplied through `opts.memory`.
22
23
  * - `surface: 'agent-profile'` → caller-supplied proposer mutates the complete
23
24
  * canonical AgentProfile JSON in one candidate.
24
- * - `surface` ∈ {`tools`, `mcp`, `hooks`, `subagents`, `agent-profile`, `code`} → no zero-config default
25
+ * - `surface` ∈ {`tools`, `mcp`, `hooks`, `subagents`, `agent-profile`} → no zero-config default
25
26
  * proposer exists (a code/config proposer needs caller-supplied wiring — a
26
27
  * worktree repo root, a candidate generator, a serializer). The facade
27
28
  * requires an explicit `opts.generator` for these and throws a `ConfigError`
28
29
  * otherwise. This is a designed boundary, not a missing default: there is
29
- * no safe value the facade could invent for those surfaces. Code also
30
- * requires `opts.code.repoRoot` so its incumbent is a real isolated checkout.
30
+ * no safe value the facade could invent for those surfaces. Code instead
31
+ * requires `opts.code.repoRoot` and accepts only the runtime-owned
32
+ * `opts.code.generator` path so every isolated checkout can be released.
31
33
  *
32
34
  * Everything else (`scenarios`, `judge`, `agent`, `budget`, `llm`) passes
33
35
  * straight through to `selfImprove`.
@@ -43,9 +45,10 @@ type ImproveOptions<TScenario extends Scenario, TArtifact> = Omit<SelfImproveOpt
43
45
  /** Which profile lever to optimize. Default `'prompt'`. Selects the default
44
46
  * generator + the baseline-surface extraction shape. */
45
47
  surface?: ImproveSurface;
46
- /** The `SurfaceProposer` that mutates the surface. When unset, the facade
48
+ /** The `SurfaceProposer` that mutates a profile surface. When unset, the facade
47
49
  * picks the default for prompt, skills, and memory; surfaces
48
- * with no default REQUIRE this (fail-loud otherwise). */
50
+ * with no default REQUIRE this (fail-loud otherwise). Forbidden for code;
51
+ * use `code.generator` so the runtime owns candidate cleanup. */
49
52
  generator?: SurfaceProposer;
50
53
  /** Gate mode. `'holdout'` (default) runs the held-out promotion gate;
51
54
  * `'none'` is a baseline-only run (`budget.generations = 0`). */
@@ -116,6 +119,9 @@ interface ImproveCodeOptions {
116
119
  baseRef?: string;
117
120
  /** Directory worktrees are created under. Default `<repoRoot>/.worktrees`. */
118
121
  worktreeDir?: string;
122
+ /** Git-compatible adapter override, primarily for tests. Candidate advancement
123
+ * still requires normal Git worktree and commit semantics. */
124
+ worktree?: WorktreeAdapter;
119
125
  /** Coding harness the agentic generator runs in each worktree. Default `claude`. */
120
126
  harness?: LocalHarness;
121
127
  /** Verify a candidate worktree before it becomes a measurable surface; failures
@@ -137,8 +143,13 @@ interface ImproveResult<TScenario extends Scenario, TArtifact> {
137
143
  lift: number;
138
144
  /** The five-valued gate verdict from `selfImprove`. */
139
145
  gateDecision: SelfImproveResult<TScenario, TArtifact>['gateDecision'];
140
- /** Full `selfImprove` result for advanced inspection. */
146
+ /** Full `selfImprove` result for advanced inspection. For code runs,
147
+ * `raw.winner.surface.worktreeRef` remains live after return whether the
148
+ * candidate shipped or held; call `dispose()` after consuming it. */
141
149
  raw: SelfImproveResult<TScenario, TArtifact>;
150
+ /** Release resources owned by this result. Idempotent; currently disposes
151
+ * the returned code worktree and is a no-op for profile-only surfaces. */
152
+ dispose(): Promise<void>;
142
153
  }
143
154
  /** Apply a promoted winner surface back into the profile field for `surface`.
144
155
  * Returns a shallow copy; never mutates the input profile. */
package/dist/index.d.ts CHANGED
@@ -1,33 +1,33 @@
1
- import { AgentProfile, AgentEvalError, AnalystFinding, KnowledgeReadinessReport, RunRecord, ControlEvalResult } from '@tangle-network/agent-eval';
1
+ import { AgentProfile, MaximumCharge, AgentEvalError, AnalystFinding, KnowledgeReadinessReport, RunRecord, ControlEvalResult } from '@tangle-network/agent-eval';
2
2
  export { AgentEvalError, AgentEvalErrorCode, ConfigError, ControlBudget, ControlDecision, ControlEvalResult, ControlRunResult, ControlStep, DataAcquisitionPlan, JudgeError, KnowledgeReadinessReport, KnowledgeRequirement, NotFoundError, RunRecord, ValidationError } from '@tangle-network/agent-eval';
3
- import { h as AgentBackendInput, O as OpenAIChatTool, i as OpenAIChatToolChoice, j as OpenAIChatResponseFormat, k as AgentExecutionBackend, l as AgentBackendContext, a as RuntimeStreamEvent, K as KnowledgeReadinessDecision, m as RunAgentTaskOptions, n as AgentTaskRunResult, o as RunAgentTaskStreamOptions, p as RuntimeSessionStore, q as RuntimeSession, R as RuntimeHooks } from './types-Kjr5W6OF.js';
4
- export { r as AgentAdapter, s as AgentKnowledgeProvider, A as AgentRuntimeEvent, t as AgentRuntimeEventSink, u as AgentTaskContext, v as AgentTaskSpec, b as AgentTaskStatus, B as BackendErrorDetail, w as RuntimeDecisionEvidenceRef, x as RuntimeDecisionKind, y as RuntimeDecisionPoint, z as RuntimeHookContext, C as RuntimeHookErrorContext, F as RuntimeHookEvent, G as RuntimeHookPhase, H as RuntimeHookTarget, J as RuntimeRunHandle, M as RuntimeRunPersistenceAdapter, N as RuntimeRunRow, P as composeRuntimeHooks, Q as defineRuntimeHooks, T as notifyRuntimeDecisionPoint, U as notifyRuntimeHookEvent, W as startRuntimeRun } from './types-Kjr5W6OF.js';
3
+ import { h as AgentBackendInput, O as OpenAIChatTool, i as OpenAIChatToolChoice, j as OpenAIChatResponseFormat, k as AgentExecutionBackend, l as AgentBackendContext, a as RuntimeStreamEvent, K as KnowledgeReadinessDecision, m as RunAgentTaskOptions, n as AgentTaskRunResult, o as RunAgentTaskStreamOptions, p as RuntimeSessionStore, q as RuntimeSession, R as RuntimeHooks } from './types-CKmyZ9TP.js';
4
+ export { r as AgentAdapter, s as AgentKnowledgeProvider, A as AgentRuntimeEvent, t as AgentRuntimeEventSink, u as AgentTaskContext, v as AgentTaskSpec, b as AgentTaskStatus, B as BackendErrorDetail, w as RuntimeDecisionEvidenceRef, x as RuntimeDecisionKind, y as RuntimeDecisionPoint, z as RuntimeHookContext, C as RuntimeHookErrorContext, F as RuntimeHookEvent, G as RuntimeHookPhase, H as RuntimeHookTarget, J as RuntimeRunHandle, M as RuntimeRunPersistenceAdapter, N as RuntimeRunRow, P as composeRuntimeHooks, Q as defineRuntimeHooks, T as notifyRuntimeDecisionPoint, U as notifyRuntimeHookEvent, W as startRuntimeRun } from './types-CKmyZ9TP.js';
5
5
  export { AgentCandidateCodeSource, AgentCandidateCodeSurfaceSource, AgentCandidateModelGrantActivateInput, AgentCandidateModelGrantClient, AgentCandidateModelGrantReservation, AgentCandidateModelGrantReserveInput, AgentCandidateModelGrantSettleInput, AgentCandidateProfileSource, AgentCandidateWorkspaceArchiveLimits, BuildAgentCandidateBundleInput, CaptureAgentCandidateWorkspaceOptions, CapturedAgentCandidateWorkspace, CreateAgentCandidateWorkspacePortOptions, CreateProtectedAgentCandidateModelPortOptions, DisposePreparedAgentCandidateOptions, FileAgentCandidateExecutionClaimStore, FileAgentCandidateExecutionClaimStoreOptions, RecoverExpiredAgentCandidateOptions, applyExactAgentProfileDiff, buildAgentCandidateBundle, candidateExecutionClaim, captureAgentCandidateWorkspace, captureAgentCandidateWorkspaceFiles, createAgentCandidateWorkspacePort, createProtectedAgentCandidateModelPort, disposePreparedAgentCandidateExecution, parseExactAgentProfile, parseExactAgentProfileDiff, persistCandidateOutputArtifact, recoverExpiredAgentCandidateExecution, verifyAgentCandidateBundle } from './candidate-execution/index.js';
6
6
  export { d as AgentCandidateArtifactPort, e as AgentCandidateBenchmarkGraderIdentity, f as AgentCandidateBenchmarkGraderPort, A as AgentCandidateBundleInput, g as AgentCandidateContainerPort, h as AgentCandidateExecutionAttemptRecord, i as AgentCandidateExecutionAttemptRef, j as AgentCandidateExecutionClaim, k as AgentCandidateExecutionClaimResult, l as AgentCandidateExecutionClaimStore, m as AgentCandidateExecutionCleanupHandles, n as AgentCandidateExecutionFailureClass, o as AgentCandidateExecutionFinishResult, p as AgentCandidateExecutionLease, q as AgentCandidateExecutionPhase, r as AgentCandidateExecutionPhaseResult, b as AgentCandidateExecutionPorts, s as AgentCandidateExecutionRecoveryEvidence, t as AgentCandidateExecutionStageResult, u as AgentCandidateExecutionTerminalRecord, v as AgentCandidateExecutionTerminalResult, w as AgentCandidateExecutionUsage, x as AgentCandidateExecutorFinalCapture, y as AgentCandidateExecutorMemoryCapture, z as AgentCandidateExecutorPort, B as AgentCandidateExecutorProfileFile, C as AgentCandidateExecutorRequest, D as AgentCandidateExecutorStopRequest, F as AgentCandidateExecutorTaskOutcomeCapture, G as AgentCandidateExecutorWorkspaceFile, H as AgentCandidateExecutorWorkspaceInput, I as AgentCandidateMemoryPort, J as AgentCandidateMemoryResetResult, K as AgentCandidateModelLimits, L as AgentCandidateModelPort, M as AgentCandidateOutputArtifactPort, N as AgentCandidateOutputPurpose, O as AgentCandidateProtectedModelActivation, Q as AgentCandidateProtectedModelCall, R as AgentCandidateProtectedModelReservation, S as AgentCandidateProtectedModelSettlement, T as AgentCandidateProtectedRunCapture, U as AgentCandidateRepositoryPort, V as AgentCandidateRetryRejection, c as AgentCandidateRunFinalization, a as AgentCandidateTaskExecution, W as AgentCandidateVerificationPorts, X as AgentCandidateWorkspacePort, Y as CANDIDATE_TRACE_ENV, Z as CANDIDATE_TRACE_TAGS, _ as CanonicalCandidateDocument, E as ExecutePreparedAgentCandidateOptions, $ as InMemoryAgentCandidateExecutionClaimStore, P as PrepareAgentCandidateExecutionOptions, a0 as PreparedAgentCandidateExecution, a1 as PreparedAgentCandidateInstruction, a2 as PreparedAgentCandidateLaunch, a3 as PreparedAgentCandidateTrace, a4 as ResolvedAgentCandidateContainer, a5 as VerifiedAgentCandidate, a6 as VerifiedAgentCandidateTaskOutcome, a7 as executePreparedAgentCandidate, a8 as prepareAgentCandidateExecution, a9 as sealAgentCandidateBundle } from './prepare-DIeVgQG3.js';
7
7
  import { Scenario, ProfileDispatchFn, ProposeContext, SurfaceProposer } from '@tangle-network/agent-eval/campaign';
8
- import { C as CandidateGenerator } from './agentic-generator-CL1q0H91.js';
9
- export { A as AgenticGeneratorOptions, I as ImprovementDriverOptions, M as ManagedImprovementDriver, V as Verifier, a as VerifyResult, b as agenticGenerator, c as commandVerifier, i as improvementDriver } from './agentic-generator-CL1q0H91.js';
10
- export { c as ImproveCodeOptions, d as ImproveMemoryOptions, a as ImproveOptions, b as ImproveResult, e as ImproveSkillsOptions, I as ImproveSurface, f as applyImprovementWinnerToProfile, i as improve } from './improve-Ciuvu2jh.js';
11
- export { M as McpServeSpec, m as mcpServeVerifier } from './mcp-serve-verifier-D7hCZIkT.js';
8
+ import { C as CandidateGenerator } from './agentic-generator-1g7GDba7.js';
9
+ export { A as AGENTIC_PROFILE_RESOURCE_ROOT, a as AgenticGeneratorOptions, b as AgenticGeneratorShotReceipt, I as ImprovementDriverOptions, M as ManagedImprovementDriver, V as Verifier, c as VerifyResult, d as agenticGenerator, e as commandVerifier, i as improvementDriver } from './agentic-generator-1g7GDba7.js';
10
+ export { c as ImproveCodeOptions, d as ImproveMemoryOptions, a as ImproveOptions, b as ImproveResult, e as ImproveSkillsOptions, I as ImproveSurface, f as applyImprovementWinnerToProfile, i as improve } from './improve-DZeatcs7.js';
11
+ export { M as McpServeSpec, m as mcpServeVerifier } from './mcp-serve-verifier-BO4MEsR3.js';
12
12
  import { AgentProfileDiff, AgentProfile as AgentProfile$1 } from '@tangle-network/agent-interface';
13
13
  import { Scenario as Scenario$1, SelfImproveOptions } from '@tangle-network/agent-eval/contract';
14
14
  import { S as SurfaceImprovementEdit } from './improvement-adapter-BieWeK5J.js';
15
15
  import { I as ImprovementAdapter } from './types-BC3bZpH0.js';
16
16
  export { AgentKnowledgeReadinessCheckOptions, KnowledgeImprovementJobMeasurement, KnowledgeImprovementJobResult, KnowledgeReadinessCheck, KnowledgeReadinessCheckInput, KnowledgeReadinessCheckResult, RESEARCH_SUPERVISOR_SYSTEM_PROMPT, RunKnowledgeImprovementJobOptions, SupervisedKnowledgeUpdateInput, SupervisedKnowledgeUpdateOptions, SupervisedKnowledgeUpdateResult, SupervisedKnowledgeUpdater, createAgentKnowledgeReadinessCheck, createSupervisedKnowledgeUpdater, formatSupervisedKnowledgeTask, knowledgeReadinessDeliverable, runKnowledgeImprovementJob, runSupervisedKnowledgeUpdate } from './knowledge.js';
17
- export { D as DELEGATED_LOOP_MODES, a as DelegatedLoopMode, b as DelegatedLoopRegistry, c as DelegatedLoopResult, d as DelegatedLoopRunner, L as LoopRunnerCliArgs, e as LoopRunnerCliResult, R as ResearchLoopResult, f as ResearchLoopRunnerOptions, g as RunDelegatedLoopOptions, V as VetoedFact, W as WorktreeLoopRunnerOptions, h as auditLoopRunner, i as isDelegatedLoopMode, p as parseLoopRunnerArgv, r as researchLoopRunner, j as runDelegatedLoop, k as runLoopRunnerCli, s as selfImproveLoopRunner, w as worktreeLoopRunner } from './loop-runner-bin-B4PwjVaF.js';
18
- export { m as mcpToolsForRuntimeMcp, a as mcpToolsForRuntimeMcpSubset } from './openai-tools-BMOu1t3A.js';
19
- export { b0 as EvalRunEvent, b1 as EvalRunGeneration, b2 as EvalRunsExportConfig, b3 as EvalRunsExportResult, b4 as INTELLIGENCE_WIRE_VERSION, b5 as LoopSpanNode, b6 as OtelAttribute, b7 as OtelExportConfig, b8 as OtelExporter, b9 as OtelSpan, ba as RuntimeEventOtelOptions, bb as buildLoopOtelSpans, bc as buildLoopSpanNodes, bd as buildRuntimeEventOtelSpans, be as createOtelExporter, bf as exportEvalRuns, bg as loopEventToOtelSpan } from './coordination-pOGZuYS7.js';
20
- import { c as RuntimeTelemetryOptions } from './sanitize-Dr3SliRC.js';
21
- export { d as RuntimeEventCollector, e as RuntimeStreamEventCollector, S as SanitizedKnowledgeReadinessReport, f as createRuntimeEventCollector, g as createRuntimeStreamEventCollector, s as sanitizeAgentRuntimeEvent, h as sanitizeKnowledgeReadinessReport, i as sanitizeRuntimeStreamEvent } from './sanitize-Dr3SliRC.js';
17
+ export { D as DELEGATED_LOOP_MODES, a as DelegatedLoopMode, b as DelegatedLoopRegistry, c as DelegatedLoopResult, d as DelegatedLoopRunner, L as LoopRunnerCliArgs, e as LoopRunnerCliResult, R as ResearchLoopResult, f as ResearchLoopRunnerOptions, g as RunDelegatedLoopOptions, V as VetoedFact, W as WorktreeLoopRunnerOptions, h as auditLoopRunner, i as isDelegatedLoopMode, p as parseLoopRunnerArgv, r as researchLoopRunner, j as runDelegatedLoop, k as runLoopRunnerCli, s as selfImproveLoopRunner, w as worktreeLoopRunner } from './loop-runner-bin-iTSxSmpv.js';
18
+ export { m as mcpToolsForRuntimeMcp, a as mcpToolsForRuntimeMcpSubset } from './openai-tools-0wACz8f8.js';
19
+ export { b0 as EvalRunEvent, b1 as EvalRunGeneration, b2 as EvalRunsExportConfig, b3 as EvalRunsExportResult, b4 as INTELLIGENCE_WIRE_VERSION, b5 as LoopSpanNode, b6 as OtelAttribute, b7 as OtelExportConfig, b8 as OtelExporter, b9 as OtelSpan, ba as RuntimeEventOtelOptions, bb as buildLoopOtelSpans, bc as buildLoopSpanNodes, bd as buildRuntimeEventOtelSpans, be as createOtelExporter, bf as exportEvalRuns, bg as loopEventToOtelSpan } from './coordination-o0TzS7Ms.js';
20
+ import { c as RuntimeTelemetryOptions } from './sanitize-Dcbjp0tU.js';
21
+ export { d as RuntimeEventCollector, e as RuntimeStreamEventCollector, S as SanitizedKnowledgeReadinessReport, f as createRuntimeEventCollector, g as createRuntimeStreamEventCollector, s as sanitizeAgentRuntimeEvent, h as sanitizeKnowledgeReadinessReport, i as sanitizeRuntimeStreamEvent } from './sanitize-Dcbjp0tU.js';
22
22
  import '@tangle-network/sandbox';
23
- import './local-harness-CePtFrwu.js';
23
+ import './local-harness-ZLMkKdZc.js';
24
24
  import 'node:child_process';
25
25
  import '@tangle-network/agent-knowledge';
26
- import './supervise-Y3w878fN.js';
27
- import './types-DHLXdLVN.js';
28
- import './completion-gate-CfX2thvL.js';
26
+ import './supervise-CRwaJIkd.js';
27
+ import './types-CogNCaw7.js';
28
+ import './completion-gate-tzwyyD-E.js';
29
29
  import './kb-gate-CwHO0vz6.js';
30
- import './worktree-fanout-DmBvR-_O.js';
30
+ import './worktree-fanout-BJy24LYe.js';
31
31
  import './substrate-DO2GHNg2.js';
32
32
  import './environment-provider.js';
33
33
  import '@tangle-network/agent-interface/environment-provider';
@@ -917,6 +917,9 @@ interface RunPersonaConfig<TScenario extends Scenario, TArtifact> {
917
917
  maxTurns?: (scenario: TScenario) => number;
918
918
  seed?: (scenario: TScenario) => string;
919
919
  workerName?: string;
920
+ /** Provider- or executor-enforced maximum for the whole worker conversation.
921
+ * Required before execution when the enclosing campaign is cost-capped. */
922
+ maximumCharge?: MaximumCharge | ((worker: AgentProfile, scenario: TScenario) => MaximumCharge | undefined);
920
923
  }
921
924
  /**
922
925
  * Wrap {@link runPersonaConversation} as a `ProfileDispatchFn` for
package/dist/index.js CHANGED
@@ -11,7 +11,7 @@ import {
11
11
  import {
12
12
  mcpToolsForRuntimeMcp,
13
13
  mcpToolsForRuntimeMcpSubset
14
- } from "./chunk-4VMRCEI6.js";
14
+ } from "./chunk-MSUWXCHD.js";
15
15
  import {
16
16
  DEFAULT_ROUTER_BASE_URL,
17
17
  cleanModelId,
@@ -30,14 +30,14 @@ import {
30
30
  runLoopRunnerCli,
31
31
  selfImproveLoopRunner,
32
32
  worktreeLoopRunner
33
- } from "./chunk-63TIZHMI.js";
33
+ } from "./chunk-KYPVUEJ4.js";
34
34
  import "./chunk-SGKPNBXE.js";
35
35
  import {
36
36
  applyImprovementWinnerToProfile,
37
37
  improve,
38
38
  improvementDriver,
39
39
  rawTraceDistiller
40
- } from "./chunk-JMT5VYY3.js";
40
+ } from "./chunk-7NCP74SL.js";
41
41
  import {
42
42
  CANDIDATE_TRACE_ENV,
43
43
  CANDIDATE_TRACE_TAGS,
@@ -62,17 +62,18 @@ import {
62
62
  normalizeBackendStreamEvent,
63
63
  nowIso,
64
64
  touchSession
65
- } from "./chunk-GKZ6DFDN.js";
66
- import "./chunk-ZQZX77MM.js";
65
+ } from "./chunk-7HH22XN4.js";
66
+ import "./chunk-QDSOD7RC.js";
67
67
  import {
68
68
  mcpBuildPrompt,
69
69
  mcpServeVerifier,
70
70
  toolBuildPrompt
71
71
  } from "./chunk-6O73TRHW.js";
72
72
  import {
73
+ AGENTIC_PROFILE_RESOURCE_ROOT,
73
74
  agenticGenerator,
74
75
  commandVerifier
75
- } from "./chunk-4WWSICFY.js";
76
+ } from "./chunk-GHXW56PO.js";
76
77
  import {
77
78
  RESEARCH_SUPERVISOR_SYSTEM_PROMPT,
78
79
  createAgentKnowledgeReadinessCheck,
@@ -81,14 +82,14 @@ import {
81
82
  knowledgeReadinessDeliverable,
82
83
  runKnowledgeImprovementJob,
83
84
  runSupervisedKnowledgeUpdate
84
- } from "./chunk-RNWDH5Z3.js";
85
+ } from "./chunk-TNUBPPZA.js";
85
86
  import "./chunk-5QOB7H74.js";
86
87
  import {
87
88
  composeRuntimeHooks,
88
89
  defineRuntimeHooks,
89
90
  notifyRuntimeDecisionPoint,
90
91
  notifyRuntimeHookEvent
91
- } from "./chunk-LWNMCOEA.js";
92
+ } from "./chunk-FRXDOBFP.js";
92
93
  import "./chunk-DPEUKJRO.js";
93
94
  import {
94
95
  INTELLIGENCE_WIRE_VERSION,
@@ -107,8 +108,8 @@ import {
107
108
  import "./chunk-WIPGQ4GT.js";
108
109
  import "./chunk-VSWBYWFK.js";
109
110
  import "./chunk-3MDZX7YU.js";
110
- import "./chunk-FVJ7M3DA.js";
111
- import "./chunk-WQA5Y6PD.js";
111
+ import "./chunk-M22PL4GH.js";
112
+ import "./chunk-EP6RVHMX.js";
112
113
  import {
113
114
  AgentEvalError,
114
115
  BackendTransportError,
@@ -1219,18 +1220,33 @@ async function runPersonaConversation(opts) {
1219
1220
  }
1220
1221
  function runPersonaDispatch(config) {
1221
1222
  return async (worker, scenario, ctx) => {
1222
- const result = await runPersonaConversation({
1223
- worker,
1224
- persona: config.personaOf(scenario),
1225
- backendFor: config.backendFor,
1226
- systemPromptOf: config.systemPromptOf,
1227
- maxTurns: config.maxTurns?.(scenario),
1228
- seed: config.seed?.(scenario),
1223
+ const model = worker.model?.default ?? "unknown";
1224
+ const maximumCharge = typeof config.maximumCharge === "function" ? config.maximumCharge(worker, scenario) : config.maximumCharge;
1225
+ const paid = await ctx.cost.runPaidCall({
1226
+ channel: "agent",
1227
+ actor: "persona-conversation",
1228
+ model,
1229
1229
  signal: ctx.signal,
1230
- workerName: config.workerName
1230
+ ...maximumCharge ? { maximumCharge } : {},
1231
+ execute: (executionSignal) => runPersonaConversation({
1232
+ worker,
1233
+ persona: config.personaOf(scenario),
1234
+ backendFor: config.backendFor,
1235
+ systemPromptOf: config.systemPromptOf,
1236
+ maxTurns: config.maxTurns?.(scenario),
1237
+ seed: config.seed?.(scenario),
1238
+ signal: executionSignal,
1239
+ workerName: config.workerName
1240
+ }),
1241
+ receipt: (result2) => ({
1242
+ model,
1243
+ inputTokens: result2.tokensIn,
1244
+ outputTokens: result2.tokensOut,
1245
+ ...result2.costUsd > 0 ? { actualCostUsd: result2.costUsd } : {}
1246
+ })
1231
1247
  });
1232
- ctx.cost.observe(result.costUsd, "persona-conversation");
1233
- ctx.cost.observeTokens({ input: result.tokensIn, output: result.tokensOut });
1248
+ if (!paid.succeeded) throw paid.error;
1249
+ const result = paid.value;
1234
1250
  return config.artifactOf(result.transcript, scenario);
1235
1251
  };
1236
1252
  }
@@ -2478,6 +2494,7 @@ function randomSuffix2(len = 8) {
2478
2494
  return Math.random().toString(36).slice(2, 2 + len);
2479
2495
  }
2480
2496
  export {
2497
+ AGENTIC_PROFILE_RESOURCE_ROOT,
2481
2498
  AgentEvalError,
2482
2499
  BackendTransportError,
2483
2500
  CANDIDATE_TRACE_ENV,