@alvin0/ai-agent-sdk-core 0.1.4 → 0.1.5
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +13 -1
- package/dist/agent/define/definition.d.ts +1 -1
- package/dist/agent/define/definition.js +1 -1
- package/dist/agent/define/definition.js.map +1 -1
- package/dist/agent/define/session/types.d.ts +6 -0
- package/dist/agent/define/session/types.d.ts.map +1 -1
- package/dist/agent/define/session.d.ts +25 -2
- package/dist/agent/define/session.d.ts.map +1 -1
- package/dist/agent/define/session.js +1 -1
- package/dist/agent/define/session.js.map +1 -1
- package/dist/agent/loop/admission.js +2 -0
- package/dist/agent/loop/admission.js.map +1 -0
- package/dist/agent/loop/events.d.ts +4 -0
- package/dist/agent/loop/events.d.ts.map +1 -1
- package/dist/agent/loop/program.js +2 -0
- package/dist/agent/loop/program.js.map +1 -0
- package/dist/agent/loop/run-turn.d.ts.map +1 -1
- package/dist/agent/loop/run-turn.js +1 -1
- package/dist/agent/loop/run-turn.js.map +1 -1
- package/dist/agent/loop/schedule.d.ts.map +1 -1
- package/dist/agent/loop/schedule.js +2 -2
- package/dist/agent/loop/schedule.js.map +1 -1
- package/dist/agent/loop/tool-call-support.js +2 -0
- package/dist/agent/loop/tool-call-support.js.map +1 -0
- package/dist/agent/loop/turn/hooks.js +1 -1
- package/dist/agent/loop/turn/hooks.js.map +1 -1
- package/dist/agent/loop/turn/model-request-boundary.js +2 -0
- package/dist/agent/loop/turn/model-request-boundary.js.map +1 -0
- package/dist/agent/loop/turn/model-round.js +1 -1
- package/dist/agent/loop/turn/model-round.js.map +1 -1
- package/dist/agent/loop/turn/step-projection.js +2 -0
- package/dist/agent/loop/turn/step-projection.js.map +1 -0
- package/dist/agent/loop/turn/types.d.ts +6 -0
- package/dist/agent/loop/turn/types.d.ts.map +1 -1
- package/dist/agent/memory/context-optimizer.d.ts +61 -0
- package/dist/agent/memory/context-optimizer.d.ts.map +1 -0
- package/dist/agent/memory/context-optimizer.js +4 -0
- package/dist/agent/memory/context-optimizer.js.map +1 -0
- package/dist/agent/memory/memory.js +1 -1
- package/dist/agent/memory/memory.js.map +1 -1
- package/dist/agent/mode/run-agent.d.ts +15 -1
- package/dist/agent/mode/run-agent.d.ts.map +1 -1
- package/dist/agent/mode/run-agent.js +2 -2
- package/dist/agent/mode/run-agent.js.map +1 -1
- package/dist/agent/skill/provider/snapshot.js +1 -1
- package/dist/agent/team/managed.d.ts +33 -64
- package/dist/agent/team/managed.d.ts.map +1 -1
- package/dist/agent/team/managed.js +6 -3
- package/dist/agent/team/managed.js.map +1 -1
- package/dist/agent/team/team.d.ts +2 -0
- package/dist/agent/team/team.d.ts.map +1 -1
- package/dist/agent/team/team.js +1 -1
- package/dist/agent/team/team.js.map +1 -1
- package/dist/agent/team/types.d.ts +1 -0
- package/dist/agent/team/types.d.ts.map +1 -1
- package/dist/agent/tool/action-fusion.d.ts +30 -0
- package/dist/agent/tool/action-fusion.d.ts.map +1 -0
- package/dist/agent/tool/action-fusion.js +2 -0
- package/dist/agent/tool/action-fusion.js.map +1 -0
- package/dist/agent/tool/capture.js +1 -1
- package/dist/agent/tool/capture.js.map +1 -1
- package/dist/agent/tool/definition.d.ts +8 -0
- package/dist/agent/tool/definition.d.ts.map +1 -1
- package/dist/agent/tool/definition.js.map +1 -1
- package/dist/agent/tool/evidence-reducer.d.ts +41 -0
- package/dist/agent/tool/evidence-reducer.d.ts.map +1 -0
- package/dist/agent/tool/evidence-reducer.js +7 -0
- package/dist/agent/tool/evidence-reducer.js.map +1 -0
- package/dist/agent/tool/nested.d.ts +117 -0
- package/dist/agent/tool/nested.d.ts.map +1 -0
- package/dist/agent/tool/nested.js +2 -0
- package/dist/agent/tool/nested.js.map +1 -0
- package/dist/agent/tool/output-budget.d.ts.map +1 -1
- package/dist/agent/tool/output-budget.js +2 -2
- package/dist/agent/tool/output-budget.js.map +1 -1
- package/dist/agent/tool/output-schema.js +2 -0
- package/dist/agent/tool/output-schema.js.map +1 -0
- package/dist/agent/tool/pipeline.d.ts +7 -0
- package/dist/agent/tool/pipeline.d.ts.map +1 -1
- package/dist/agent/tool/pipeline.js +2 -2
- package/dist/agent/tool/pipeline.js.map +1 -1
- package/dist/agent/tool/program-results.js +2 -0
- package/dist/agent/tool/program-results.js.map +1 -0
- package/dist/agent.d.ts +6 -2
- package/dist/agent.js +1 -1
- package/dist/composition/agent/definition.js +1 -1
- package/dist/composition/agent/options.js +1 -1
- package/dist/composition/agent/options.js.map +1 -1
- package/dist/composition/agent/session.js +1 -1
- package/dist/composition/agent/session.js.map +1 -1
- package/dist/composition/agent/types.d.ts +6 -0
- package/dist/composition/agent/types.d.ts.map +1 -1
- package/dist/composition/tool-source/snapshot.js +1 -1
- package/dist/index.d.ts +2 -1
- package/dist/index.js +1 -1
- package/dist/memory.d.ts +2 -1
- package/dist/memory.js +1 -1
- package/dist/observability/bus.js +1 -1
- package/dist/primitives/version.d.ts +1 -1
- package/dist/primitives/version.js +1 -1
- package/dist/primitives/version.js.map +1 -1
- package/dist/runtime/registry.js +1 -1
- package/dist/tools.d.ts +4 -1
- package/dist/tools.js +1 -1
- package/package.json +1 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"run-turn.js","names":[],"sources":["../../../src/agent/loop/run-turn.ts"],"sourcesContent":["import { createUserMessage } from '../../message/index.ts'\nimport { detachedFrozen } from '../../primitives/index.ts'\nimport type { ModelCallReport } from '../../observation/index.ts'\nimport { waitForSettlement } from '../../async/index.ts'\nimport { authoritativeTokenUsage, budgetTokenTotal, summarizeModelCallUsage } from '../accounting/ledger.ts'\nimport { createSpanId, createTraceId, type TraceRef } from '../trace/trace.ts'\nimport type { AgentEvent, ExhaustedBudget, ToolDeclineReason, TurnHooks, TurnOutcome } from './types.ts'\nimport { AwaitedEventQueue } from './queue.ts'\nimport { runToolCalls } from './schedule.ts'\nimport { type RunTurnOptions } from './turn/types.ts'\nimport { resolveBounds, positiveFinite, snapshotRunTurnOptions } from './turn/config.ts'\nimport { codedRuntimeError, messageOf, errorCodeOf, now } from './turn/common.ts'\nimport { runOptionalHook, runHook } from './turn/hooks.ts'\nimport { maintenanceEmitter, emitAssistantContent, textOf } from './turn/content.ts'\nimport { repeatKey, toolActionPattern, repeatedSuffixCycle } from './turn/repetition.ts'\nimport { modelRound } from './turn/model-round.ts'\nimport { accountingUsageStop } from './turn/usage-stop.ts'\nimport { ContextSectionRuntime } from '../context/section.ts'\nimport type { ContextToolTouch } from '../context/types.ts'\n\nfunction hasCallableTools(options: RunTurnOptions): boolean {\n if (options.toolChoice === 'none') return false\n return (options.tools?.names().length ?? 0) > 0 || (options.nativeTools?.length ?? 0) > 0\n}\n\n/** Run one bounded turn as a backpressured event stream. */\nexport function runTurn(options: RunTurnOptions): AsyncIterable<AgentEvent> {\n return {\n async * [Symbol.asyncIterator]() {\n const invocation = snapshotRunTurnOptions(options)\n const queue = new AwaitedEventQueue<AgentEvent>()\n const consumer = new AbortController()\n const teardownTimeoutMs = positiveFinite(invocation.teardownTimeoutMs ?? 30_000, 'teardownTimeoutMs')\n const signal = invocation.signal === undefined\n ? consumer.signal\n : AbortSignal.any([invocation.signal, consumer.signal])\n const task = driveTurn(invocation, signal, event => queue.push(detachedFrozen(event)))\n .then(() => queue.close(), error => queue.fail(error))\n try {\n while (true) {\n const item = await queue.take()\n if (item.done) break\n yield item.value\n }\n await task\n } finally {\n consumer.abort(new Error('turn event consumer stopped'))\n queue.close()\n if (!await waitForSettlement(task, teardownTimeoutMs)) {\n throw codedRuntimeError(\n `turn producer ignored cancellation for more than ${teardownTimeoutMs}ms`,\n 'TURN_TEARDOWN_TIMEOUT',\n consumer.signal.reason,\n )\n }\n }\n },\n }\n}\n\nasync function driveTurn(\n options: RunTurnOptions,\n signal: AbortSignal,\n emit: (event: AgentEvent) => Promise<void>,\n): Promise<void> {\n const bounds = resolveBounds(options.bounds)\n const maxTotalTokens = bounds.maxTotalTokens === 'auto' ? Infinity : bounds.maxTotalTokens\n // Infinity is local control flow only. Public configuration/events retain\n // the serializable 'auto' value, and all other admission guards still apply.\n const maxSteps = bounds.maxSteps === 'auto' ? Infinity : bounds.maxSteps\n const traceId = options.trace?.traceId ?? createTraceId()\n const root: TraceRef = { traceId, spanId: createSpanId(), parentSpanId: options.trace?.parentSpanId ?? null }\n const turn = Math.max(1, options.history.entries().filter(entry =>\n entry.event.kind === 'user' && entry.event.message.source.kind === 'user').length)\n const startedAt = now()\n let steps = 0\n let toolCalls = 0\n // Descending, so \"how many are below the remainder\" counts the crossings.\n const budgetReminders = [...bounds.toolBudgetRemindAt]\n .filter(threshold => threshold > 0 && threshold < bounds.maxToolCalls)\n .sort((left, right) => right - left)\n let budgetRemindersSent = 0\n /** How many full budgets an unwalled turn has spent and been told about. */\n let overBudgetNoticesSent = 0\n /** Sequence of the budget notice currently on the surface, if any. */\n let budgetNoticeSeq: number | undefined\n let stepReminderSent = false\n let tokenRemindersSent = 0\n let consecutiveErrors = 0\n let text = ''\n const modelCallReports: ModelCallReport[] = []\n let reason: TurnOutcome['reason'] | undefined\n let outcome: TurnOutcome\n let lastRepeat: { key: string; count: number } | undefined\n const actionSteps: string[] = []\n const emitMaintenance = maintenanceEmitter(emit, root)\n /**\n * Put the current budget notice on the surface, replacing the previous one.\n *\n * One live notice, never a pile of them. Appending each new remainder leaves\n * \"16 calls remain\" and \"6 calls remain\" both readable, and a model that\n * plans against the older number plans against a budget it no longer has.\n * Codex keeps exactly one `<rollout_budget>` fragment for the same reason\n * (`context/rollout_budget.rs`), replacing it as the number moves.\n * @param text - What the model should read now.\n */\n const appendBudgetNotice = (text: string): void => {\n const message = createUserMessage({\n source: { kind: 'app', producer: 'tool-loop-budget-guard' },\n content: [{ type: 'text', text }],\n })\n const previous = budgetNoticeSeq\n // Replacing is best-effort. Compaction can shadow the earlier notice\n // between steps, and a replace whose target is no longer on the surface is\n // rejected — which must cost the model a reminder, never the turn.\n if (previous !== undefined) {\n try {\n budgetNoticeSeq = options.history.append(\n { kind: 'user', message },\n { op: 'replace', from: previous, to: previous, targets: [previous] },\n ).seq\n return\n } catch {\n budgetNoticeSeq = undefined\n }\n }\n budgetNoticeSeq = options.history.append({ kind: 'user', message }).seq\n }\n const contextSections = options.contextSections === undefined || options.contextSections.length === 0\n ? undefined\n : new ContextSectionRuntime({\n sections: options.contextSections,\n history: options.history,\n ...options.logger === undefined ? {} : { logger: options.logger },\n guard: (pending, name) => runHook(pending, options, signal, name),\n scope: { agentId: options.trace?.agentId, conversationId: options.trace?.conversationId },\n })\n /** Tool calls committed since the last section reconcile. */\n let contextTouches: ContextToolTouch[] = []\n let rootStarted = false\n let rootEnded = false\n const callableTools = hasCallableTools(options)\n const dedicatedFinalOutput = options.outputFormat?.type === 'json_schema' && callableTools\n const turnOperationId = options.accounting?.startOperation('turn', {\n data: { turn, model: options.config.model },\n })\n let turnOperationEnded = false\n let usageStop: TurnOutcome['reason'] | undefined\n // Shared by retries, hook continuations, and both finalizer paths. Finalizers\n // may have a separate step allowance, never a separate token allowance.\n const admissionStop = (): TurnOutcome['reason'] | undefined => {\n if (signal.aborted) return { kind: 'aborted' }\n const mandatoryStop = accountingUsageStop(options.accounting)\n if (mandatoryStop !== undefined) return mandatoryStop\n if (usageStop !== undefined) return usageStop\n const tokens = budgetTokenTotal(summarizeModelCallUsage(modelCallReports))\n return tokens !== undefined && tokens >= maxTotalTokens\n ? { kind: 'budget-exhausted', budget: 'tokens', forcedFinalAnswer: false }\n : undefined\n }\n\n try {\n await emit({\n type: 'span-start', trace: root, at: startedAt,\n name: `invoke_agent ${options.trace?.agentId ?? 'agent'}`, kind: 'invoke_agent',\n attributes: {\n 'gen_ai.operation.name': 'invoke_agent',\n 'gen_ai.agent.id': options.trace?.agentId ?? 'agent',\n 'gen_ai.agent.name': options.trace?.agentName ?? options.trace?.agentId ?? 'agent',\n 'gen_ai.request.model': options.config.model,\n ...options.trace?.conversationId === undefined\n ? {}\n : { 'gen_ai.conversation.id': options.trace.conversationId },\n },\n })\n rootStarted = true\n await emit({ type: 'turn-start', turn, trace: root })\n\n turnLifecycle: while (true) {\n while (reason === undefined && steps < maxSteps && !signal.aborted) {\n reason = admissionStop()\n if (reason !== undefined) break\n // Auto has no step countdown. Warn from the same usage total as admission,\n // before a hard token stop can leave the agent without a reporting call.\n const usedTokens = budgetTokenTotal(summarizeModelCallUsage(modelCallReports))\n if (bounds.maxTotalTokens !== 'auto' && usedTokens !== undefined) {\n const crossed = [0.5, 0.75, 0.9].filter(ratio => usedTokens >= maxTotalTokens * ratio).length\n if (crossed > tokenRemindersSent) {\n tokenRemindersSent = crossed\n const remaining = Math.max(0, maxTotalTokens - usedTokens)\n options.history.append({ kind: 'user', message: createUserMessage({\n source: { kind: 'app', producer: 'tool-loop-token-guard' },\n content: [{ type: 'text', text: `Token budget: ${remaining} of ${bounds.maxTotalTokens} aggregate tokens remain. Each request also spends input tokens on the accumulated context. `\n + (crossed >= 2 ? 'Stop broad exploration. ' : 'Prioritize outstanding verification and reporting. ')\n + 'Reserve capacity for the required self-check, honest todo reconciliation and substantive final report. State unavailable evidence and unfinished work; do not claim it is verified. No extra model call is allowed after the hard token limit.',\n }],\n }) })\n }\n }\n // Leave time to reconcile a plan and submit a result before the final\n // tools-disabled summary. Tool-call reminders do not cover step limits.\n if (!stepReminderSent && steps > 0 && maxSteps - steps <= 2) {\n stepReminderSent = true\n options.history.append({ kind: 'user', message: createUserMessage({\n source: { kind: 'app', producer: 'tool-loop-step-guard' },\n content: [{ type: 'text', text:\n `${maxSteps - steps} work steps remain. Finish essential verification, update any task list honestly, and submit the result if required. Summarize findings, evidence, and unfinished work; do not start new exploration.`,\n }],\n }) })\n }\n // Recomputed before the request that will read it, so a section reacting to\n // the previous step's tool calls is already on the surface.\n if (contextSections !== undefined) {\n await contextSections.reconcile(steps, contextTouches, signal)\n contextTouches = []\n }\n const step = steps + 1\n const round = await modelRound(\n options, signal, emit, emitMaintenance, root, turn, step,\n dedicatedFinalOutput\n ? 'process'\n : options.outputFormat?.type === 'json_schema' ? 'final' : 'standard',\n )\n steps++\n if (round.report !== undefined) modelCallReports.push(round.report)\n if (round.message !== undefined) {\n options.history.append({\n kind: 'assistant', message: round.message,\n ...round.finish.kind === 'aborted' ? { interrupted: true as const } : {},\n ...round.usage === undefined ? {} : { usage: round.usage },\n })\n await emit({ type: 'assistant-message', message: round.message, trace: round.trace })\n await emitAssistantContent(round, emit)\n text = textOf(round.message.content)\n }\n usageStop = accountingUsageStop(options.accounting) ?? (round.usageRequired\n ? { kind: 'error', failure: { message: 'provider usage is required by the configured run policy', code: 'USAGE_REQUIRED' } }\n : round.usageUnavailable\n ? { kind: 'usage-unavailable', modelCallId: round.report?.modelCallId ?? 'unknown' }\n : undefined)\n if (signal.aborted || round.finish.kind === 'aborted') { reason = { kind: 'aborted' }; break }\n // Pair emitted tool calls with declined results even when policy stops the\n // run; never execute those calls or allow a retry hook to override policy.\n if (round.finish.kind === 'error' && usageStop !== undefined) {\n reason = { kind: 'error', failure: round.finish.failure }\n break\n }\n if (round.usageRequired && (round.calls.length === 0 || options.tools === undefined)) { reason = usageStop; break }\n if (round.finish.kind === 'error' && !round.usageRequired) {\n reason = admissionStop()\n if (reason !== undefined) break\n const decision = await runOptionalHook(options.hooks?.onRequestError, [{\n turn, step, failure: round.finish.failure, snapshot: options.history.snapshot(), signal,\n ...(options.logger === undefined ? {} : { logger: options.logger }),\n emit: emitMaintenance,\n }], options, signal, 'onRequestError')\n const maintenanceStop = accountingUsageStop(options.accounting)\n if (maintenanceStop !== undefined) { reason = signal.aborted ? { kind: 'aborted' } : maintenanceStop; break }\n if (decision === 'retry' && steps < maxSteps) continue\n reason = { kind: 'error', failure: round.finish.failure }\n break\n }\n if (round.finish.kind === 'max-tokens' && !round.usageRequired) { reason = { kind: 'max-tokens' }; break }\n if (round.calls.length === 0 && round.usageUnavailable) {\n reason = accountingUsageStop(options.accounting) ?? { kind: 'usage-unavailable', modelCallId: round.report?.modelCallId ?? 'unknown' }\n break\n }\n if (round.calls.length === 0 && dedicatedFinalOutput) {\n reason = admissionStop()\n if (reason !== undefined) break\n options.history.append({ kind: 'user', message: createUserMessage({\n source: { kind: 'app', producer: 'structured-output-finalizer' },\n content: [{\n type: 'text',\n text: 'The process phase is complete. Return the final answer now in the requested output format. Do not call tools.',\n }],\n }) })\n const final = await modelRound(\n options, signal, emit, emitMaintenance, root, turn, steps + 1, 'final',\n )\n steps++\n if (final.report !== undefined) modelCallReports.push(final.report)\n if (final.message !== undefined) {\n options.history.append({\n kind: 'assistant', message: final.message,\n ...final.usage === undefined ? {} : { usage: final.usage },\n })\n await emit({ type: 'assistant-message', message: final.message, trace: final.trace })\n await emitAssistantContent(final, emit)\n text = textOf(final.message.content)\n }\n if (final.finish.kind === 'aborted') reason = { kind: 'aborted' }\n else if (final.finish.kind === 'error') reason = { kind: 'error', failure: final.finish.failure }\n else if (final.finish.kind === 'max-tokens') reason = { kind: 'max-tokens' }\n else if (final.usageRequired) reason = { kind: 'error', failure: {\n message: 'provider usage is required by the configured run policy',\n code: 'USAGE_REQUIRED',\n } }\n else if (final.usageUnavailable) {\n reason = accountingUsageStop(options.accounting) ?? { kind: 'usage-unavailable', modelCallId: final.report?.modelCallId ?? 'unknown' }\n } else reason = { kind: 'completed' }\n break\n }\n // A provider that repeated an id had the repeat dropped. Saying so is what\n // keeps the model from reading one result for two calls as a tool that\n // silently ignored it.\n if (round.droppedDuplicateCalls !== undefined) {\n options.history.append({ kind: 'user', message: createUserMessage({\n source: { kind: 'app', producer: 'tool-loop-duplicate-guard' },\n content: [{\n type: 'text',\n text: `You reused the tool-call id ${round.droppedDuplicateCalls.map(id => `'${id}'`).join(', ')}.`\n + ' A result pairs to exactly one call, so the repeat was not run and only the first'\n + ' call of that id has a result. Give every call its own id, and call again if you'\n + ' still need what the dropped one would have done.',\n }],\n }) })\n }\n if (round.calls.length === 0 || options.tools === undefined) { reason = { kind: 'completed' }; break }\n\n // Calls the budget does not govern: submitting, asking, delegating. They\n // are dispatched even when the budget is spent, so the model always has a\n // legal way to finish. See `ToolDefinition.budgetExempt`.\n const budgetedCalls = round.calls\n .filter(call => options.tools?.get(call.toolName)?.budgetExempt !== true).length\n const remaining = Math.max(0, bounds.maxToolCalls - toolCalls)\n let repeatProjection = lastRepeat\n const projectedRepeats = round.calls.map(call => {\n const key = repeatKey(call)\n // Count consecutive calls, not lifetime visits to a source or test command.\n // Distinct intervening work may change its result. Alternating loops are\n // handled separately by the step-cycle guard below.\n const count = repeatProjection?.key === key ? repeatProjection.count + 1 : 1\n repeatProjection = { key, count }\n return count\n })\n const repeatedLimitBeforeDispatch = projectedRepeats.some(count => count >= bounds.repeatToolLimit)\n const actionPattern = toolActionPattern(round.calls)\n const projectedCycle = repeatedSuffixCycle(\n [...actionSteps, actionPattern],\n bounds.maxToolCycleLength,\n )\n const cycleLimitBeforeDispatch = projectedCycle !== undefined\n && projectedCycle.repetitions >= bounds.toolCycleLimit\n const currentUsage = summarizeModelCallUsage(modelCallReports)\n const budgetTokens = budgetTokenTotal(currentUsage)\n const tokenLimitBeforeDispatch = budgetTokens !== undefined\n && budgetTokens >= maxTotalTokens\n const guardDeclined = repeatedLimitBeforeDispatch || cycleLimitBeforeDispatch || tokenLimitBeforeDispatch || round.usageRequired\n // Name the limit that actually declined the call. Reporting a repeat guard\n // as an empty budget teaches the model the wrong lesson, and it repeats the\n // call on the next turn with the budget it was told it lacked.\n const declineReason: ToolDeclineReason = tokenLimitBeforeDispatch\n ? 'tokens'\n : cycleLimitBeforeDispatch\n ? 'tool-call-cycle'\n : repeatedLimitBeforeDispatch\n ? 'repeated-tool-call'\n : round.usageRequired\n ? 'usage-required'\n : 'tool-calls'\n // `continue` takes the wall down: the budget becomes a notice and the turn\n // is bounded by steps, tokens, and the run-level ledger instead. Guards\n // that mean \"this is not working\" still decline, whatever the setting.\n const budgetIsAWall = bounds.onExhausted !== 'continue'\n const scheduled = await runToolCalls({\n calls: round.calls, catalog: options.tools, history: options.history,\n position: { turn, step,\n ...(options.accounting === undefined ? {} : { runId: options.accounting.runId }),\n ...(options.trace?.conversationId === undefined ? {} : { conversationId: options.trace.conversationId }),\n }, signal, parentTrace: root,\n maxParallel: bounds.maxParallel,\n dispatchLimit: guardDeclined ? 0 : budgetIsAWall ? remaining : round.calls.length,\n declineReason,\n maxResultBytes: bounds.maxToolResultBytes,\n maxResultTokens: bounds.maxToolResultTokens,\n resultOverflow: bounds.toolResultOverflow,\n ...options.spillStore === undefined ? {} : { spillStore: options.spillStore },\n maxDurationMs: bounds.maxToolDurationMs,\n teardownTimeoutMs: bounds.toolTeardownTimeoutMs,\n ...(options.logger === undefined ? {} : { logger: options.logger }),\n ...options.interceptors === undefined ? {} : { interceptors: options.interceptors },\n ...options.approvals === undefined ? {} : { approvals: options.approvals },\n ...options.accounting === undefined ? {} : { accounting: options.accounting },\n emit,\n ...options.hooks?.checkpoint === undefined ? {} : {\n checkpoint: (context: Parameters<NonNullable<TurnHooks['checkpoint']>>[0]) => runHook(\n Promise.resolve(options.hooks?.checkpoint?.(context)), options, signal, 'checkpoint',\n ),\n },\n })\n // Results commit in model order, one per requested call, so the pairing\n // holds for declined calls too. A short result list means a sibling failed\n // its contract and the turn is already unwinding; reporting a guessed\n // outcome would be worse than reporting nothing.\n if (contextSections !== undefined && scheduled.results.length === round.calls.length) {\n contextTouches.push(...round.calls.map((call, index) => ({\n toolName: call.toolName,\n rawArguments: call.rawArguments,\n failed: scheduled.results[index]?.isError ?? true,\n })))\n }\n toolCalls += scheduled.budgeted\n const remainingAfterDispatch = Math.max(0, bounds.maxToolCalls - toolCalls)\n // One reminder per threshold crossed, not one per turn.\n //\n // This was a single boolean: the model was told once, at 25% remaining,\n // and then never again however close it came to the end. A model warned at\n // sixteen calls left and still exploring at four has been told nothing\n // since, and runs into the wall with no notice — which is what produces a\n // red \"no remaining tool-call budget\" where an answer should have been.\n //\n // Codex counts thresholds rather than remembering a flag\n // (`rollout_budget.rs`, `reminder_index`): every threshold now below the\n // remaining budget that has not been reported yet gets reported. Crossing\n // several at once collapses into the one that matters, the lowest.\n const crossed = budgetReminders.filter(threshold => remainingAfterDispatch <= threshold).length\n if (crossed > budgetRemindersSent && remainingAfterDispatch > 0) {\n budgetRemindersSent = crossed\n appendBudgetNotice(\n `Tool budget: ${remainingAfterDispatch} of ${bounds.maxToolCalls} calls remain in this turn.`\n + ' Stop broad exploration, make the necessary edits, and reserve calls for'\n + (budgetIsAWall\n ? ' verification. When the budget runs out no further work call will run, so'\n + ' finish with what you can still verify.'\n : ' verification. Past the budget you are expected to be wrapping up, not'\n + ' opening new lines of work.'),\n )\n }\n // Past the budget with the wall down. The turn is not stopped — the model\n // keeps its tools — but it is told, once per further budget spent, that it\n // is now expected to be finishing. This is the shape of Codex's\n // `budget_limit` goal prompt: no new substantive work, wrap up, name what\n // is left.\n if (!budgetIsAWall && remainingAfterDispatch === 0) {\n const windows = Math.floor(toolCalls / bounds.maxToolCalls)\n if (windows > overBudgetNoticesSent) {\n overBudgetNoticesSent = windows\n appendBudgetNotice(\n `Tool budget spent: ${toolCalls} calls made against a budget of ${bounds.maxToolCalls}.`\n + ' Do not start new substantive work. Finish what is in flight, verify what you'\n + ' can, and answer — stating plainly what is unverified or unfinished.',\n )\n }\n }\n await emit({ type: 'step-end', turn, step, trace: round.trace })\n\n actionSteps.push(actionPattern)\n let repeatedLimit = repeatedLimitBeforeDispatch\n for (let index = 0; index < round.calls.length; index++) {\n const call = round.calls[index]\n const result = scheduled.results[index]\n if (call === undefined || result === undefined) continue\n consecutiveErrors = result.isError ? consecutiveErrors + 1 : 0\n const key = repeatKey(call)\n const count = lastRepeat?.key === key ? lastRepeat.count + 1 : 1\n lastRepeat = { key, count }\n if (count === bounds.repeatToolWarningAt) {\n options.history.append({ kind: 'user', message: createUserMessage({\n source: { kind: 'app', producer: 'tool-loop-repeat-guard' },\n content: [{ type: 'text', text: `You have called ${call.toolName} with the same arguments ${count} consecutive times. Reassess before repeating it.` }],\n }) })\n }\n if (count >= bounds.repeatToolLimit) repeatedLimit = true\n }\n if (projectedCycle?.repetitions === bounds.toolCycleWarningAt) {\n options.history.append({ kind: 'user', message: createUserMessage({\n source: { kind: 'app', producer: 'tool-loop-cycle-guard' },\n content: [{\n type: 'text',\n text: `Tool-use pattern repeated ${projectedCycle.repetitions} times across ${projectedCycle.period} step(s). Reassess the approach and identify concrete new evidence before continuing.`,\n }],\n }) })\n }\n if (scheduled.concluded) { reason = { kind: 'concluded-by-tool', toolName: scheduled.concludedBy ?? 'unknown' }; break }\n if (signal.aborted) { reason = { kind: 'aborted' }; break }\n if (round.usageRequired) { reason = usageStop; break }\n if (round.usageUnavailable) {\n reason = accountingUsageStop(options.accounting) ?? { kind: 'usage-unavailable', modelCallId: round.report?.modelCallId ?? 'unknown' }\n break\n }\n let exhausted: ExhaustedBudget | undefined\n const reportReserveReached = bounds.maxTotalTokens !== 'auto'\n && bounds.finalReportReserveTokens > 0 && budgetTokens !== undefined\n && budgetTokens >= maxTotalTokens - bounds.finalReportReserveTokens\n if (tokenLimitBeforeDispatch) exhausted = 'tokens'\n else if (reportReserveReached) exhausted = 'tokens'\n else if (cycleLimitBeforeDispatch) exhausted = 'tool-call-cycle'\n else if (budgetIsAWall && budgetedCalls > remaining) exhausted = 'tool-calls'\n else if (consecutiveErrors >= bounds.maxConsecutiveToolErrors) exhausted = 'consecutive-tool-errors'\n else if (repeatedLimit) exhausted = 'repeated-tool-call'\n else if (steps >= maxSteps) exhausted = 'steps'\n if (exhausted !== undefined) {\n const forced = (exhausted !== 'tokens' || (reportReserveReached && !tokenLimitBeforeDispatch))\n && bounds.onExhausted !== 'stop'\n && admissionStop() === undefined\n if (forced) {\n const final = await modelRound(\n options, signal, emit, emitMaintenance, root, turn, steps + 1, 'forced-final',\n )\n steps++\n if (final.report !== undefined) modelCallReports.push(final.report)\n if (final.message !== undefined) {\n options.history.append({ kind: 'assistant', message: final.message, ...final.usage === undefined ? {} : { usage: final.usage } })\n await emit({ type: 'assistant-message', message: final.message, trace: final.trace })\n await emitAssistantContent(final, emit)\n text = textOf(final.message.content)\n }\n if (final.finish.kind === 'aborted') {\n reason = { kind: 'aborted' }\n break\n }\n if (final.finish.kind === 'error') {\n reason = { kind: 'error', failure: final.finish.failure }\n break\n }\n if (final.finish.kind === 'max-tokens') {\n reason = { kind: 'max-tokens' }\n break\n }\n if (final.usageRequired) {\n reason = { kind: 'error', failure: {\n message: 'provider usage is required by the configured run policy',\n code: 'USAGE_REQUIRED',\n } }\n break\n }\n if (final.usageUnavailable) {\n reason = accountingUsageStop(options.accounting) ?? { kind: 'usage-unavailable', modelCallId: final.report?.modelCallId ?? 'unknown' }\n break\n }\n }\n reason = { kind: 'budget-exhausted', budget: exhausted, forcedFinalAnswer: forced,\n ...(exhausted === 'tokens' && reportReserveReached && !tokenLimitBeforeDispatch\n ? { trigger: 'report-reserve' as const } : {}),\n }\n }\n }\n\n if (reason === undefined) {\n reason = signal.aborted\n ? { kind: 'aborted' }\n : { kind: 'budget-exhausted', budget: 'steps', forcedFinalAnswer: false }\n }\n const usageReport = summarizeModelCallUsage(modelCallReports)\n const usage = authoritativeTokenUsage(usageReport)\n const candidate: TurnOutcome = {\n reason, text, steps, usageReport, toolCalls, traceId,\n ...usage === undefined ? {} : { usage },\n }\n const entriesBeforeHook = options.history.entries().length\n const canContinue = reason.kind === 'completed'\n && steps < maxSteps\n && admissionStop() === undefined\n await runOptionalHook(options.hooks?.onTurnEnd, [{\n outcome: candidate,\n snapshot: options.history.snapshot(),\n canContinue,\n }], options, signal, 'onTurnEnd')\n // Hooks object by appending context rather than by returning a veto. Re-run only\n // a normally completed turn; abort/error/budget outcomes remain terminal.\n if (canContinue\n && options.history.entries().length > entriesBeforeHook\n && !signal.aborted) {\n reason = undefined\n continue turnLifecycle\n }\n outcome = candidate\n break\n }\n await emit({\n type: 'span-end', trace: root, at: now(),\n status: outcome.reason.kind === 'error' ? 'error' : outcome.reason.kind === 'aborted' ? 'aborted' : 'success',\n output: { reason: outcome.reason, text },\n ...outcome.usage === undefined ? {} : { usage: outcome.usage },\n ...outcome.reason.kind === 'error' ? { error: { type: 'ModelError', message: outcome.reason.failure.message, code: outcome.reason.failure.code } } : {},\n })\n rootEnded = true\n if (turnOperationId !== undefined) {\n options.accounting?.endOperation(\n turnOperationId,\n outcome.reason.kind === 'error' ? 'error' : outcome.reason.kind === 'aborted' ? 'aborted' : 'success',\n { data: { reason: outcome.reason.kind, steps, toolCalls } },\n )\n turnOperationEnded = true\n }\n await emit({ type: 'turn-end', outcome, trace: root })\n } catch (error: unknown) {\n const code = errorCodeOf(error)\n if (rootStarted && !rootEnded) {\n await emit({\n type: 'span-end', trace: root, at: now(), status: signal.aborted ? 'aborted' : 'error',\n error: {\n type: error instanceof Error ? error.name : 'RuntimeError',\n message: messageOf(error),\n ...code === undefined ? {} : { code },\n },\n }).catch(() => undefined)\n }\n if (turnOperationId !== undefined && !turnOperationEnded) {\n options.accounting?.endOperation(\n turnOperationId,\n signal.aborted ? 'aborted' : 'error',\n { error },\n )\n turnOperationEnded = true\n }\n throw error\n }\n}\n\n\nexport type { RunTurnOptions } from './turn/types.ts'\n"],"mappings":"qkCAoBA,SAAS,EAAiB,EAAkC,CAE1D,OADI,EAAQ,aAAe,OAAe,IAClC,EAAQ,OAAO,MAAM,CAAC,CAAC,QAAU,GAAK,IAAM,EAAQ,aAAa,QAAU,GAAK,CAC1F,CAGA,SAAgB,EAAQ,EAAoD,CAC1E,MAAO,CACL,OAAS,OAAO,gBAAiB,CAC/B,IAAM,EAAa,EAAuB,CAAO,EAC3C,EAAQ,IAAI,EACZ,EAAW,IAAI,gBACf,EAAoB,EAAe,EAAW,mBAAqB,IAAQ,mBAAmB,EAI9F,EAAO,EAAU,EAHR,EAAW,SAAW,IAAA,GACjC,EAAS,OACT,YAAY,IAAI,CAAC,EAAW,OAAQ,EAAS,MAAM,CAAC,EACb,GAAS,EAAM,KAAK,EAAe,CAAK,CAAC,CAAC,CAAC,CACnF,SAAW,EAAM,MAAM,EAAG,GAAS,EAAM,KAAK,CAAK,CAAC,EACvD,GAA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G,EAAQ,OAAO,OAAS,QAAU,CAAE,MAAO,CAAE,KAAM,aAAc,QAAS,EAAQ,OAAO,QAAQ,QAAS,KAAM,EAAQ,OAAO,QAAQ,IAAK,CAAE,EAAI,CAAC,CACxJ,CAAC,EACD,EAAY,GACR,IAAoB,IAAA,KACtB,EAAQ,YAAY,aAClB,EACA,EAAQ,OAAO,OAAS,QAAU,QAAU,EAAQ,OAAO,OAAS,UAAY,UAAY,UAC5F,CAAE,KAAM,CAAE,OAAQ,EAAQ,OAAO,KAAM,QAAO,WAAU,CAAE,CAC5D,EACA,EAAqB,IAEvB,MAAM,EAAK,CAAE,KAAM,WAAY,UAAS,MAAO,CAAK,CAAC,CACrD,OAAS,EAAgB,CACvB,IAAM,EAAO,EAAY,CAAK,EAmB9B,MAlBI,GAAe,CAAC,GAClB,MAAM,EAAK,CACT,KAAM,WAAY,MAAO,EAAM,GAAI,EAAI,EAAG,OAAQ,EAAO,QAAU,UAAY,QAC/E,MAAO,CACL,KAAM,aAAiB,MAAQ,EAAM,KAAO,eAC5C,QAAS,EAAU,CAAK,EACxB,GAAG,IAAS,IAAA,GAAY,CAAC,EAAI,CAAE,MAAK,CACtC,CACF,CAAC,CAAC,CAAC,UAAY,IAAA,EAAS,EAEtB,IAAoB,IAAA,IAAa,CAAC,IACpC,EAAQ,YAAY,aAClB,EACA,EAAO,QAAU,UAAY,QAC7B,CAAE,OAAM,CACV,EACA,EAAqB,IAEjB,CACR,CACF"}
|
|
1
|
+
{"version":3,"file":"run-turn.js","names":[],"sources":["../../../src/agent/loop/run-turn.ts"],"sourcesContent":["import { createUserMessage } from '../../message/index.ts'\nimport { detachedFrozen } from '../../primitives/index.ts'\nimport type { ModelCallReport } from '../../observation/index.ts'\nimport { waitForSettlement } from '../../async/index.ts'\nimport { authoritativeTokenUsage, budgetTokenTotal, summarizeModelCallUsage } from '../accounting/ledger.ts'\nimport { createSpanId, createTraceId, type TraceRef } from '../trace/trace.ts'\nimport type { AgentEvent, ExhaustedBudget, ToolDeclineReason, TurnHooks, TurnOutcome } from './types.ts'\nimport { AwaitedEventQueue } from './queue.ts'\nimport { scheduleToolCalls } from './schedule.ts'\nimport { captureProgramGrants } from '../tool/nested.ts'\nimport { ProgramResultStore } from '../tool/program-results.ts'\nimport { type RunTurnOptions } from './turn/types.ts'\nimport { resolveBounds, positiveFinite, snapshotRunTurnOptions } from './turn/config.ts'\nimport { codedRuntimeError, messageOf, errorCodeOf, now } from './turn/common.ts'\nimport { runOptionalHook, runHook } from './turn/hooks.ts'\nimport { maintenanceEmitter, emitAssistantContent, textOf } from './turn/content.ts'\nimport { repeatKey, toolActionPattern, repeatedSuffixCycle } from './turn/repetition.ts'\nimport { modelRound } from './turn/model-round.ts'\nimport { accountingUsageStop } from './turn/usage-stop.ts'\nimport { ContextSectionRuntime } from '../context/section.ts'\nimport type { ContextToolTouch } from '../context/types.ts'\n\nfunction hasCallableTools(options: RunTurnOptions): boolean {\n if (options.toolChoice === 'none') return false\n return (options.tools?.names().length ?? 0) > 0 || (options.nativeTools?.length ?? 0) > 0\n}\n\n/** Run one bounded turn as a backpressured event stream. */\nexport function runTurn(options: RunTurnOptions): AsyncIterable<AgentEvent> {\n return {\n async * [Symbol.asyncIterator]() {\n const invocation = snapshotRunTurnOptions(options)\n const queue = new AwaitedEventQueue<AgentEvent>()\n const consumer = new AbortController()\n const teardownTimeoutMs = positiveFinite(invocation.teardownTimeoutMs ?? 30_000, 'teardownTimeoutMs')\n const signal = invocation.signal === undefined\n ? consumer.signal\n : AbortSignal.any([invocation.signal, consumer.signal])\n const task = driveTurn(invocation, signal, event => queue.push(detachedFrozen(event)))\n .then(() => queue.close(), error => queue.fail(error))\n try {\n while (true) {\n const item = await queue.take()\n if (item.done) break\n yield item.value\n }\n await task\n } finally {\n consumer.abort(new Error('turn event consumer stopped'))\n queue.close()\n if (!await waitForSettlement(task, teardownTimeoutMs)) {\n throw codedRuntimeError(\n `turn producer ignored cancellation for more than ${teardownTimeoutMs}ms`,\n 'TURN_TEARDOWN_TIMEOUT',\n consumer.signal.reason,\n )\n }\n }\n },\n }\n}\n\nasync function driveTurn(\n options: RunTurnOptions,\n signal: AbortSignal,\n emit: (event: AgentEvent) => Promise<void>,\n): Promise<void> {\n const bounds = resolveBounds(options.bounds)\n const maxTotalTokens = bounds.maxTotalTokens === 'auto' ? Infinity : bounds.maxTotalTokens\n // Infinity is local control flow only. Public configuration/events retain\n // the serializable 'auto' value, and all other admission guards still apply.\n const maxSteps = bounds.maxSteps === 'auto' ? Infinity : bounds.maxSteps\n const traceId = options.trace?.traceId ?? createTraceId()\n const root: TraceRef = { traceId, spanId: createSpanId(), parentSpanId: options.trace?.parentSpanId ?? null }\n const turn = Math.max(1, options.history.entries().filter(entry =>\n entry.event.kind === 'user' && entry.event.message.source.kind === 'user').length)\n const startedAt = now()\n let steps = 0\n let toolCalls = 0\n // Descending, so \"how many are below the remainder\" counts the crossings.\n const budgetReminders = [...bounds.toolBudgetRemindAt]\n .filter(threshold => threshold > 0 && threshold < bounds.maxToolCalls)\n .sort((left, right) => right - left)\n let budgetRemindersSent = 0\n /** How many full budgets an unwalled turn has spent and been told about. */\n let overBudgetNoticesSent = 0\n /** Sequence of the budget notice currently on the surface, if any. */\n let budgetNoticeSeq: number | undefined\n let stepReminderSent = false\n let tokenRemindersSent = 0\n let consecutiveErrors = 0\n let text = ''\n const modelCallReports: ModelCallReport[] = []\n let reason: TurnOutcome['reason'] | undefined\n let outcome: TurnOutcome\n let lastRepeat: { key: string; count: number } | undefined\n const actionSteps: string[] = []\n const emitMaintenance = maintenanceEmitter(emit, root)\n /**\n * Put the current budget notice on the surface, replacing the previous one.\n *\n * One live notice, never a pile of them. Appending each new remainder leaves\n * \"16 calls remain\" and \"6 calls remain\" both readable, and a model that\n * plans against the older number plans against a budget it no longer has.\n * Codex keeps exactly one `<rollout_budget>` fragment for the same reason\n * (`context/rollout_budget.rs`), replacing it as the number moves.\n * @param text - What the model should read now.\n */\n const appendBudgetNotice = (text: string): void => {\n const message = createUserMessage({\n source: { kind: 'app', producer: 'tool-loop-budget-guard' },\n content: [{ type: 'text', text }],\n })\n const previous = budgetNoticeSeq\n // Replacing is best-effort. Compaction can shadow the earlier notice\n // between steps, and a replace whose target is no longer on the surface is\n // rejected — which must cost the model a reminder, never the turn.\n if (previous !== undefined) {\n try {\n budgetNoticeSeq = options.history.append(\n { kind: 'user', message },\n { op: 'replace', from: previous, to: previous, targets: [previous] },\n ).seq\n return\n } catch {\n budgetNoticeSeq = undefined\n }\n }\n budgetNoticeSeq = options.history.append({ kind: 'user', message }).seq\n }\n const contextSections = options.contextSections === undefined || options.contextSections.length === 0\n ? undefined\n : new ContextSectionRuntime({\n sections: options.contextSections,\n history: options.history,\n ...options.logger === undefined ? {} : { logger: options.logger },\n guard: (pending, name) => runHook(pending, options, signal, name),\n scope: { agentId: options.trace?.agentId, conversationId: options.trace?.conversationId },\n })\n /** Tool calls committed since the last section reconcile. */\n let contextTouches: ContextToolTouch[] = []\n let rootStarted = false\n let rootEnded = false\n const callableTools = hasCallableTools(options)\n const programs = options.experimentalPrograms === undefined ? undefined : captureProgramGrants(options.experimentalPrograms)\n // Handles programs retain live for this turn only.\n const programResults = programs === undefined ? undefined : new ProgramResultStore()\n const dedicatedFinalOutput = options.outputFormat?.type === 'json_schema' && callableTools\n const turnOperationId = options.accounting?.startOperation('turn', {\n data: { turn, model: options.config.model },\n })\n let turnOperationEnded = false\n let usageStop: TurnOutcome['reason'] | undefined\n // Shared by retries, hook continuations, and both finalizer paths. Finalizers\n // may have a separate step allowance, never a separate token allowance.\n const admissionStop = (): TurnOutcome['reason'] | undefined => {\n if (signal.aborted) return { kind: 'aborted' }\n const mandatoryStop = accountingUsageStop(options.accounting)\n if (mandatoryStop !== undefined) return mandatoryStop\n if (usageStop !== undefined) return usageStop\n const tokens = budgetTokenTotal(summarizeModelCallUsage(modelCallReports))\n return tokens !== undefined && tokens >= maxTotalTokens\n ? { kind: 'budget-exhausted', budget: 'tokens', forcedFinalAnswer: false }\n : undefined\n }\n\n try {\n await emit({\n type: 'span-start', trace: root, at: startedAt,\n name: `invoke_agent ${options.trace?.agentId ?? 'agent'}`, kind: 'invoke_agent',\n attributes: {\n 'gen_ai.operation.name': 'invoke_agent',\n 'gen_ai.agent.id': options.trace?.agentId ?? 'agent',\n 'gen_ai.agent.name': options.trace?.agentName ?? options.trace?.agentId ?? 'agent',\n 'gen_ai.request.model': options.config.model,\n ...options.trace?.conversationId === undefined\n ? {}\n : { 'gen_ai.conversation.id': options.trace.conversationId },\n },\n })\n rootStarted = true\n await emit({ type: 'turn-start', turn, trace: root })\n\n turnLifecycle: while (true) {\n while (reason === undefined && steps < maxSteps && !signal.aborted) {\n reason = admissionStop()\n if (reason !== undefined) break\n // Auto has no step countdown. Warn from the same usage total as admission,\n // before a hard token stop can leave the agent without a reporting call.\n const usedTokens = budgetTokenTotal(summarizeModelCallUsage(modelCallReports))\n if (bounds.maxTotalTokens !== 'auto' && usedTokens !== undefined) {\n const crossed = [0.5, 0.75, 0.9].filter(ratio => usedTokens >= maxTotalTokens * ratio).length\n if (crossed > tokenRemindersSent) {\n tokenRemindersSent = crossed\n const remaining = Math.max(0, maxTotalTokens - usedTokens)\n options.history.append({ kind: 'user', message: createUserMessage({\n source: { kind: 'app', producer: 'tool-loop-token-guard' },\n content: [{ type: 'text', text: `Token budget: ${remaining} of ${bounds.maxTotalTokens} aggregate tokens remain. Each request also spends input tokens on the accumulated context. `\n + (crossed >= 2 ? 'Stop broad exploration. ' : 'Prioritize outstanding verification and reporting. ')\n + 'Reserve capacity for the required self-check, honest todo reconciliation and substantive final report. State unavailable evidence and unfinished work; do not claim it is verified. No extra model call is allowed after the hard token limit.',\n }],\n }) })\n }\n }\n // Leave time to reconcile a plan and submit a result before the final\n // tools-disabled summary. Tool-call reminders do not cover step limits.\n if (!stepReminderSent && steps > 0 && maxSteps - steps <= 2) {\n stepReminderSent = true\n options.history.append({ kind: 'user', message: createUserMessage({\n source: { kind: 'app', producer: 'tool-loop-step-guard' },\n content: [{ type: 'text', text:\n `${maxSteps - steps} work steps remain. Finish essential verification, update any task list honestly, and submit the result if required. Summarize findings, evidence, and unfinished work; do not start new exploration.`,\n }],\n }) })\n }\n // Recomputed before the request that will read it, so a section reacting to\n // the previous step's tool calls is already on the surface.\n if (contextSections !== undefined) {\n await contextSections.reconcile(steps, contextTouches, signal)\n contextTouches = []\n }\n const step = steps + 1\n const round = await modelRound(\n options, signal, emit, emitMaintenance, root, turn, step,\n dedicatedFinalOutput\n ? 'process'\n : options.outputFormat?.type === 'json_schema' ? 'final' : 'standard',\n )\n steps++\n if (round.report !== undefined) modelCallReports.push(round.report)\n if (round.message !== undefined) {\n options.history.append({\n kind: 'assistant', message: round.message,\n ...round.finish.kind === 'aborted' ? { interrupted: true as const } : {},\n ...round.usage === undefined ? {} : { usage: round.usage },\n })\n await emit({ type: 'assistant-message', message: round.message, trace: round.trace })\n await emitAssistantContent(round, emit)\n text = textOf(round.message.content)\n }\n usageStop = accountingUsageStop(options.accounting) ?? (round.usageRequired\n ? { kind: 'error', failure: { message: 'provider usage is required by the configured run policy', code: 'USAGE_REQUIRED' } }\n : round.usageUnavailable\n ? { kind: 'usage-unavailable', modelCallId: round.report?.modelCallId ?? 'unknown' }\n : undefined)\n if (signal.aborted || round.finish.kind === 'aborted') { reason = { kind: 'aborted' }; break }\n // Pair emitted tool calls with declined results even when policy stops the\n // run; never execute those calls or allow a retry hook to override policy.\n if (round.finish.kind === 'error' && usageStop !== undefined) {\n reason = { kind: 'error', failure: round.finish.failure }\n break\n }\n if (round.usageRequired && (round.calls.length === 0 || options.tools === undefined)) { reason = usageStop; break }\n if (round.finish.kind === 'error' && !round.usageRequired) {\n reason = admissionStop()\n if (reason !== undefined) break\n const decision = await runOptionalHook(options.hooks?.onRequestError, [{\n turn, step, failure: round.finish.failure, snapshot: options.history.snapshot(), signal,\n ...(options.logger === undefined ? {} : { logger: options.logger }),\n emit: emitMaintenance,\n }], options, signal, 'onRequestError')\n const maintenanceStop = accountingUsageStop(options.accounting)\n if (maintenanceStop !== undefined) { reason = signal.aborted ? { kind: 'aborted' } : maintenanceStop; break }\n if (decision === 'retry' && steps < maxSteps) continue\n reason = { kind: 'error', failure: round.finish.failure }\n break\n }\n if (round.finish.kind === 'max-tokens' && !round.usageRequired) { reason = { kind: 'max-tokens' }; break }\n if (round.calls.length === 0 && round.usageUnavailable) {\n reason = accountingUsageStop(options.accounting) ?? { kind: 'usage-unavailable', modelCallId: round.report?.modelCallId ?? 'unknown' }\n break\n }\n if (round.calls.length === 0 && dedicatedFinalOutput) {\n reason = admissionStop()\n if (reason !== undefined) break\n options.history.append({ kind: 'user', message: createUserMessage({\n source: { kind: 'app', producer: 'structured-output-finalizer' },\n content: [{\n type: 'text',\n text: 'The process phase is complete. Return the final answer now in the requested output format. Do not call tools.',\n }],\n }) })\n const final = await modelRound(\n options, signal, emit, emitMaintenance, root, turn, steps + 1, 'final',\n )\n steps++\n if (final.report !== undefined) modelCallReports.push(final.report)\n if (final.message !== undefined) {\n options.history.append({\n kind: 'assistant', message: final.message,\n ...final.usage === undefined ? {} : { usage: final.usage },\n })\n await emit({ type: 'assistant-message', message: final.message, trace: final.trace })\n await emitAssistantContent(final, emit)\n text = textOf(final.message.content)\n }\n if (final.finish.kind === 'aborted') reason = { kind: 'aborted' }\n else if (final.finish.kind === 'error') reason = { kind: 'error', failure: final.finish.failure }\n else if (final.finish.kind === 'max-tokens') reason = { kind: 'max-tokens' }\n else if (final.usageRequired) reason = { kind: 'error', failure: {\n message: 'provider usage is required by the configured run policy',\n code: 'USAGE_REQUIRED',\n } }\n else if (final.usageUnavailable) {\n reason = accountingUsageStop(options.accounting) ?? { kind: 'usage-unavailable', modelCallId: final.report?.modelCallId ?? 'unknown' }\n } else reason = { kind: 'completed' }\n break\n }\n // A provider that repeated an id had the repeat dropped. Saying so is what\n // keeps the model from reading one result for two calls as a tool that\n // silently ignored it.\n if (round.droppedDuplicateCalls !== undefined) {\n options.history.append({ kind: 'user', message: createUserMessage({\n source: { kind: 'app', producer: 'tool-loop-duplicate-guard' },\n content: [{\n type: 'text',\n text: `You reused the tool-call id ${round.droppedDuplicateCalls.map(id => `'${id}'`).join(', ')}.`\n + ' A result pairs to exactly one call, so the repeat was not run and only the first'\n + ' call of that id has a result. Give every call its own id, and call again if you'\n + ' still need what the dropped one would have done.',\n }],\n }) })\n }\n if (round.calls.length === 0 || options.tools === undefined) { reason = { kind: 'completed' }; break }\n\n // Calls the budget does not govern: submitting, asking, delegating. They\n // are dispatched even when the budget is spent, so the model always has a\n // legal way to finish. See `ToolDefinition.budgetExempt`.\n const budgetedCalls = round.calls\n .filter(call => options.tools?.get(call.toolName)?.budgetExempt !== true).length\n const remaining = Math.max(0, bounds.maxToolCalls - toolCalls)\n let repeatProjection = lastRepeat\n const projectedRepeats = round.calls.map(call => {\n const key = repeatKey(call)\n // Count consecutive calls, not lifetime visits to a source or test command.\n // Distinct intervening work may change its result. Alternating loops are\n // handled separately by the step-cycle guard below.\n const count = repeatProjection?.key === key ? repeatProjection.count + 1 : 1\n repeatProjection = { key, count }\n return count\n })\n const repeatedLimitBeforeDispatch = projectedRepeats.some(count => count >= bounds.repeatToolLimit)\n const actionPattern = toolActionPattern(round.calls)\n const projectedCycle = repeatedSuffixCycle(\n [...actionSteps, actionPattern],\n bounds.maxToolCycleLength,\n )\n const cycleLimitBeforeDispatch = projectedCycle !== undefined\n && projectedCycle.repetitions >= bounds.toolCycleLimit\n const currentUsage = summarizeModelCallUsage(modelCallReports)\n const budgetTokens = budgetTokenTotal(currentUsage)\n const tokenLimitBeforeDispatch = budgetTokens !== undefined\n && budgetTokens >= maxTotalTokens\n const guardDeclined = repeatedLimitBeforeDispatch || cycleLimitBeforeDispatch || tokenLimitBeforeDispatch || round.usageRequired\n // Name the limit that actually declined the call. Reporting a repeat guard\n // as an empty budget teaches the model the wrong lesson, and it repeats the\n // call on the next turn with the budget it was told it lacked.\n const declineReason: ToolDeclineReason = tokenLimitBeforeDispatch\n ? 'tokens'\n : cycleLimitBeforeDispatch\n ? 'tool-call-cycle'\n : repeatedLimitBeforeDispatch\n ? 'repeated-tool-call'\n : round.usageRequired\n ? 'usage-required'\n : 'tool-calls'\n // `continue` takes the wall down: the budget becomes a notice and the turn\n // is bounded by steps, tokens, and the run-level ledger instead. Guards\n // that mean \"this is not working\" still decline, whatever the setting.\n const budgetIsAWall = bounds.onExhausted !== 'continue'\n const scheduled = await scheduleToolCalls({\n calls: round.calls, catalog: options.tools, history: options.history,\n position: { turn, step,\n ...(options.accounting === undefined ? {} : { runId: options.accounting.runId }),\n ...(options.trace?.conversationId === undefined ? {} : { conversationId: options.trace.conversationId }),\n }, signal, parentTrace: root,\n maxParallel: bounds.maxParallel,\n dispatchLimit: guardDeclined ? 0 : budgetIsAWall ? remaining : round.calls.length,\n declineReason,\n maxResultBytes: bounds.maxToolResultBytes,\n maxResultTokens: bounds.maxToolResultTokens,\n resultOverflow: bounds.toolResultOverflow,\n ...options.spillStore === undefined ? {} : { spillStore: options.spillStore },\n maxDurationMs: bounds.maxToolDurationMs,\n teardownTimeoutMs: bounds.toolTeardownTimeoutMs,\n ...(options.logger === undefined ? {} : { logger: options.logger }),\n ...options.interceptors === undefined ? {} : { interceptors: options.interceptors },\n ...options.approvals === undefined ? {} : { approvals: options.approvals },\n ...options.accounting === undefined ? {} : { accounting: options.accounting },\n emit,\n ...options.hooks?.checkpoint === undefined ? {} : {\n checkpoint: (context: Parameters<NonNullable<TurnHooks['checkpoint']>>[0]) => runHook(\n Promise.resolve(options.hooks?.checkpoint?.(context)), options, signal, 'checkpoint',\n ),\n },\n }, {\n admissionLimit: guardDeclined ? 0 : budgetIsAWall ? remaining : 'unbounded',\n ...programs === undefined ? {} : { programs },\n ...programResults === undefined ? {} : { programResults },\n })\n // Results commit in model order, one per requested call, so the pairing\n // holds for declined calls too. A short result list means a sibling failed\n // its contract and the turn is already unwinding; reporting a guessed\n // outcome would be worse than reporting nothing.\n if (contextSections !== undefined && scheduled.results.length === round.calls.length) {\n contextTouches.push(...round.calls.map((call, index) => ({\n toolName: call.toolName,\n rawArguments: call.rawArguments,\n failed: scheduled.results[index]?.isError ?? true,\n })))\n }\n toolCalls += scheduled.budgeted\n const remainingAfterDispatch = Math.max(0, bounds.maxToolCalls - toolCalls)\n // One reminder per threshold crossed, not one per turn.\n //\n // This was a single boolean: the model was told once, at 25% remaining,\n // and then never again however close it came to the end. A model warned at\n // sixteen calls left and still exploring at four has been told nothing\n // since, and runs into the wall with no notice — which is what produces a\n // red \"no remaining tool-call budget\" where an answer should have been.\n //\n // Codex counts thresholds rather than remembering a flag\n // (`rollout_budget.rs`, `reminder_index`): every threshold now below the\n // remaining budget that has not been reported yet gets reported. Crossing\n // several at once collapses into the one that matters, the lowest.\n const crossed = budgetReminders.filter(threshold => remainingAfterDispatch <= threshold).length\n if (crossed > budgetRemindersSent && remainingAfterDispatch > 0) {\n budgetRemindersSent = crossed\n appendBudgetNotice(\n `Tool budget: ${remainingAfterDispatch} of ${bounds.maxToolCalls} calls remain in this turn.`\n + ' Stop broad exploration, make the necessary edits, and reserve calls for'\n + (budgetIsAWall\n ? ' verification. When the budget runs out no further work call will run, so'\n + ' finish with what you can still verify.'\n : ' verification. Past the budget you are expected to be wrapping up, not'\n + ' opening new lines of work.'),\n )\n }\n // Past the budget with the wall down. The turn is not stopped — the model\n // keeps its tools — but it is told, once per further budget spent, that it\n // is now expected to be finishing. This is the shape of Codex's\n // `budget_limit` goal prompt: no new substantive work, wrap up, name what\n // is left.\n if (!budgetIsAWall && remainingAfterDispatch === 0) {\n const windows = Math.floor(toolCalls / bounds.maxToolCalls)\n if (windows > overBudgetNoticesSent) {\n overBudgetNoticesSent = windows\n appendBudgetNotice(\n `Tool budget spent: ${toolCalls} calls made against a budget of ${bounds.maxToolCalls}.`\n + ' Do not start new substantive work. Finish what is in flight, verify what you'\n + ' can, and answer — stating plainly what is unverified or unfinished.',\n )\n }\n }\n await emit({ type: 'step-end', turn, step, trace: round.trace })\n\n actionSteps.push(actionPattern)\n let repeatedLimit = repeatedLimitBeforeDispatch\n for (let index = 0; index < round.calls.length; index++) {\n const call = round.calls[index]\n const result = scheduled.results[index]\n if (call === undefined || result === undefined) continue\n consecutiveErrors = result.isError ? consecutiveErrors + 1 : 0\n const key = repeatKey(call)\n const count = lastRepeat?.key === key ? lastRepeat.count + 1 : 1\n lastRepeat = { key, count }\n if (count === bounds.repeatToolWarningAt) {\n options.history.append({ kind: 'user', message: createUserMessage({\n source: { kind: 'app', producer: 'tool-loop-repeat-guard' },\n content: [{ type: 'text', text: `You have called ${call.toolName} with the same arguments ${count} consecutive times. Reassess before repeating it.` }],\n }) })\n }\n if (count >= bounds.repeatToolLimit) repeatedLimit = true\n }\n if (projectedCycle?.repetitions === bounds.toolCycleWarningAt) {\n options.history.append({ kind: 'user', message: createUserMessage({\n source: { kind: 'app', producer: 'tool-loop-cycle-guard' },\n content: [{\n type: 'text',\n text: `Tool-use pattern repeated ${projectedCycle.repetitions} times across ${projectedCycle.period} step(s). Reassess the approach and identify concrete new evidence before continuing.`,\n }],\n }) })\n }\n if (scheduled.concluded) { reason = { kind: 'concluded-by-tool', toolName: scheduled.concludedBy ?? 'unknown' }; break }\n if (signal.aborted) { reason = { kind: 'aborted' }; break }\n if (round.usageRequired) { reason = usageStop; break }\n if (round.usageUnavailable) {\n reason = accountingUsageStop(options.accounting) ?? { kind: 'usage-unavailable', modelCallId: round.report?.modelCallId ?? 'unknown' }\n break\n }\n let exhausted: ExhaustedBudget | undefined\n const reportReserveReached = bounds.maxTotalTokens !== 'auto'\n && bounds.finalReportReserveTokens > 0 && budgetTokens !== undefined\n && budgetTokens >= maxTotalTokens - bounds.finalReportReserveTokens\n if (tokenLimitBeforeDispatch) exhausted = 'tokens'\n else if (reportReserveReached) exhausted = 'tokens'\n else if (cycleLimitBeforeDispatch) exhausted = 'tool-call-cycle'\n else if (budgetIsAWall && budgetedCalls > remaining) exhausted = 'tool-calls'\n else if (consecutiveErrors >= bounds.maxConsecutiveToolErrors) exhausted = 'consecutive-tool-errors'\n else if (repeatedLimit) exhausted = 'repeated-tool-call'\n else if (steps >= maxSteps) exhausted = 'steps'\n if (exhausted !== undefined) {\n const forced = (exhausted !== 'tokens' || (reportReserveReached && !tokenLimitBeforeDispatch))\n && bounds.onExhausted !== 'stop'\n && admissionStop() === undefined\n if (forced) {\n const final = await modelRound(\n options, signal, emit, emitMaintenance, root, turn, steps + 1, 'forced-final',\n )\n steps++\n if (final.report !== undefined) modelCallReports.push(final.report)\n if (final.message !== undefined) {\n options.history.append({ kind: 'assistant', message: final.message, ...final.usage === undefined ? {} : { usage: final.usage } })\n await emit({ type: 'assistant-message', message: final.message, trace: final.trace })\n await emitAssistantContent(final, emit)\n text = textOf(final.message.content)\n }\n if (final.finish.kind === 'aborted') {\n reason = { kind: 'aborted' }\n break\n }\n if (final.finish.kind === 'error') {\n reason = { kind: 'error', failure: final.finish.failure }\n break\n }\n if (final.finish.kind === 'max-tokens') {\n reason = { kind: 'max-tokens' }\n break\n }\n if (final.usageRequired) {\n reason = { kind: 'error', failure: {\n message: 'provider usage is required by the configured run policy',\n code: 'USAGE_REQUIRED',\n } }\n break\n }\n if (final.usageUnavailable) {\n reason = accountingUsageStop(options.accounting) ?? { kind: 'usage-unavailable', modelCallId: final.report?.modelCallId ?? 'unknown' }\n break\n }\n }\n reason = { kind: 'budget-exhausted', budget: exhausted, forcedFinalAnswer: forced,\n ...(exhausted === 'tokens' && reportReserveReached && !tokenLimitBeforeDispatch\n ? { trigger: 'report-reserve' as const } : {}),\n }\n }\n }\n\n if (reason === undefined) {\n reason = signal.aborted\n ? { kind: 'aborted' }\n : { kind: 'budget-exhausted', budget: 'steps', forcedFinalAnswer: false }\n }\n const usageReport = summarizeModelCallUsage(modelCallReports)\n const usage = authoritativeTokenUsage(usageReport)\n const candidate: TurnOutcome = {\n reason, text, steps, usageReport, toolCalls, traceId,\n ...usage === undefined ? {} : { usage },\n }\n const entriesBeforeHook = options.history.entries().length\n const canContinue = reason.kind === 'completed'\n && steps < maxSteps\n && admissionStop() === undefined\n await runOptionalHook(options.hooks?.onTurnEnd, [{\n outcome: candidate,\n snapshot: options.history.snapshot(),\n canContinue,\n }], options, signal, 'onTurnEnd')\n // Hooks object by appending context rather than by returning a veto. Re-run only\n // a normally completed turn; abort/error/budget outcomes remain terminal.\n if (canContinue\n && options.history.entries().length > entriesBeforeHook\n && !signal.aborted) {\n reason = undefined\n continue turnLifecycle\n }\n outcome = candidate\n break\n }\n if (outcome.reason.kind === 'aborted') {\n // Without this, the next turn sees an unfinished request and a cancelled\n // tool call, and a model resumes the abandoned work instead of answering\n // the new message (observed live). Codex and Claude Code record the same\n // interruption marker.\n options.history.append({ kind: 'user', message: createUserMessage({\n source: { kind: 'app', producer: 'turn-interrupted' },\n content: [{ type: 'text', text: 'The previous request was interrupted before it finished. Use the next message to determine what to do next.' }],\n }) })\n }\n await emit({\n type: 'span-end', trace: root, at: now(),\n status: outcome.reason.kind === 'error' ? 'error' : outcome.reason.kind === 'aborted' ? 'aborted' : 'success',\n output: { reason: outcome.reason, text },\n ...outcome.usage === undefined ? {} : { usage: outcome.usage },\n ...outcome.reason.kind === 'error' ? { error: { type: 'ModelError', message: outcome.reason.failure.message, code: outcome.reason.failure.code } } : {},\n })\n rootEnded = true\n if (turnOperationId !== undefined) {\n options.accounting?.endOperation(\n turnOperationId,\n outcome.reason.kind === 'error' ? 'error' : outcome.reason.kind === 'aborted' ? 'aborted' : 'success',\n { data: { reason: outcome.reason.kind, steps, toolCalls } },\n )\n turnOperationEnded = true\n }\n await emit({ type: 'turn-end', outcome, trace: root })\n } catch (error: unknown) {\n const code = errorCodeOf(error)\n if (rootStarted && !rootEnded) {\n await emit({\n type: 'span-end', trace: root, at: now(), status: signal.aborted ? 'aborted' : 'error',\n error: {\n type: error instanceof Error ? error.name : 'RuntimeError',\n message: messageOf(error),\n ...code === undefined ? {} : { code },\n },\n }).catch(() => undefined)\n }\n if (turnOperationId !== undefined && !turnOperationEnded) {\n options.accounting?.endOperation(\n turnOperationId,\n signal.aborted ? 'aborted' : 'error',\n { error },\n )\n turnOperationEnded = true\n }\n throw error\n } finally {\n programResults?.close()\n }\n}\n\n\nexport type { RunTurnOptions } from './turn/types.ts'\n"],"mappings":"osCAsBA,SAAS,EAAiB,EAAkC,CAE1D,OADI,EAAQ,aAAe,OAAe,IAClC,EAAQ,OAAO,MAAM,CAAC,CAAC,QAAU,GAAK,IAAM,EAAQ,aAAa,QAAU,GAAK,CAC1F,CAGA,SAAgB,EAAQ,EAAoD,CAC1E,MAAO,CACL,OAAS,OAAO,gBAAiB,CAC/B,IAAM,EAAa,EAAuB,CAAO,EAC3C,EAAQ,IAAI,EACZ,EAAW,IAAI,gBACf,EAAoB,EAAe,EAAW,mBAAqB,IAAQ,mBAAmB,EAI9F,EAAO,EAAU,EAHR,EAAW,SAAW,IAAA,GACjC,EAAS,OACT,YAAY,IAAI,CAAC,EAAW,OAAQ,EAAS,MAAM,CAAC,EACb,GAAS,EAAM,KAAK,EAAe,CAAK,CAAC,CAAC,CAAC,CACnF,SAAW,EAAM,MAAM,EAAG,GAAS,EAAM,KAAK,CAAK,CAAC,EACvD,GAAI,CACF,OAAa,CACX,IAAM,EAAO,MAAM,EAAM,KAAK,EAC9B,GAAI,EAAK,KAAM,MACf,MAAM,EAAK,KACb,CACA,MAAM,CACR,QAAU,CAGR,GAFA,EAAS,MAAU,MAAM,6BAA6B,CAAC,EACvD,EAAM,MAAM,EACR,CAAC,MAAM,EAAkB,EAAM,CAAiB,EAClD,MAAM,EACJ,oDAAoD,EAAkB,IACtE,wBACA,EAAS,OAAO,MAClB,CAEJ,CACF,CACF,CACF,CAEA,eAAe,EACb,EACA,EACA,EACe,CACf,IAAM,EAAS,EAAc,EAAQ,MAAM,EACrC,EAAiB,EAAO,iBAAmB,OAAS,IAAW,EAAO,eAGtE,EAAW,EAAO,WAAa,OAAS,IAAW,EAAO,SAC1D,EAAU,EAAQ,OAAO,SAAW,EAAc,EAClD,EAAiB,CA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,OAAO,OAAS,QAAU,CAAE,MAAO,CAAE,KAAM,aAAc,QAAS,EAAQ,OAAO,QAAQ,QAAS,KAAM,EAAQ,OAAO,QAAQ,IAAK,CAAE,EAAI,CAAC,CACxJ,CAAC,EACD,EAAY,GACR,IAAoB,IAAA,KACtB,EAAQ,YAAY,aAClB,EACA,EAAQ,OAAO,OAAS,QAAU,QAAU,EAAQ,OAAO,OAAS,UAAY,UAAY,UAC5F,CAAE,KAAM,CAAE,OAAQ,EAAQ,OAAO,KAAM,QAAO,WAAU,CAAE,CAC5D,EACA,EAAqB,IAEvB,MAAM,EAAK,CAAE,KAAM,WAAY,UAAS,MAAO,CAAK,CAAC,CACrD,OAAS,EAAgB,CACvB,IAAM,EAAO,EAAY,CAAK,EAmB9B,MAlBI,GAAe,CAAC,GAClB,MAAM,EAAK,CACT,KAAM,WAAY,MAAO,EAAM,GAAI,EAAI,EAAG,OAAQ,EAAO,QAAU,UAAY,QAC/E,MAAO,CACL,KAAM,aAAiB,MAAQ,EAAM,KAAO,eAC5C,QAAS,EAAU,CAAK,EACxB,GAAG,IAAS,IAAA,GAAY,CAAC,EAAI,CAAE,MAAK,CACtC,CACF,CAAC,CAAC,CAAC,UAAY,IAAA,EAAS,EAEtB,IAAoB,IAAA,IAAa,CAAC,IACpC,EAAQ,YAAY,aAClB,EACA,EAAO,QAAU,UAAY,QAC7B,CAAE,OAAM,CACV,EACA,EAAqB,IAEjB,CACR,QAAU,CACR,GAAgB,MAAM,CACxB,CACF"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"schedule.d.ts","names":[],"sources":["../../../src/agent/loop/schedule.ts"],"mappings":";;;;;;;;;;;
|
|
1
|
+
{"version":3,"file":"schedule.d.ts","names":[],"sources":["../../../src/agent/loop/schedule.ts"],"mappings":";;;;;;;;;;;UA8BiB;WACN,gBAAgB;WAChB,SAAS;WACT,SAAS;WACT,UAAU;WACV,QAAQ;WACR,SAAS;WACT,aAAa;WACb;;;;;;;WAOA;;WAEA,gBAAgB;;WAEhB;;WAEA,iBAAiB;;WAEjB,aAAa;;WAEb;;WAEA;;WAEA;WACA,wBAAwB;WACxB,YAAY;WACZ,QAAQ,OAAO,eAAe;WAC9B,aAAa;WACb,aAAa;;UAEP;WACN,kBAAkB;WAClB;WACA;WACA;;WAEA;;WAEA;;;iBAgCW,aAAa,SAAS,sBAAsB,QAAQ"}
|
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import{detachedFrozen as e}from"../../primitives/snapshot.js";import{waitForSettlement as t}from"../../async/settlement.js";import{createSpanId as n}from"../../observation/context.js";import{createToolResultMessage as r,createUserMessage as i}from"../../message/message.js";import{estimateTextBlockTokens as a,previewForSpill as o,truncateMiddleToTokens as s}from"../tool/output-budget.js";import{TOOL_ERROR_CODES as c,ToolError as l,toolErrorDisposition as u}from"../tool/errors.js";import{
|
|
2
|
-
`),f=e.resultOverflow??`auto`,p=e.spillStore;if(f!==`truncate`&&p!==void 0)try{let e=await p.save(d,{toolName:t.call.toolName,callId:String(t.call.callId)});return
|
|
1
|
+
import{detachedFrozen as e}from"../../primitives/snapshot.js";import{waitForSettlement as t}from"../../async/settlement.js";import{createSpanId as n}from"../../observation/context.js";import{createToolResultMessage as r,createUserMessage as i}from"../../message/message.js";import{estimateTextBlockTokens as a,previewForSpill as o,truncateMiddleToTokens as s}from"../tool/output-budget.js";import{TOOL_ERROR_CODES as c,ToolError as l,toolErrorDisposition as u}from"../tool/errors.js";import{NESTED_TOOL_ERROR_CODES as d,attachNestedToolPort as f}from"../tool/nested.js";import{authorizeToolCall as p,dispatchAuthorizedToolCall as m,finalizeToolCall as h,prepareToolCall as g,toolFailure as _}from"../tool/pipeline.js";import{createToolAdmission as v}from"./admission.js";import{emitEvent as y,errorCode as b,immutableResult as x,messageOf as S,now as C,raceWithSignal as w,teardownFailure as T,withApprovalEvents as E}from"./tool-call-support.js";import{ProgramRun as D,validPrograms as O}from"./program.js";async function k(e){return await A(e)}async function A(e,t={}){let n=H(e.maxParallel??8,`maxParallel`),r=H(e.maxResultBytes??4194304,`maxResultBytes`),i=H(e.maxDurationMs??6e5,`maxDurationMs`),a=H(e.teardownTimeoutMs??3e4,`teardownTimeoutMs`),o=Object.freeze(e.calls.map(B)),s=v(t.admissionLimit??Math.max(0,e.dispatchLimit??o.length)),c={admission:s,maxDurationMs:i,teardownTimeoutMs:a,maxResultBytes:r,programs:O(t.programs),programResults:t.programResults},l=[],u=0,d=0,f,p=0,m;for(;p<o.length;){let t=o[p];if(t===void 0)break;let i=m??j(e,t);if(m=void 0,i.mode===`exclusive`){let n=await M(e,i,c);u+=+!!n.dispatched,d+=+(n.declined===!0);let a=await L(e,n,r);l.push(a),f===void 0&&!a.isError&&a.concludesTurn&&(f=t.toolName),p++;continue}let a=[],s=new AbortController,h={...e,signal:AbortSignal.any([e.signal,s.signal])},g=i;try{for(;p<o.length&&a.length<n&&o[p]!==void 0;){let e=g;if(e.mode!==`parallel`)break;let t=await M(h,e,c);u+=+!!t.dispatched,d+=+(t.declined===!0),a.push(t),p++;let r=o[p];r!==void 0&&a.length<n&&(g=j(h,r),g.mode!==`parallel`&&(m=g))}}catch(t){throw s.abort(t),await I(e,a,r),t}if(a.length===0)continue;let _,v=!1;for(let t of a)try{let n=await L(e,t,r);l.push(n),f===void 0&&!n.isError&&n.concludesTurn&&(f=t.call.toolName)}catch(e){v||(_=e),v=!0,s.abort(e)}if(v)throw _}return{results:Object.freeze(l),concluded:f!==void 0,...f===void 0?{}:{concludedBy:f},dispatched:u,budgeted:s.budgeted,declined:d}}function j(e,t){return g({catalog:e.catalog,call:t,position:e.position,signal:e.signal,...e.logger===void 0?{}:{logger:e.logger},...e.interceptors===void 0?{}:{interceptors:e.interceptors},...e.approvals===void 0?{}:{approvals:e.approvals}})}async function M(e,t,r){let{maxDurationMs:i,teardownTimeoutMs:a}=r,o=AbortSignal.timeout(i),s=AbortSignal.any([e.signal,o]),c={...t,options:{...t.options,signal:s,teardownTimeoutMs:a},context:{...t.context,signal:s}},l=c.options.call,u={traceId:e.parentTrace.traceId,spanId:n(),parentSpanId:e.parentTrace.spanId};e.history.append({kind:`tool-call`,callId:l.callId,name:l.toolName,rawArguments:l.rawArguments}),await y(e,{type:`span-start`,trace:u,at:C(),name:`execute_tool ${l.toolName}`,kind:`execute_tool`,attributes:{"gen_ai.operation.name":`execute_tool`,"gen_ai.tool.name":l.toolName,"gen_ai.tool.call.id":l.callId},input:l.rawArguments}),await y(e,{type:`tool-call`,call:l,trace:u});let f=e.catalog.get(l.toolName)?.budgetExempt===!0,p=r.programs.get(l.toolName);if(p!==void 0&&(f||t.mode!==`exclusive`))return{call:l,trace:u,signal:s,deadline:o,teardownTimeoutMs:a,dispatched:!1,pending:Promise.resolve(_(`this program tool must be exclusive and must not be budget-exempt`,d.CONFIGURATION))};let m=r.admission.reserve(f);if(m===void 0)return{call:l,trace:u,signal:s,deadline:o,teardownTimeoutMs:a,dispatched:!1,declined:!0,pending:Promise.resolve(P(e.declineReason??`tool-calls`))};try{return await N(e,c,l,u,s,o,m,r,p)}finally{m.release()}}async function N(e,n,r,i,a,o,s,u,d){let{maxDurationMs:h,teardownTimeoutMs:g}=u;if(e.signal.aborted)return{call:r,trace:i,signal:a,deadline:o,teardownTimeoutMs:g,dispatched:!1,pending:Promise.resolve(_(`the call was cancelled before it started`,c.ABORTED_BEFORE_DISPATCH))};let v=p(E(e,n,i)),y;try{y=await w(v,a)}catch(e){if(!a.aborted)throw e;if(!await t(v,g))throw T(r.toolName,`authorization`,g,e);return{call:r,trace:i,signal:a,deadline:o,teardownTimeoutMs:g,dispatched:!1,pending:Promise.resolve(V(o,h))}}if(y.kind===`final`)return{call:r,trace:i,signal:a,deadline:o,teardownTimeoutMs:g,dispatched:!1,pending:Promise.resolve(y.result)};try{let n=Promise.resolve(e.checkpoint?.({kind:`before-tool-dispatch`,call:r,snapshot:e.history.snapshot(),signal:a,...e.logger===void 0?{}:{logger:e.logger}}));try{await w(n,a)}catch(e){if(!a.aborted)throw e;if(!await t(n,g))throw T(r.toolName,`checkpoint`,g,e)}}catch(e){if(e instanceof l&&e.code===c.TEARDOWN_TIMEOUT)throw e;return{call:r,trace:i,signal:a,deadline:o,teardownTimeoutMs:g,dispatched:!1,pending:Promise.resolve(_(`history checkpoint failed: ${S(e)}`,c.CHECKPOINT_FAILED))}}if(a.aborted)return{call:r,trace:i,signal:a,deadline:o,teardownTimeoutMs:g,dispatched:!1,pending:Promise.resolve(V(o,h))};let b=d===void 0?void 0:new D(e,u,d,{call:r,trace:i,signal:a});b!==void 0&&f(y.call,b.port,e=>b.bindExecutionSignal(e)),s.confirm();let x=m(y.call);return x.catch(()=>void 0),{call:r,trace:i,signal:a,deadline:o,teardownTimeoutMs:g,authorized:y.call,dispatched:!0,...b===void 0?{}:{program:b},pending:x}}function P(e){return{isError:!1,value:void 0,content:[{type:`text`,text:F(e)}],meta:{declined:!0,reason:e}}}function F(e){let t=` Answer now from what you already have, and say plainly what is unverified or unfinished.`;switch(e){case`tool-calls`:return`This call was not run: the turn has spent its tool-call budget. Further work calls will not run either, so do not retry it.`+t;case`repeated-tool-call`:return`This call was not run: it repeats a call already made with the same arguments, and repeating it cannot produce a new result. Change approach or finish.`+t;case`tool-call-cycle`:return`This call was not run: the same sequence of calls has repeated several times without progress. Break the cycle rather than re-entering it.`+t;case`tokens`:return`This call was not run: the turn has spent its token budget.`+t;case`consecutive-tool-errors`:return`This call was not run: too many calls in a row have failed. Something in the approach is wrong, not the individual call.`+t;case`steps`:return`This call was not run: the turn has no model steps left.`+t;case`usage-required`:return`This call was not run: the run policy requires provider usage reporting that the last model call did not supply.`+t}}async function I(e,t,n){for(let r of t)try{await L(e,r,n)}catch{}}async function L(e,n,a){let o,s,c=!1;try{let r;try{r=await w(n.pending,n.signal)}catch(e){if(!n.signal.aborted)throw e;if(!await t(n.pending,n.teardownTimeoutMs))throw T(n.call.toolName,`execution`,n.teardownTimeoutMs,e);r=V(n.deadline)}if(n.program!==void 0){if(!await n.program.close(n.teardownTimeoutMs))throw T(n.call.toolName,`nested call`,n.teardownTimeoutMs,void 0);let e=n.program.fatal;if(e!==void 0)throw u(e)===`fatal`?e:l.fatal(S(e),b(e),{cause:e})}let i=r;if(n.authorized!==void 0){let e=h(n.authorized,r);try{i=await w(e,n.signal)}catch(r){if(!n.signal.aborted)throw r;if(!await t(e,n.teardownTimeoutMs))throw T(n.call.toolName,`finalization`,n.teardownTimeoutMs,r);i=V(n.deadline)}}o=x(await R(e,n,i),a)}catch(e){n.program?.abort(e),c=u(e)===`fatal`,s=e,o=x(_(S(e),b(e)),a)}let d=r({callId:n.call.callId,content:[...o.content],isError:o.isError});if(e.history.append({kind:`tool-result`,callId:n.call.callId,message:d,result:o}),await y(e,{type:`tool-result`,call:n.call,result:o,trace:n.trace}),await y(e,{type:`span-end`,trace:n.trace,at:C(),status:o.isError?`error`:`success`,output:o.isError?{error:o.error}:o.value,...o.isError?{error:{type:`ToolError`,message:o.error.message,code:o.error.code}}:{}}),o.additionalContext!==void 0&&e.history.append({kind:`user`,message:i({content:[...o.additionalContext],source:{kind:`app`,producer:`tool:${n.call.toolName}`}})}),c)throw s;return o}async function R(e,t,n){let r=e.maxResultTokens,i=e.catalog.get(t.call.toolName)?.maxOutputTokens,c=r===void 0?i:i===void 0?r:Math.min(r,i);if(c===void 0)return n;let l=a(n.content);if(l<=c)return n;let u=n.content.filter(e=>e.type===`text`);if(u.length===0)return n;let d=u.map(e=>e.text).join(`
|
|
2
|
+
`),f=e.resultOverflow??`auto`,p=e.spillStore;if(f!==`truncate`&&p!==void 0)try{let e=await p.save(d,{toolName:t.call.toolName,callId:String(t.call.callId)});return z(n,`${o(d,Math.max(1,Math.floor(c*.75)))}\n\n[Output exceeded this call's budget of ${String(c)} estimated tokens. The full ${String(e.bytes)} bytes are saved. ${e.retrieval}]`,{outputSpilled:{locator:e.locator,bytes:e.bytes,estimatedTokens:l}})}catch{}let m=s(d,c);return z(n,m.text+`\n\n[Output was ${String(m.originalTokens)} estimated tokens, over this call's budget of ${String(c)}. Omitted output does not mean the operation failed. Check an existing receipt or current state; repeat the operation only when the host confirms it is safe.]`,{outputTruncated:{estimatedTokens:m.originalTokens,budget:c}})}function z(e,t,n){let r=!1,i=[];for(let n of e.content){if(n.type!==`text`){i.push(n);continue}r||(r=!0,i.push({type:`text`,text:t}))}return{...e,content:i,meta:{...e.meta,...n}}}function B(t){if(typeof t.callId!=`string`||t.callId.length===0||typeof t.toolName!=`string`||t.toolName.length===0||typeof t.rawArguments!=`string`)throw TypeError(`tool call identity, name, and raw arguments must be strings`);return e(t)}function V(e,t){let n=t===void 0?`configured time limit`:`${t}ms time limit`;return e.aborted?_(`the tool exceeded its ${n}`,c.TIMEOUT):_(`the call was cancelled`,c.ABORTED)}function H(e,t){if(!Number.isInteger(e)||e<1)throw RangeError(`${t} must be a positive integer`);return e}export{k as runToolCalls,A as scheduleToolCalls};
|
|
3
3
|
//# sourceMappingURL=schedule.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"schedule.js","names":[],"sources":["../../../src/agent/loop/schedule.ts"],"sourcesContent":["import { createToolResultMessage, createUserMessage } from '../../message/index.ts'\nimport type { ContentBlock } from '../../message/index.ts'\nimport { detachedFrozen } from '../../primitives/index.ts'\nimport type { JsonObject } from '../../primitives/index.ts'\nimport { waitForSettlement } from '../../async/index.ts'\nimport type { History } from '../history/history.ts'\nimport type { ApprovalBroker } from '../tool/approval.ts'\nimport type { ToolCallPosition, ToolExecutionResult } from '../tool/definition.ts'\nimport {\n estimateTextBlockTokens, previewForSpill, truncateMiddleToTokens,\n type SpillStore, type ToolOutputOverflowPolicy,\n} from '../tool/output-budget.ts'\nimport { TOOL_ERROR_CODES, ToolError, toolErrorDisposition } from '../tool/errors.ts'\nimport {\n authorizeToolCall, dispatchAuthorizedToolCall, finalizeToolCall, prepareToolCall, toolFailure,\n type AuthorizedToolCall, type ToolCallRequest, type ToolInterceptor,\n} from '../tool/pipeline.ts'\nimport type { ToolCatalog } from '../tool/registry.ts'\nimport { createSpanId, type TraceRef } from '../trace/trace.ts'\nimport type { AgentEvent, ToolDeclineReason, TurnHooks } from './events.ts'\nimport type { RunAccountingPort } from '../accounting/contracts.ts'\nimport type { SdkLogger } from '../../logging/types.ts'\n\nexport interface RunToolCallsOptions {\n readonly calls: readonly ToolCallRequest[]\n readonly catalog: ToolCatalog\n readonly history: History\n readonly position: ToolCallPosition\n readonly signal: AbortSignal\n readonly logger?: SdkLogger\n readonly parentTrace: TraceRef\n readonly maxParallel?: number\n /**\n * How many BUDGETED calls may still be dispatched this step.\n *\n * Calls to a `budgetExempt` tool are not counted against it, so a spent\n * budget never blocks the model from submitting, asking, or delegating.\n */\n readonly dispatchLimit?: number\n /** Why calls past `dispatchLimit` are not run; shown to the model verbatim. */\n readonly declineReason?: ToolDeclineReason\n /** Estimated tokens of text one result may put in front of the model. */\n readonly maxResultTokens?: number\n /** What happens to output over that budget. Defaults to `auto`. */\n readonly resultOverflow?: ToolOutputOverflowPolicy\n /** Where spilled output goes; `auto` spills only when this is mounted. */\n readonly spillStore?: SpillStore\n /** Maximum serialized bytes retained for one finalized result. Defaults to 4 MiB. */\n readonly maxResultBytes?: number\n /** End-to-end wall-clock allowance for one call. Defaults to 10 minutes. */\n readonly maxDurationMs?: number\n /** Maximum cancellation settlement wait. Defaults to 30 seconds. */\n readonly teardownTimeoutMs?: number\n readonly interceptors?: readonly ToolInterceptor[]\n readonly approvals?: ApprovalBroker\n readonly emit?: (event: AgentEvent) => Promise<void>\n readonly checkpoint?: TurnHooks['checkpoint']\n readonly accounting?: RunAccountingPort\n}\nexport interface ToolCallsOutcome {\n readonly results: readonly ToolExecutionResult[]\n readonly concluded: boolean\n readonly concludedBy?: string\n readonly dispatched: number\n /** Dispatched calls that spent budget; exempt tools are excluded. */\n readonly budgeted: number\n /** Calls the loop refused to run, for the reason in `declineReason`. */\n readonly declined: number\n}\n\ninterface Slot {\n readonly call: ToolCallRequest\n readonly trace: TraceRef\n readonly authorized?: AuthorizedToolCall\n readonly pending: Promise<ToolExecutionResult>\n readonly dispatched: boolean\n /** Whether this dispatch spent turn budget; exempt tools never do. */\n readonly budgeted?: boolean\n /** Set when the loop refused to run the call. */\n readonly declined?: boolean\n readonly signal: AbortSignal\n readonly deadline: AbortSignal\n readonly teardownTimeoutMs: number\n}\n\n/** Execute safe siblings concurrently while committing every result in model order. */\nexport async function runToolCalls(options: RunToolCallsOptions): Promise<ToolCallsOutcome> {\n const maxParallel = positiveInteger(options.maxParallel ?? 8, 'maxParallel')\n const maxResultBytes = positiveInteger(options.maxResultBytes ?? 4 * 1024 * 1024, 'maxResultBytes')\n const maxDurationMs = positiveInteger(options.maxDurationMs ?? 10 * 60_000, 'maxDurationMs')\n const teardownTimeoutMs = positiveInteger(options.teardownTimeoutMs ?? 30_000, 'teardownTimeoutMs')\n const calls = Object.freeze(options.calls.map(immutableCall))\n const dispatchLimit = Math.max(0, options.dispatchLimit ?? calls.length)\n const results: ToolExecutionResult[] = []\n let dispatched = 0\n let budgeted = 0\n let declined = 0\n let concludedBy: string | undefined\n let index = 0\n let carried: ReturnType<typeof prepareToolCall> | undefined\n\n while (index < calls.length) {\n const first = calls[index]\n if (first === undefined) break\n const prepared = carried ?? prepare(options, first)\n carried = undefined\n if (prepared.mode === 'exclusive') {\n const slot = await start(options, prepared, budgeted < dispatchLimit, maxDurationMs, teardownTimeoutMs)\n dispatched += slot.dispatched ? 1 : 0\n budgeted += slot.budgeted === true ? 1 : 0\n declined += slot.declined === true ? 1 : 0\n const result = await commit(options, slot, maxResultBytes)\n results.push(result)\n if (concludedBy === undefined && !result.isError && result.concludesTurn) concludedBy = first.toolName\n index++\n continue\n }\n\n // A rolling parallel segment. Re-prepare each call immediately before start;\n // an updated registry can therefore turn the next call into a barrier.\n const segment: Slot[] = []\n const segmentAbort = new AbortController()\n const segmentOptions: RunToolCallsOptions = {\n ...options,\n signal: AbortSignal.any([options.signal, segmentAbort.signal]),\n }\n let nextPrepared = prepared\n try {\n while (index < calls.length && segment.length < maxParallel) {\n const call = calls[index]\n if (call === undefined) break\n const candidate = nextPrepared\n if (candidate.mode !== 'parallel') break\n const slot = await start(segmentOptions, candidate, budgeted < dispatchLimit, maxDurationMs, teardownTimeoutMs)\n dispatched += slot.dispatched ? 1 : 0\n budgeted += slot.budgeted === true ? 1 : 0\n declined += slot.declined === true ? 1 : 0\n segment.push(slot)\n index++\n const nextCall = calls[index]\n if (nextCall !== undefined && segment.length < maxParallel) {\n nextPrepared = prepare(segmentOptions, nextCall)\n if (nextPrepared.mode !== 'parallel') carried = nextPrepared\n }\n }\n } catch (error: unknown) {\n // Admission of a later sibling failed after earlier bodies started.\n // Cancel and drain everything already owned before propagating that error.\n segmentAbort.abort(error)\n await drainSegment(options, segment, maxResultBytes)\n throw error\n }\n if (segment.length === 0) continue\n // Bodies have already started. Finalization and history publication remain ordered.\n let fatal: unknown\n let hasFatal = false\n for (const slot of segment) {\n try {\n const result = await commit(options, slot, maxResultBytes)\n results.push(result)\n if (concludedBy === undefined && !result.isError && result.concludesTurn) concludedBy = slot.call.toolName\n } catch (error: unknown) {\n if (!hasFatal) fatal = error\n hasFatal = true\n segmentAbort.abort(error)\n }\n }\n // Every parallel body was already dispatched. Commit/drain all siblings so\n // none is orphaned, then propagate the first fatal contract violation.\n if (hasFatal) throw fatal\n }\n return {\n results: Object.freeze(results),\n concluded: concludedBy !== undefined,\n ...concludedBy === undefined ? {} : { concludedBy },\n dispatched,\n budgeted,\n declined,\n }\n}\n\nfunction prepare(options: RunToolCallsOptions, call: ToolCallRequest) {\n return prepareToolCall({\n catalog: options.catalog, call, position: options.position, signal: options.signal,\n ...(options.logger === undefined ? {} : { logger: options.logger }),\n ...options.interceptors === undefined ? {} : { interceptors: options.interceptors },\n ...options.approvals === undefined ? {} : { approvals: options.approvals },\n })\n}\n\nasync function start(\n options: RunToolCallsOptions,\n prepared: ReturnType<typeof prepareToolCall>,\n hasBudget: boolean,\n maxDurationMs: number,\n teardownTimeoutMs: number,\n): Promise<Slot> {\n const deadline = AbortSignal.timeout(maxDurationMs)\n const signal = AbortSignal.any([options.signal, deadline])\n const boundedPrepared = {\n ...prepared,\n options: { ...prepared.options, signal, teardownTimeoutMs },\n context: { ...prepared.context, signal },\n }\n const call = boundedPrepared.options.call\n const trace: TraceRef = {\n traceId: options.parentTrace.traceId,\n spanId: createSpanId(),\n parentSpanId: options.parentTrace.spanId,\n }\n options.history.append({ kind: 'tool-call', callId: call.callId, name: call.toolName, rawArguments: call.rawArguments })\n await emitEvent(options, { type: 'span-start', trace, at: now(), name: `execute_tool ${call.toolName}`, kind: 'execute_tool', attributes: {\n 'gen_ai.operation.name': 'execute_tool', 'gen_ai.tool.name': call.toolName, 'gen_ai.tool.call.id': call.callId,\n }, input: call.rawArguments })\n await emitEvent(options, { type: 'tool-call', call, trace })\n // A tool the model may always reach: submitting, asking, delegating. Letting\n // a budget block these is what turns a spent budget into a dead run.\n const exempt = options.catalog.get(call.toolName)?.budgetExempt === true\n if (!hasBudget && !exempt) return {\n call, trace, signal, deadline, teardownTimeoutMs, dispatched: false, declined: true,\n pending: Promise.resolve(declinedResult(options.declineReason ?? 'tool-calls')),\n }\n if (options.signal.aborted) return {\n call, trace, signal, deadline, teardownTimeoutMs, dispatched: false,\n pending: Promise.resolve(toolFailure('the call was cancelled before it started', TOOL_ERROR_CODES.ABORTED_BEFORE_DISPATCH)),\n }\n let approvalOperation: string | undefined\n const withApprovalEvent = {\n ...boundedPrepared,\n options: {\n ...boundedPrepared.options,\n onApprovalRequest: async (request: Parameters<NonNullable<typeof prepared.options.onApprovalRequest>>[0]) => {\n approvalOperation = options.accounting?.startOperation('user-input', {\n toolCallId: request.callId,\n data: { action: 'approval', toolName: request.toolName },\n })\n await emitEvent(options, { type: 'approval-request', request, trace })\n },\n ...options.accounting === undefined ? {} : {\n onApprovalSettled: (status: 'success' | 'error' | 'aborted', error?: unknown) => {\n if (approvalOperation !== undefined) {\n options.accounting?.endOperation(approvalOperation, status, error === undefined ? {} : { error })\n approvalOperation = undefined\n }\n },\n },\n },\n }\n const authorizationPending = authorizeToolCall(withApprovalEvent)\n let authorization: Awaited<ReturnType<typeof authorizeToolCall>>\n try {\n authorization = await raceWithSignal(authorizationPending, signal)\n } catch (error: unknown) {\n if (!signal.aborted) throw error\n const settled = await waitForSettlement(authorizationPending, teardownTimeoutMs)\n if (!settled) throw teardownFailure(call.toolName, 'authorization', teardownTimeoutMs, error)\n return {\n call, trace, signal, deadline, teardownTimeoutMs, dispatched: false,\n pending: Promise.resolve(cancelledResult(deadline, maxDurationMs)),\n }\n }\n if (authorization.kind === 'final') return {\n call, trace, signal, deadline, teardownTimeoutMs,\n dispatched: false, pending: Promise.resolve(authorization.result),\n }\n try {\n await options.checkpoint?.({\n kind: 'before-tool-dispatch', call, snapshot: options.history.snapshot(), signal,\n ...(options.logger === undefined ? {} : { logger: options.logger }),\n })\n } catch (error: unknown) {\n return {\n call, trace, signal, deadline, teardownTimeoutMs, dispatched: false,\n pending: Promise.resolve(toolFailure(`history checkpoint failed: ${messageOf(error)}`, TOOL_ERROR_CODES.CHECKPOINT_FAILED)),\n }\n }\n const pending = dispatchAuthorizedToolCall(authorization.call)\n // Observe rejection in the same turn in which dispatch creates the promise.\n // commit() still receives and propagates the original rejection in order.\n void pending.catch(() => undefined)\n return {\n call, trace, signal, deadline, teardownTimeoutMs,\n authorized: authorization.call, dispatched: true, budgeted: !exempt,\n pending,\n }\n}\n\n/**\n * What the model reads when the loop refuses to run a call.\n *\n * Not a failure. A failure is something that went wrong, and a model answers\n * one by retrying — with a smaller argument, a different path — which spends\n * exactly what is no longer there. This says what happened and what to do\n * instead, in the plainest terms available, and nothing about it reads as\n * broken tooling.\n * @param reason - Which limit refused the call.\n * @returns A successful result carrying the instruction.\n */\nfunction declinedResult(reason: ToolDeclineReason): ToolExecutionResult {\n return {\n isError: false,\n value: undefined,\n content: [{ type: 'text', text: declineText(reason) }],\n // Never shown to the model; lets a UI render this as declined rather than\n // as work that succeeded.\n meta: { declined: true, reason },\n }\n}\n\n/**\n * The instruction for one decline reason.\n *\n * Each limit gets its own wording: a model told \"no remaining tool-call\n * budget\" when it actually tripped the repeat guard learns the wrong lesson\n * and repeats the call in the next turn.\n * @param reason - Which limit refused the call.\n * @returns The sentence the model reads.\n */\nfunction declineText(reason: ToolDeclineReason): string {\n const finish = ' Answer now from what you already have, and say plainly what is'\n + ' unverified or unfinished.'\n switch (reason) {\n case 'tool-calls':\n return 'This call was not run: the turn has spent its tool-call budget.'\n + ' Further work calls will not run either, so do not retry it.' + finish\n case 'repeated-tool-call':\n return 'This call was not run: it repeats a call already made with the same'\n + ' arguments, and repeating it cannot produce a new result. Change'\n + ' approach or finish.' + finish\n case 'tool-call-cycle':\n return 'This call was not run: the same sequence of calls has repeated'\n + ' several times without progress. Break the cycle rather than'\n + ' re-entering it.' + finish\n case 'tokens':\n return 'This call was not run: the turn has spent its token budget.' + finish\n case 'consecutive-tool-errors':\n return 'This call was not run: too many calls in a row have failed.'\n + ' Something in the approach is wrong, not the individual call.' + finish\n case 'steps':\n return 'This call was not run: the turn has no model steps left.' + finish\n case 'usage-required':\n return 'This call was not run: the run policy requires provider usage'\n + ' reporting that the last model call did not supply.' + finish\n }\n}\n\nasync function drainSegment(\n options: RunToolCallsOptions,\n segment: readonly Slot[],\n maxResultBytes: number,\n): Promise<void> {\n for (const slot of segment) {\n try { await commit(options, slot, maxResultBytes) }\n catch { /* The admission failure remains primary after every owned slot settles. */ }\n }\n}\n\nasync function commit(\n options: RunToolCallsOptions,\n slot: Slot,\n maxResultBytes: number,\n): Promise<ToolExecutionResult> {\n let result: ToolExecutionResult\n let fatal: unknown\n let hasFatal = false\n try {\n let pending: ToolExecutionResult\n try {\n pending = await raceWithSignal(slot.pending, slot.signal)\n } catch (error: unknown) {\n if (!slot.signal.aborted) throw error\n const settled = await waitForSettlement(slot.pending, slot.teardownTimeoutMs)\n if (!settled) throw teardownFailure(slot.call.toolName, 'execution', slot.teardownTimeoutMs, error)\n pending = cancelledResult(slot.deadline)\n }\n let finalized = pending\n if (slot.authorized !== undefined) {\n const finalizing = finalizeToolCall(slot.authorized, pending)\n try {\n finalized = await raceWithSignal(finalizing, slot.signal)\n } catch (error: unknown) {\n if (!slot.signal.aborted) throw error\n const settled = await waitForSettlement(finalizing, slot.teardownTimeoutMs)\n if (!settled) throw teardownFailure(slot.call.toolName, 'finalization', slot.teardownTimeoutMs, error)\n finalized = cancelledResult(slot.deadline)\n }\n }\n result = immutableResult(await boundOutput(options, slot, finalized), maxResultBytes)\n } catch (error: unknown) {\n hasFatal = toolErrorDisposition(error) === 'fatal'\n fatal = error\n result = immutableResult(toolFailure(messageOf(error), errorCode(error)), maxResultBytes)\n }\n const message = createToolResultMessage({ callId: slot.call.callId, content: [...result.content], isError: result.isError })\n options.history.append({ kind: 'tool-result', callId: slot.call.callId, message, result })\n await emitEvent(options, { type: 'tool-result', call: slot.call, result, trace: slot.trace })\n await emitEvent(options, {\n type: 'span-end', trace: slot.trace, at: now(), status: result.isError ? 'error' : 'success',\n output: result.isError ? { error: result.error } : result.value,\n ...result.isError ? { error: { type: 'ToolError', message: result.error.message, code: result.error.code } } : {},\n })\n if (result.additionalContext !== undefined) {\n // Additional context is deliberately a separate application message.\n options.history.append({ kind: 'user', message: createUserMessage({\n content: [...result.additionalContext], source: { kind: 'app', producer: `tool:${slot.call.toolName}` },\n }) })\n }\n if (hasFatal) throw fatal\n return result\n}\n\n/**\n * Keep one tool result inside its share of the context window.\n *\n * This runs at the RESULT boundary rather than when the request is assembled,\n * which is the whole point: by the time an oversized result reaches the model\n * the window is already gone, and the turn's only remaining move is to lose\n * everything it has paid for. Both reference harnesses cut here.\n *\n * The budget is the stricter of the turn's and the tool's own declaration, so\n * a tool that knows it returns a lot can ask for room without any tool being\n * able to exceed what the host allows.\n * @param options - The scheduling options carrying budget and store.\n * @param slot - The call this result belongs to.\n * @param result - The finalized result.\n * @returns The result the model will read.\n */\nasync function boundOutput(\n options: RunToolCallsOptions,\n slot: Slot,\n result: ToolExecutionResult,\n): Promise<ToolExecutionResult> {\n const turnBudget = options.maxResultTokens\n const toolBudget = options.catalog.get(slot.call.toolName)?.maxOutputTokens\n const budget = turnBudget === undefined\n ? toolBudget\n : toolBudget === undefined ? turnBudget : Math.min(turnBudget, toolBudget)\n if (budget === undefined) return result\n const tokens = estimateTextBlockTokens(result.content)\n if (tokens <= budget) return result\n\n // Only text is shortened. Cutting an image block produces a corrupt image\n // rather than a smaller one, so those pass through and are counted by the\n // byte cap instead.\n const texts = result.content.filter(block => block.type === 'text')\n if (texts.length === 0) return result\n const full = texts.map(block => block.text).join('\\n')\n const policy = options.resultOverflow ?? 'auto'\n const store = options.spillStore\n\n if (policy !== 'truncate' && store !== undefined) {\n try {\n // Reserve room for the notice inside the budget, so the replacement is\n // never bigger than what it replaced.\n const record = await store.save(full, {\n toolName: slot.call.toolName, callId: String(slot.call.callId),\n })\n const preview = previewForSpill(full, Math.max(1, Math.floor(budget * 0.75)))\n return replaceText(result, `${preview}\\n\\n[Output exceeded this call's budget of `\n + `${String(budget)} estimated tokens. The full ${String(record.bytes)} bytes are saved. `\n + `${record.retrieval}]`, {\n outputSpilled: { locator: record.locator, bytes: record.bytes, estimatedTokens: tokens },\n })\n } catch {\n // Best-effort, deliberately: a store that is full or unreachable must not\n // cost the model a result it can still read most of.\n }\n }\n\n const truncated = truncateMiddleToTokens(full, budget)\n return replaceText(result, truncated.text\n + `\\n\\n[Output was ${String(truncated.originalTokens)} estimated tokens, over this call's `\n + `budget of ${String(budget)}. Re-run more narrowly if you need the omitted part.]`, {\n outputTruncated: { estimatedTokens: truncated.originalTokens, budget },\n })\n}\n\n/**\n * Swap a result's text for one shortened block, keeping everything else.\n * @param result - The original result.\n * @param text - The replacement text.\n * @param meta - What a UI should know about the replacement.\n * @returns The rewritten result.\n */\nfunction replaceText(\n result: ToolExecutionResult,\n text: string,\n meta: JsonObject,\n): ToolExecutionResult {\n // The replacement takes the FIRST text block's position and the other text\n // blocks drop out. Appending it after the non-text blocks instead would\n // reorder a result whose image came after its caption.\n let placed = false\n const content: ContentBlock[] = []\n for (const block of result.content) {\n if (block.type !== 'text') { content.push(block); continue }\n if (placed) continue\n placed = true\n content.push({ type: 'text', text })\n }\n // `value` is deliberately untouched: it is what a host logs and replays, and\n // shortening it would make the record disagree with what the tool returned.\n return { ...result, content, meta: { ...result.meta, ...meta } }\n}\n\nfunction immutableCall(call: ToolCallRequest): ToolCallRequest {\n if (typeof call.callId !== 'string' || call.callId.length === 0\n || typeof call.toolName !== 'string' || call.toolName.length === 0\n || typeof call.rawArguments !== 'string') {\n throw new TypeError('tool call identity, name, and raw arguments must be strings')\n }\n return detachedFrozen(call)\n}\n\nfunction immutableResult(result: ToolExecutionResult, maxResultBytes: number): ToolExecutionResult {\n try {\n if (serializedBytes(result) > maxResultBytes) {\n return detachedFrozen(toolFailure(\n `tool result exceeds the ${maxResultBytes}-byte retention limit`,\n TOOL_ERROR_CODES.INVALID_RESULT,\n ))\n }\n const detached = detachedFrozen(result)\n const bytes = serializedBytes(detached)\n if (bytes > maxResultBytes) {\n return detachedFrozen(toolFailure(\n `tool result exceeds the ${maxResultBytes}-byte retention limit`,\n TOOL_ERROR_CODES.INVALID_RESULT,\n ))\n }\n return detached\n } catch (error: unknown) {\n throw ToolError.fatal(\n 'tool result could not be detached as lossless structured data',\n TOOL_ERROR_CODES.INVALID_RESULT,\n { cause: error },\n )\n }\n}\n\nfunction serializedBytes(value: unknown): number {\n const serialized = JSON.stringify(value)\n if (serialized === undefined) throw new TypeError('tool result is not lossless JSON')\n return new TextEncoder().encode(serialized).byteLength\n}\n\nfunction cancelledResult(deadline: AbortSignal, maxDurationMs?: number): ToolExecutionResult {\n const limit = maxDurationMs === undefined ? 'configured time limit' : `${maxDurationMs}ms time limit`\n return deadline.aborted\n ? toolFailure(\n `the tool exceeded its ${limit}`,\n TOOL_ERROR_CODES.TIMEOUT,\n )\n : toolFailure('the call was cancelled', TOOL_ERROR_CODES.ABORTED)\n}\n\nfunction teardownFailure(\n toolName: string,\n stage: string,\n timeoutMs: number,\n cause: unknown,\n): ToolError {\n return ToolError.fatal(\n `tool \"${toolName}\" ${stage} ignored cancellation for more than ${timeoutMs}ms; the in-process operation may still be running`,\n TOOL_ERROR_CODES.TEARDOWN_TIMEOUT,\n { cause },\n )\n}\n\nasync function raceWithSignal<T>(pending: Promise<T>, signal: AbortSignal): Promise<T> {\n if (signal.aborted) throw signal.reason ?? new Error('tool call aborted')\n return await new Promise<T>((resolve, reject) => {\n const abort = () => {\n signal.removeEventListener('abort', abort)\n reject(signal.reason ?? new Error('tool call aborted'))\n }\n signal.addEventListener('abort', abort, { once: true })\n void pending.then(\n value => { signal.removeEventListener('abort', abort); resolve(value) },\n error => { signal.removeEventListener('abort', abort); reject(error) },\n )\n })\n}\n\nasync function emitEvent(options: RunToolCallsOptions, event: AgentEvent): Promise<void> {\n await options.emit?.(detachedFrozen(event))\n}\n\nfunction positiveInteger(value: number, name: string): number {\n if (!Number.isInteger(value) || value < 1) throw new RangeError(`${name} must be a positive integer`)\n return value\n}\nfunction errorCode(error: unknown): string {\n return typeof error === 'object' && error !== null && 'code' in error && typeof error.code === 'string'\n ? error.code : TOOL_ERROR_CODES.FAILED\n}\nfunction messageOf(error: unknown): string { return error instanceof Error ? error.message : String(error) }\nfunction now(): string { return new Date().toISOString() }\n"],"mappings":"wnBAsFA,eAAsB,EAAa,EAAyD,CAC1F,IAAM,EAAc,EAAgB,EAAQ,aAAe,EAAG,aAAa,EACrE,EAAiB,EAAgB,EAAQ,gBAAkB,QAAiB,gBAAgB,EAC5F,EAAgB,EAAgB,EAAQ,eAAiB,IAAa,eAAe,EACrF,EAAoB,EAAgB,EAAQ,mBAAqB,IAAQ,mBAAmB,EAC5F,EAAQ,OAAO,OAAO,EAAQ,MAAM,IAAI,CAAa,CAAC,EACtD,EAAgB,KAAK,IAAI,EAAG,EAAQ,eAAiB,EAAM,MAAM,EACjE,EAAiC,CAAC,EACpC,EAAa,EACb,EAAW,EACX,EAAW,EACX,EAC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AW,CAC/C,IAAM,MAAc,CAClB,EAAO,oBAAoB,QAAS,CAAK,EACzC,EAAO,EAAO,QAAc,MAAM,mBAAmB,CAAC,CACxD,EACA,EAAO,iBAAiB,QAAS,EAAO,CAAE,KAAM,EAAK,CAAC,EACtD,EAAa,KACX,GAAS,CAAE,EAAO,oBAAoB,QAAS,CAAK,EAAG,EAAQ,CAAK,CAAE,EACtE,GAAS,CAAE,EAAO,oBAAoB,QAAS,CAAK,EAAG,EAAO,CAAK,CAAE,CACvE,CACF,CAAC,CACH,CAEA,eAAe,EAAU,EAA8B,EAAkC,CACvF,MAAM,EAAQ,OAAO,EAAe,CAAK,CAAC,CAC5C,CAEA,SAAS,EAAgB,EAAe,EAAsB,CAC5D,GAAI,CAAC,OAAO,UAAU,CAAK,GAAK,EAAQ,EAAG,MAAU,WAAW,GAAG,EAAK,4BAA4B,EACpG,OAAO,CACT,CACA,SAAS,EAAU,EAAwB,CACzC,OAAO,OAAO,GAAU,UAAY,GAAkB,SAAU,GAAS,OAAO,EAAM,MAAS,SAC3F,EAAM,KAAO,EAAiB,MACpC,CACA,SAAS,EAAU,EAAwB,CAAE,OAAO,aAAiB,MAAQ,EAAM,QAAU,OAAO,CAAK,CAAE,CAC3G,SAAS,GAAc,CAAE,OAAO,IAAI,KAAK,CAAA,CAAE,YAAY,CAAE"}
|
|
1
|
+
{"version":3,"file":"schedule.js","names":[],"sources":["../../../src/agent/loop/schedule.ts"],"sourcesContent":["import { createToolResultMessage, createUserMessage } from '../../message/index.ts'\nimport type { ContentBlock } from '../../message/index.ts'\nimport { detachedFrozen } from '../../primitives/index.ts'\nimport type { JsonObject } from '../../primitives/index.ts'\nimport { waitForSettlement } from '../../async/index.ts'\nimport type { History } from '../history/history.ts'\nimport type { ApprovalBroker } from '../tool/approval.ts'\nimport type { ToolCallPosition, ToolExecutionResult } from '../tool/definition.ts'\nimport {\n estimateTextBlockTokens, previewForSpill, truncateMiddleToTokens,\n type SpillStore, type ToolOutputOverflowPolicy,\n} from '../tool/output-budget.ts'\nimport { TOOL_ERROR_CODES, ToolError, toolErrorDisposition } from '../tool/errors.ts'\nimport {\n authorizeToolCall, dispatchAuthorizedToolCall, finalizeToolCall, prepareToolCall, toolFailure,\n type AuthorizedToolCall, type ToolCallRequest, type ToolInterceptor,\n} from '../tool/pipeline.ts'\nimport type { ToolCatalog } from '../tool/registry.ts'\nimport { createSpanId, type TraceRef } from '../trace/trace.ts'\nimport type { AgentEvent, ToolDeclineReason, TurnHooks } from './events.ts'\nimport type { RunAccountingPort } from '../accounting/contracts.ts'\nimport type { SdkLogger } from '../../logging/types.ts'\nimport { createToolAdmission, type AdmissionTicket } from './admission.ts'\nimport { ProgramRun, validPrograms, type StepRuntime } from './program.ts'\nimport {\n emitEvent, errorCode, immutableResult, messageOf, now, raceWithSignal, teardownFailure, withApprovalEvents,\n} from './tool-call-support.ts'\nimport { attachNestedToolPort, NESTED_TOOL_ERROR_CODES, type ProgramGrant } from '../tool/nested.ts'\nimport type { ProgramResultStore } from '../tool/program-results.ts'\n\nexport interface RunToolCallsOptions {\n readonly calls: readonly ToolCallRequest[]\n readonly catalog: ToolCatalog\n readonly history: History\n readonly position: ToolCallPosition\n readonly signal: AbortSignal\n readonly logger?: SdkLogger\n readonly parentTrace: TraceRef\n readonly maxParallel?: number\n /**\n * How many BUDGETED calls may still be dispatched this step.\n *\n * Calls to a `budgetExempt` tool are not counted against it, so a spent\n * budget never blocks the model from submitting, asking, or delegating.\n */\n readonly dispatchLimit?: number\n /** Why calls past `dispatchLimit` are not run; shown to the model verbatim. */\n readonly declineReason?: ToolDeclineReason\n /** Estimated tokens of text one result may put in front of the model. */\n readonly maxResultTokens?: number\n /** What happens to output over that budget. Defaults to `auto`. */\n readonly resultOverflow?: ToolOutputOverflowPolicy\n /** Where spilled output goes; `auto` spills only when this is mounted. */\n readonly spillStore?: SpillStore\n /** Maximum serialized bytes retained for one finalized result. Defaults to 4 MiB. */\n readonly maxResultBytes?: number\n /** End-to-end wall-clock allowance for one call. Defaults to 10 minutes. */\n readonly maxDurationMs?: number\n /** Maximum cancellation settlement wait. Defaults to 30 seconds. */\n readonly teardownTimeoutMs?: number\n readonly interceptors?: readonly ToolInterceptor[]\n readonly approvals?: ApprovalBroker\n readonly emit?: (event: AgentEvent) => Promise<void>\n readonly checkpoint?: TurnHooks['checkpoint']\n readonly accounting?: RunAccountingPort\n}\nexport interface ToolCallsOutcome {\n readonly results: readonly ToolExecutionResult[]\n readonly concluded: boolean\n readonly concludedBy?: string\n readonly dispatched: number\n /** Dispatched calls that spent budget; exempt tools are excluded. */\n readonly budgeted: number\n /** Calls the loop refused to run, for the reason in `declineReason`. */\n readonly declined: number\n}\n\ninterface Slot {\n readonly call: ToolCallRequest\n readonly trace: TraceRef\n readonly authorized?: AuthorizedToolCall\n readonly pending: Promise<ToolExecutionResult>\n readonly dispatched: boolean\n /** The program this call hosts, when the host granted it one. */\n readonly program?: ProgramRun\n /** Set when the loop refused to run the call. */\n readonly declined?: boolean\n readonly signal: AbortSignal\n readonly deadline: AbortSignal\n readonly teardownTimeoutMs: number\n}\n\n/** Scheduler options the loop owns and does not publish. */\nexport interface InternalScheduleOptions {\n /** Overrides `dispatchLimit`; `unbounded` when the budget is a notice rather than a wall. */\n readonly admissionLimit?: number | 'unbounded'\n /**\n * Program tools and what each may call. Research seam for SP-01; the public\n * way to enable programs is not decided.\n */\n readonly programs?: ReadonlyMap<string, ProgramGrant>\n /** Where programs retain values; owned and closed by the caller. */\n readonly programResults?: ProgramResultStore\n}\n\n/** Execute safe siblings concurrently while committing every result in model order. */\nexport async function runToolCalls(options: RunToolCallsOptions): Promise<ToolCallsOutcome> {\n return await scheduleToolCalls(options)\n}\n\n/** {@link runToolCalls} with the loop's internal options. */\nexport async function scheduleToolCalls(\n options: RunToolCallsOptions,\n internal: InternalScheduleOptions = {},\n): Promise<ToolCallsOutcome> {\n const maxParallel = positiveInteger(options.maxParallel ?? 8, 'maxParallel')\n const maxResultBytes = positiveInteger(options.maxResultBytes ?? 4 * 1024 * 1024, 'maxResultBytes')\n const maxDurationMs = positiveInteger(options.maxDurationMs ?? 10 * 60_000, 'maxDurationMs')\n const teardownTimeoutMs = positiveInteger(options.teardownTimeoutMs ?? 30_000, 'teardownTimeoutMs')\n const calls = Object.freeze(options.calls.map(immutableCall))\n const admission = createToolAdmission(internal.admissionLimit ?? Math.max(0, options.dispatchLimit ?? calls.length))\n const step: StepRuntime = {\n admission, maxDurationMs, teardownTimeoutMs, maxResultBytes,\n programs: validPrograms(internal.programs),\n programResults: internal.programResults,\n }\n const results: ToolExecutionResult[] = []\n let dispatched = 0\n let declined = 0\n let concludedBy: string | undefined\n let index = 0\n let carried: ReturnType<typeof prepareToolCall> | undefined\n\n while (index < calls.length) {\n const first = calls[index]\n if (first === undefined) break\n const prepared = carried ?? prepare(options, first)\n carried = undefined\n if (prepared.mode === 'exclusive') {\n const slot = await start(options, prepared, step)\n dispatched += slot.dispatched ? 1 : 0\n declined += slot.declined === true ? 1 : 0\n const result = await commit(options, slot, maxResultBytes)\n results.push(result)\n if (concludedBy === undefined && !result.isError && result.concludesTurn) concludedBy = first.toolName\n index++\n continue\n }\n\n // A rolling parallel segment. Re-prepare each call immediately before start;\n // an updated registry can therefore turn the next call into a barrier.\n const segment: Slot[] = []\n const segmentAbort = new AbortController()\n const segmentOptions: RunToolCallsOptions = {\n ...options,\n signal: AbortSignal.any([options.signal, segmentAbort.signal]),\n }\n let nextPrepared = prepared\n try {\n while (index < calls.length && segment.length < maxParallel) {\n const call = calls[index]\n if (call === undefined) break\n const candidate = nextPrepared\n if (candidate.mode !== 'parallel') break\n const slot = await start(segmentOptions, candidate, step)\n dispatched += slot.dispatched ? 1 : 0\n declined += slot.declined === true ? 1 : 0\n segment.push(slot)\n index++\n const nextCall = calls[index]\n if (nextCall !== undefined && segment.length < maxParallel) {\n nextPrepared = prepare(segmentOptions, nextCall)\n if (nextPrepared.mode !== 'parallel') carried = nextPrepared\n }\n }\n } catch (error: unknown) {\n // Admission of a later sibling failed after earlier bodies started.\n // Cancel and drain everything already owned before propagating that error.\n segmentAbort.abort(error)\n await drainSegment(options, segment, maxResultBytes)\n throw error\n }\n if (segment.length === 0) continue\n // Bodies have already started. Finalization and history publication remain ordered.\n let fatal: unknown\n let hasFatal = false\n for (const slot of segment) {\n try {\n const result = await commit(options, slot, maxResultBytes)\n results.push(result)\n if (concludedBy === undefined && !result.isError && result.concludesTurn) concludedBy = slot.call.toolName\n } catch (error: unknown) {\n if (!hasFatal) fatal = error\n hasFatal = true\n segmentAbort.abort(error)\n }\n }\n // Every parallel body was already dispatched. Commit/drain all siblings so\n // none is orphaned, then propagate the first fatal contract violation.\n if (hasFatal) throw fatal\n }\n return {\n results: Object.freeze(results),\n concluded: concludedBy !== undefined,\n ...concludedBy === undefined ? {} : { concludedBy },\n dispatched,\n budgeted: admission.budgeted,\n declined,\n }\n}\n\nfunction prepare(options: RunToolCallsOptions, call: ToolCallRequest) {\n return prepareToolCall({\n catalog: options.catalog, call, position: options.position, signal: options.signal,\n ...(options.logger === undefined ? {} : { logger: options.logger }),\n ...options.interceptors === undefined ? {} : { interceptors: options.interceptors },\n ...options.approvals === undefined ? {} : { approvals: options.approvals },\n })\n}\n\nasync function start(\n options: RunToolCallsOptions,\n prepared: ReturnType<typeof prepareToolCall>,\n step: StepRuntime,\n): Promise<Slot> {\n const { maxDurationMs, teardownTimeoutMs } = step\n const deadline = AbortSignal.timeout(maxDurationMs)\n const signal = AbortSignal.any([options.signal, deadline])\n const boundedPrepared = {\n ...prepared,\n options: { ...prepared.options, signal, teardownTimeoutMs },\n context: { ...prepared.context, signal },\n }\n const call = boundedPrepared.options.call\n const trace: TraceRef = {\n traceId: options.parentTrace.traceId,\n spanId: createSpanId(),\n parentSpanId: options.parentTrace.spanId,\n }\n options.history.append({ kind: 'tool-call', callId: call.callId, name: call.toolName, rawArguments: call.rawArguments })\n await emitEvent(options, { type: 'span-start', trace, at: now(), name: `execute_tool ${call.toolName}`, kind: 'execute_tool', attributes: {\n 'gen_ai.operation.name': 'execute_tool', 'gen_ai.tool.name': call.toolName, 'gen_ai.tool.call.id': call.callId,\n }, input: call.rawArguments })\n await emitEvent(options, { type: 'tool-call', call, trace })\n // A tool the model may always reach: submitting, asking, delegating. Letting\n // a budget block these is what turns a spent budget into a dead run.\n const exempt = options.catalog.get(call.toolName)?.budgetExempt === true\n const grant = step.programs.get(call.toolName)\n // A program spends the budget it is charged for; it can never be the free\n // call, and a parallel program would race its own children for siblings.\n if (grant !== undefined && (exempt || prepared.mode !== 'exclusive')) return {\n call, trace, signal, deadline, teardownTimeoutMs, dispatched: false,\n pending: Promise.resolve(toolFailure(\n 'this program tool must be exclusive and must not be budget-exempt',\n NESTED_TOOL_ERROR_CODES.CONFIGURATION,\n )),\n }\n const ticket = step.admission.reserve(exempt)\n if (ticket === undefined) return {\n call, trace, signal, deadline, teardownTimeoutMs, dispatched: false, declined: true,\n pending: Promise.resolve(declinedResult(options.declineReason ?? 'tool-calls')),\n }\n // Every path below that does not start the body returns the reservation.\n try {\n return await authorizeAndDispatch(options, boundedPrepared, call, trace, signal, deadline, ticket, step, grant)\n } finally {\n ticket.release()\n }\n}\n\nasync function authorizeAndDispatch(\n options: RunToolCallsOptions,\n boundedPrepared: ReturnType<typeof prepareToolCall>,\n call: ToolCallRequest,\n trace: TraceRef,\n signal: AbortSignal,\n deadline: AbortSignal,\n ticket: AdmissionTicket,\n step: StepRuntime,\n grant: ProgramGrant | undefined,\n): Promise<Slot> {\n const { maxDurationMs, teardownTimeoutMs } = step\n if (options.signal.aborted) return {\n call, trace, signal, deadline, teardownTimeoutMs, dispatched: false,\n pending: Promise.resolve(toolFailure('the call was cancelled before it started', TOOL_ERROR_CODES.ABORTED_BEFORE_DISPATCH)),\n }\n const authorizationPending = authorizeToolCall(withApprovalEvents(options, boundedPrepared, trace))\n let authorization: Awaited<ReturnType<typeof authorizeToolCall>>\n try {\n authorization = await raceWithSignal(authorizationPending, signal)\n } catch (error: unknown) {\n if (!signal.aborted) throw error\n const settled = await waitForSettlement(authorizationPending, teardownTimeoutMs)\n if (!settled) throw teardownFailure(call.toolName, 'authorization', teardownTimeoutMs, error)\n return {\n call, trace, signal, deadline, teardownTimeoutMs, dispatched: false,\n pending: Promise.resolve(cancelledResult(deadline, maxDurationMs)),\n }\n }\n if (authorization.kind === 'final') return {\n call, trace, signal, deadline, teardownTimeoutMs,\n dispatched: false, pending: Promise.resolve(authorization.result),\n }\n try {\n const checkpointing = Promise.resolve(options.checkpoint?.({\n kind: 'before-tool-dispatch', call, snapshot: options.history.snapshot(), signal,\n ...(options.logger === undefined ? {} : { logger: options.logger }),\n }))\n try { await raceWithSignal(checkpointing, signal) }\n catch (error: unknown) {\n if (!signal.aborted) throw error\n if (!await waitForSettlement(checkpointing, teardownTimeoutMs)) {\n throw teardownFailure(call.toolName, 'checkpoint', teardownTimeoutMs, error)\n }\n }\n } catch (error: unknown) {\n if (error instanceof ToolError && error.code === TOOL_ERROR_CODES.TEARDOWN_TIMEOUT) throw error\n return {\n call, trace, signal, deadline, teardownTimeoutMs, dispatched: false,\n pending: Promise.resolve(toolFailure(`history checkpoint failed: ${messageOf(error)}`, TOOL_ERROR_CODES.CHECKPOINT_FAILED)),\n }\n }\n if (signal.aborted) return {\n call, trace, signal, deadline, teardownTimeoutMs, dispatched: false,\n pending: Promise.resolve(cancelledResult(deadline, maxDurationMs)),\n }\n const program = grant === undefined\n ? undefined\n : new ProgramRun(options, step, grant, { call, trace, signal })\n if (program !== undefined) attachNestedToolPort(authorization.call, program.port, signal => program.bindExecutionSignal(signal))\n ticket.confirm()\n const pending = dispatchAuthorizedToolCall(authorization.call)\n // Observe rejection in the same turn in which dispatch creates the promise.\n // commit() still receives and propagates the original rejection in order.\n void pending.catch(() => undefined)\n return {\n call, trace, signal, deadline, teardownTimeoutMs,\n authorized: authorization.call, dispatched: true,\n ...program === undefined ? {} : { program },\n pending,\n }\n}\n\n/**\n * What the model reads when the loop refuses to run a call.\n *\n * Not a failure. A failure is something that went wrong, and a model answers\n * one by retrying — with a smaller argument, a different path — which spends\n * exactly what is no longer there. This says what happened and what to do\n * instead, in the plainest terms available, and nothing about it reads as\n * broken tooling.\n * @param reason - Which limit refused the call.\n * @returns A successful result carrying the instruction.\n */\nfunction declinedResult(reason: ToolDeclineReason): ToolExecutionResult {\n return {\n isError: false,\n value: undefined,\n content: [{ type: 'text', text: declineText(reason) }],\n // Never shown to the model; lets a UI render this as declined rather than\n // as work that succeeded.\n meta: { declined: true, reason },\n }\n}\n\n/**\n * The instruction for one decline reason.\n *\n * Each limit gets its own wording: a model told \"no remaining tool-call\n * budget\" when it actually tripped the repeat guard learns the wrong lesson\n * and repeats the call in the next turn.\n * @param reason - Which limit refused the call.\n * @returns The sentence the model reads.\n */\nfunction declineText(reason: ToolDeclineReason): string {\n const finish = ' Answer now from what you already have, and say plainly what is'\n + ' unverified or unfinished.'\n switch (reason) {\n case 'tool-calls':\n return 'This call was not run: the turn has spent its tool-call budget.'\n + ' Further work calls will not run either, so do not retry it.' + finish\n case 'repeated-tool-call':\n return 'This call was not run: it repeats a call already made with the same'\n + ' arguments, and repeating it cannot produce a new result. Change'\n + ' approach or finish.' + finish\n case 'tool-call-cycle':\n return 'This call was not run: the same sequence of calls has repeated'\n + ' several times without progress. Break the cycle rather than'\n + ' re-entering it.' + finish\n case 'tokens':\n return 'This call was not run: the turn has spent its token budget.' + finish\n case 'consecutive-tool-errors':\n return 'This call was not run: too many calls in a row have failed.'\n + ' Something in the approach is wrong, not the individual call.' + finish\n case 'steps':\n return 'This call was not run: the turn has no model steps left.' + finish\n case 'usage-required':\n return 'This call was not run: the run policy requires provider usage'\n + ' reporting that the last model call did not supply.' + finish\n }\n}\n\nasync function drainSegment(\n options: RunToolCallsOptions,\n segment: readonly Slot[],\n maxResultBytes: number,\n): Promise<void> {\n for (const slot of segment) {\n try { await commit(options, slot, maxResultBytes) }\n catch { /* The admission failure remains primary after every owned slot settles. */ }\n }\n}\n\nasync function commit(\n options: RunToolCallsOptions,\n slot: Slot,\n maxResultBytes: number,\n): Promise<ToolExecutionResult> {\n let result: ToolExecutionResult\n let fatal: unknown\n let hasFatal = false\n try {\n let pending: ToolExecutionResult\n try {\n pending = await raceWithSignal(slot.pending, slot.signal)\n } catch (error: unknown) {\n if (!slot.signal.aborted) throw error\n const settled = await waitForSettlement(slot.pending, slot.teardownTimeoutMs)\n if (!settled) throw teardownFailure(slot.call.toolName, 'execution', slot.teardownTimeoutMs, error)\n pending = cancelledResult(slot.deadline)\n }\n if (slot.program !== undefined) {\n // The body has returned; no child may start or publish after this point.\n const closed = await slot.program.close(slot.teardownTimeoutMs)\n if (!closed) throw teardownFailure(slot.call.toolName, 'nested call', slot.teardownTimeoutMs, undefined)\n const latched: unknown = slot.program.fatal\n if (latched !== undefined) {\n throw toolErrorDisposition(latched) === 'fatal'\n ? latched\n : ToolError.fatal(messageOf(latched), errorCode(latched), { cause: latched })\n }\n }\n let finalized = pending\n if (slot.authorized !== undefined) {\n const finalizing = finalizeToolCall(slot.authorized, pending)\n try {\n finalized = await raceWithSignal(finalizing, slot.signal)\n } catch (error: unknown) {\n if (!slot.signal.aborted) throw error\n const settled = await waitForSettlement(finalizing, slot.teardownTimeoutMs)\n if (!settled) throw teardownFailure(slot.call.toolName, 'finalization', slot.teardownTimeoutMs, error)\n finalized = cancelledResult(slot.deadline)\n }\n }\n result = immutableResult(await boundOutput(options, slot, finalized), maxResultBytes)\n } catch (error: unknown) {\n slot.program?.abort(error)\n hasFatal = toolErrorDisposition(error) === 'fatal'\n fatal = error\n result = immutableResult(toolFailure(messageOf(error), errorCode(error)), maxResultBytes)\n }\n const message = createToolResultMessage({ callId: slot.call.callId, content: [...result.content], isError: result.isError })\n options.history.append({ kind: 'tool-result', callId: slot.call.callId, message, result })\n await emitEvent(options, { type: 'tool-result', call: slot.call, result, trace: slot.trace })\n await emitEvent(options, {\n type: 'span-end', trace: slot.trace, at: now(), status: result.isError ? 'error' : 'success',\n output: result.isError ? { error: result.error } : result.value,\n ...result.isError ? { error: { type: 'ToolError', message: result.error.message, code: result.error.code } } : {},\n })\n if (result.additionalContext !== undefined) {\n // Additional context is deliberately a separate application message.\n options.history.append({ kind: 'user', message: createUserMessage({\n content: [...result.additionalContext], source: { kind: 'app', producer: `tool:${slot.call.toolName}` },\n }) })\n }\n if (hasFatal) throw fatal\n return result\n}\n\n/**\n * Keep one tool result inside its share of the context window.\n *\n * This runs at the RESULT boundary rather than when the request is assembled,\n * which is the whole point: by the time an oversized result reaches the model\n * the window is already gone, and the turn's only remaining move is to lose\n * everything it has paid for. Both reference harnesses cut here.\n *\n * The budget is the stricter of the turn's and the tool's own declaration, so\n * a tool that knows it returns a lot can ask for room without any tool being\n * able to exceed what the host allows.\n * @param options - The scheduling options carrying budget and store.\n * @param slot - The call this result belongs to.\n * @param result - The finalized result.\n * @returns The result the model will read.\n */\nasync function boundOutput(\n options: RunToolCallsOptions,\n slot: Slot,\n result: ToolExecutionResult,\n): Promise<ToolExecutionResult> {\n const turnBudget = options.maxResultTokens\n const toolBudget = options.catalog.get(slot.call.toolName)?.maxOutputTokens\n const budget = turnBudget === undefined\n ? toolBudget\n : toolBudget === undefined ? turnBudget : Math.min(turnBudget, toolBudget)\n if (budget === undefined) return result\n const tokens = estimateTextBlockTokens(result.content)\n if (tokens <= budget) return result\n\n // Only text is shortened. Cutting an image block produces a corrupt image\n // rather than a smaller one, so those pass through and are counted by the\n // byte cap instead.\n const texts = result.content.filter(block => block.type === 'text')\n if (texts.length === 0) return result\n const full = texts.map(block => block.text).join('\\n')\n const policy = options.resultOverflow ?? 'auto'\n const store = options.spillStore\n\n if (policy !== 'truncate' && store !== undefined) {\n try {\n // Reserve room for the notice inside the budget, so the replacement is\n // never bigger than what it replaced.\n const record = await store.save(full, {\n toolName: slot.call.toolName, callId: String(slot.call.callId),\n })\n const preview = previewForSpill(full, Math.max(1, Math.floor(budget * 0.75)))\n return replaceText(result, `${preview}\\n\\n[Output exceeded this call's budget of `\n + `${String(budget)} estimated tokens. The full ${String(record.bytes)} bytes are saved. `\n + `${record.retrieval}]`, {\n outputSpilled: { locator: record.locator, bytes: record.bytes, estimatedTokens: tokens },\n })\n } catch {\n // Best-effort, deliberately: a store that is full or unreachable must not\n // cost the model a result it can still read most of.\n }\n }\n\n const truncated = truncateMiddleToTokens(full, budget)\n return replaceText(result, truncated.text\n + `\\n\\n[Output was ${String(truncated.originalTokens)} estimated tokens, over this call's `\n + `budget of ${String(budget)}. Omitted output does not mean the operation failed. `\n + 'Check an existing receipt or current state; repeat the operation only when the host confirms it is safe.]', {\n outputTruncated: { estimatedTokens: truncated.originalTokens, budget },\n })\n}\n\n/**\n * Swap a result's text for one shortened block, keeping everything else.\n * @param result - The original result.\n * @param text - The replacement text.\n * @param meta - What a UI should know about the replacement.\n * @returns The rewritten result.\n */\nfunction replaceText(\n result: ToolExecutionResult,\n text: string,\n meta: JsonObject,\n): ToolExecutionResult {\n // The replacement takes the FIRST text block's position and the other text\n // blocks drop out. Appending it after the non-text blocks instead would\n // reorder a result whose image came after its caption.\n let placed = false\n const content: ContentBlock[] = []\n for (const block of result.content) {\n if (block.type !== 'text') { content.push(block); continue }\n if (placed) continue\n placed = true\n content.push({ type: 'text', text })\n }\n // `value` is deliberately untouched: it is what a host logs and replays, and\n // shortening it would make the record disagree with what the tool returned.\n return { ...result, content, meta: { ...result.meta, ...meta } }\n}\n\nfunction immutableCall(call: ToolCallRequest): ToolCallRequest {\n if (typeof call.callId !== 'string' || call.callId.length === 0\n || typeof call.toolName !== 'string' || call.toolName.length === 0\n || typeof call.rawArguments !== 'string') {\n throw new TypeError('tool call identity, name, and raw arguments must be strings')\n }\n return detachedFrozen(call)\n}\n\nfunction cancelledResult(deadline: AbortSignal, maxDurationMs?: number): ToolExecutionResult {\n const limit = maxDurationMs === undefined ? 'configured time limit' : `${maxDurationMs}ms time limit`\n return deadline.aborted\n ? toolFailure(\n `the tool exceeded its ${limit}`,\n TOOL_ERROR_CODES.TIMEOUT,\n )\n : toolFailure('the call was cancelled', TOOL_ERROR_CODES.ABORTED)\n}\n\nfunction positiveInteger(value: number, name: string): number {\n if (!Number.isInteger(value) || value < 1) throw new RangeError(`${name} must be a positive integer`)\n return value\n}\n"],"mappings":"g/BA0GA,eAAsB,EAAa,EAAyD,CAC1F,OAAO,MAAM,EAAkB,CAAO,CACxC,CAGA,eAAsB,EACpB,EACA,EAAoC,CAAC,EACV,CAC3B,IAAM,EAAc,EAAgB,EAAQ,aAAe,EAAG,aAAa,EACrE,EAAiB,EAAgB,EAAQ,gBAAkB,QAAiB,gBAAgB,EAC5F,EAAgB,EAAgB,EAAQ,eAAiB,IAAa,eAAe,EACrF,EAAoB,EAAgB,EAAQ,mBAAqB,IAAQ,mBAAmB,EAC5F,EAAQ,OAAO,OAAO,EAAQ,MAAM,IAAI,CAAa,CAAC,EACtD,EAAY,EAAoB,EAAS,gBAAkB,KAAK,IAAI,EAAG,EAAQ,eAAiB,EAAM,MAAM,CAAC,EAC7G,EAAoB,CACxB,YAAW,gBAAe,oBAAmB,iBAC7C,SAAU,EAAc,EAAS,QAAQ,EACzC,eAAgB,EAAS,cAC3B,EACM,EAAiC,CAAC,EACpC,EAAa,EACb,EAAW,EACX,EACA,EAAQ,EACR,EAEJ,KAAO,EAAQ,EAAM,QAAQ,CAC3B,IAAM,EAAQ,EAAM,GACpB,GAAI,IAAU,IAAA,GAAW,MACzB,IAAM,EAAW,GAAW,EAAQ,EAAS,CAAK,EAElD,GADA,EAAU,IAAA,GACN,EAAS,OAAS,YAAa,CACjC,IAAM,EAAO,MAAM,EAAM,EAAS,EAAU,CAAI,EAChD,GAAc,KAAK,WACnB,GAAY,IAAK,WAAa,IAC9B,IAAM,EAAS,MAAM,EAAO,EAAS,EAAM,CAAc,EACzD,EAAQ,KAAK,CAAM,EACf,IAAgB,IAAA,IAAa,CAAC,EAAO,SAAW,EAAO,gBAAe,EAAc,EAAM,UAC9F,IACA,QACF,CAIA,IAAM,EAAkB,CAAC,EACnB,EAAe,IAAI,gBACnB,E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uB,EAAM,CAAM,EACrD,OAAO,EAAY,EAAQ,EAAU,KACjC,mBAAmB,OAAO,EAAU,cAAc,EAAE,gDACvC,OAAO,CAAM,EAAE,gKACiF,CAC/G,gBAAiB,CAAE,gBAAiB,EAAU,eAAgB,QAAO,CACvE,CAAC,CACH,CASA,SAAS,EACP,EACA,EACA,EACqB,CAIrB,IAAI,EAAS,GACP,EAA0B,CAAC,EACjC,IAAK,IAAM,KAAS,EAAO,QAAS,CAClC,GAAI,EAAM,OAAS,OAAQ,CAAE,EAAQ,KAAK,CAAK,EAAG,QAAS,CACvD,IACJ,EAAS,GACT,EAAQ,KAAK,CAAE,KAAM,OAAQ,MAAK,CAAC,EACrC,CAGA,MAAO,CAAE,GAAG,EAAQ,UAAS,KAAM,CAAE,GAAG,EAAO,KAAM,GAAG,CAAK,CAAE,CACjE,CAEA,SAAS,EAAc,EAAwC,CAC7D,GAAI,OAAO,EAAK,QAAW,UAAY,EAAK,OAAO,SAAW,GACzD,OAAO,EAAK,UAAa,UAAY,EAAK,SAAS,SAAW,GAC9D,OAAO,EAAK,cAAiB,SAChC,MAAU,UAAU,6DAA6D,EAEnF,OAAO,EAAe,CAAI,CAC5B,CAEA,SAAS,EAAgB,EAAuB,EAA6C,CAC3F,IAAM,EAAQ,IAAkB,IAAA,GAAY,wBAA0B,GAAG,EAAc,eACvF,OAAO,EAAS,QACZ,EACE,yBAAyB,IACzB,EAAiB,OACnB,EACA,EAAY,yBAA0B,EAAiB,OAAO,CACpE,CAEA,SAAS,EAAgB,EAAe,EAAsB,CAC5D,GAAI,CAAC,OAAO,UAAU,CAAK,GAAK,EAAQ,EAAG,MAAU,WAAW,GAAG,EAAK,4BAA4B,EACpG,OAAO,CACT"}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{detachedFrozen as e}from"../../primitives/snapshot.js";import{TOOL_ERROR_CODES as t,ToolError as n}from"../tool/errors.js";import{toolFailure as r}from"../tool/pipeline.js";function i(e,t,n){let r;return{...t,options:{...t.options,onApprovalRequest:async t=>{r=e.accounting?.startOperation(`user-input`,{toolCallId:t.callId,data:{action:`approval`,toolName:t.toolName}}),await l(e,{type:`approval-request`,request:t,trace:n})},...e.accounting===void 0?{}:{onApprovalSettled:(t,n)=>{r!==void 0&&(e.accounting?.endOperation(r,t,n===void 0?{}:{error:n}),r=void 0)}}}}}function a(i,a){try{if(o(i)>a)return e(r(`tool result exceeds the ${a}-byte retention limit`,t.INVALID_RESULT));let n=e(i);return o(n)>a?e(r(`tool result exceeds the ${a}-byte retention limit`,t.INVALID_RESULT)):n}catch(e){throw n.fatal(`tool result could not be detached as lossless structured data`,t.INVALID_RESULT,{cause:e})}}function o(e){let t=JSON.stringify(e);if(t===void 0)throw TypeError(`tool result is not lossless JSON`);return new TextEncoder().encode(t).byteLength}function s(e,r,i,a){return n.fatal(`tool "${e}" ${r} ignored cancellation for more than ${i}ms; the in-process operation may still be running`,t.TEARDOWN_TIMEOUT,{cause:a})}async function c(e,t){if(e.catch(()=>void 0),t.aborted)throw t.reason??Error(`tool call aborted`);return await new Promise((n,r)=>{let i=()=>{t.removeEventListener(`abort`,i),r(t.reason??Error(`tool call aborted`))};t.addEventListener(`abort`,i,{once:!0}),e.then(e=>{t.removeEventListener(`abort`,i),n(e)},e=>{t.removeEventListener(`abort`,i),r(e)})})}async function l(t,n){await t.emit?.(e(n))}function u(e){try{let n=typeof e==`object`&&e?Reflect.get(e,`code`):void 0;return typeof n==`string`?n:t.FAILED}catch{return t.FAILED}}function d(e){try{return e instanceof Error?String(e.message):String(e)}catch{return`tool failed with an unreadable error`}}function f(){return new Date().toISOString()}export{l as emitEvent,u as errorCode,a as immutableResult,d as messageOf,f as now,c as raceWithSignal,o as serializedBytes,s as teardownFailure,i as withApprovalEvents};
|
|
2
|
+
//# sourceMappingURL=tool-call-support.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"tool-call-support.js","names":[],"sources":["../../../src/agent/loop/tool-call-support.ts"],"sourcesContent":["/** Helpers the scheduler and nested programs share. Internal to the loop. */\nimport { detachedFrozen } from '../../primitives/index.ts'\nimport type { ApprovalBroker } from '../tool/approval.ts'\nimport type { ToolCallPosition, ToolExecutionResult } from '../tool/definition.ts'\nimport { TOOL_ERROR_CODES, ToolError } from '../tool/errors.ts'\nimport { toolFailure, type prepareToolCall, type ToolInterceptor } from '../tool/pipeline.ts'\nimport type { ToolCatalog } from '../tool/registry.ts'\nimport type { TraceRef } from '../trace/trace.ts'\nimport type { History } from '../history/history.ts'\nimport type { AgentEvent, TurnHooks } from './events.ts'\nimport type { RunAccountingPort } from '../accounting/contracts.ts'\nimport type { SdkLogger } from '../../logging/types.ts'\n\n/** What scheduling shares with its helpers. `RunToolCallsOptions` satisfies it. */\nexport interface ToolCallHost {\n readonly catalog: ToolCatalog\n readonly history: History\n readonly position: ToolCallPosition\n readonly logger?: SdkLogger\n readonly interceptors?: readonly ToolInterceptor[]\n readonly approvals?: ApprovalBroker\n readonly emit?: (event: AgentEvent) => Promise<void>\n readonly checkpoint?: TurnHooks['checkpoint']\n readonly accounting?: RunAccountingPort\n}\n\n/** Pair the broker wait with its public event and its accounting operation. */\nexport function withApprovalEvents(\n options: ToolCallHost,\n prepared: ReturnType<typeof prepareToolCall>,\n trace: TraceRef,\n): ReturnType<typeof prepareToolCall> {\n let approvalOperation: string | undefined\n return {\n ...prepared,\n options: {\n ...prepared.options,\n onApprovalRequest: async (request: Parameters<NonNullable<typeof prepared.options.onApprovalRequest>>[0]) => {\n approvalOperation = options.accounting?.startOperation('user-input', {\n toolCallId: request.callId,\n data: { action: 'approval', toolName: request.toolName },\n })\n await emitEvent(options, { type: 'approval-request', request, trace })\n },\n ...options.accounting === undefined ? {} : {\n onApprovalSettled: (status: 'success' | 'error' | 'aborted', error?: unknown) => {\n if (approvalOperation !== undefined) {\n options.accounting?.endOperation(approvalOperation, status, error === undefined ? {} : { error })\n approvalOperation = undefined\n }\n },\n },\n },\n }\n}\n\nexport function immutableResult(result: ToolExecutionResult, maxResultBytes: number): ToolExecutionResult {\n try {\n if (serializedBytes(result) > maxResultBytes) {\n return detachedFrozen(toolFailure(\n `tool result exceeds the ${maxResultBytes}-byte retention limit`,\n TOOL_ERROR_CODES.INVALID_RESULT,\n ))\n }\n const detached = detachedFrozen(result)\n const bytes = serializedBytes(detached)\n if (bytes > maxResultBytes) {\n return detachedFrozen(toolFailure(\n `tool result exceeds the ${maxResultBytes}-byte retention limit`,\n TOOL_ERROR_CODES.INVALID_RESULT,\n ))\n }\n return detached\n } catch (error: unknown) {\n throw ToolError.fatal(\n 'tool result could not be detached as lossless structured data',\n TOOL_ERROR_CODES.INVALID_RESULT,\n { cause: error },\n )\n }\n}\n\nexport function serializedBytes(value: unknown): number {\n const serialized = JSON.stringify(value)\n if (serialized === undefined) throw new TypeError('tool result is not lossless JSON')\n return new TextEncoder().encode(serialized).byteLength\n}\n\nexport function teardownFailure(\n toolName: string,\n stage: string,\n timeoutMs: number,\n cause: unknown,\n): ToolError {\n return ToolError.fatal(\n `tool \"${toolName}\" ${stage} ignored cancellation for more than ${timeoutMs}ms; the in-process operation may still be running`,\n TOOL_ERROR_CODES.TEARDOWN_TIMEOUT,\n { cause },\n )\n}\n\nexport async function raceWithSignal<T>(pending: Promise<T>, signal: AbortSignal): Promise<T> {\n // The owner has already started this promise; observe it even if cancellation won earlier.\n void pending.catch(() => undefined)\n if (signal.aborted) throw signal.reason ?? new Error('tool call aborted')\n return await new Promise<T>((resolve, reject) => {\n const abort = () => {\n signal.removeEventListener('abort', abort)\n reject(signal.reason ?? new Error('tool call aborted'))\n }\n signal.addEventListener('abort', abort, { once: true })\n void pending.then(\n value => { signal.removeEventListener('abort', abort); resolve(value) },\n error => { signal.removeEventListener('abort', abort); reject(error) },\n )\n })\n}\n\nexport async function emitEvent(options: ToolCallHost, event: AgentEvent): Promise<void> {\n await options.emit?.(detachedFrozen(event))\n}\n\nexport function errorCode(error: unknown): string {\n try {\n const code: unknown = typeof error === 'object' && error !== null ? Reflect.get(error, 'code') : undefined\n return typeof code === 'string' ? code : TOOL_ERROR_CODES.FAILED\n } catch { return TOOL_ERROR_CODES.FAILED }\n}\nexport function messageOf(error: unknown): string {\n try { return error instanceof Error ? String(error.message) : String(error) }\n catch { return 'tool failed with an unreadable error' }\n}\nexport function now(): string { return new Date().toISOString() }\n"],"mappings":"oLA2BA,SAAgB,EACd,EACA,EACA,EACoC,CACpC,IAAI,EACJ,MAAO,CACL,GAAG,EACH,QAAS,CACP,GAAG,EAAS,QACZ,kBAAmB,KAAO,IAAmF,CAC3G,EAAoB,EAAQ,YAAY,eAAe,aAAc,CACnE,WAAY,EAAQ,OACpB,KAAM,CAAE,OAAQ,WAAY,SAAU,EAAQ,QAAS,CACzD,CAAC,EACD,MAAM,EAAU,EAAS,CAAE,KAAM,mBAAoB,UAAS,OAAM,CAAC,CACvE,EACA,GAAG,EAAQ,aAAe,IAAA,GAAY,CAAC,EAAI,CACzC,mBAAoB,EAAyC,IAAoB,CAC3E,IAAsB,IAAA,KACxB,EAAQ,YAAY,aAAa,EAAmB,EAAQ,IAAU,IAAA,GAAY,CAAC,EAAI,CAAE,OAAM,CAAC,EAChG,EAAoB,IAAA,GAExB,CACF,CACF,CACF,CACF,CAEA,SAAgB,EAAgB,EAA6B,EAA6C,CACxG,GAAI,CACF,GAAI,EAAgB,CAAM,EAAI,EAC5B,OAAO,EAAe,EACpB,2BAA2B,EAAe,uBAC1C,EAAiB,cACnB,CAAC,EAEH,IAAM,EAAW,EAAe,CAAM,EAQtC,OAPc,EAAgB,CACtB,EAAI,EACH,EAAe,EACpB,2BAA2B,EAAe,uBAC1C,EAAiB,cACnB,CAAC,EAEI,CACT,OAAS,EAAgB,CACvB,MAAM,EAAU,MACd,gEACA,EAAiB,eACjB,CAAE,MAAO,CAAM,CACjB,CACF,CACF,CAEA,SAAgB,EAAgB,EAAwB,CACtD,IAAM,EAAa,KAAK,UAAU,CAAK,EACvC,GAAI,IAAe,IAAA,GAAW,MAAU,UAAU,kCAA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
|
|
1
|
-
import{waitForSettlement as e}from"../../../async/settlement.js";import{positiveSafeInteger as t}from"./config.js";import{codedRuntimeError as n}from"./common.js";import{nextValueWithAbort as r}from"./cancellation.js";async function i(e,t,n,r,i){if(e
|
|
1
|
+
import{waitForSettlement as e}from"../../../async/settlement.js";import{positiveSafeInteger as t}from"./config.js";import{codedRuntimeError as n}from"./common.js";import{nextValueWithAbort as r}from"./cancellation.js";async function i(e,t,n,r,i){if(e===void 0)return;let o=new AbortController,s=AbortSignal.any([r,o.signal]),c=t.map(e=>typeof e==`object`&&e&&`signal`in e?{...e,signal:s}:e);return await a(Promise.resolve().then(()=>e(...c)),n,r,i,e=>o.abort(e))}async function a(i,a,o,s,c){let l=a.accounting?.startOperation(`hook`,{data:{name:s}}),u=t(a.hookTimeoutMs??6e5,`hookTimeoutMs`),d=t(a.hookTeardownTimeoutMs??3e4,`hookTeardownTimeoutMs`),f=AbortSignal.timeout(u),p=AbortSignal.any([o,f]);try{let e=await r(i,p);return l!==void 0&&a.accounting?.endOperation(l,`success`),e}catch(t){if(!p.aborted)throw l!==void 0&&a.accounting?.endOperation(l,`error`,{error:t}),t;if(c?.(p.reason),!await e(i,d)){let e=n(`turn hook '${s}' ignored cancellation for more than ${d}ms`,`HOOK_TEARDOWN_TIMEOUT`,t);throw l!==void 0&&a.accounting?.endOperation(l,`error`,{error:e}),e}if(f.aborted&&!o.aborted){let e=n(`turn hook '${s}' exceeded ${u}ms`,`HOOK_TIMEOUT`,t);throw l!==void 0&&a.accounting?.endOperation(l,`error`,{error:e}),e}throw l!==void 0&&a.accounting?.endOperation(l,`aborted`,{error:t}),t}}export{a as runHook,i as runOptionalHook};
|
|
2
2
|
//# sourceMappingURL=hooks.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"hooks.js","names":[],"sources":["../../../../src/agent/loop/turn/hooks.ts"],"sourcesContent":["import { waitForSettlement } from '../../../async/index.ts'\nimport { type RunTurnOptions } from './types.ts'\nimport { positiveSafeInteger } from './config.ts'\nimport { codedRuntimeError } from './common.ts'\nimport { nextValueWithAbort } from './cancellation.ts'\n\nexport async function runOptionalHook<TArgs extends readonly unknown[], TResult>(\n hook: ((...args: TArgs) => TResult | Promise<TResult>) | undefined,\n args: TArgs,\n options: RunTurnOptions,\n signal: AbortSignal,\n name: string,\n): Promise<Awaited<TResult> | undefined> {\n if (hook === undefined) return undefined\n const pending = Promise.resolve().then(() => hook(...
|
|
1
|
+
{"version":3,"file":"hooks.js","names":[],"sources":["../../../../src/agent/loop/turn/hooks.ts"],"sourcesContent":["import { waitForSettlement } from '../../../async/index.ts'\nimport { type RunTurnOptions } from './types.ts'\nimport { positiveSafeInteger } from './config.ts'\nimport { codedRuntimeError } from './common.ts'\nimport { nextValueWithAbort } from './cancellation.ts'\n\nexport async function runOptionalHook<TArgs extends readonly unknown[], TResult>(\n hook: ((...args: TArgs) => TResult | Promise<TResult>) | undefined,\n args: TArgs,\n options: RunTurnOptions,\n signal: AbortSignal,\n name: string,\n): Promise<Awaited<TResult> | undefined> {\n if (hook === undefined) return undefined\n const owned = new AbortController()\n const hookSignal = AbortSignal.any([signal, owned.signal])\n const scoped = args.map(arg => typeof arg === 'object' && arg !== null && 'signal' in arg\n ? { ...arg, signal: hookSignal } : arg) as unknown as TArgs\n const pending = Promise.resolve().then(() => hook(...scoped))\n return await runHook(pending, options, signal, name, reason => owned.abort(reason))\n}\nexport async function runHook<T>(\n pending: Promise<T>,\n options: RunTurnOptions,\n signal: AbortSignal,\n name: string,\n onCancellation?: (reason: unknown) => void,\n): Promise<T> {\n const operation = options.accounting?.startOperation('hook', { data: { name } })\n const timeoutMs = positiveSafeInteger(options.hookTimeoutMs ?? 10 * 60_000, 'hookTimeoutMs')\n const teardownTimeoutMs = positiveSafeInteger(\n options.hookTeardownTimeoutMs ?? 30_000,\n 'hookTeardownTimeoutMs',\n )\n const deadline = AbortSignal.timeout(timeoutMs)\n const combined = AbortSignal.any([signal, deadline])\n try {\n const value = await nextValueWithAbort(pending, combined)\n if (operation !== undefined) options.accounting?.endOperation(operation, 'success')\n return value\n } catch (error: unknown) {\n if (!combined.aborted) {\n if (operation !== undefined) options.accounting?.endOperation(operation, 'error', { error })\n throw error\n }\n onCancellation?.(combined.reason)\n const settled = await waitForSettlement(pending, teardownTimeoutMs)\n if (!settled) {\n const runtimeError = codedRuntimeError(\n `turn hook '${name}' ignored cancellation for more than ${teardownTimeoutMs}ms`,\n 'HOOK_TEARDOWN_TIMEOUT',\n error,\n )\n if (operation !== undefined) options.accounting?.endOperation(operation, 'error', { error: runtimeError })\n throw runtimeError\n }\n if (deadline.aborted && !signal.aborted) {\n const runtimeError = codedRuntimeError(`turn hook '${name}' exceeded ${timeoutMs}ms`, 'HOOK_TIMEOUT', error)\n if (operation !== undefined) options.accounting?.endOperation(operation, 'error', { error: runtimeError })\n throw runtimeError\n }\n if (operation !== undefined) options.accounting?.endOperation(operation, 'aborted', { error })\n throw error\n }\n}\n"],"mappings":"0NAMA,eAAsB,EACpB,EACA,EACA,EACA,EACA,EACuC,CACvC,GAAI,IAAS,IAAA,GAAW,OACxB,IAAM,EAAQ,IAAI,gBACZ,EAAa,YAAY,IAAI,CAAC,EAAQ,EAAM,MAAM,CAAC,EACnD,EAAS,EAAK,IAAI,GAAO,OAAO,GAAQ,UAAY,GAAgB,WAAY,EAClF,CAAE,GAAG,EAAK,OAAQ,CAAW,EAAI,CAAG,EAExC,OAAO,MAAM,EADG,QAAQ,QAAQ,CAAC,CAAC,SAAW,EAAK,GAAG,CAAM,CAChC,EAAG,EAAS,EAAQ,EAAM,GAAU,EAAM,MAAM,CAAM,CAAC,CACpF,CACA,eAAsB,EACpB,EACA,EACA,EACA,EACA,EACY,CACZ,IAAM,EAAY,EAAQ,YAAY,eAAe,OAAQ,CAAE,KAAM,CAAE,MAAK,CAAE,CAAC,EACzE,EAAY,EAAoB,EAAQ,eAAiB,IAAa,eAAe,EACrF,EAAoB,EACxB,EAAQ,uBAAyB,IACjC,uBACF,EACM,EAAW,YAAY,QAAQ,CAAS,EACxC,EAAW,YAAY,IAAI,CAAC,EAAQ,CAAQ,CAAC,EACnD,GAAI,CACF,IAAM,EAAQ,MAAM,EAAmB,EAAS,CAAQ,EAExD,OADI,IAAc,IAAA,IAAW,EAAQ,YAAY,aAAa,EAAW,SAAS,EAC3E,CACT,OAAS,EAAgB,CACvB,GAAI,CAAC,EAAS,QAEZ,MADI,IAAc,IAAA,IAAW,EAAQ,YAAY,aAAa,EAAW,QAAS,CAAE,OAAM,CAAC,EACrF,EAIR,GAFA,IAAiB,EAAS,MAAM,EAE5B,CAAC,MADiB,EAAkB,EAAS,CAAiB,EACpD,CACZ,IAAM,EAAe,EACnB,cAAc,EAAK,uCAAuC,EAAkB,IAC5E,wBACA,CACF,EAEA,MADI,IAAc,IAAA,IAAW,EAAQ,YAAY,aAAa,EAAW,QAAS,CAAE,MAAO,CAAa,CAAC,EACnG,CACR,CACA,GAAI,EAAS,SAAW,CAAC,EAAO,QAAS,CACvC,IAAM,EAAe,EAAkB,cAAc,EAAK,aAAa,EAAU,IAAK,eAAgB,CAAK,EAE3G,MADI,IAAc,IAAA,IAAW,EAAQ,YAAY,aAAa,EAAW,QAAS,CAAE,MAAO,CAAa,CAAC,EACnG,CACR,CAEA,MADI,IAAc,IAAA,IAAW,EAAQ,YAAY,aAAa,EAAW,UAAW,CAAE,OAAM,CAAC,EACvF,CACR,CACF"}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"model-request-boundary.js","names":[],"sources":["../../../../src/agent/loop/turn/model-request-boundary.ts"],"sourcesContent":["import type { History } from '../../history/history.ts'\n\n// Session bookkeeping is separate from user hooks and their operation ledger.\nconst observers = new WeakMap<History, (inFlight: boolean) => void>()\n\nexport function bindModelRequestBoundary(history: History, observer?: (inFlight: boolean) => void): void {\n if (observer === undefined) observers.delete(history)\n else observers.set(history, observer)\n}\n\nexport function observeModelRequestBoundary(history: History, inFlight: boolean): void {\n observers.get(history)?.(inFlight)\n}\n"],"mappings":"AAGA,MAAM,EAAY,IAAI,QAEtB,SAAgB,EAAyB,EAAkB,EAA8C,CACnG,IAAa,IAAA,GAAW,EAAU,OAAO,CAAO,EAC/C,EAAU,IAAI,EAAS,CAAQ,CACtC,CAEA,SAAgB,EAA4B,EAAkB,EAAyB,CACrF,EAAU,IAAI,CAAO,CAAC,GAAG,CAAQ,CACnC"}
|