@tangle-network/agent-runtime 10.0.6 → 10.0.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.
- package/CHANGELOG.md +13 -0
- package/dist/{activation-CT-rr2-5.d.ts → activation-Gi19oho7.d.ts} +2 -2
- package/dist/{activation-B3qLMoog.js → activation-pRO-xNlo.js} +2 -2
- package/dist/{activation-B3qLMoog.js.map → activation-pRO-xNlo.js.map} +1 -1
- package/dist/agent.d.ts +1 -1
- package/dist/agent.js +2 -2
- package/dist/{delegate-BFP1uCNY.js → delegate-ChsxEeFK.js} +2 -2
- package/dist/{delegate-BFP1uCNY.js.map → delegate-ChsxEeFK.js.map} +1 -1
- package/dist/{driver-control-acknowledgers-jdlf49OQ.js → driver-control-acknowledgers-DL-lN2Pb.js} +2 -2
- package/dist/{driver-control-acknowledgers-jdlf49OQ.js.map → driver-control-acknowledgers-DL-lN2Pb.js.map} +1 -1
- package/dist/durable.d.ts +1 -1
- package/dist/durable.js +4 -4
- package/dist/{graph-CiApRth2.js → graph-CKdDENlv.js} +4 -4
- package/dist/{graph-CiApRth2.js.map → graph-CKdDENlv.js.map} +1 -1
- package/dist/{improve-LJaiGxdI.js → improve-DNOZVLb-.js} +5 -5
- package/dist/{improve-LJaiGxdI.js.map → improve-DNOZVLb-.js.map} +1 -1
- package/dist/index.d.ts +3 -3
- package/dist/index.js +8 -8
- package/dist/intelligence.d.ts +2 -2
- package/dist/intelligence.js +3 -3
- package/dist/kernel.d.ts +1 -1
- package/dist/kernel.js +10 -10
- package/dist/{loop-runner-D6egvap-.d.ts → loop-runner-CPxQyiWQ.d.ts} +2 -2
- package/dist/{loop-runner-Dgow637w.js → loop-runner-DmDW9BKB.js} +2 -2
- package/dist/{loop-runner-Dgow637w.js.map → loop-runner-DmDW9BKB.js.map} +1 -1
- package/dist/loop-runner-bin.d.ts +1 -1
- package/dist/loop-runner-bin.js +1 -1
- package/dist/mcp/bin.js +2 -2
- package/dist/mcp/index.d.ts +1 -1
- package/dist/mcp/index.js +4 -4
- package/dist/profiles.d.ts +1 -1
- package/dist/{provision-supervisor-DLOeyFHV.js → provision-supervisor-DdsrpA3I.js} +3 -3
- package/dist/{provision-supervisor-DLOeyFHV.js.map → provision-supervisor-DdsrpA3I.js.map} +1 -1
- package/dist/{run-state-Bcci4zIN.js → run-state-CX8OTr-9.js} +2 -2
- package/dist/{run-state-Bcci4zIN.js.map → run-state-CX8OTr-9.js.map} +1 -1
- package/dist/{runtime-DCo0OP4n.js → runtime-ERkXbzFe.js} +10 -10
- package/dist/{runtime-DCo0OP4n.js.map → runtime-ERkXbzFe.js.map} +1 -1
- package/dist/{search-executor-Dn5YmHsg.js → search-executor-DDb4sT3E.js} +2 -2
- package/dist/{search-executor-Dn5YmHsg.js.map → search-executor-DDb4sT3E.js.map} +1 -1
- package/dist/{server-DxpG9y6W.js → server-B9tOx3CY.js} +2 -2
- package/dist/{server-DxpG9y6W.js.map → server-B9tOx3CY.js.map} +1 -1
- package/dist/{structural-rollout-DOmjcEMD.js → structural-rollout-B6RlFKxq.js} +2 -2
- package/dist/{structural-rollout-DOmjcEMD.js.map → structural-rollout-B6RlFKxq.js.map} +1 -1
- package/dist/{supervise-D7jtypE-.js → supervise-CikShHxF.js} +3 -3
- package/dist/{supervise-D7jtypE-.js.map → supervise-CikShHxF.js.map} +1 -1
- package/dist/{supervisor-BFs4u2Vo.js → supervisor-BvEe3y0c.js} +13 -9
- package/dist/supervisor-BvEe3y0c.js.map +1 -0
- package/dist/testing.d.ts +1 -1
- package/dist/testing.js +11 -11
- package/dist/tool-loop.d.ts +10 -1
- package/dist/tool-loop.js +182 -142
- package/dist/tool-loop.js.map +1 -1
- package/dist/tui/index.d.ts +1 -1
- package/dist/tui/index.js +1 -1
- package/dist/{types-CKsn_wgO.d.ts → types-BYiwLO2L.d.ts} +10 -1
- package/package.json +4 -3
- package/dist/supervisor-BFs4u2Vo.js.map +0 -1
package/dist/tool-loop.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"tool-loop.js","names":[],"sources":["../src/tool-loop.ts"],"sourcesContent":["/**\n * Bounded turn-level tool-dispatch loop.\n *\n * `runAgentTaskStream` runs ONE model turn; `runAgentRounds` orchestrates DELEGATED\n * multi-agent topologies (refine / fanout-vote). Neither is the everyday\n * interactive shape: a chat turn where the model may emit tool calls, each is\n * executed, the results are folded back, and the turn re-runs until the model\n * stops (or a turn cap). Every agent app hand-rolls that loop — this is it,\n * as a reusable primitive.\n *\n * Substrate-neutral by design: the caller supplies `streamTurn` (wrapping\n * whatever backend / `runAgentTaskStream` it uses) and `executeToolCall`\n * (routing to its executors). This module owns the LOOP; the caller owns the\n * model and the executors. `Raw` (streaming variant) is the caller's own\n * event type. The only imported contract is the runtime hook type: hooks are\n * execution-scoped observers, not part of the agent profile.\n */\n\nimport type { RuntimeDecisionEvidenceRef, RuntimeHooks } from './runtime-hooks'\nimport { notifyRuntimeDecisionPoint, notifyRuntimeHookEvent } from './runtime-hooks'\n\nexport interface ToolLoopCall {\n toolCallId?: string\n toolName: string\n args: Record<string, unknown>\n /**\n * Provider-specific fields the model attached to this call, echoed back on\n * its assistant `tool_calls` entry in the next request. Gemini 3 returns\n * `extra_content: { google: { thought_signature } }` on each call and answers\n * HTTP 400 when the next request omits it.\n */\n providerFields?: Record<string, unknown>\n}\n\n/** Outcome of one tool dispatch — structurally compatible with a hub/integration\n * tool-outcome union, so callers can fold either through the loop. */\nexport type ToolCallOutcome =\n | { ok: true; result: unknown }\n | { ok: false; code: string; message: string; status?: number }\n\n/** Runaway-backstop: stops an infinite tool loop where cost is unmetered. Set\n * far above any legitimate workflow — this is a watchdog, not a policy cap.\n * Legitimate per-call budgets come from `maxCostUsd` + `costOf`. */\nconst RUNAWAY_BACKSTOP_TURNS = 200\nconst DEFAULT_DECISION_CONTEXT_CHARS = 12_000\nconst FAILURE_RECOVERY_ACTIONS = ['retry', 'verify', 'continue', 'stop']\n/** Consecutive identical calls (same tool + canonical-JSON args) that trigger\n * stuck-loop detection. The window resets on any different call. */\nconst STUCK_LOOP_THRESHOLD = 3\n\n/** One OpenAI-shaped tool-call entry carried on an assistant message, plus any\n * provider-specific fields the model attached to the call (`ToolLoopCall.providerFields`). */\nexport interface ToolLoopAssistantToolCall {\n [providerField: string]: unknown\n id: string\n type: 'function'\n function: { name: string; arguments: string }\n}\n\n/**\n * A message in the running conversation the loop sends to `streamTurn`.\n *\n * The base `{ role, content }` covers `system` / `user` / plain `assistant`\n * turns. Two optional fields carry the OpenAI function-calling contract so a\n * strict model (Claude, and any OpenAI-compatible provider that validates tool\n * history) reads its own tool use back instead of re-issuing the same call:\n *\n * - an assistant turn that emitted tool calls carries `tool_calls`, and its\n * `content` is `null` when the turn was tool-only;\n * - each tool result is its own `{ role: 'tool', tool_call_id, content }`\n * message keyed to the call that produced it.\n *\n * Widening is additive: a `streamTurn` that reads only `role` + `content` still\n * works; one that forwards the whole message to an OpenAI-compatible endpoint\n * now sends correct tool history.\n */\nexport type ToolLoopMessage = {\n role: string\n content: string | null\n tool_calls?: ToolLoopAssistantToolCall[]\n tool_call_id?: string\n}\n\n/** A tool-call id is required to key a `role: 'tool'` result back to its call.\n * When the model omitted one, derive a stable id from the tool name so the\n * assistant `tool_calls` entry and its `tool` result still match. */\nfunction toolCallId(call: ToolLoopCall): string {\n return call.toolCallId ?? `call_${call.toolName}`\n}\n\n/** The assistant turn that emitted `pending`, in OpenAI shape: text content\n * (null when the turn was tool-only) plus its `tool_calls` array. */\nfunction assistantToolCallMessage(turnText: string, pending: ToolLoopCall[]): ToolLoopMessage {\n return {\n role: 'assistant',\n content: turnText.trim() || null,\n tool_calls: pending.map((call) => ({\n ...call.providerFields,\n id: toolCallId(call),\n type: 'function',\n function: { name: call.toolName, arguments: JSON.stringify(call.args) },\n })),\n }\n}\n\n/** One `role: 'tool'` result message keyed to its call by `tool_call_id`. */\nfunction toolResultMessage(call: ToolLoopCall, content: string): ToolLoopMessage {\n return { role: 'tool', tool_call_id: toolCallId(call), content }\n}\n\n/**\n * One progress report from a running tool, shaped like an MCP `notifications/progress`\n * payload: a free-text `message`, a monotonic `progress` count with an optional\n * `total`, and any structured `data` the caller's UI understands.\n */\nexport interface ToolProgressUpdate {\n message?: string\n progress?: number\n total?: number\n data?: unknown\n}\n\n/** What the loop hands a running tool besides its call. */\nexport interface ToolCallContext {\n /**\n * Report progress while the call runs. The streaming loop yields each update as a\n * `tool_progress` step, in order, before the call's `tool_result`; updates sent after\n * the call settles are dropped.\n */\n progress: (update: ToolProgressUpdate) => void\n}\n\n/** Executes one tool call. Implementations that take only the call stay valid. */\nexport type ToolCallExecutor = (\n call: ToolLoopCall,\n context: ToolCallContext,\n) => Promise<ToolCallOutcome>\n\nfunction defaultRender(label: string, outcome: ToolCallOutcome): string {\n if (outcome.ok) return `- ${label} → ok: ${JSON.stringify(outcome.result)}`\n return `- ${label} → failed (${outcome.code}): ${outcome.message}`\n}\n\n// ── Awaitable variant (drain-only callers, tests) ──────────────────────────\n\nexport type ToolLoopEvent =\n | { type: 'text'; text: string }\n | { type: 'tool_call'; call: ToolLoopCall }\n | { type: 'other'; event: unknown }\n\n/** Why the loop stopped. `completed` = model finished naturally; `stuck-loop` =\n * ≥3 consecutive identical tool calls (same tool + args); `backstop` = hit the\n * runaway-backstop cap (200 by default); `deadline` = wall-clock deadlineMs\n * exceeded; `budget` = maxCostUsd exhausted. Non-`completed` stops are infra /\n * resource outcomes — eval scoring must distinguish them from capability failure. */\nexport type ToolLoopStopReason = 'completed' | 'stuck-loop' | 'backstop' | 'deadline' | 'budget'\n\nexport interface ToolLoopResult {\n finalText: string\n toolResults: Array<{ call: ToolLoopCall; label: string; outcome: ToolCallOutcome }>\n turns: number\n stopReason: ToolLoopStopReason\n /** @deprecated Use `stopReason !== 'completed'` instead. */\n cappedOut: boolean\n}\n\nexport interface RunToolLoopOptions {\n systemPrompt: string\n userMessage: string\n priorMessages?: ToolLoopMessage[]\n streamTurn: (messages: ToolLoopMessage[]) => AsyncIterable<ToolLoopEvent>\n executeToolCall: ToolCallExecutor\n /** Receives each progress update a running tool reports, in order. */\n onToolProgress?: (call: ToolLoopCall, update: ToolProgressUpdate) => void\n isExecutableTool: (toolName: string) => boolean\n /** Runaway-backstop cap. Default 200 — set far above any legitimate workflow.\n * For per-workflow limits, use `maxCostUsd` or `deadlineMs` instead. */\n maxToolTurns?: number\n /** Wall-clock deadline in ms since epoch (Date.now()-based). When exceeded the\n * loop stops with stopReason `deadline`. */\n deadlineMs?: number\n /** Maximum total cost in USD. Requires `costOf` to meter each tool call. */\n maxCostUsd?: number\n /** Return the USD cost of one outcome. Required for `maxCostUsd` to work. */\n costOf?: (call: ToolLoopCall, outcome: ToolCallOutcome) => number\n renderResult?: (label: string, outcome: ToolCallOutcome) => string\n labelFor?: (call: ToolLoopCall) => string\n runId?: string\n scenarioId?: string\n hooks?: RuntimeHooks\n}\n\n/** Run the bounded tool loop and return the final text + every executed tool\n * outcome. Awaitable — callers needing to stream events to a UI use\n * {@link streamToolLoop}. */\nexport async function runToolLoop(opts: RunToolLoopOptions): Promise<ToolLoopResult> {\n const backstop = opts.maxToolTurns ?? RUNAWAY_BACKSTOP_TURNS\n const render = opts.renderResult ?? defaultRender\n const labelFor = opts.labelFor ?? ((c: ToolLoopCall) => c.toolName)\n const runId = opts.runId ?? `agent-run-${randomSuffix()}`\n const messages: ToolLoopMessage[] = [\n { role: 'system', content: opts.systemPrompt },\n ...(opts.priorMessages ?? []),\n { role: 'user', content: opts.userMessage },\n ]\n const observer = createToolLoopObserver(opts.hooks, runId, opts.scenarioId)\n const toolResults: ToolLoopResult['toolResults'] = []\n let finalText = ''\n let turns = 0\n let accumulatedCostUsd = 0\n // Stuck-loop detection: track the last canonical-JSON call signature and how\n // many consecutive times we've seen it.\n let lastCallHash: string | null = null\n let consecutiveCount = 0\n\n observer.loopBefore(backstop, messages.length)\n\n for (let toolTurn = 0; ; toolTurn++) {\n turns++\n\n // Wall-clock deadline check — before every new turn.\n if (opts.deadlineMs !== undefined && Date.now() >= opts.deadlineMs) {\n observer.loopAfter({ turns, toolResults: toolResults.length, stopReason: 'deadline' })\n return { finalText, toolResults, turns, stopReason: 'deadline', cappedOut: true }\n }\n\n let turnText = ''\n const pending: ToolLoopCall[] = []\n const turnEventId = observer.turnBefore(toolTurn, messages.length)\n for await (const ev of opts.streamTurn([...messages])) {\n if (ev.type === 'text') {\n turnText += ev.text\n finalText += ev.text\n } else if (ev.type === 'tool_call' && opts.isExecutableTool(ev.call.toolName)) {\n pending.push(ev.call)\n }\n }\n if (pending.length === 0) {\n observer.turnAfter(toolTurn, turnEventId, {\n pendingToolCalls: 0,\n finalTextChars: finalText.length,\n })\n break\n }\n\n // Runaway backstop — the model keeps emitting calls past the safety ceiling.\n if (toolTurn >= backstop) {\n observer.turnAfter(toolTurn, turnEventId, {\n pendingToolCalls: pending.length,\n stopReason: 'backstop',\n })\n observer.loopAfter({ turns, toolResults: toolResults.length, stopReason: 'backstop' })\n return { finalText, toolResults, turns, stopReason: 'backstop', cappedOut: true }\n }\n\n // The assistant turn that emitted the calls, carrying its tool_calls array,\n // so a strict model reads its own tool use back in OpenAI shape.\n messages.push(assistantToolCallMessage(turnText, pending))\n const outcomes: ExecutedToolCall[] = []\n for (const [callIndex, call] of pending.entries()) {\n // Stuck-loop detection: hash the first pending call each turn (a model\n // stuck in a loop re-issues the same call repeatedly, not alternating calls).\n const callHash = canonicalCallHash(call)\n if (callHash === lastCallHash) {\n consecutiveCount++\n } else {\n lastCallHash = callHash\n consecutiveCount = 1\n }\n if (consecutiveCount >= STUCK_LOOP_THRESHOLD) {\n observer.turnAfter(toolTurn, turnEventId, {\n pendingToolCalls: pending.length,\n stopReason: 'stuck-loop',\n })\n observer.loopAfter({ turns, toolResults: toolResults.length, stopReason: 'stuck-loop' })\n return { finalText, toolResults, turns, stopReason: 'stuck-loop', cappedOut: true }\n }\n\n const callEventId = observer.toolCallBefore(toolTurn, turnEventId, callIndex, call)\n let settled = false\n const outcome = await executeGuarded(opts.executeToolCall, call, (update) => {\n if (!settled) opts.onToolProgress?.(call, update)\n })\n settled = true\n\n // Budget check after each tool call.\n if (opts.maxCostUsd !== undefined && opts.costOf !== undefined) {\n accumulatedCostUsd += opts.costOf(call, outcome)\n if (accumulatedCostUsd >= opts.maxCostUsd) {\n const label = labelFor(call)\n toolResults.push({ call, label, outcome })\n messages.push(toolResultMessage(call, render(label, outcome)))\n observer.toolCallAfter(toolTurn, callEventId, call, outcome)\n observer.turnAfter(toolTurn, turnEventId, {\n pendingToolCalls: pending.length,\n stopReason: 'budget',\n })\n observer.loopAfter({ turns, toolResults: toolResults.length, stopReason: 'budget' })\n return { finalText, toolResults, turns, stopReason: 'budget', cappedOut: true }\n }\n }\n\n const label = labelFor(call)\n const rendered = render(label, outcome)\n toolResults.push({ call, label, outcome })\n outcomes.push({ call, label, outcome, rendered })\n // One role:'tool' message per result, keyed to its call by tool_call_id.\n messages.push(toolResultMessage(call, rendered))\n observer.toolCallAfter(toolTurn, callEventId, call, outcome)\n }\n observer.failureRecovery({\n toolTurn,\n messages,\n turnText,\n outcomes,\n })\n observer.turnAfter(toolTurn, turnEventId, {\n pendingToolCalls: pending.length,\n toolResults: outcomes.map((item) => ({\n toolName: item.call.toolName,\n toolCallId: item.call.toolCallId,\n ok: item.outcome.ok,\n })),\n failedToolCalls: outcomes.filter((item) => !item.outcome.ok).length,\n })\n }\n observer.loopAfter({ turns, toolResults: toolResults.length, stopReason: 'completed' })\n return { finalText, toolResults, turns, stopReason: 'completed', cappedOut: false }\n}\n\n// ── Streaming variant (SSE chat runtimes + per-event telemetry) ────────────\n\nexport type StreamToolLoopYield<Raw> =\n | { kind: 'event'; event: Raw }\n | {\n kind: 'tool_progress'\n toolName: string\n toolCallId?: string\n update: ToolProgressUpdate\n }\n | {\n kind: 'tool_result'\n toolName: string\n toolCallId?: string\n label: string\n outcome: ToolCallOutcome\n }\n | {\n kind: 'capped'\n pending: number\n stopReason: Exclude<ToolLoopStopReason, 'completed'>\n /** On `deadline` only: the conversation after the system prompt, every tool call answered.\n * Passing it back as `priorMessages` with no `userMessage` continues the same turn. */\n messages?: ToolLoopMessage[]\n }\n\nexport interface StreamToolLoopOptions<Raw> {\n systemPrompt: string\n /** Omit to continue a checkpointed turn whose `priorMessages` already end with tool results. */\n userMessage?: string\n priorMessages?: ToolLoopMessage[]\n streamTurn: (messages: ToolLoopMessage[]) => AsyncIterable<Raw>\n extractText: (event: Raw) => string\n extractToolCall: (event: Raw) => ToolLoopCall | null\n isExecutableTool: (toolName: string) => boolean\n executeToolCall: ToolCallExecutor\n /** Runaway-backstop cap. Default 200 — set far above any legitimate workflow. */\n maxToolTurns?: number\n /** Wall-clock deadline in ms since epoch (Date.now()-based). */\n deadlineMs?: number\n /** Maximum total cost in USD. Requires `costOf` to meter each tool call. */\n maxCostUsd?: number\n /** Return the USD cost of one outcome. Required for `maxCostUsd` to work. */\n costOf?: (call: ToolLoopCall, outcome: ToolCallOutcome) => number\n renderResult?: (label: string, outcome: ToolCallOutcome) => string\n labelFor?: (call: ToolLoopCall) => string\n runId?: string\n scenarioId?: string\n hooks?: RuntimeHooks\n}\n\n/** Streaming bounded tool loop: yields each raw turn event (the caller maps +\n * telemetries + re-emits it), each `tool_progress` a running tool reports, and\n * each executed `tool_result`; emits one `capped` if it stops for any\n * non-completed reason with calls still pending. */\nexport async function* streamToolLoop<Raw>(\n opts: StreamToolLoopOptions<Raw>,\n): AsyncGenerator<StreamToolLoopYield<Raw>, void, unknown> {\n const backstop = opts.maxToolTurns ?? RUNAWAY_BACKSTOP_TURNS\n const render = opts.renderResult ?? defaultRender\n const labelFor = opts.labelFor ?? ((c: ToolLoopCall) => c.toolName)\n const runId = opts.runId ?? `agent-run-${randomSuffix()}`\n const messages: ToolLoopMessage[] = [\n { role: 'system', content: opts.systemPrompt },\n ...(opts.priorMessages ?? []),\n ...(opts.userMessage !== undefined\n ? [{ role: 'user' as const, content: opts.userMessage }]\n : []),\n ]\n const observer = createToolLoopObserver(opts.hooks, runId, opts.scenarioId)\n let accumulatedCostUsd = 0\n let lastCallHash: string | null = null\n let consecutiveCount = 0\n\n observer.loopBefore(backstop, messages.length)\n\n for (let toolTurn = 0; ; toolTurn++) {\n // Wall-clock deadline check before every new turn.\n if (opts.deadlineMs !== undefined && Date.now() >= opts.deadlineMs) {\n observer.loopAfter({ turns: toolTurn + 1, stopReason: 'deadline' })\n // A turn boundary: every call is answered, so the history is a resumable checkpoint.\n yield { kind: 'capped', pending: 0, stopReason: 'deadline', messages: messages.slice(1) }\n return\n }\n\n let turnText = ''\n const pending: ToolLoopCall[] = []\n const turnEventId = observer.turnBefore(toolTurn, messages.length)\n for await (const event of opts.streamTurn([...messages])) {\n yield { kind: 'event', event }\n turnText += opts.extractText(event)\n const call = opts.extractToolCall(event)\n if (call && opts.isExecutableTool(call.toolName)) pending.push(call)\n }\n if (pending.length === 0) {\n observer.turnAfter(toolTurn, turnEventId, { pendingToolCalls: 0 })\n observer.loopAfter({ turns: toolTurn + 1, stopReason: 'completed' })\n return\n }\n\n // Runaway backstop.\n if (toolTurn >= backstop) {\n observer.turnAfter(toolTurn, turnEventId, {\n pendingToolCalls: pending.length,\n stopReason: 'backstop',\n })\n observer.loopAfter({ turns: toolTurn + 1, stopReason: 'backstop' })\n yield { kind: 'capped', pending: pending.length, stopReason: 'backstop' }\n return\n }\n\n // The assistant turn that emitted the calls, carrying its tool_calls array,\n // so a strict model reads its own tool use back in OpenAI shape.\n messages.push(assistantToolCallMessage(turnText, pending))\n const outcomes: ExecutedToolCall[] = []\n for (const [callIndex, call] of pending.entries()) {\n // Stuck-loop detection.\n const callHash = canonicalCallHash(call)\n if (callHash === lastCallHash) {\n consecutiveCount++\n } else {\n lastCallHash = callHash\n consecutiveCount = 1\n }\n if (consecutiveCount >= STUCK_LOOP_THRESHOLD) {\n observer.turnAfter(toolTurn, turnEventId, {\n pendingToolCalls: pending.length,\n stopReason: 'stuck-loop',\n })\n observer.loopAfter({ turns: toolTurn + 1, stopReason: 'stuck-loop' })\n yield { kind: 'capped', pending: pending.length, stopReason: 'stuck-loop' }\n return\n }\n\n const callEventId = observer.toolCallBefore(toolTurn, turnEventId, callIndex, call)\n // Progress arrives while the call is in flight; yield it as it lands, in order,\n // and stop accepting it once the call settles so it never trails the result.\n const progress: ToolProgressUpdate[] = []\n let wake: (() => void) | undefined\n let settled = false\n const running = executeGuarded(opts.executeToolCall, call, (update) => {\n if (settled) return\n progress.push(update)\n wake?.()\n }).then((result) => {\n settled = true\n wake?.()\n return result\n })\n while (!settled || progress.length > 0) {\n const update = progress.shift()\n if (update !== undefined) {\n yield {\n kind: 'tool_progress',\n toolName: call.toolName,\n toolCallId: call.toolCallId,\n update,\n }\n continue\n }\n await new Promise<void>((resolve) => {\n wake = resolve\n })\n wake = undefined\n }\n const outcome = await running\n\n // Budget check after each tool call.\n if (opts.maxCostUsd !== undefined && opts.costOf !== undefined) {\n accumulatedCostUsd += opts.costOf(call, outcome)\n if (accumulatedCostUsd >= opts.maxCostUsd) {\n const label = labelFor(call)\n yield {\n kind: 'tool_result',\n toolName: call.toolName,\n toolCallId: call.toolCallId,\n label,\n outcome,\n }\n messages.push(toolResultMessage(call, render(label, outcome)))\n observer.toolCallAfter(toolTurn, callEventId, call, outcome)\n observer.turnAfter(toolTurn, turnEventId, {\n pendingToolCalls: pending.length,\n stopReason: 'budget',\n })\n observer.loopAfter({ turns: toolTurn + 1, stopReason: 'budget' })\n yield { kind: 'capped', pending: pending.length, stopReason: 'budget' }\n return\n }\n }\n\n const label = labelFor(call)\n yield {\n kind: 'tool_result',\n toolName: call.toolName,\n toolCallId: call.toolCallId,\n label,\n outcome,\n }\n const rendered = render(label, outcome)\n outcomes.push({ call, label, outcome, rendered })\n // One role:'tool' message per result, keyed to its call by tool_call_id.\n messages.push(toolResultMessage(call, rendered))\n observer.toolCallAfter(toolTurn, callEventId, call, outcome)\n }\n observer.failureRecovery({\n toolTurn,\n messages,\n turnText,\n outcomes,\n })\n observer.turnAfter(toolTurn, turnEventId, {\n pendingToolCalls: pending.length,\n toolResults: outcomes.map((item) => ({\n toolName: item.call.toolName,\n toolCallId: item.call.toolCallId,\n ok: item.outcome.ok,\n })),\n failedToolCalls: outcomes.filter((item) => !item.outcome.ok).length,\n })\n }\n}\n\n/** Run one call; a thrown executor becomes an `executor_error` outcome. */\nasync function executeGuarded(\n execute: ToolCallExecutor,\n call: ToolLoopCall,\n progress: (update: ToolProgressUpdate) => void,\n): Promise<ToolCallOutcome> {\n try {\n return await execute(call, { progress })\n } catch (err) {\n return {\n ok: false,\n code: 'executor_error',\n message: err instanceof Error ? err.message : String(err),\n }\n }\n}\n\ninterface ExecutedToolCall {\n call: ToolLoopCall\n label: string\n outcome: ToolCallOutcome\n rendered: string\n}\n\ninterface NotifyToolFailureRecoveryOptions {\n hooks?: RuntimeHooks\n runId: string\n scenarioId?: string\n stepIndex: number\n messages: ToolLoopMessage[]\n turnText: string\n outcomes: ExecutedToolCall[]\n}\n\ninterface NotifyToolLoopEventOptions {\n hooks?: RuntimeHooks\n runId: string\n scenarioId?: string\n target: 'agent.run' | 'agent.turn' | 'agent.tool_call'\n phase: 'before' | 'after' | 'error' | 'event'\n id?: string\n stepIndex?: number\n parentId?: string\n payload?: Record<string, unknown>\n metadata?: Record<string, unknown>\n}\n\ninterface ToolLoopObserver {\n loopBefore(maxToolTurns: number, messageCount: number): void\n loopAfter(payload: Record<string, unknown>): void\n turnBefore(toolTurn: number, messageCount: number): string\n turnAfter(toolTurn: number, turnEventId: string, payload: Record<string, unknown>): void\n toolCallBefore(\n toolTurn: number,\n turnEventId: string,\n callIndex: number,\n call: ToolLoopCall,\n ): string\n toolCallAfter(\n toolTurn: number,\n callEventId: string,\n call: ToolLoopCall,\n outcome: ToolCallOutcome,\n ): void\n failureRecovery(options: {\n toolTurn: number\n messages: ToolLoopMessage[]\n turnText: string\n outcomes: ExecutedToolCall[]\n }): void\n}\n\nfunction createToolLoopObserver(\n hooks: RuntimeHooks | undefined,\n runId: string,\n scenarioId: string | undefined,\n): ToolLoopObserver {\n const loopEventId = `${runId}:agent.run`\n return {\n loopBefore: (maxToolTurns, messageCount) => {\n notifyToolLoopEvent({\n hooks,\n runId,\n scenarioId,\n target: 'agent.run',\n phase: 'before',\n id: `${loopEventId}:before`,\n payload: { maxToolTurns, messageCount },\n })\n },\n loopAfter: (payload) => {\n notifyToolLoopEvent({\n hooks,\n runId,\n scenarioId,\n target: 'agent.run',\n phase: 'after',\n id: `${loopEventId}:after`,\n payload,\n })\n },\n turnBefore: (toolTurn, messageCount) => {\n const turnEventId = `${loopEventId}:${toolTurn}`\n notifyToolLoopEvent({\n hooks,\n runId,\n scenarioId,\n target: 'agent.turn',\n phase: 'before',\n id: turnEventId,\n stepIndex: toolTurn,\n parentId: loopEventId,\n payload: { messageCount },\n })\n return turnEventId\n },\n turnAfter: (toolTurn, turnEventId, payload) => {\n notifyToolLoopEvent({\n hooks,\n runId,\n scenarioId,\n target: 'agent.turn',\n phase: 'after',\n id: `${turnEventId}:after`,\n stepIndex: toolTurn,\n parentId: turnEventId,\n payload,\n })\n },\n toolCallBefore: (toolTurn, turnEventId, callIndex, call) => {\n const callEventId = `${turnEventId}:tool-call:${callIndex}`\n notifyToolLoopEvent({\n hooks,\n runId,\n scenarioId,\n target: 'agent.tool_call',\n phase: 'before',\n id: callEventId,\n stepIndex: toolTurn,\n parentId: turnEventId,\n payload: toolCallPayload(call),\n })\n return callEventId\n },\n toolCallAfter: (toolTurn, callEventId, call, outcome) => {\n notifyToolLoopEvent({\n hooks,\n runId,\n scenarioId,\n target: 'agent.tool_call',\n phase: 'after',\n id: `${callEventId}:after`,\n stepIndex: toolTurn,\n parentId: callEventId,\n payload: { ...toolCallPayload(call), outcome: outcomePayload(outcome) },\n })\n },\n failureRecovery: (options) => {\n notifyToolFailureRecovery({\n hooks,\n runId,\n scenarioId,\n stepIndex: options.toolTurn,\n messages: options.messages,\n turnText: options.turnText,\n outcomes: options.outcomes,\n })\n },\n }\n}\n\nfunction notifyToolLoopEvent(options: NotifyToolLoopEventOptions): void {\n notifyRuntimeHookEvent(options.hooks, {\n id: options.id ?? `${options.runId}:${options.target}:${options.phase}`,\n runId: options.runId,\n scenarioId: options.scenarioId,\n target: options.target,\n phase: options.phase,\n timestamp: Date.now(),\n stepIndex: options.stepIndex,\n parentId: options.parentId,\n payload: options.payload,\n metadata: { producer: 'tool-loop', ...options.metadata },\n })\n}\n\nfunction notifyToolFailureRecovery(options: NotifyToolFailureRecoveryOptions): void {\n const failed = options.outcomes.filter((item) => !item.outcome.ok)\n if (failed.length === 0) return\n\n const evidence: RuntimeDecisionEvidenceRef[] = []\n for (const item of failed) {\n const id = item.call.toolCallId ?? `${options.stepIndex}:${item.label}`\n evidence.push({\n source: 'tool_call',\n id,\n detail: `${item.call.toolName} ${stringifySafe(item.call.args, 2_000)}`,\n metadata: { toolName: item.call.toolName, label: item.label },\n })\n evidence.push({\n source: 'tool_result',\n id: `${id}:result`,\n detail: item.rendered,\n metadata: failureMetadata(item.outcome),\n })\n }\n\n notifyRuntimeDecisionPoint(options.hooks, {\n id: `${options.runId}:agent.turn:${options.stepIndex}:failure-recovery`,\n runId: options.runId,\n scenarioId: options.scenarioId,\n stepIndex: options.stepIndex,\n kind: 'retry',\n candidateActions: [...FAILURE_RECOVERY_ACTIONS],\n context: renderDecisionContext(options.messages, options.turnText, options.outcomes),\n evidence,\n metadata: {\n target: 'failure-recovery',\n source: 'agent.turn',\n failedToolCount: failed.length,\n toolNames: failed.map((item) => item.call.toolName),\n },\n })\n}\n\nfunction toolCallPayload(call: ToolLoopCall): Record<string, unknown> {\n return {\n toolName: call.toolName,\n toolCallId: call.toolCallId,\n argsPreview: stringifySafe(call.args, 2_000),\n }\n}\n\nfunction outcomePayload(outcome: ToolCallOutcome): Record<string, unknown> {\n if (!outcome.ok) {\n return {\n ok: false,\n code: outcome.code,\n message: trimText(outcome.message, 2_000),\n status: outcome.status,\n }\n }\n return {\n ok: true,\n resultPreview: stringifySafe(outcome.result, 2_000),\n }\n}\n\nfunction failureMetadata(outcome: ToolCallOutcome): Record<string, unknown> | undefined {\n if (outcome.ok) return undefined\n return {\n code: outcome.code,\n message: outcome.message,\n status: outcome.status,\n }\n}\n\nfunction renderDecisionContext(\n messages: ToolLoopMessage[],\n turnText: string,\n outcomes: ExecutedToolCall[],\n): string {\n const recent = messages.slice(-6).map((message) => `[${message.role}]\\n${message.content ?? ''}`)\n const assistant = turnText.trim() ? [`[assistant]\\n${turnText}`] : []\n const toolResults = [`[tool results]\\n${outcomes.map((item) => item.rendered).join('\\n')}`]\n return trimText(\n [...recent, ...assistant, ...toolResults].join('\\n\\n'),\n DEFAULT_DECISION_CONTEXT_CHARS,\n )\n}\n\n/** Canonical identifier for a tool call used by stuck-loop detection.\n * Keys are sorted so `{b:1,a:2}` and `{a:2,b:1}` produce the same hash. */\nfunction canonicalCallHash(call: ToolLoopCall): string {\n const sortedArgs = Object.fromEntries(\n Object.entries(call.args).sort(([a], [b]) => a.localeCompare(b)),\n )\n return `${call.toolName}:${JSON.stringify(sortedArgs)}`\n}\n\nfunction stringifySafe(value: unknown, max: number): string {\n let text: string\n try {\n text = JSON.stringify(value) ?? String(value)\n } catch {\n text = String(value)\n }\n return trimText(text, max)\n}\n\nfunction trimText(text: string, max: number): string {\n if (text.length <= max) return text\n return `${text.slice(0, max)}…`\n}\n\nfunction randomSuffix(len = 8): string {\n return Math.random()\n .toString(36)\n .slice(2, 2 + len)\n}\n"],"mappings":";;;;;AA2CA,MAAM,yBAAyB;AAC/B,MAAM,iCAAiC;AACvC,MAAM,2BAA2B;CAAC;CAAS;CAAU;CAAY;AAAM;;;AAGvE,MAAM,uBAAuB;;;;AAsC7B,SAAS,WAAW,MAA4B;CAC9C,OAAO,KAAK,cAAc,QAAQ,KAAK;AACzC;;;AAIA,SAAS,yBAAyB,UAAkB,SAA0C;CAC5F,OAAO;EACL,MAAM;EACN,SAAS,SAAS,KAAK,KAAK;EAC5B,YAAY,QAAQ,KAAK,UAAU;GACjC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;EAAC,GAAG;EAAQ,GAAG;EAAW,GAAG;CAAW,CAAC,CAAC,KAAK,MAAM,GACrD,8BACF;AACF;;;AAIA,SAAS,kBAAkB,MAA4B;CACrD,MAAM,aAAa,OAAO,YACxB,OAAO,QAAQ,KAAK,IAAI,CAAC,CAAC,MAAM,CAAC,IAAI,CAAC,OAAO,EAAE,cAAc,CAAC,CAAC,CACjE;CACA,OAAO,GAAG,KAAK,SAAS,GAAG,KAAK,UAAU,UAAU;AACtD;AAEA,SAAS,cAAc,OAAgB,KAAqB;CAC1D,IAAI;CACJ,IAAI;EACF,OAAO,KAAK,UAAU,KAAK,KAAK,OAAO,KAAK;CAC9C,QAAQ;EACN,OAAO,OAAO,KAAK;CACrB;CACA,OAAO,SAAS,MAAM,GAAG;AAC3B;AAEA,SAAS,SAAS,MAAc,KAAqB;CACnD,IAAI,KAAK,UAAU,KAAK,OAAO;CAC/B,OAAO,GAAG,KAAK,MAAM,GAAG,GAAG,EAAE;AAC/B;AAEA,SAAS,aAAa,MAAM,GAAW;CACrC,OAAO,KAAK,OAAO,CAAC,CACjB,SAAS,EAAE,CAAC,CACZ,MAAM,GAAG,IAAI,GAAG;AACrB"}
|
|
1
|
+
{"version":3,"file":"tool-loop.js","names":[],"sources":["../src/tool-loop.ts"],"sourcesContent":["/**\n * Bounded turn-level tool-dispatch loop.\n *\n * `runAgentTaskStream` runs ONE model turn; `runAgentRounds` orchestrates DELEGATED\n * multi-agent topologies (refine / fanout-vote). Neither is the everyday\n * interactive shape: a chat turn where the model may emit tool calls, each is\n * executed, the results are folded back, and the turn re-runs until the model\n * stops (or a turn cap). Every agent app hand-rolls that loop — this is it,\n * as a reusable primitive.\n *\n * Substrate-neutral by design: the caller supplies `streamTurn` (wrapping\n * whatever backend / `runAgentTaskStream` it uses) and `executeToolCall`\n * (routing to its executors). This module owns the LOOP; the caller owns the\n * model and the executors. `Raw` (streaming variant) is the caller's own\n * event type. The only imported contracts are the runtime hook type (hooks are\n * execution-scoped observers, not part of the agent profile) and the task queue\n * a turn's calls run on.\n */\n\nimport { runTaskQueue } from './runtime/task-queue'\nimport type { RuntimeDecisionEvidenceRef, RuntimeHooks } from './runtime-hooks'\nimport { notifyRuntimeDecisionPoint, notifyRuntimeHookEvent } from './runtime-hooks'\n\nexport interface ToolLoopCall {\n toolCallId?: string\n toolName: string\n args: Record<string, unknown>\n /**\n * Provider-specific fields the model attached to this call, echoed back on\n * its assistant `tool_calls` entry in the next request. Gemini 3 returns\n * `extra_content: { google: { thought_signature } }` on each call and answers\n * HTTP 400 when the next request omits it.\n */\n providerFields?: Record<string, unknown>\n}\n\n/** Outcome of one tool dispatch — structurally compatible with a hub/integration\n * tool-outcome union, so callers can fold either through the loop. */\nexport type ToolCallOutcome =\n | { ok: true; result: unknown }\n | { ok: false; code: string; message: string; status?: number }\n\n/** Runaway-backstop: stops an infinite tool loop where cost is unmetered. Set\n * far above any legitimate workflow — this is a watchdog, not a policy cap.\n * Legitimate per-call budgets come from `maxCostUsd` + `costOf`. */\nconst RUNAWAY_BACKSTOP_TURNS = 200\nconst DEFAULT_DECISION_CONTEXT_CHARS = 12_000\nconst FAILURE_RECOVERY_ACTIONS = ['retry', 'verify', 'continue', 'stop']\n/** Consecutive model turns issuing the same call set (tool + canonical-JSON args)\n * that trigger stuck-loop detection. The window resets on any different set. */\nconst STUCK_LOOP_THRESHOLD = 3\n/** Calls of one model turn that run at once unless `maxConcurrentToolCalls` says otherwise. */\nconst DEFAULT_CONCURRENT_TOOL_CALLS = 1\n\n/** One OpenAI-shaped tool-call entry carried on an assistant message, plus any\n * provider-specific fields the model attached to the call (`ToolLoopCall.providerFields`). */\nexport interface ToolLoopAssistantToolCall {\n [providerField: string]: unknown\n id: string\n type: 'function'\n function: { name: string; arguments: string }\n}\n\n/**\n * A message in the running conversation the loop sends to `streamTurn`.\n *\n * The base `{ role, content }` covers `system` / `user` / plain `assistant`\n * turns. Two optional fields carry the OpenAI function-calling contract so a\n * strict model (Claude, and any OpenAI-compatible provider that validates tool\n * history) reads its own tool use back instead of re-issuing the same call:\n *\n * - an assistant turn that emitted tool calls carries `tool_calls`, and its\n * `content` is `null` when the turn was tool-only;\n * - each tool result is its own `{ role: 'tool', tool_call_id, content }`\n * message keyed to the call that produced it.\n *\n * Widening is additive: a `streamTurn` that reads only `role` + `content` still\n * works; one that forwards the whole message to an OpenAI-compatible endpoint\n * now sends correct tool history.\n */\nexport type ToolLoopMessage = {\n role: string\n content: string | null\n tool_calls?: ToolLoopAssistantToolCall[]\n tool_call_id?: string\n}\n\n/** A tool-call id is required to key a `role: 'tool'` result back to its call.\n * When the model omitted one, derive a stable id from the tool name so the\n * assistant `tool_calls` entry and its `tool` result still match. */\nfunction toolCallId(call: ToolLoopCall): string {\n return call.toolCallId ?? `call_${call.toolName}`\n}\n\n/** The assistant turn that emitted `pending`, in OpenAI shape: text content\n * (null when the turn was tool-only) plus its `tool_calls` array. */\nfunction assistantToolCallMessage(turnText: string, pending: ToolLoopCall[]): ToolLoopMessage {\n return {\n role: 'assistant',\n content: turnText.trim() || null,\n tool_calls: pending.map((call) => ({\n ...call.providerFields,\n id: toolCallId(call),\n type: 'function',\n function: { name: call.toolName, arguments: JSON.stringify(call.args) },\n })),\n }\n}\n\n/** One `role: 'tool'` result message keyed to its call by `tool_call_id`. */\nfunction toolResultMessage(call: ToolLoopCall, content: string): ToolLoopMessage {\n return { role: 'tool', tool_call_id: toolCallId(call), content }\n}\n\n/**\n * One progress report from a running tool, shaped like an MCP `notifications/progress`\n * payload: a free-text `message`, a monotonic `progress` count with an optional\n * `total`, and any structured `data` the caller's UI understands.\n */\nexport interface ToolProgressUpdate {\n message?: string\n progress?: number\n total?: number\n data?: unknown\n}\n\n/** What the loop hands a running tool besides its call. */\nexport interface ToolCallContext {\n /**\n * Report progress while the call runs. The streaming loop yields each update as a\n * `tool_progress` step, in order, before the call's `tool_result`; updates sent after\n * the call settles are dropped.\n */\n progress: (update: ToolProgressUpdate) => void\n}\n\n/** Executes one tool call. Implementations that take only the call stay valid. */\nexport type ToolCallExecutor = (\n call: ToolLoopCall,\n context: ToolCallContext,\n) => Promise<ToolCallOutcome>\n\nfunction defaultRender(label: string, outcome: ToolCallOutcome): string {\n if (outcome.ok) return `- ${label} → ok: ${JSON.stringify(outcome.result)}`\n return `- ${label} → failed (${outcome.code}): ${outcome.message}`\n}\n\n// ── Awaitable variant (drain-only callers, tests) ──────────────────────────\n\nexport type ToolLoopEvent =\n | { type: 'text'; text: string }\n | { type: 'tool_call'; call: ToolLoopCall }\n | { type: 'other'; event: unknown }\n\n/** Why the loop stopped. `completed` = model finished naturally; `stuck-loop` =\n * ≥3 consecutive model turns issuing the same calls (tool + args); `backstop` = hit the\n * runaway-backstop cap (200 by default); `deadline` = wall-clock deadlineMs\n * exceeded; `budget` = maxCostUsd exhausted. Non-`completed` stops are infra /\n * resource outcomes — eval scoring must distinguish them from capability failure. */\nexport type ToolLoopStopReason = 'completed' | 'stuck-loop' | 'backstop' | 'deadline' | 'budget'\n\nexport interface ToolLoopResult {\n finalText: string\n toolResults: Array<{ call: ToolLoopCall; label: string; outcome: ToolCallOutcome }>\n turns: number\n stopReason: ToolLoopStopReason\n /** @deprecated Use `stopReason !== 'completed'` instead. */\n cappedOut: boolean\n}\n\nexport interface RunToolLoopOptions {\n systemPrompt: string\n userMessage: string\n priorMessages?: ToolLoopMessage[]\n streamTurn: (messages: ToolLoopMessage[]) => AsyncIterable<ToolLoopEvent>\n executeToolCall: ToolCallExecutor\n /** Receives each progress update a running tool reports, in order. */\n onToolProgress?: (call: ToolLoopCall, update: ToolProgressUpdate) => void\n isExecutableTool: (toolName: string) => boolean\n /** Runaway-backstop cap. Default 200 — set far above any legitimate workflow.\n * For per-workflow limits, use `maxCostUsd` or `deadlineMs` instead. */\n maxToolTurns?: number\n /** Wall-clock deadline in ms since epoch (Date.now()-based). When exceeded the\n * loop stops with stopReason `deadline`. */\n deadlineMs?: number\n /** Maximum total cost in USD. Requires `costOf` to meter each tool call. */\n maxCostUsd?: number\n /** Return the USD cost of one outcome. Required for `maxCostUsd` to work. */\n costOf?: (call: ToolLoopCall, outcome: ToolCallOutcome) => number\n /** How many of one model turn's calls run at once. Default 1: one at a time, in call order.\n * Above 1, results and tool messages still keep call order; once `maxCostUsd` is spent no\n * further call starts, and the turn stops with `budget` after the started calls settle. */\n maxConcurrentToolCalls?: number\n renderResult?: (label: string, outcome: ToolCallOutcome) => string\n labelFor?: (call: ToolLoopCall) => string\n runId?: string\n scenarioId?: string\n hooks?: RuntimeHooks\n}\n\n/** Run the bounded tool loop and return the final text + every executed tool\n * outcome. Awaitable — callers needing to stream events to a UI use\n * {@link streamToolLoop}. */\nexport async function runToolLoop(opts: RunToolLoopOptions): Promise<ToolLoopResult> {\n const backstop = opts.maxToolTurns ?? RUNAWAY_BACKSTOP_TURNS\n const render = opts.renderResult ?? defaultRender\n const labelFor = opts.labelFor ?? ((c: ToolLoopCall) => c.toolName)\n const runId = opts.runId ?? `agent-run-${randomSuffix()}`\n const messages: ToolLoopMessage[] = [\n { role: 'system', content: opts.systemPrompt },\n ...(opts.priorMessages ?? []),\n { role: 'user', content: opts.userMessage },\n ]\n const observer = createToolLoopObserver(opts.hooks, runId, opts.scenarioId)\n const toolResults: ToolLoopResult['toolResults'] = []\n let finalText = ''\n let turns = 0\n let accumulatedCostUsd = 0\n const overBudget = () =>\n opts.maxCostUsd !== undefined &&\n opts.costOf !== undefined &&\n accumulatedCostUsd >= opts.maxCostUsd\n const width = opts.maxConcurrentToolCalls ?? DEFAULT_CONCURRENT_TOOL_CALLS\n const isStuck = stuckLoopDetector()\n\n observer.loopBefore(backstop, messages.length)\n\n for (let toolTurn = 0; ; toolTurn++) {\n turns++\n\n // Wall-clock deadline check — before every new turn.\n if (opts.deadlineMs !== undefined && Date.now() >= opts.deadlineMs) {\n observer.loopAfter({ turns, toolResults: toolResults.length, stopReason: 'deadline' })\n return { finalText, toolResults, turns, stopReason: 'deadline', cappedOut: true }\n }\n\n let turnText = ''\n const pending: ToolLoopCall[] = []\n const turnEventId = observer.turnBefore(toolTurn, messages.length)\n for await (const ev of opts.streamTurn([...messages])) {\n if (ev.type === 'text') {\n turnText += ev.text\n finalText += ev.text\n } else if (ev.type === 'tool_call' && opts.isExecutableTool(ev.call.toolName)) {\n pending.push(ev.call)\n }\n }\n if (pending.length === 0) {\n observer.turnAfter(toolTurn, turnEventId, {\n pendingToolCalls: 0,\n finalTextChars: finalText.length,\n })\n break\n }\n\n // Runaway backstop — the model keeps emitting calls past the safety ceiling.\n if (toolTurn >= backstop) {\n observer.turnAfter(toolTurn, turnEventId, {\n pendingToolCalls: pending.length,\n stopReason: 'backstop',\n })\n observer.loopAfter({ turns, toolResults: toolResults.length, stopReason: 'backstop' })\n return { finalText, toolResults, turns, stopReason: 'backstop', cappedOut: true }\n }\n\n if (isStuck(pending)) {\n observer.turnAfter(toolTurn, turnEventId, {\n pendingToolCalls: pending.length,\n stopReason: 'stuck-loop',\n })\n observer.loopAfter({ turns, toolResults: toolResults.length, stopReason: 'stuck-loop' })\n return { finalText, toolResults, turns, stopReason: 'stuck-loop', cappedOut: true }\n }\n\n // The assistant turn that emitted the calls, carrying its tool_calls array,\n // so a strict model reads its own tool use back in OpenAI shape.\n messages.push(assistantToolCallMessage(turnText, pending))\n const queue = turnCalls(pending, width, overBudget, async (call, callIndex) => {\n const callEventId = observer.toolCallBefore(toolTurn, turnEventId, callIndex, call)\n let settled = false\n const outcome = await executeGuarded(opts.executeToolCall, call, (update) => {\n if (!settled) opts.onToolProgress?.(call, update)\n })\n settled = true\n if (opts.maxCostUsd !== undefined && opts.costOf !== undefined) {\n accumulatedCostUsd += opts.costOf(call, outcome)\n }\n observer.toolCallAfter(toolTurn, callEventId, call, outcome)\n return outcome\n })\n const executed: ToolCallOutcome[] = []\n for await (const settlement of queue) {\n if (settlement.status === 'rejected') throw settlement.reason\n executed[settlement.task.value] = settlement.value\n }\n const outcomes: ExecutedToolCall[] = []\n for (const [callIndex, outcome] of executed.entries()) {\n const call = pending[callIndex]!\n const label = labelFor(call)\n const rendered = render(label, outcome)\n toolResults.push({ call, label, outcome })\n outcomes.push({ call, label, outcome, rendered })\n // One role:'tool' message per result, keyed to its call by tool_call_id.\n messages.push(toolResultMessage(call, rendered))\n }\n if (overBudget()) {\n observer.turnAfter(toolTurn, turnEventId, {\n pendingToolCalls: pending.length,\n stopReason: 'budget',\n })\n observer.loopAfter({ turns, toolResults: toolResults.length, stopReason: 'budget' })\n return { finalText, toolResults, turns, stopReason: 'budget', cappedOut: true }\n }\n observer.failureRecovery({\n toolTurn,\n messages,\n turnText,\n outcomes,\n })\n observer.turnAfter(toolTurn, turnEventId, {\n pendingToolCalls: pending.length,\n toolResults: outcomes.map((item) => ({\n toolName: item.call.toolName,\n toolCallId: item.call.toolCallId,\n ok: item.outcome.ok,\n })),\n failedToolCalls: outcomes.filter((item) => !item.outcome.ok).length,\n })\n }\n observer.loopAfter({ turns, toolResults: toolResults.length, stopReason: 'completed' })\n return { finalText, toolResults, turns, stopReason: 'completed', cappedOut: false }\n}\n\n// ── Streaming variant (SSE chat runtimes + per-event telemetry) ────────────\n\nexport type StreamToolLoopYield<Raw> =\n | { kind: 'event'; event: Raw }\n | {\n kind: 'tool_progress'\n toolName: string\n toolCallId?: string\n update: ToolProgressUpdate\n }\n | {\n kind: 'tool_result'\n toolName: string\n toolCallId?: string\n label: string\n outcome: ToolCallOutcome\n }\n | {\n kind: 'capped'\n pending: number\n stopReason: Exclude<ToolLoopStopReason, 'completed'>\n /** On `deadline` only: the conversation after the system prompt, every tool call answered.\n * Passing it back as `priorMessages` with no `userMessage` continues the same turn. */\n messages?: ToolLoopMessage[]\n }\n\nexport interface StreamToolLoopOptions<Raw> {\n systemPrompt: string\n /** Omit to continue a checkpointed turn whose `priorMessages` already end with tool results. */\n userMessage?: string\n priorMessages?: ToolLoopMessage[]\n streamTurn: (messages: ToolLoopMessage[]) => AsyncIterable<Raw>\n extractText: (event: Raw) => string\n extractToolCall: (event: Raw) => ToolLoopCall | null\n isExecutableTool: (toolName: string) => boolean\n executeToolCall: ToolCallExecutor\n /** Runaway-backstop cap. Default 200 — set far above any legitimate workflow. */\n maxToolTurns?: number\n /** Wall-clock deadline in ms since epoch (Date.now()-based). */\n deadlineMs?: number\n /** Maximum total cost in USD. Requires `costOf` to meter each tool call. */\n maxCostUsd?: number\n /** Return the USD cost of one outcome. Required for `maxCostUsd` to work. */\n costOf?: (call: ToolLoopCall, outcome: ToolCallOutcome) => number\n /** How many of one model turn's calls run at once. Default 1: one at a time, in call order.\n * Above 1, each call's `tool_progress` streams as it lands; `tool_result`s and tool messages\n * keep call order. Once `maxCostUsd` is spent no further call starts, and the turn stops\n * with `budget` after the started calls settle. */\n maxConcurrentToolCalls?: number\n renderResult?: (label: string, outcome: ToolCallOutcome) => string\n labelFor?: (call: ToolLoopCall) => string\n runId?: string\n scenarioId?: string\n hooks?: RuntimeHooks\n}\n\n/** Streaming bounded tool loop: yields each raw turn event (the caller maps +\n * telemetries + re-emits it), each `tool_progress` a running tool reports, and\n * each executed `tool_result`; emits one `capped` if it stops for any\n * non-completed reason with calls still pending. */\nexport async function* streamToolLoop<Raw>(\n opts: StreamToolLoopOptions<Raw>,\n): AsyncGenerator<StreamToolLoopYield<Raw>, void, unknown> {\n const backstop = opts.maxToolTurns ?? RUNAWAY_BACKSTOP_TURNS\n const render = opts.renderResult ?? defaultRender\n const labelFor = opts.labelFor ?? ((c: ToolLoopCall) => c.toolName)\n const runId = opts.runId ?? `agent-run-${randomSuffix()}`\n const messages: ToolLoopMessage[] = [\n { role: 'system', content: opts.systemPrompt },\n ...(opts.priorMessages ?? []),\n ...(opts.userMessage !== undefined\n ? [{ role: 'user' as const, content: opts.userMessage }]\n : []),\n ]\n const observer = createToolLoopObserver(opts.hooks, runId, opts.scenarioId)\n let accumulatedCostUsd = 0\n const overBudget = () =>\n opts.maxCostUsd !== undefined &&\n opts.costOf !== undefined &&\n accumulatedCostUsd >= opts.maxCostUsd\n const width = opts.maxConcurrentToolCalls ?? DEFAULT_CONCURRENT_TOOL_CALLS\n const isStuck = stuckLoopDetector()\n\n observer.loopBefore(backstop, messages.length)\n\n for (let toolTurn = 0; ; toolTurn++) {\n // Wall-clock deadline check before every new turn.\n if (opts.deadlineMs !== undefined && Date.now() >= opts.deadlineMs) {\n observer.loopAfter({ turns: toolTurn + 1, stopReason: 'deadline' })\n // A turn boundary: every call is answered, so the history is a resumable checkpoint.\n yield { kind: 'capped', pending: 0, stopReason: 'deadline', messages: messages.slice(1) }\n return\n }\n\n let turnText = ''\n const pending: ToolLoopCall[] = []\n const turnEventId = observer.turnBefore(toolTurn, messages.length)\n for await (const event of opts.streamTurn([...messages])) {\n yield { kind: 'event', event }\n turnText += opts.extractText(event)\n const call = opts.extractToolCall(event)\n if (call && opts.isExecutableTool(call.toolName)) pending.push(call)\n }\n if (pending.length === 0) {\n observer.turnAfter(toolTurn, turnEventId, { pendingToolCalls: 0 })\n observer.loopAfter({ turns: toolTurn + 1, stopReason: 'completed' })\n return\n }\n\n // Runaway backstop.\n if (toolTurn >= backstop) {\n observer.turnAfter(toolTurn, turnEventId, {\n pendingToolCalls: pending.length,\n stopReason: 'backstop',\n })\n observer.loopAfter({ turns: toolTurn + 1, stopReason: 'backstop' })\n yield { kind: 'capped', pending: pending.length, stopReason: 'backstop' }\n return\n }\n\n if (isStuck(pending)) {\n observer.turnAfter(toolTurn, turnEventId, {\n pendingToolCalls: pending.length,\n stopReason: 'stuck-loop',\n })\n observer.loopAfter({ turns: toolTurn + 1, stopReason: 'stuck-loop' })\n yield { kind: 'capped', pending: pending.length, stopReason: 'stuck-loop' }\n return\n }\n\n // The assistant turn that emitted the calls, carrying its tool_calls array,\n // so a strict model reads its own tool use back in OpenAI shape.\n messages.push(assistantToolCallMessage(turnText, pending))\n // Progress streams as it lands, attributed to its call; results stream in call order,\n // each after its own call's progress, and no update is accepted once its call settles.\n const progress: StreamToolLoopYield<Raw>[] = []\n const settled: ToolCallOutcome[] = []\n let wake: (() => void) | undefined\n const queue = turnCalls(pending, width, overBudget, async (call, callIndex) => {\n const callEventId = observer.toolCallBefore(toolTurn, turnEventId, callIndex, call)\n let done = false\n const outcome = await executeGuarded(opts.executeToolCall, call, (update) => {\n if (done) return\n progress.push({\n kind: 'tool_progress',\n toolName: call.toolName,\n toolCallId: call.toolCallId,\n update,\n })\n wake?.()\n })\n done = true\n if (opts.maxCostUsd !== undefined && opts.costOf !== undefined) {\n accumulatedCostUsd += opts.costOf(call, outcome)\n }\n observer.toolCallAfter(toolTurn, callEventId, call, outcome)\n return outcome\n })\n const outcomes: ExecutedToolCall[] = []\n // The queue admits a call only while this generator pulls it, which it does only when it has\n // nothing to yield: call k+1 starts after the consumer has taken result k at width 1.\n let pull: ReturnType<typeof queue.next> | undefined\n try {\n while (outcomes.length < pending.length) {\n const update = progress.shift()\n if (update !== undefined) {\n yield update\n continue\n }\n const outcome = settled[outcomes.length]\n if (outcome !== undefined) {\n const call = pending[outcomes.length]!\n const label = labelFor(call)\n yield {\n kind: 'tool_result',\n toolName: call.toolName,\n toolCallId: call.toolCallId,\n label,\n outcome,\n }\n const rendered = render(label, outcome)\n outcomes.push({ call, label, outcome, rendered })\n // One role:'tool' message per result, keyed to its call by tool_call_id.\n messages.push(toolResultMessage(call, rendered))\n continue\n }\n pull ??= queue.next()\n const woke = new Promise<null>((resolve) => {\n wake = () => resolve(null)\n })\n const step = await Promise.race([pull, woke])\n wake = undefined\n if (step === null) continue\n pull = undefined\n if (step.done) break\n if (step.value.status === 'rejected') throw step.value.reason\n settled[step.value.task.value] = step.value.value\n }\n } finally {\n // Closing early (break, `return()` or a throw) stops admission and settles the started calls.\n await queue.return(undefined)\n }\n if (overBudget()) {\n observer.turnAfter(toolTurn, turnEventId, {\n pendingToolCalls: pending.length,\n stopReason: 'budget',\n })\n observer.loopAfter({ turns: toolTurn + 1, stopReason: 'budget' })\n yield { kind: 'capped', pending: pending.length, stopReason: 'budget' }\n return\n }\n observer.failureRecovery({\n toolTurn,\n messages,\n turnText,\n outcomes,\n })\n observer.turnAfter(toolTurn, turnEventId, {\n pendingToolCalls: pending.length,\n toolResults: outcomes.map((item) => ({\n toolName: item.call.toolName,\n toolCallId: item.call.toolCallId,\n ok: item.outcome.ok,\n })),\n failedToolCalls: outcomes.filter((item) => !item.outcome.ok).length,\n })\n }\n}\n\n/** Run one call; a thrown executor becomes an `executor_error` outcome. */\nasync function executeGuarded(\n execute: ToolCallExecutor,\n call: ToolLoopCall,\n progress: (update: ToolProgressUpdate) => void,\n): Promise<ToolCallOutcome> {\n try {\n return await execute(call, { progress })\n } catch (err) {\n return {\n ok: false,\n code: 'executor_error',\n message: err instanceof Error ? err.message : String(err),\n }\n }\n}\n\n/** One model turn's calls as a task queue keyed by call index: admitted in call order, at most\n * `width` at once, each only when the queue is pulled. The turn's first call always starts and\n * no later one starts once the budget is spent, so width 1 checks it after each call. */\nfunction turnCalls(\n calls: ToolLoopCall[],\n width: number,\n spent: () => boolean,\n run: (call: ToolLoopCall, callIndex: number) => Promise<ToolCallOutcome>,\n) {\n let next = 0\n return runTaskQueue<number, ToolCallOutcome>({\n concurrency: width,\n take: () =>\n next < calls.length && (next === 0 || !spent())\n ? { id: String(next), value: next++ }\n : undefined,\n execute: ({ value }) => run(calls[value]!, value),\n })\n}\n\ninterface ExecutedToolCall {\n call: ToolLoopCall\n label: string\n outcome: ToolCallOutcome\n rendered: string\n}\n\ninterface NotifyToolFailureRecoveryOptions {\n hooks?: RuntimeHooks\n runId: string\n scenarioId?: string\n stepIndex: number\n messages: ToolLoopMessage[]\n turnText: string\n outcomes: ExecutedToolCall[]\n}\n\ninterface NotifyToolLoopEventOptions {\n hooks?: RuntimeHooks\n runId: string\n scenarioId?: string\n target: 'agent.run' | 'agent.turn' | 'agent.tool_call'\n phase: 'before' | 'after' | 'error' | 'event'\n id?: string\n stepIndex?: number\n parentId?: string\n payload?: Record<string, unknown>\n metadata?: Record<string, unknown>\n}\n\ninterface ToolLoopObserver {\n loopBefore(maxToolTurns: number, messageCount: number): void\n loopAfter(payload: Record<string, unknown>): void\n turnBefore(toolTurn: number, messageCount: number): string\n turnAfter(toolTurn: number, turnEventId: string, payload: Record<string, unknown>): void\n toolCallBefore(\n toolTurn: number,\n turnEventId: string,\n callIndex: number,\n call: ToolLoopCall,\n ): string\n toolCallAfter(\n toolTurn: number,\n callEventId: string,\n call: ToolLoopCall,\n outcome: ToolCallOutcome,\n ): void\n failureRecovery(options: {\n toolTurn: number\n messages: ToolLoopMessage[]\n turnText: string\n outcomes: ExecutedToolCall[]\n }): void\n}\n\nfunction createToolLoopObserver(\n hooks: RuntimeHooks | undefined,\n runId: string,\n scenarioId: string | undefined,\n): ToolLoopObserver {\n const loopEventId = `${runId}:agent.run`\n return {\n loopBefore: (maxToolTurns, messageCount) => {\n notifyToolLoopEvent({\n hooks,\n runId,\n scenarioId,\n target: 'agent.run',\n phase: 'before',\n id: `${loopEventId}:before`,\n payload: { maxToolTurns, messageCount },\n })\n },\n loopAfter: (payload) => {\n notifyToolLoopEvent({\n hooks,\n runId,\n scenarioId,\n target: 'agent.run',\n phase: 'after',\n id: `${loopEventId}:after`,\n payload,\n })\n },\n turnBefore: (toolTurn, messageCount) => {\n const turnEventId = `${loopEventId}:${toolTurn}`\n notifyToolLoopEvent({\n hooks,\n runId,\n scenarioId,\n target: 'agent.turn',\n phase: 'before',\n id: turnEventId,\n stepIndex: toolTurn,\n parentId: loopEventId,\n payload: { messageCount },\n })\n return turnEventId\n },\n turnAfter: (toolTurn, turnEventId, payload) => {\n notifyToolLoopEvent({\n hooks,\n runId,\n scenarioId,\n target: 'agent.turn',\n phase: 'after',\n id: `${turnEventId}:after`,\n stepIndex: toolTurn,\n parentId: turnEventId,\n payload,\n })\n },\n toolCallBefore: (toolTurn, turnEventId, callIndex, call) => {\n const callEventId = `${turnEventId}:tool-call:${callIndex}`\n notifyToolLoopEvent({\n hooks,\n runId,\n scenarioId,\n target: 'agent.tool_call',\n phase: 'before',\n id: callEventId,\n stepIndex: toolTurn,\n parentId: turnEventId,\n payload: toolCallPayload(call),\n })\n return callEventId\n },\n toolCallAfter: (toolTurn, callEventId, call, outcome) => {\n notifyToolLoopEvent({\n hooks,\n runId,\n scenarioId,\n target: 'agent.tool_call',\n phase: 'after',\n id: `${callEventId}:after`,\n stepIndex: toolTurn,\n parentId: callEventId,\n payload: { ...toolCallPayload(call), outcome: outcomePayload(outcome) },\n })\n },\n failureRecovery: (options) => {\n notifyToolFailureRecovery({\n hooks,\n runId,\n scenarioId,\n stepIndex: options.toolTurn,\n messages: options.messages,\n turnText: options.turnText,\n outcomes: options.outcomes,\n })\n },\n }\n}\n\nfunction notifyToolLoopEvent(options: NotifyToolLoopEventOptions): void {\n notifyRuntimeHookEvent(options.hooks, {\n id: options.id ?? `${options.runId}:${options.target}:${options.phase}`,\n runId: options.runId,\n scenarioId: options.scenarioId,\n target: options.target,\n phase: options.phase,\n timestamp: Date.now(),\n stepIndex: options.stepIndex,\n parentId: options.parentId,\n payload: options.payload,\n metadata: { producer: 'tool-loop', ...options.metadata },\n })\n}\n\nfunction notifyToolFailureRecovery(options: NotifyToolFailureRecoveryOptions): void {\n const failed = options.outcomes.filter((item) => !item.outcome.ok)\n if (failed.length === 0) return\n\n const evidence: RuntimeDecisionEvidenceRef[] = []\n for (const item of failed) {\n const id = item.call.toolCallId ?? `${options.stepIndex}:${item.label}`\n evidence.push({\n source: 'tool_call',\n id,\n detail: `${item.call.toolName} ${stringifySafe(item.call.args, 2_000)}`,\n metadata: { toolName: item.call.toolName, label: item.label },\n })\n evidence.push({\n source: 'tool_result',\n id: `${id}:result`,\n detail: item.rendered,\n metadata: failureMetadata(item.outcome),\n })\n }\n\n notifyRuntimeDecisionPoint(options.hooks, {\n id: `${options.runId}:agent.turn:${options.stepIndex}:failure-recovery`,\n runId: options.runId,\n scenarioId: options.scenarioId,\n stepIndex: options.stepIndex,\n kind: 'retry',\n candidateActions: [...FAILURE_RECOVERY_ACTIONS],\n context: renderDecisionContext(options.messages, options.turnText, options.outcomes),\n evidence,\n metadata: {\n target: 'failure-recovery',\n source: 'agent.turn',\n failedToolCount: failed.length,\n toolNames: failed.map((item) => item.call.toolName),\n },\n })\n}\n\nfunction toolCallPayload(call: ToolLoopCall): Record<string, unknown> {\n return {\n toolName: call.toolName,\n toolCallId: call.toolCallId,\n argsPreview: stringifySafe(call.args, 2_000),\n }\n}\n\nfunction outcomePayload(outcome: ToolCallOutcome): Record<string, unknown> {\n if (!outcome.ok) {\n return {\n ok: false,\n code: outcome.code,\n message: trimText(outcome.message, 2_000),\n status: outcome.status,\n }\n }\n return {\n ok: true,\n resultPreview: stringifySafe(outcome.result, 2_000),\n }\n}\n\nfunction failureMetadata(outcome: ToolCallOutcome): Record<string, unknown> | undefined {\n if (outcome.ok) return undefined\n return {\n code: outcome.code,\n message: outcome.message,\n status: outcome.status,\n }\n}\n\nfunction renderDecisionContext(\n messages: ToolLoopMessage[],\n turnText: string,\n outcomes: ExecutedToolCall[],\n): string {\n const recent = messages.slice(-6).map((message) => `[${message.role}]\\n${message.content ?? ''}`)\n const assistant = turnText.trim() ? [`[assistant]\\n${turnText}`] : []\n const toolResults = [`[tool results]\\n${outcomes.map((item) => item.rendered).join('\\n')}`]\n return trimText(\n [...recent, ...assistant, ...toolResults].join('\\n\\n'),\n DEFAULT_DECISION_CONTEXT_CHARS,\n )\n}\n\n/** Stuck-loop detection across model turns: true once {@link STUCK_LOOP_THRESHOLD}\n * consecutive turns issue the same call set. Repeats inside one parallel batch\n * are not a loop; each runs and its result reaches the model. */\nfunction stuckLoopDetector(): (batch: ToolLoopCall[]) => boolean {\n let last: string | undefined\n let count = 0\n return (batch) => {\n const signature = [...new Set(batch.map(canonicalCallHash))].sort().join('\\n')\n count = signature === last ? count + 1 : 1\n last = signature\n return count >= STUCK_LOOP_THRESHOLD\n }\n}\n\n/** Canonical identifier for a tool call used by stuck-loop detection.\n * Keys are sorted so `{b:1,a:2}` and `{a:2,b:1}` produce the same hash. */\nfunction canonicalCallHash(call: ToolLoopCall): string {\n const sortedArgs = Object.fromEntries(\n Object.entries(call.args).sort(([a], [b]) => a.localeCompare(b)),\n )\n return `${call.toolName}:${JSON.stringify(sortedArgs)}`\n}\n\nfunction stringifySafe(value: unknown, max: number): string {\n let text: string\n try {\n text = JSON.stringify(value) ?? String(value)\n } catch {\n text = String(value)\n }\n return trimText(text, max)\n}\n\nfunction trimText(text: string, max: number): string {\n if (text.length <= max) return text\n return `${text.slice(0, max)}…`\n}\n\nfunction randomSuffix(len = 8): string {\n return Math.random()\n .toString(36)\n .slice(2, 2 + len)\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;AA6CA,MAAM,yBAAyB;AAC/B,MAAM,iCAAiC;AACvC,MAAM,2BAA2B;CAAC;CAAS;CAAU;CAAY;AAAM;;;AAGvE,MAAM,uBAAuB;;AAE7B,MAAM,gCAAgC;;;;AAsCtC,SAAS,WAAW,MAA4B;CAC9C,OAAO,KAAK,cAAc,QAAQ,KAAK;AACzC;;;AAIA,SAAS,yBAAyB,UAAkB,SAA0C;CAC5F,OAAO;EACL,MAAM;EACN,SAAS,SAAS,KAAK,KAAK;EAC5B,YAAY,QAAQ,KAAK,UAAU;GACjC,GAAG,KAAK;GACR,IAAI,WAAW,IAAI;GACnB,MAAM;GACN,UAAU;IAAE,MAAM,KAAK;IAAU,WAAW,KAAK,UAAU,KAAK,IAAI;GAAE;EACxE,EAAE;CACJ;AACF;;AAGA,SAAS,kBAAkB,MAAoB,SAAkC;CAC/E,OAAO;EAAE,MAAM;EAAQ,cAAc,WAAW,IAAI;EAAG;CAAQ;AACjE;AA8BA,SAAS,cAAc,OAAe,SAAkC;CACtE,IAAI,QAAQ,IAAI,OAAO,KAAK,MAAM,SAAS,KAAK,UAAU,QAAQ,MAAM;CACxE,OAAO,KAAK,MAAM,aAAa,QAAQ,KAAK,KAAK,QAAQ;AAC3D;;;;AA0DA,eAAsB,YAAY,MAAmD;CACnF,MAAM,WAAW,KAAK,gBAAgB;CACtC,MAAM,SAAS,KAAK,gBAA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AAO,SACL;EAAC,GAAG;EAAQ,GAAG;EAAW,GAAG;CAAW,CAAC,CAAC,KAAK,MAAM,GACrD,8BACF;AACF;;;;AAKA,SAAS,oBAAwD;CAC/D,IAAI;CACJ,IAAI,QAAQ;CACZ,QAAQ,UAAU;EAChB,MAAM,YAAY,CAAC,GAAG,IAAI,IAAI,MAAM,IAAI,iBAAiB,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,KAAK,IAAI;EAC7E,QAAQ,cAAc,OAAO,QAAQ,IAAI;EACzC,OAAO;EACP,OAAO,SAAS;CAClB;AACF;;;AAIA,SAAS,kBAAkB,MAA4B;CACrD,MAAM,aAAa,OAAO,YACxB,OAAO,QAAQ,KAAK,IAAI,CAAC,CAAC,MAAM,CAAC,IAAI,CAAC,OAAO,EAAE,cAAc,CAAC,CAAC,CACjE;CACA,OAAO,GAAG,KAAK,SAAS,GAAG,KAAK,UAAU,UAAU;AACtD;AAEA,SAAS,cAAc,OAAgB,KAAqB;CAC1D,IAAI;CACJ,IAAI;EACF,OAAO,KAAK,UAAU,KAAK,KAAK,OAAO,KAAK;CAC9C,QAAQ;EACN,OAAO,OAAO,KAAK;CACrB;CACA,OAAO,SAAS,MAAM,GAAG;AAC3B;AAEA,SAAS,SAAS,MAAc,KAAqB;CACnD,IAAI,KAAK,UAAU,KAAK,OAAO;CAC/B,OAAO,GAAG,KAAK,MAAM,GAAG,GAAG,EAAE;AAC/B;AAEA,SAAS,aAAa,MAAM,GAAW;CACrC,OAAO,KAAK,OAAO,CAAC,CACjB,SAAS,EAAE,CAAC,CACZ,MAAM,GAAG,IAAI,GAAG;AACrB"}
|
package/dist/tui/index.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { $d as PursuitProjection, E as Budget, Ga as NodeExecutionIdentity, Ka as ProfileMaterializationReceipt, Ra as ExecutionBindingReceipt, Sb as RouteFlowEvent, Xd as PursuitNodeProjection, aa as ResultBlobStore, dC as HarnessTranscriptArtifact, ef as PursuitRunProjection, j as Spend, mC as HarnessTranscriptEvidence, zr as provisionSupervisor } from "../types-
|
|
1
|
+
import { $d as PursuitProjection, E as Budget, Ga as NodeExecutionIdentity, Ka as ProfileMaterializationReceipt, Ra as ExecutionBindingReceipt, Sb as RouteFlowEvent, Xd as PursuitNodeProjection, aa as ResultBlobStore, dC as HarnessTranscriptArtifact, ef as PursuitRunProjection, j as Spend, mC as HarnessTranscriptEvidence, zr as provisionSupervisor } from "../types-BYiwLO2L.js";
|
|
2
2
|
import { c as AgentCandidateArtifactPort } from "../workspace-archive-DS9E9tUr.js";
|
|
3
3
|
type BaselineAuthority = {
|
|
4
4
|
readonly kind: 'retained-workspace' | 'git-object' | 'git-diff';
|
package/dist/tui/index.js
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import { t as provisionSupervisor } from "../provision-supervisor-
|
|
1
|
+
import { t as provisionSupervisor } from "../provision-supervisor-DdsrpA3I.js";
|
|
2
2
|
import { _ as topAgentMetadata, a as buildSupervisorView, d as topSnapshot, g as readTopAgentInspection, h as readTopAgentHistory, m as harnessSessionRows, o as isSpawnEvent, p as createTopAgentStream, r as serveTopWeb, s as loadTopSnapshot, t as TOP_SNAPSHOT_RECONCILE_MS, v as topAgentWorker } from "../top-web-oDO4xhNE.js";
|
|
3
3
|
export { TOP_SNAPSHOT_RECONCILE_MS, createTopAgentStream, harnessSessionRows, isSpawnEvent as isTopJournalEvent, loadTopSnapshot, topSnapshot as projectTopSnapshot, buildSupervisorView as projectTopSupervisor, provisionSupervisor, readTopAgentHistory, readTopAgentInspection, serveTopWeb, topAgentMetadata, topAgentWorker };
|
|
@@ -6407,6 +6407,15 @@ interface ProviderExecutorOptions {
|
|
|
6407
6407
|
* `false` ends the execution on the refused turn.
|
|
6408
6408
|
*/
|
|
6409
6409
|
unavailablePause?: UnavailablePausePolicy | false;
|
|
6410
|
+
/**
|
|
6411
|
+
* How long a retained execution waits for room, in ms, after Sandbox refuses it placement (a
|
|
6412
|
+
* 503 such as `CAPACITY_EXHAUSTED`) while it is acquired or observed, before the refusal counts
|
|
6413
|
+
* as a failed attempt. The same execution is reattached after each wait, which honors
|
|
6414
|
+
* Retry-After and lasts at most 30 s. Acquisition in a run with a deadline waits until the
|
|
6415
|
+
* deadline instead. Default 10 min; a value that is not a non-negative number fails the
|
|
6416
|
+
* executor's construction with a `ValidationError`.
|
|
6417
|
+
*/
|
|
6418
|
+
capacityRetryWindowMs?: number;
|
|
6410
6419
|
}
|
|
6411
6420
|
/** Provider object or registry name accepted by runtime provider adapters.
|
|
6412
6421
|
* @experimental */
|
|
@@ -19809,4 +19818,4 @@ interface KnowledgeReadinessDecision {
|
|
|
19809
19818
|
nonBlockingGapIds: string[];
|
|
19810
19819
|
}
|
|
19811
19820
|
export { BlockedToolReport as $, LoopLineageOptions as $C, RetainedRunEffect as $S, FeedbackRating as $_, ExecutorCancellationRequest as $a, DEFAULT_PEER_MAIL_LIMITS as $b, LoopCampaignDispatchOptions as $c, PursuitProjection as $d, IsolatedCheckOutputEvidence as $f, RouterResponseReceipt as $g, Inbox as $h, DesignerToolsEnv as $i, strategyAuthorContract as $l, CoordinationRejectReason as $m, searchPresets as $n, structuralRollout as $o, ReservationRejection as $p, workerFromInteractiveProvider as $r, ResolveSandboxClientOptions as $s, AnalystAuthoring as $t, PersonaExecutors as $u, HarnessUsage as $v, SqlAdapter as $x, SanitizedKnowledgeRequirement as $y, ResourceSpend as A, RetainedHarnessTranscriptDescriptor as AC, AgentEvalError$1 as AS, DelegationResumeContext as A_, Agent as Aa, QuestionEscalationOutcome as Ab, PairedCommandInput as Ac, NextPursuitVersion as Ad, EdgeDeliveryOutcome as Af, WorkerProgress as Ag, McpEventRecord as Ah, graphFromStored as Ai, ArtifactHandle as Al, StopDecision as Am, gitWorkspace as An, CheckExecChannel as Ao, dumbContinuationPassPrompt as Ap, RemoteSupervisorSteerResult as Ar, acquireSandbox as As, CreateSandboxOptions$1 as At, PanelVerdict as Au, ExecutorResultMapping as Av, ToolStepInput as Ax, bestSoFar as Ay, SpawnOpts as B, ExecutorToolCall as BC, ReconnectRetainedRunOptions as BS, DelegateResearchArgs as B_, ExecutorMaterialization as Ba, AuthorizedDownMessage as Bb, McpEndpoint as Bc, SupervisePursuitError as Bd, runGraph as Bf, resolveMcpServerLaunch as Bg, CliSeam as Bh, taskShapeDigest as Bi, sample as Bl, DeliveredOutput as Bm, createRootHandle as Bn, StructuralRolloutResult as Bo, WorkerTraceResolver as Bp, ProfileRegistryDir as Br, startRetainedRunInEnvironment as Bs, makeFinding$1 as Bt, Verify as Bu, sentinelCompletion as Bv, AuthoredAnalystDefinition as Bx, OtelExportConfig as By, RuntimeFailureCause as C, BoundHarnessSession as CC, readRunCancelRequest as CS, createFleetWorkspaceExecutor as C_, RootStreamReceipt as Ca, RouteGate as Cb, CreateScopeAnalystOptions as Cc, assertDeclaredCheck as Cd, GraphCheckNode as Cf, ProviderPlacement as Cg, environmentReader as Ch, GraphRunRecord as Ci, connectStdioMcp as Cl, SupervisorToolInvocationContext as Cm, copyUntrackedIntoClone as Cn, ProfileRichnessThresholds as Co, PromptHandle as Cp, workerInboxFileFromEventDir as Cr, TurnResult as Cs, AgentSessionRef as Ct, FanoutSynthesis as Cu, FileDelegationStoreOptions as Cv, RuntimeRunRow as Cw, EventBus as Cx, renderLeaderboardSvg as Cy, BudgetOverspend as D, HarnessTranscriptReadLimits as DC, contentAddress as DS, runDetachedTurn as D_, ExecutorFactory as Da, EscalateQuestion as Db, createScopeAnalyst as Dc, declaredCheckJudge as Dd, GraphCommandCheck as Df, ExecutorProgress as Dg, createMcpServer as Dh, digestOfGraph as Di, AgenticSurface as Dl, NoProgressForOptions as Dm, Workspace as Dn, profileRichnessFinding as Do, createPromptRegistry as Dp, RemoteSupervisorCancelResult as Dr, createSandboxLineage as Ds, CheckpointRef as Dt, Panel as Du, CheckVerdict as Dv, defaultToolDetectors as Dx, AnytimeTaskCurve as Dy, Budget as E, HarnessTranscriptMetadata as EC, InMemorySpawnJournal as ES, RunDetachedTurnOptions as E_, ExecutorContext as Ea, ChildQuestionInbox as Eb, buildSteerContext as Ec, declaredCheckDigest as Ed, GraphCheckPlacement as Ef, DEFAULT_STALL_AFTER_MS as Eg, McpServerOptions as Eh, StoredGraphInput as Ei, AgenticRunResult as El, AllWorkersStalledOptions as Em, Shell as En, defaultProfileRichnessThresholds as Eo, analyzesFindingsReportPrompt as Ep, RemoteSupervisorAgent as Er, SandboxLineageHandle as Es, AnalystFinding$1 as Et, LoopUntilState as Eu, CheckUnavailableError as Ev, WatchTraceOptions as Ex, AnytimeStrategySummary as Ey, NodeId as F, ProviderWorkspaceCaptureProvenance as FC, NotFoundError as FS, DelegationTaskQueueOptions as F_, UnconfirmedTeardown as Fa, QuestionPolicy as Fb, CanonicalObservedModelParts as Fc, SettledPursuitVersion as Fd, GraphResult as Ff, BridgeSeam as Fg, createDelegateHandler as Fh, lookupGraph as Fi, SurfaceScore as Fl, plateau as Fm, analyzeTrace as Fn, CheckSourceCtx as Fo, SupervisorSpanAttributes as Fp, ProvisionSupervisorConnection as Fr, PrivateCasNamespaceObject as Fs, ResourceRequest$1 as Ft, ScopeWidenGate as Fu, CompletionEvidence as Fv, AnalystKind as Fx, WaterfallSpan as Fy, TreeView as G, Driver as GC, RetainedInteractiveEnvironmentAdmission as GS, DelegationError as G_, NodeExecutionIdentity as Ga, DownMessageDeliveryOutcome as Gb, BenchmarkConfig as Gc, RunReopen as Gd, portableContinuationPolicySchema as Gf, SandboxToolPartState as Gg, RouterToolsSeam as Gh, DispatchReport as Gi, StrategyArtifacts as Gl, CoordinationAuthentication as Gm, createFencedSqlRunContext as Gn, defaultExtractCandidate as Go, RunParkingRecord as Gp, profileRegistry as Gr, startRetainedInteractiveRun as Gs, SurfaceDiff as Gt, WidenSpec as Gu, CodexRolloutStoreReader as Gv, RunLocalHarnessOptions as Gx, createOtelExporter as Gy, SpawnRejection as H, UsageEvent as HC, RecoverRetainedRunOptions as HS, DelegateUiAuditArgs as H_, MaterializedExecutionIdentity as Ha, ContinuityMode as Hb, createMcpEnvironment as Hc, SupervisedPursuitResult as Hd, defaultEdgeTraversalCap as Hf, secretEnvOfMcpServer as Hg, CliWorktreeSeam as Hh, graphFileNeedSchema as Hi, AuthoredStrategy as Hl, FinalizerSettled as Hm, validateStoredGraph as Hn, canDisplace as Ho, ParkedRun as Hp, bestProfileFor as Hr, claimRetainedInteractiveControl as Hs, createVerifierEnvironment as Ht, Widen as Hu, CodexForkBoundary as Hv, DefinedAnalystRecord as Hx, OtelExporter as Hy, NodeSnapshot as I, ProviderWorkspaceCaptureReceipt as IC, ValidationError as IS, SubmitInput as I_, WidenGate as Ia, QuestionRecord as Ib, SnapshotKind as Ic, VersionJudge as Id, GraphTopology as If, KeyProvider as Ig, createExecutorRegistry as Ih, pickBestGraph as Ii, breadthStrategy as Il, ReentryContinuity as Im, WorkerToolTraceArtifact as In, RepairStop as Io, SupervisorSpanOptions as Ip, ProvisionSupervisorRequest as Ir, PrivateCasNamespaceRetirement as Is, SandboxEvent$1 as It, SteerContext as Iu, CompletionPolicy as Iv, AnalystLensOutput as Ix, createWaterfallCollector as Iy, DriverAttemptRecord as J, LoopDecisionPayload as JC, RetainedRunAdmission as JS, DelegationHistoryEntry as J_, UnknownMaterializationReason as Ja, MapItemFailurePolicy as Jb, BenchmarkStrategySummary as Jc, PursuitNodeCost as Jd, IsolatedCheckCommandEvidence as Jf, mapSandboxToolEvent as Jg, SandboxSteeringOptions as Jh, RollingDispatchOptions as Ji, adaptiveRefine as Jl, CoordinationPublicAddress as Jm, SearchSpec as Jn, modelAuthoredChecks as Jo, BudgetPoolRestore as Jp, profileBridgeWireModel as Jr, RetainedInteractiveAdmissionHook as Js, SurfaceReader as Jt, DefinePersonaInput as Ju, CodexStoreDelta as Jv, LocalHarness as Jx, RuntimeStreamEventCollector as Jy, EvidencePendingEvent as K, ExecCtx as KC, RetainedInteractiveIntentAdmission as KS, DelegationFeedbackSnapshot as K_, ProfileMaterializationReceipt as Ka, DownMessageEvent as Kb, BenchmarkLift as Kc, PursuitObserverDelivery as Kd, IsolatedCheckBox as Kf, createSandboxToolPartState as Kg, SandboxSeam as Kh, DispatchStopReason as Ki, StrategyCtx as Kl, CoordinationControlAccess as Km, CompiledSearchSpec as Kn, defaultStructuralRolloutPolicy as Ko, readRunParking as Kp, profileRunsForName as Kr, ReconnectRetainedInteractiveRunOptions as Ks, SurfaceReadBox as Kt, WinnerStrategy as Ku, CodexRolloutStoreRef as Kv, runLocalHarness as Kx, loopEventToOtelSpan as Ky, NodeStatus as L, ProviderWorkspaceCaptureResult as LC, NativeContextContinuationExecution as LS, SubmitOutput as L_, AgentExecutionRef as La, QuestionUrgency as Lb, canonicalObservedModelParts as Lc, VersionVerdict as Ld, RunGraphOptions as Lf, ResolvedMcpServerLaunch as Lg, ExecutorConfig as Lh, recordGraphRun as Li, depthStrategy as Ll, ReentryTaskInput as Lm, parseWorkerToolTraceArtifact as Ln, StructuralRolloutConfig as Lo, SupervisorSpanOutcome as Lp, ProvisionedSupervisor as Lr, reconnectRetainedRun as Ls, SandboxInstance$1 as Lt, TrajectoryNode as Lu, CompletionVerdict as Lv, AnalystRegistry$1 as Lx, RunAgentRoundsOptions as Ly, SpendChannel as M, resolveHarnessTranscriptCapture as MC, BackendTransportError as MS, DelegationResumeTick as M_, ResumedKeyState as Ma, QuestionEscalationTarget as Mb, PairedCommandOptions as Mc, PursuitVersionChain as Md, GraphEdge as Mf, readWorkerProgress as Mg, DelegateError as Mh, graphRunsFor as Mi, RunAgenticOptions as Ml, allWorkersStalled as Mm, localShell as Mn, CheckRunContext as Mo, kernelPromptRegistry as Mp, RemoteWorkerEvents as Mr, S3PrivateCasStoreOptions as Ms, ExecResult as Mt, RenderCorpusToInstructionsOptions as Mu, mapExecutorResult as Mv, createPushTraceSource as Mx, renderAnytimeTable as My, SpendGap as N, retainHarnessTranscript as NC, ConfigError as NS, DelegationRunContext as N_, ResumedWork as Na, QuestionLevel as Nb, measurePairedCommands as Nc, PursuitVersionStop as Nd, GraphEdgeCapError as Nf, BridgeHarnessStore as Ng, DelegateHandlerOptions as Nh, listGraphRuns as Ni, StrategyMessage as Nl, anyOf as Nm, runInWorkspace as Nn, CheckRunner as No, naiveContinuationPrompt as Np, connectRemoteSupervisor as Nr, createS3PrivateCasStore as Ns, ForkRequest as Nt, ScopeAnalyst as Nu, verdictFromJudgeScore as Nv, AnalystAssignmentRecord as Nx, WaterfallCollector as Ny, BudgetViolation as O, HarnessTranscriptReadOptions as OC, Redactor as OS, DelegationArgs as O_, ExecutorRegistry as Oa, Question as Ob, registryScopeAnalyst as Oc, readDeclaredCheck as Od, GraphFromStoredOptions as Of, ScopeProgressInput as Og, EventSubscription as Oh, graphCorpusSummary as Oi, AgenticTask as Ol, PlateauOptions as Om, WorkspaceCommit as On, supervisorInstructions as Oo, delegatesWorkerBriefPrompt as Op, RemoteSupervisorControl as Or, SandboxEvidenceReceipt as Os, CheckpointRequest as Ot, PanelJudge as Ou, CompletionCheckContext as Ov, watchTrace as Ox, anytimeReport as Oy, Handle as P, ProviderWorkspaceAttemptProvenance as PC, JudgeError as PS, DelegationTaskQueue as P_, Scope as Pa, QuestionOption as Pb, observationFromRegistry as Pc, PursuitVersions as Pd, GraphNode as Pf, BridgeModelCredential as Pg, DelegateResult as Ph, loadGraph as Pi, StrategyShotResult as Pl, noProgressFor as Pm, TrajectoryAnalysis as Pn, CheckSource as Po, promptHandle as Pp, connectRemoteSupervisorControl as Pr, PrivateCasNamespaceInventory as Ps, PlacementInfo as Pt, ScopeAnalyzeInput as Pu, CompletionAnalyst as Pv, AnalystFindingEvent as Px, WaterfallReport as Py, DriverRepromptRefusal as Q, LoopIterationStartedPayload as QC, RetainedRunDispatchedAdmission as QS, DelegationStatusResult as Q_, ExecutorCancellation as Qa, AUTHORITY_MARKERS as Qb, runBenchmark as Qc, PursuitNodeUsage as Qd, IsolatedCheckOutputDeclaration as Qf, sumSandboxUsage as Qg, AuthorityInboxMessage as Qh, DesignerRunGraphEnv as Qi, sampleThenRefine as Ql, CoordinationHttpAudit as Qm, compileSearchSpec as Qn, selectBestIndex as Qo, ReservationHolder as Qp, InteractiveWorkerResult as Qr, StartRetainedInteractiveRunOptions as Qs, harvestSurfaceDiffs as Qt, PersonaContext as Qu, readCodexRolloutSession as Qv, openSqlRunStore as Qx, SanitizedKnowledgeReadinessReport as Qy, RetainedExecutionState as R, ProviderWorkspaceEntryMetadata as RC, NativeContextContinuationHandle as RS, DelegateCodeArgs as R_, ExecutionBindingReceipt as Ra, questionEscalationTargets as Rb, observedModelHasSnapshot as Rc, assertPursuitVersions as Rd, RunGraphTestOptions as Rf, envKeyProvider as Rg, createExecutor as Rh, recordStoredGraphRun as Ri, refine as Rl, UNPROVEN_CONTINUITY as Rm, DEFAULT_MAX_DEPTH as Rn, StructuralRolloutMessage as Ro, SupervisorSpanRecorder as Rp, SupervisorCleanupReceipt as Rr, recoverRetainedRun as Rs, WorkspaceRequest as Rt, TrajectoryReport as Ru, completionAuthorizes as Rv, AnalystRunContext as Rx, runAgentRounds as Ry, RuntimeStreamEvent as S, persistHarnessTranscript as SC, cancelRunAsync as SS, SiblingSandboxExecutorOptions as S_, RootProviderModelEvidence as Sa, RouteFlowEvent as Sb, widen as Sc, DeclaredCheckStateCapture as Sd, SuperviseRegistryTable as Sf, UnavailablePausePolicy as Sg, SpawnResourceReader as Sh, GraphRunQuery as Si, StdioMcpServerSpec as Sl, SupervisorToolDescriptor as Sm, UntrackedCopyStats as Sn, ProfileRichness as So, withRunContext as Sp, supervisorRunsRoot as Sr, SandboxRunAbortError as Ss, AgentSession as St, FanoutOptions as Su, FileDelegationStore as Sv, RuntimeRunPersistenceAdapter as Sw, BusStats as Sx, renderLeaderboardMarkdown as Sy, RuntimeFailureOwner as T, HarnessFileBinding as TC, InMemoryResultBlobStore as TS, DetachedTurn as T_, AgentSpec as Ta, RouteWhen as Tb, assertTraceDerivedFindings as Tc, declaredCheckDeliverable as Td, GraphCheckOutput as Tf, ActivityNote as Tg, McpServer as Th, StoredGraph as Ti, AgenticOptions as Tl, SupervisorProfile as Tm, GitWorkspaceOptions as Tn, assessAuthoredProfile as To, RegisteredPrompt as Tp, writeWorkerSteerAsync as Tr, SandboxLineage as Ts, AgentTurnResult$2 as Tt, LoopUntilSpec as Tu, CoderTask as Tv, startRuntimeRun as Tw, createEventBus as Tx, AnytimeReport as Ty, SubtreeResult as U, AgentRunSpec as UC, RecoverRetainedRunResult as US, DelegateUiAuditConfig as U_, MaterializedModelIdentity as Ua, DownMessageAuthorizationInput as Ub, sanitizeMcpToolSchema as Uc, superviseGraphPursuit as Ud, GraphRouteError as Uf, SandboxLeafOut as Ug, ProviderSeam as Uh, graphFileSchema as Ui, ShotSpec as Ul, SupervisorFinalizer as Um, FencedSqlRunContext as Un, compareCheckOutcomes as Uo, RunParkedError as Up, loadProfile as Ur, reconnectRetainedInteractiveRun as Us, BoxSurfaceReaderOptions as Ut, WidenDecision as Uu, CodexRolloutIdentity as Uv, CodexExecutionEvidence as Ux, OtelSpan as Uy, SpawnPrior as V, TokenUsageProvenance as VC, RecoverRetainedRunIntentOptions as VS, DelegateResearchConfig as V_, ExecutorNodeContext as Va, ContinuationInstruction as Vb, McpEnvironmentOptions as Vc, SupervisePursuitOptions as Vd, runGraphWithTestBrain as Vf, resolveSecretEnv as Vg, CliWorktreeBridgeSeam as Vh, GraphTriggerBinding as Vi, AuthorStrategyOptions as Vl, FinalizeContext as Vm, ValidateStoredGraphOptions as Vn, VisibleCheck as Vo, DeadlineCheckIn as Vp, ProfileRunRecord as Vr, ClaimRetainedInteractiveControlOptions as Vs, VerifierEnvironmentOptions as Vt, VerifySpec as Vu, stopSentinel as Vv, AuthoredAnalystLimits as Vx, OtelExportStats as Vy, SubtreeSummary as W, DefaultVerdict$2 as WC, RetainedInteractiveAdmission as WS, DelegateUiAuditRoute as W_, MaterializedResources as Wa, DownMessageDeliveryAttempt as Wb, BenchmarkCell as Wc, supervisePursuit as Wd, PortableContinuationPolicy as Wf, SandboxOutputMarker as Wg, RouterSeam as Wh, graphRouteWhenSchema as Wi, Strategy as Wl, bestDelivered as Wm, SqlRunContextOptions as Wn, composeCheckSources as Wo, RunParkingPolicy as Wp, pickBestProfile as Wr, recoverRetainedInteractiveRun as Ws, HarvestSurfaceDiffsOptions as Wt, WidenLineage as Wu, CodexRolloutSession as Wv, LocalHarnessResult as Wx, buildLoopOtelSpans as Wy, DriverContinuationRecord as X, LoopIterationDispatchPayload as XC, RetainedRunCancelOptions as XS, DelegationResultPayload as X_, Executor as Xa, MapSpawnMarker as Xb, Environment as Xc, PursuitNodeProjection as Xd, IsolatedCheckResult as Xf, SandboxUsageLedger as Xg, SteerableSandboxSession as Xh, queueOf as Xi, authorStrategy as Xl, CoordinationTransportOptions as Xm, SearchSpecOwnedOption as Xn, resolveEntrySymbol as Xo, LeakedReservation as Xp, InteractiveWorkerKeyInput as Xr, RetainedInteractiveRunHandle as Xs, boxSurfaceReader as Xt, Outcome as Xu, createCodexRolloutStoreReader as Xv, CodexExecutionPolicy as Xx, RuntimeStreamEventSummary as Xy, DriverAttemptStop as Y, LoopEndedPayload as YC, RetainedRunAdmissionHook as YS, DelegationProgress as Y_, EnvironmentTeardownReceipt as Ya, MapOnSettleRoute as Yb, BenchmarkTaskRow as Yc, PursuitNodePlatform as Yd, IsolatedCheckOptions as Yf, SandboxServedBackend as Yg, SteerableSandboxArgs as Yh, freeSlots as Yi, assertStrategyContract as Yl, CoordinationReadAccess as Ym, SearchSpecInputs as Yn, officialChecksFromMeta as Yo, BudgetReadout as Yp, InteractiveWorkerEnvironment as Yr, RetainedInteractiveEnvironmentInput as Ys, WatchedSurface as Yt, LoopShape as Yu, addHarnessUsage as Yv, CodexTokenUsage as Yx, RuntimeStreamEventSink as Yy, DriverFailureClass as Z, LoopIterationEndedPayload as ZC, RetainedRunCancellation as ZS, DelegationStatus as Z_, ExecutorAccounting as Za, MapTraversalEvent as Zb, printBenchmarkReport as Zc, PursuitNodeTiming as Zd, runIsolatedCheck as Zf, extractLlmCallEvent as Zg, createSteerableSandboxSession as Zh, rollingDispatch as Zi, defineStrategy as Zl, serveCoordinationMcp as Zm, assertSearchSpec as Zn, sandboxCheckRunner as Zo, ReservationFloor as Zp, InteractiveWorkerOptions as Zr, RetainedInteractiveStartMaterial as Zs, fsSurfaceReader as Zt, Persona as Zu, harnessUsageIsEmpty as Zv, SqlRunOwnershipError as Zx, RuntimeTelemetryOptions as Zy, RunAgentTaskOptions as _, HarnessTranscriptUnavailableReason as _C, readRunState as _S, UiAuditorDelegate as __, SupervisorOpts as _a, DecideGate as _b, loopUntil as _c, LeaderboardScore as _d, SuperviseOptions as _f, resolveAgentEnvironmentProvider as _g, DriverRetryPolicy as _h, graphWorkspace as _i, LocalMcpMaterialization as _l, ResolveSupervisorTools as _m, closingWorkerNote as _n, ChatWorkerSeamOptions as _o, InMemoryRunContextOptions as _p, readWorkerCancellation as _r, Deliverable as _s, AgentEnvironmentProvider$1 as _t, CorpusFilter as _u, readTraceContextFromEnv as _v, Validator as _w, McpToolAnnotations as _x, ProfileKeyOf as _y, AgentKnowledgeProvider as a, RetainedRunSnapshot as aC, SpawnForestNode as aS, ToolLoopCompaction as a_, ResultBlobStore as aa, WorktreeCommandResult as ab, PrivateCasOffloadReport as ac, readHarnessTranscriptSessions as ad, ObserverJournal as af, SharedBoxCloseReceipt as ag, ContinuationAppend as ah, setGraphStrings as ai, loopDispatch as al, RootStreamRecord as am, WorktreeCliExecutorOptions as an, Runtime as ao, IsolatedCheckCpuIdentity as ap, TRACE_SUMMARY_SCHEMA as ar, StreamAgentTurnOptions as as, MakeWorkerAgent as at, harvestCorpus as au, UiFindingScreenshot as av, LoopTeardownFailedPayload as aw, PeerMailReadout as ax, CodeModeToolset as ay, RuntimeSession as b, captureHarnessTranscript as bC, RunCancellation as bS, FleetHandle as b_, ProviderModelAttemptEvidence as ba, JsonScalar as bb, selectValidWinner as bc, DeclaredCheck as bd, createWorkerSlots as bf, ProviderPromptOptions as bg, SpawnResourceBytes as bh, GraphCorpusSummary as bi, McpSpawnFault as bl, SupervisorNodeContext as bm, spendFromUsageEvents as bn, createChatSessionStore as bo, createFileRunContext as bp, safeWorkerFile as br, OpenSandboxRunPromptOptions as bs, AgentEnvironmentSummary as bt, EqualKOnCostOptions as bu, DelegationPersistenceError as bv, RuntimeRunHandle as bw, BusEvent as bx, pairwiseSignificance as by, AgentTaskContext as c, StartRetainedRunInEnvironmentOptions as cC, FileResultBlobStore as cS, ToolLoopToolCall as c_, TraceRootReceipt as ca, GitRunner as cb, equalKOnCost as cc, RetainedFileOutput as cd, observerRecordDigest as cf, SharedBoxStats as cg, ContinuationPanelInput as ch, GraphSessionObservationOptions as ci, TERMINAL_DECISIONS as cl, SettledUsage as cm, AttachWorkerOptions as cn, WorkerTraceEvidence as co, IsolatedCheckCpuSessionResult as cp, RunTraceSources as cr, EvolutionAuthor as cs, SpawnPreflight as ct, ObservationError as cu, KnowledgeItem as cv, LoopTraceEvent as cw, PeerMailbox as cx, runCodeMode as cy, AgentTaskStatus as d, HarnessTranscriptArtifact as dC, SpawnJournalReadOptions as dS, CoderDelegate as d_, RootHandle as da, EventAcknowledgement as db, runPersonified as dc, LeaderboardBenchTask as dd, supervise as df, ROUTER_CLIENT_HEADER as dg, ContinuationProfile as dh, graphFlowSpawnProfile as di, inlineSandboxClient as dl, CoordinationToolFace as dm, attachWorker as dn, WorkerEventEntry as do, SeatSelection as dp, WorkerSteerAcknowledgement as dr, StrategyEvolutionConfig as ds, SpawnRefusalCause as dt, defaultAnalystInstruction as du, ResearchSource as dv, MountRecorder as dw, createPeerMailbox as dx, Interval as dy, RetainedRunEnvironmentAdmission as eC, materializeTreeView as eS, RouterTransportConfig as e_, GraphDesignerExtraTools as ea, createRuntimeEventCollector as eb, resolveSandboxClient as ec, RunPersonified as ed, PursuitRunProjection as ef, InboxLease as eg, CoordinationDeliveryEvidence as eh, InPlaceCliExecutorOptions as ei, LoopDispatchOptions as el, ReservationShortfall as em, analystsFromRegistry as en, ExecutorResult as eo, IsolatedCheckOutputFailure as ep, searchSpecDigest as er, visibleCheckScore as es, CoordinationStats as et, strategyAuthorSystemPrompt as eu, FeedbackRefersTo as ev, LoopPlanDescription as ew, PEER_MAIL_WIRE_KEY as ex, decodeHarnessUsage as ey, BackendErrorDetail as f, HarnessTranscriptBinding as fC, SpawnJournalReadRecord as fS, CoderReview as f_, RootSegment as fa, LeadMessage as fb, FileCorpus as fc, LeaderboardBenchmarkAdapter as fd, superviseFleetCapabilities as ff, sharedBoxRefusal as fg, PanelFinding as fh, GraphFileNeed as fi, InProcessOnPrompt as fl, CoordinationVerbs as fm, readWorkerInteractiveBinding as fn, WorkerEventPage as fo, SeatSelectionInput as fp, WorkerSteerRequest as fr, StrategyTournament as fs, SuperviseProfileEntry as ft, observe as fu, ResearchTask as fv, OutputAdapter as fw, isPeerMailEnvelope as fx, Leaderboard as fy, OpenAIChatToolChoice as g, HarnessTranscriptUnavailable as gC, RunState as gS, DetachedWinnerSelection as g_, Supervisor as ga, WorkerWatchOptions as gb, flatWidenGate as gc, LeaderboardScenario as gd, AuthorizedSpawnContext as gf, createAgentEnvironmentProviderRegistry as gg, DriverReentry as gh, LoadedGraphFile as gi, HttpMcpServerSpec as gl, ResolveDriveHarness as gm, WorkerEvidenceInput as gn, ChatTransportTool as go, InMemoryRunContext as gp, legacySupervisorRunDir as gr, strategyTournament as gs, AgentEnvironmentEvent$1 as gt, Corpus as gu, createPropagatingTraceEmitter as gv, ValidationCtx as gw, JsonRpcResponse as gx, PairwiseVerdict as gy, OpenAIChatTool as h, HarnessTranscriptFile as hC, FileSpawnJournal as hS, DetachedSessionDelegateOptions as h_, SteerableRootHandle as ha, ToolOutcomeEvent as hb, fanout as hc, LeaderboardRunContext as hd, AuthorizedSpawn as hf, AgentEnvironmentProviderRegistry as hg, DriverContractState as hh, LoadGraphFileOptions as hi, inProcessSandboxClient as hl, ObserveSupervisorNodeEvent as hm, VERIFY_TAIL_CHARS as hn, ChatTransportExecutorOptions as ho, subscriptionUsageLimitSignal as hp, fileEscalateQuestion as hr, runStrategyEvolution as hs, AgentEnvironmentCapabilities$1 as ht, CombinatorShape as hu, TraceContext as hv, SelectionReceipt as hw, JsonRpcMessage as hx, PairwiseOptions as hy, AgentExecutionBackend as i, RetainedRunReplayPoint as iC, SpawnForestMissingTree as iS, ToolLoopChat as i_, delegate as ia, WorktreeCheckRunner as ib, PrivateCasDurableStore as ic, ShapeRegistry as id, FileObserverJournal as if, DEFAULT_SHARED_BOX_WORKERS as ig, CheckRead as ih, setGraphProfile as ii, loopCampaignDispatch as il, createBudgetPool as im, worktreeFanout as in, HeldRelease as io, IsolatedCheckCpuEvidence as ip, TRACE_ROOT_SCHEMA as ir, CollectedAgentTurn as is, GraphSubtasks as it, HarvestReport as iu, UiFinding as iv, LoopStartedPayload as iw, PeerMailOutcome as ix, CodeModeToolsOptions as iy, Spend as j, readBoundHarnessSessions$1 as jC, AgentEvalErrorCode as jS, DelegationResumeDriver as j_, ReenteredWorkers as ja, QuestionEscalationRecord as jb, PairedCommandMeasurement as jc, NextPursuitVersionInput as jd, EdgeTraversal as jf, createActivityLog as jg, McpEventSource as jh, graphRegistry as ji, CorpusReadbackOptions as jl, StopRule as jm, jjWorkspace as jn, CheckOutcome as jo, formatPromptHandle as jp, RemoteSupervisorTree as jr, S3PrivateCasStore as js, ExecRequest as jt, PipelineStage as ju, gateOnDeliverable as jv, TraceSource as jx, plateauLength as jy, ResourceLimit as k, RetainedHarnessTranscriptCapture as kC, defaultRedactor as kS, DelegationRecord as k_, SpawnModelSubstitution as ka, QuestionDecision as kb, PairedCommandCall as kc, JudgedPursuitVersion as kd, AgentGraph as kf, TeamProgress as kg, EventSubscriptionStore as kh, graphDigest as ki, AgenticTool as kl, ProgressView as km, WorkspaceRun as kn, RunCancellationReason as ko, dumbContinuationFailPrompt as kp, RemoteSupervisorReader as kr, AcquireOptions as ks, CreateAgentEnvironmentInput$1 as kt, PanelSpec as ku, DeliverableSpec as kv, SessionMessageLike as kx, areaUnderCurve as ky, AgentTaskRunResult as l, StartRetainedRunOptions as lC, replaySpawnTree as lS, FeedbackEvent as l_, WorkspaceCheckpointMarker as la, AwaitWakeInput as lb, trajectoryReport as lc, DefinedLeaderboard as ld, PursuitFork as lf, SharedWorkerIdentity as lg, ContinuationPanelResult as lh, ObservedSessionFacts as li, TerminalDecision as ll, supervisorAgent as lm, WorkerInteractiveBinding as ln, WorkerTraceUnavailableReason as lo, createIsolatedCheckCpuSession as lp, runToolSpans as lr, EvolutionReport as ls, SpawnPreflightContext as lt, ObserveInput as lu, KnowledgeUpdate as lv, LoopWinner as lw, PeerMailboxOptions as lx, AxisScoresOf as ly, OpenAIChatResponseFormat as m, HarnessTranscriptEvidence as mC, readSpawnJournal as mS, DelegateRunCtx as m_, RootSignal as ma, ManagerWake as mb, renderCorpusToInstructions as mc, LeaderboardIterationInfo as md, workerFromBackend as mf, AgentEnvironmentProviderRef as mg, admitContinuationPolicy as mh, GraphFileSeat as mi, InProcessSandboxClientOptions as ml, DriveHarnessOwnerContext as mm, NOTE_MAX_CHARS as mn, ChatSessionStore as mo, SelectSeat as mp, cancelWorker as mr, TournamentRow as ms, AgentEnvironment$1 as mt, AssertTraceDerivedFindings as mu, researcherProfile as mv, SandboxClient as mw, peerMailVerbNames as mx, LeaderboardRow as my, AgentBackendContext as n, RetainedRunHandle as nC, SpawnForestEvent as nS, ToolSpec as n_, DelegateOptions as na, sanitizeKnowledgeReadinessReport as nb, profileOptimizerModelCall as nc, ShapeBudget as nd, PursuitStatus as nf, PeerInboxMessage as ng, FileCoordinationLog as nh, readGraphProfile as ni, SuperviseDispatchOptions as nl, ReservationTicket as nm, AuthoredHarness as nn, HeldEnvironment as no, validateIsolatedCheckOutputs as np, createScope as nr, AgentTurnInput$1 as ns, CoordinationToolsOptions as nt, HarvestError as nu, UiAuditLensFilter as nv, LoopResult as nw, PeerMailEvent as nx, CodeModeTool as ny, AgentRuntimeEvent as o, RetainedRunStartMaterial as oC, SpawnForestTree as oS, ToolLoopCompactionOptions as o_, SpawnEvent as oa, WorktreeHarnessResult as ob, PrivateCasOptions as oc, ProviderAsSandboxClientOptions as od, ObserverRecord as of, SharedBoxPlacement as og, ContinuationEntry as oh, DeepReadonly as oi, superviseDispatch as ol, readRootStream as om, WorktreePatchArtifact as on, WorkerInteractiveSession as oo, IsolatedCheckCpuResources as op, TraceRootArtifact as or, collectAgentTurn as os, PeerAuditAccess as ot, Observation as ou, UiFindingSeverity as ov, LoopTokenUsage as ow, PeerMailRefusal as ox, RunCodeModeOptions as oy, KnowledgeReadinessDecision as p, HarnessTranscriptCapture as pC, SpawnJournalReadResult as pS, CoderReviewer as p_, RootSegmentEntry as pa, ManagerReentryState as pb, InMemoryCorpus as pc, LeaderboardFlagSpec as pd, superviseWithTestBrain as pf, sharedWorkerClientName as pg, VerdictSummary as ph, GraphFileResolutionError as pi, InProcessPromptCtx as pl, DriveHarness as pm, EVIDENCE_MAX_CHARS as pn, ChatCompletionsTransport as po, SeatStage as pp, WriteWorkerSteerOptions as pr, TournamentCell as ps, WorkerSpawnContext as pt, renderReport as pu, ResearcherProfileOptions as pv, RunProvenance as pw, peerMailTools as px, LeaderboardOptions as py, RetainedPendingCause as q, Iteration as qC, RetainedInteractiveStartedAdmission as qS, DelegationHistoryArgs as q_, RootMaterialization as qa, WorkerResumeContext as qb, BenchmarkReport as qc, PursuitCostProvenance as qd, IsolatedCheckBoxEvidence as qf, mapSandboxEvent as qg, DEFAULT_SANDBOX_STEERING_MAX_TURNS as qh, DispatchUnit as qi, StrategyResult as ql, CoordinationMcpHandle as qm, SEARCH_SPEC_CORRELATION_KEY as qn, filterAuthoredAsserts as qo, BudgetPool as qp, recordProfileRun as qr, RecoverRetainedInteractiveRunOptions as qs, SurfaceReadOutcome as qt, DefinePersona as qu, CodexRolloutTurn as qv, LOCAL_HARNESSES as qx, RuntimeEventCollector as qy, AgentBackendInput as r, RetainedRunIntentAdmission as rC, SpawnForestInDoubtNode as rS, ToolLoopCallContext as r_, defaultDelegateBudget as ra, InPlaceHarnessResult as rb, PrivateCasArtifactPort as rc, ShapeContext as rd, projectPursuit as rf, DEFAULT_SHARED_BOX_RESOURCES as rg, PriorCoordination as rh, readGraphStrings as ri, SuperviseOptionsForDispatch as rl, ReserveOptions as rm, WorktreeFanoutOptions as rn, HeldForContinuation as ro, IsolatedCheckCpuCounters as rp, ScopeArgs as rr, AgentTurnUsage as rs, GraphSubtaskPreparation as rt, HarvestFailure as ru, UiAuditorDelegationOutput as rv, LoopSandboxPlacement as rw, PeerMailLimits as rx, CodeModeToolContext as ry, AgentRuntimeEventSink as s, RetainedRunTurnInput as sC, loadSpawnForest as sS, ToolLoopMessageRecord as s_, SpawnJournal as sa, WorktreeProfileMaterializationReceipt as sb, createPrivateCasArtifactPort as sc, providerAsSandboxClient as sd, ObserverRecordKind as sf, SharedBoxPlacementOptions as sg, ContinuationPanel as sh, ReadonlyAgentProfile as si, LocalSandboxClientOptions as sl, readRootStreamReceipt as sm, createWorktreeCliExecutor as sn, WorkerInteractiveUnavailableReason as so, IsolatedCheckCpuSession as sp, TraceSummary as sr, streamAgentTurn as ss, SettledWorker as st, ObservationAnalysis as su, UiLens as sv, LoopTraceEmitter as sw, PeerMailSendInput as sx, createCodeModeTools as sy, AgentAdapter as t, RetainedRunEventOptions as tC, SpawnForest as tS, RouterRouting as t_, graphDesignerExtraTools as ta, createRuntimeStreamEventCollector as tb, profileChatClient as tc, RunPersonifiedOptions as td, PursuitRunTotals as tf, InboxMessage as tg, CoordinationLog as th, createInPlaceCliExecutor as ti, LoopOptionsForDispatch as tl, ReservationStage as tm, failuresAnalyst as tn, ExecutorTeardownWarning as to, IsolatedCheckOutputOptions as tp, settledToIteration as tr, AgentTurnBackend as ts, CoordinationTools as tt, HarvestCorpusOptions as tu, ResearchOutputShape as tv, LoopPlanPayload as tw, PeerMailEnvelope as tx, CodeModeStore as ty, AgentTaskSpec as u, HARNESS_TRANSCRIPT_SETTLE_TIMEOUT_MS as uC, SpawnJournalCursor as uS, FeedbackStore as u_, RecursiveReservationPolicy as ua, CoordinationEvent as ub, definePersona as uc, LeaderboardBenchScore as ud, RUN_FORK_CORRELATION_KEYS as uf, sharedBoxPlacement as ug, ContinuationPolicy as uh, graphFromSessionFacts as ui, defaultSelectWinner as ul, supervisorAgentWithTestBrain as um, WorkerInteractiveProviderSource as un, WorkerEventCursor as uo, SeatSegment as up, WorkerCancellation as ur, EvolutionStrategy as us, SpawnRefusal as ut, ObserveOptions as uu, ResearchOutput as uv, MountManifestEntry as uw, claimsAuthority as ux, GroupOf as uy, RunAgentTaskStreamOptions as v, ReadableEnvironment as vC, CancelRunOptions as vS, detachedSessionDelegate as v_, FleetYield as va, GateDecision as vb, panel as vc, LeaderboardSpec as vd, SuperviseTestOptions as vf, ProviderExecutorOptions as vg, ResolveSpawnResourcePathsResult as vh, loadGraphFile as vi, MaterializeLocalMcpOptions as vl, SupervisorAgentDeps as vm, composeWorkerEvidence as vn, chatTransportExecutor as vo, RunContext as vp, readWorkerSteerAcknowledgement as vr, OpenSandboxRunBeforeStartContext as vs, AgentEnvironmentQuery as vt, CorpusRecord as vu, DelegationTraceSpan as vv, RuntimeRunCompleteInput as vw, McpToolDescriptor as vx, ScoreOf as vy, RuntimeFailureCode as w, HARNESS_TRANSCRIPT_READ_LIMITS as wC, readRunCancellation as wS, createSiblingSandboxExecutor as w_, SupervisedResult as wa, RouteMatch as wb, RegistryAnalyzeProjection as wc, checkProgramDigest as wd, GraphCheckNodes as wf, ActivityLog as wg, resolveSpawnResourcePaths as wh, GraphSelection as wi, materializeLocalMcp as wl, ManagerWakePolicy as wm, withUntrackedArtifacts as wn, asAuthoredProfile as wo, PromptRegistry as wp, writeWorkerSteer as wr, openSandboxRun as ws, AgentSessionStatus$1 as wt, FanoutWinnerSelector as wu, CoderOutput as wv, RuntimeRunStatus as ww, PublishOptions as wx, renderPairwiseMarkdown as wy, RuntimeSessionStore as x, harnessTranscriptArtifact as xC, cancelRun as xS, FleetWorkspaceExecutorOptions as x_, ProviderModelExecutionEvidence as xa, RouteFlow as xb, verify as xc, DeclaredCheckPlacement as xd, SuperviseRegistry as xf, providerAsExecutor as xg, SpawnResourceRead as xh, GraphRegistryDir as xi, StdioMcpConnection as xl, SupervisorNodeContextSeed as xm, CopyOptions as xn, AuthoredProfile as xo, createInMemoryRunContext as xp, supervisorRunDir as xr, SandboxRun as xs, AgentProfile$2 as xt, EqualKVerdict as xu, DelegationStore as xv, RuntimeRunOptions as xw, BusRecord as xx, renderLeaderboardHtml as xy, RuntimeCanonicalStreamEvent as y, captureBoundHarnessTranscript as yC, RunCancelRequest as yS, DelegationExecutor as y_, NoWinnerError as ya, GateRequest as yb, pipeline as yc, defineLeaderboard as yd, WorkerSlots as yf, ProviderLeafOut as yg, ResolvedSpawnResourcePath as yh, GraphCorpusGroup as yi, McpListedTool as yl, SupervisorAgentTestDeps as ym, settledWorkerOut as yn, chatWorkerSeam as yo, RunContextLease as yp, readWorkerSteerRequests as yr, OpenSandboxRunOptions as ys, AgentEnvironmentStatus as yt, EqualKArm as yu, composeLoopTraceEmitters as yv, RuntimeRunCost as yw, McpTransport as yx, leaderboard as yy, Settled as z, ExecutorProgressEvent as zC, NativeContextContinuationInput as zS, DelegateCodeConfig as z_, ExecutorExecutionBinding as za, AuthorizeDownMessage as zb, observedModelMatchesDeclared as zc, SuperviseGraphPursuitOptions as zd, TraversalContinuity as zf, mcpSecretEnvMetadataKey as zg, CliInPlaceSeam as zh, storedGraphDigests as zi, runAgentic as zl, composeReentryTask as zm, createSupervisor as zn, StructuralRolloutPolicy as zo, createSupervisorSpanRecorder as zp, provisionSupervisor as zr, startRetainedRun as zs, computeFindingId$1 as zt, TrajectoryReportOptions as zu, deterministicCompletion as zv, AnalyzeOnSettleRoute as zx, OtelAttribute as zy };
|
|
19812
|
-
//# sourceMappingURL=types-
|
|
19821
|
+
//# sourceMappingURL=types-BYiwLO2L.d.ts.map
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@tangle-network/agent-runtime",
|
|
3
|
-
"version": "10.0.
|
|
3
|
+
"version": "10.0.8",
|
|
4
4
|
"description": "Shared task-lifecycle skeleton for agents: a recursive loop kernel for chat turns, one-shot tasks, and multi-attempt loops, with trace capture and eval-gated self-improvement. Domain behavior lives in adapters; scoring and ship-gates in @tangle-network/agent-eval.",
|
|
5
5
|
"homepage": "https://github.com/tangle-network/agent-runtime#readme",
|
|
6
6
|
"repository": {
|
|
@@ -120,7 +120,7 @@
|
|
|
120
120
|
"@biomejs/biome": "^2.6.4",
|
|
121
121
|
"@modelcontextprotocol/sdk": "1.32.2",
|
|
122
122
|
"@tangle-network/agent-eval": "1.0.32",
|
|
123
|
-
"@tangle-network/agent-interface": "5.10.
|
|
123
|
+
"@tangle-network/agent-interface": "5.10.27",
|
|
124
124
|
"@tangle-network/agent-provider-cli-bridge": "2.0.10",
|
|
125
125
|
"@tangle-network/agent-provider-daytona": "0.8.0",
|
|
126
126
|
"@tangle-network/agent-provider-e2b": "0.7.0",
|
|
@@ -147,7 +147,7 @@
|
|
|
147
147
|
"license": "MIT",
|
|
148
148
|
"peerDependencies": {
|
|
149
149
|
"@tangle-network/agent-eval": "^1.0.32",
|
|
150
|
-
"@tangle-network/agent-interface": "^5.10.
|
|
150
|
+
"@tangle-network/agent-interface": "^5.10.27",
|
|
151
151
|
"@tangle-network/sandbox": "^1.0.265"
|
|
152
152
|
},
|
|
153
153
|
"dependencies": {
|
|
@@ -165,6 +165,7 @@
|
|
|
165
165
|
"build": "tsdown --on-success 'mkdir -p dist/viewer && viewer_out=\"$PWD/dist/viewer\" && cd node_modules/@tangle-network/sandbox-ui && cp -R dist/workspace-viewer.js dist/styles.css dist/runtime-viewer dist/report-viewer.js LICENSE \"$viewer_out/\"'",
|
|
166
166
|
"dev": "pnpm run build --watch",
|
|
167
167
|
"test": "pnpm run build && pnpm run typecheck && pnpm run lint && vitest run",
|
|
168
|
+
"test:affected": "base=$(git merge-base \"${AFFECTED_BASE:-origin/main}\" HEAD) && pnpm run build && pnpm run typecheck && pnpm run lint && vitest run --changed \"$base\" --passWithNoTests",
|
|
168
169
|
"test:watch": "vitest",
|
|
169
170
|
"lint": "biome check src tests examples",
|
|
170
171
|
"lint:fix": "biome check --write src tests examples",
|