@alvin0/ai-agent-sdk-core 0.1.5 → 0.1.6
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/dist/agent/define/session.d.ts +17 -3
- 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/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/turn/model-request-boundary.js +1 -1
- package/dist/agent/loop/turn/model-request-boundary.js.map +1 -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/team/contracts.d.ts +5 -0
- package/dist/agent/team/contracts.d.ts.map +1 -1
- 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/composition/agent/session.js +1 -1
- package/dist/composition/agent/session.js.map +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/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 { 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,CAAE,UAAS,OAAQ,EAAa,EAAG,aAAc,EAAQ,OAAO,cAAgB,IAAK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,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
|
+
{"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 { deliverQueuedInput } from './turn/model-request-boundary.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 // Input the person sent while the final answer was being written is owed an\n // answer too: when nothing else continues the turn, take it and continue.\n if (canContinue\n && !signal.aborted\n && (options.history.entries().length > entriesBeforeHook || deliverQueuedInput(options.history))) {\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":"ywCAuBA,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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AAK,EACvC,GAAG,EAAQ,QAAU,IAAA,GAAY,CAAC,EAAI,CAAE,MAAO,EAAQ,KAAM,EAC7D,GAAG,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,QAAU,CACR,GAAgB,MAAM,CACxB,CACF"}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
const e=new WeakMap;function t(t,n){n===void 0?e.delete(t):e.set(t,n)}function n(t,n){e.get(t)?.(n)}export{t as bindModelRequestBoundary,n as observeModelRequestBoundary};
|
|
1
|
+
const e=new WeakMap;function t(t,n){n===void 0?e.delete(t):e.set(t,n)}function n(t,n){e.get(t)?.(n)}const r=new WeakMap;function i(e,t){t===void 0?r.delete(e):r.set(e,t)}function a(e){return r.get(e)?.()??!1}export{t as bindModelRequestBoundary,i as bindQueuedInput,a as deliverQueuedInput,n as observeModelRequestBoundary};
|
|
2
2
|
//# sourceMappingURL=model-request-boundary.js.map
|
|
@@ -1 +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"}
|
|
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\n// Input the owning session queued while a final answer was being written.\nconst queuedInput = new WeakMap<History, () => boolean>()\n\n/** Let a session hand the loop input it is still holding when a turn would end. */\nexport function bindQueuedInput(history: History, deliver?: () => boolean): void {\n if (deliver === undefined) queuedInput.delete(history)\n else queuedInput.set(history, deliver)\n}\n\n/**\n * Append whatever input the owning session is holding, and say whether any\n * was. Called by the loop only when the turn is free to continue, so the\n * input is answered in this run rather than left behind for the next one.\n */\nexport function deliverQueuedInput(history: History): boolean {\n return queuedInput.get(history)?.() ?? false\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,CAGA,MAAM,EAAc,IAAI,QAGxB,SAAgB,EAAgB,EAAkB,EAA+B,CAC3E,IAAY,IAAA,GAAW,EAAY,OAAO,CAAO,EAChD,EAAY,IAAI,EAAS,CAAO,CACvC,CAOA,SAAgB,EAAmB,EAA2B,CAC5D,OAAO,EAAY,IAAI,CAAO,CAAC,GAAG,GAAK,EACzC"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"run-agent.d.ts","names":[],"sources":["../../../src/agent/mode/run-agent.ts"],"mappings":";;;;;;;cAkBa,qBAAmB;WACpB;WACQ;;;;;;;;;;;;;;;cAgBP;;KAGD;UAEF,uBAAuB,KAAK;;WAE3B,QAAQ;WACR,QAAQ;WACR;;;WAGA;WACA,SAAS,KAAK,QAAQ;WACtB,aAAa;WACb,QAAQ;;UAGF,0BAA0B;WAChC;;UAGM,yBAAyB;WAC/B;;WAEA,YAAY;;UAGN,gCAAgC;WACtC;;WAEA,WAAW;;KAGV,kBAAkB,oBAAoB,mBAAmB;UAEpD;WACN;WACA;;UAGM,wBAAwB;WAC9B,MAAM;;WAEN;WACA,aAAa;;UAGd;WACC;WACA,MAAM;WACN;;UAED;WACC;WACA,SAAS;;UAEV;WACC;WACA,SAAS;WACT,UAAU;;UAEX;WACC;WACA,SAAS;;KAGR,gBAAgB,aACxB,sBACA,wBACA,yBACA;;;;;;;;
|
|
1
|
+
{"version":3,"file":"run-agent.d.ts","names":[],"sources":["../../../src/agent/mode/run-agent.ts"],"mappings":";;;;;;;cAkBa,qBAAmB;WACpB;WACQ;;;;;;;;;;;;;;;cAgBP;;KAGD;UAEF,uBAAuB,KAAK;;WAE3B,QAAQ;WACR,QAAQ;WACR;;;WAGA;WACA,SAAS,KAAK,QAAQ;WACtB,aAAa;WACb,QAAQ;;UAGF,0BAA0B;WAChC;;UAGM,yBAAyB;WAC/B;;WAEA,YAAY;;UAGN,gCAAgC;WACtC;;WAEA,WAAW;;KAGV,kBAAkB,oBAAoB,mBAAmB;UAEpD;WACN;WACA;;UAGM,wBAAwB;WAC9B,MAAM;;WAEN;WACA,aAAa;;UAGd;WACC;WACA,MAAM;WACN;;UAED;WACC;WACA,SAAS;;UAEV;WACC;WACA,SAAS;WACT,UAAU;;UAEX;WACC;WACA,SAAS;;KAGR,gBAAgB,aACxB,sBACA,wBACA,yBACA;;;;;;;;iBA4CY,SAAS,SAAS,kBAAkB,cAAc"}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{detachedFrozen as e}from"../../primitives/snapshot.js";import{waitForSettlement as t}from"../../async/settlement.js";import{createMessage as n,createUserMessage as r}from"../../message/message.js";import{defineTool as i}from"../tool/definition.js";import{readSpillTool as a}from"../tool/output-budget.js";import{AwaitedEventQueue as o}from"../loop/queue.js";import{runTurn as s}from"../loop/run-turn.js";const c=Object.freeze({complete:`submit_result`,requestUserInput:`request_user_input`}),l=`<<deep-mode:answer-unchanged>>`;function u(n){return{async*[Symbol.asyncIterator](){let r=new o,i=new AbortController,a=k(n.teardownTimeoutMs??3e4,`teardownTimeoutMs`),s=n.signal===void 0?i.signal:AbortSignal.any([n.signal,i.signal]),c=Promise.resolve(),l=d(n,s,t=>{let n=c.then(()=>r.push(e(t)));return c=n.catch(()=>void 0),n}).then(async()=>{await c,r.close()},async e=>{await c,r.fail(e)});try{for(;;){let e=await r.take();if(e.done)break;yield e.value}await l}finally{if(i.abort(Error(`agent event consumer stopped`)),r.close(),!await t(l,a)){let e=Error(`agent producer ignored cancellation for more than ${a}ms`,{cause:i.signal.reason});throw e.code=`AGENT_TEARDOWN_TIMEOUT`,e}}}}}async function d(e,t,r){let i=e.mode??`basic`;if(![`basic`,`deep`,`deep-human-in-loop`].includes(i))throw RangeError(`unsupported agent mode "${String(i)}"`);let o=`userInput`in e?e.userInput:void 0;if(i===`deep-human-in-loop`&&(o===void 0||typeof o.request!=`function`))throw TypeError(`deep-human-in-loop mode requires a UserInputBroker`);let l=e.maxTurns??16;if(l!==`auto`&&(!Number.isSafeInteger(l)||l<1))throw RangeError(`maxTurns must be a positive safe integer or 'auto'`);await r({type:`agent-start`,mode:i,maxTurns:l});let u={completion:void 0,userAborted:!1,unverifiedAnswers:0,completionInvalidated:!1,draftAnswer:void 0},d=i!==`basic`,_=e.mode===`deep`||e.mode===`deep-human-in-loop`?o:void 0,x=[];e.spillStore!==void 0&&x.push(a(e.spillStore)),d&&x.push(m(u)),_!==void 0&&i!==`basic`&&x.push(h(i,_,u,r,e.accounting));let S=x.length===0?e.tools:v(e.tools,x),C=d?g(e.hooks,e.history,u,l):e.hooks,w={registry:e.registry,config:e.config,history:e.history,...S===void 0?{}:{tools:S},...e.nativeTools===void 0?{}:{nativeTools:e.nativeTools},...e.toolChoice===void 0?{}:{toolChoice:e.toolChoice},...e.imagePolicy===void 0?{}:{imagePolicy:e.imagePolicy},...e.documentPolicy===void 0?{}:{documentPolicy:e.documentPolicy},...e.validateOutput===void 0?{}:{validateOutput:e.validateOutput},...e.outputFormat===void 0?{}:{outputFormat:e.outputFormat},system:E(e.system,T(i,_!==void 0)),...e.interceptors===void 0?{}:{interceptors:y(e.interceptors)},...e.approvals===void 0?{}:{approvals:e.approvals},bounds:{...e.bounds,maxSteps:l},...C===void 0?{}:{hooks:C},signal:t,...e.logger===void 0?{}:{logger:e.logger},commentary:e.commentary??`auto`,teardownTimeoutMs:e.teardownTimeoutMs??3e4,...e.modelTimeoutMs===void 0?{}:{modelTimeoutMs:e.modelTimeoutMs},...e.maxModelRequestBytes===void 0?{}:{maxModelRequestBytes:e.maxModelRequestBytes},...e.maxModelResponseBytes===void 0?{}:{maxModelResponseBytes:e.maxModelResponseBytes},...e.maxModelStreamEvents===void 0?{}:{maxModelStreamEvents:e.maxModelStreamEvents},...e.hookTimeoutMs===void 0?{}:{hookTimeoutMs:e.hookTimeoutMs},...e.hookTeardownTimeoutMs===void 0?{}:{hookTeardownTimeoutMs:e.hookTeardownTimeoutMs},...e.trace===void 0?{}:{trace:e.trace},...e.accounting===void 0?{}:{accounting:e.accounting},...e.spillStore===void 0?{}:{spillStore:e.spillStore},...e.experimentalPrograms===void 0?{}:{experimentalPrograms:e.experimentalPrograms},...e.contextSections===void 0?{}:{contextSections:e.contextSections}},D,O=[],k,A=!1,j=``,M=[],N=async()=>{let e=M;M=[];for(let t of e)await r(t)},P=async e=>{if(e.type===`step-start`&&(await N(),A=u.completion!==void 0&&u.draftAnswer!==void 0,j=``),A&&(e.type===`text-delta`||e.type===`text-end`)){j=e.type===`text-end`?e.text:j+e.text,M.push(e),(!`<<deep-mode:answer-unchanged>>`.startsWith(j.trimStart())&&j.trim()!==`<<deep-mode:answer-unchanged>>`||e.type===`text-end`&&e.incomplete)&&(A=!1,await N());return}if(A&&e.type===`assistant-message`){let t=e.message.content,i=u.draftAnswer,a=i!==void 0&&t.length===1&&t[0]?.type===`text`&&t[0].text.trim()===`<<deep-mode:answer-unchanged>>`;if(A=!1,a){let t=M;M=[];for(let e of t)e.type!==`text-delta`&&e.type!==`text-end`&&await r(e);await r({...e,message:n({role:`assistant`,content:[{type:`text`,text:i,phase:`final-answer`}],source:{kind:`app`,producer:`deep-mode-kept-answer`}})});return}await N()}else if(M.length>0){if(e.type===`turn-end`||e.type===`tool-call`)A=!1,await N();else{M.push(e);return}}await r(e)};for await(let t of s(w)){if(t.type===`step-start`?(O=[],k=void 0):t.type===`tool-call`?(O.push(t.call.toolName),t.call.toolName!==c.complete&&S?.get(t.call.toolName)?.completionExempt!==!0&&(u.completion!==void 0&&(u.completionInvalidated=!0),u.completion=void 0,u.unverifiedAnswers=0)):t.type===`tool-result`&&t.call.toolName===c.complete&&!t.result.isError?k=b(t.result.value):t.type===`step-end`&&k!==void 0&&O.filter(e=>e===c.complete).length===1&&O.every(e=>e===c.complete||S?.get(e)?.completionExempt===!0)&&(u.completion=k,u.completionInvalidated=!1),t.type===`turn-end`){D=f(t.outcome,u),D!==t.outcome&&p(e.history,D.text),await P({...t,outcome:D});continue}await P(t)}if(D===void 0)throw Error(`runTurn ended without a turn-end event`);let F=i===`basic`?D.reason.kind===`completed`||D.reason.kind===`concluded-by-tool`:u.completion!==void 0&&!u.userAborted&&(D.reason.kind===`completed`||D.reason.kind===`concluded-by-tool`||D.reason.kind===`budget-exhausted`&&D.reason.forcedFinalAnswer)&&D.text.trim()!==``;await r({type:`agent-end`,outcome:{...D,mode:i,completed:F,...u.completion===void 0?{}:{completion:u.completion}}})}function f(e,t){return t.completion!==void 0&&t.draftAnswer!==void 0&&e.text.trim()===`<<deep-mode:answer-unchanged>>`?{...e,text:t.draftAnswer}:e}function p(e,t){let r=e.entries(),i;for(let e=r.length-1;e>=0;e--){let t=r[e];if(t?.event.kind===`assistant`){i=t;break}}let a=i?.event.kind===`assistant`?i.event.message.content:void 0;if(i===void 0||a===void 0||a.length!==1)return;let[o]=a;if(o?.type===`text`&&o.text.trim()===`<<deep-mode:answer-unchanged>>`)try{e.append({kind:`assistant`,message:n({role:`assistant`,content:[{type:`text`,text:t,phase:`final-answer`}],source:{kind:`app`,producer:`deep-mode-kept-answer`}})},{op:`replace`,from:i.seq,to:i.seq})}catch{}}function m(e){return i({name:c.complete,description:`Submit the self-check only when the user objective and constraints are fully satisfied. After acceptance, give the user the final answer.`,budgetExempt:!0,parameters:{type:`object`,properties:{summary:{type:`string`,description:`Concise statement of what was completed.`},evidence:{type:`array`,items:{type:`string`},description:`Concrete checks or tool results showing the objective is satisfied.`}},required:[`summary`,`evidence`],additionalProperties:!1},parse:S,execute:t=>({accepted:!0,summary:t.summary,evidence:[...t.evidence],instruction:e.draftAnswer===void 0?`This self-check is accepted for the current run. Now deliver the answer or artifact requested by the current user or assigned task, preserving its requested content and format. For exact text, only JSON, only a number, or another constrained format, return only the requested output. The summary and evidence in this tool result are verification metadata; keep them out of the final answer unless the task requests them. If the task requests a report, provide the substantive findings or changes, supporting evidence or sources, and relevant limitations. Do not merely say the self-check passed or refer to an earlier message. Do not call submit_result again in this run unless you perform new substantive tool work that invalidates this submission. A later user request or worker follow-up starts a new run and needs its own self-check.`:`This self-check is accepted for the current run. You already gave the user a complete answer earlier in this run, before this check. If that answer is still correct and complete, reply with exactly ${l} and nothing else — no summary, no reference to it, no repeating it; the earlier answer is kept as the final answer. Only if this check found something to correct or add, give the complete corrected answer in full, as if the earlier one did not exist: never summarize it, point back to it, or say the self-check passed. Do not call submit_result again in this run unless you perform new substantive tool work that invalidates this submission. A later user request or worker follow-up starts a new run and needs its own self-check.`})})}function h(e,t,n,r,a){return i({name:c.requestUserInput,budgetExempt:!0,description:e===`deep-human-in-loop`?`Ask the user one to three short questions when a material choice or missing fact requires human input, then wait for the response. Provide 2-3 mutually exclusive suggestions; free-form input is added by the client.`:`Ask the user one to three short clarification questions only when blocked, then wait for the response. Provide suggested choices; free-form input is added by the client.`,parameters:w(),parse:C,execute:async({questions:e},i)=>{let o=a?.startOperation(`user-input`,{toolCallId:i.callId,data:{questionCount:e.length}}),s={requestId:i.callId,callId:i.callId,turn:i.turn,step:i.step,questions:e,isBlocking:!0};try{let c=t.request(s,i.signal);await r({type:`user-input-request`,request:s});let l=await c;return await r({type:`user-input-response`,request:s,response:l}),l===`abort`?(n.userAborted=!0,i.concludeTurn(),o!==void 0&&a?.endOperation(o,`aborted`),{aborted:!0}):(o!==void 0&&a?.endOperation(o,`success`),x(l,e))}catch(e){throw o!==void 0&&a?.endOperation(o,i.signal.aborted?`aborted`:`error`,{error:e}),e}}})}function g(e,t,n,i){return{...e,onTurnEnd:async a=>{let o=f(a.outcome,n);await e?.onTurnEnd?.(o===a.outcome?a:{...a,outcome:o}),!(a.outcome.reason.kind!==`completed`||i!==`auto`&&a.outcome.steps>=i||n.completion!==void 0||n.userAborted)&&(n.unverifiedAnswers++,!(n.unverifiedAnswers>=3)&&(a.outcome.text.trim()!==``&&a.outcome.text.trim()!==`<<deep-mode:answer-unchanged>>`&&(n.draftAnswer=a.outcome.text),t.append({kind:`user`,message:r({source:{kind:`app`,producer:`deep-mode-self-check`},content:[{type:`text`,text:(n.completionInvalidated?`Your previously accepted submission is no longer current because you called another substantive tool afterwards. Review the later tool results and call ${c.complete} again when complete; the old instruction not to resubmit no longer applies. `:``)+`Self-check required: this run has no accepted current self-check. Acceptance recorded in an earlier run does not complete this request or follow-up; an earlier instruction not to resubmit applied only to that earlier run. Compare the current result against the user's objective and every constraint. If anything is missing, continue with tools. If blocked and request_user_input is available, ask the user. Only when the work is actually complete, call ${c.complete}. Keep verification in that tool call and then deliver the current user or assigned task's requested output in its original format. This reminder does not change the task or request a process report. Rephrasing a completion claim without submitting does not satisfy this gate.`}]})})))}}}var _=class{definitions;constructor(e,t){let n=new Map;for(let t of e?.names()??[]){let r=e?.get(t);r!==void 0&&n.set(t,r)}for(let e of t){if(n.has(e.name))throw Error(`tool name "${e.name}" is reserved by the selected agent mode`);n.set(e.name,e)}this.definitions=n}get(e){return this.definitions.get(e)}has(e){return this.definitions.has(e)}names(){return[...this.definitions.keys()]}schemas(){return[...this.definitions.values()].map(({name:e,description:t,parameters:n})=>({name:e,description:t,parameters:structuredClone(n)}))}executionMode(e,t){let n=this.definitions.get(e);if(n===void 0)return`exclusive`;try{return n.isConcurrencySafe?.(t)===!0?`parallel`:`exclusive`}catch{return`exclusive`}}};function v(e,t){return new _(e,t)}function y(e){let t=new Set(Object.values(c));return e.map(e=>({name:e.name,...e.before===void 0?{}:{before:(n,r)=>t.has(n.toolName)?r():e.before(n,r)},...e.around===void 0?{}:{around:(n,r)=>t.has(n.toolName)?r():e.around(n,r)},...e.after===void 0?{}:{after:(n,r,i)=>t.has(n.toolName)?i():e.after(n,r,i)}}))}function b(e){let t=D(e,`submit_result result`);return S({summary:t.summary,evidence:t.evidence})}function x(e,t){let n=new Set(t.map(e=>e.id));for(let t of n){let n=e.answers[t];if(n===void 0||!Array.isArray(n.answers)||n.answers.length===0||n.answers.some(e=>typeof e!=`string`||e.trim().length===0))throw Error(`the user-input broker returned no valid answer for "${t}"`)}for(let t of Object.keys(e.answers))if(!n.has(t))throw Error(`the user-input broker returned an answer for unknown question "${t}"`);return e}function S(e){let t=D(e,`submit_result arguments`);if(typeof t.summary!=`string`||t.summary.trim().length===0)throw Error(`summary must be a non-empty string`);if(!Array.isArray(t.evidence)||t.evidence.some(e=>typeof e!=`string`||e.trim().length===0))throw Error(`evidence must be an array of non-empty strings`);return{summary:t.summary,evidence:t.evidence}}function C(e){let t=D(e,`request_user_input arguments`);if(!Array.isArray(t.questions)||t.questions.length<1||t.questions.length>3)throw Error(`questions must contain one to three items`);let n=new Set,r=t.questions.map((e,t)=>{let r=D(e,`questions[${t}]`),i=O(r.id,`questions[${t}].id`);if(!/^[a-z][a-z0-9_]*$/.test(i))throw Error(`questions[${t}].id must be snake_case`);if(n.has(i))throw Error(`question id "${i}" is duplicated`);n.add(i);let a=O(r.header,`questions[${t}].header`),o=O(r.question,`questions[${t}].question`);if(!Array.isArray(r.options)||r.options.length<2||r.options.length>3)throw Error(`questions[${t}].options must contain two or three choices`);let s=r.options.map((e,n)=>{let r=D(e,`questions[${t}].options[${n}]`);return{label:O(r.label,`questions[${t}].options[${n}].label`),description:O(r.description,`questions[${t}].options[${n}].description`)}});return Object.freeze({id:i,header:a,question:o,options:Object.freeze(s),allowFreeForm:!0})});return{questions:Object.freeze(r)}}function w(){return{type:`object`,properties:{questions:{type:`array`,minItems:1,maxItems:3,description:`Questions to show the user. Prefer one and do not exceed three.`,items:{type:`object`,additionalProperties:!1,properties:{id:{type:`string`,description:`Stable snake_case answer key.`},header:{type:`string`,description:`Short UI label, ideally 12 characters or fewer.`},question:{type:`string`,description:`Single-sentence question.`},options:{type:`array`,minItems:2,maxItems:3,description:`Mutually exclusive choices. Put the recommended choice first and suffix its label with "(Recommended)". Do not add Other; the client supplies free-form input.`,items:{type:`object`,additionalProperties:!1,properties:{label:{type:`string`,description:`User-facing label, one to five words.`},description:{type:`string`,description:`One sentence explaining impact or trade-off.`}},required:[`label`,`description`]}}},required:[`id`,`header`,`question`,`options`]}}},required:[`questions`],additionalProperties:!1}}function T(e,t){if(e===`basic`)return[`Work as a bounded tool-using agent. Use available tools proactively when they materially improve correctness.`,`Stay within the configured iteration budget, then give the best final answer supported by the gathered results.`].join(` `);let n=t?`If a missing fact or material user choice blocks correct progress, call ${c.requestUserInput} and continue after the answer.`:`If blocked by missing user input, state that limitation plainly in the final response.`,r=e===`deep-human-in-loop`?`For material choices, surface 2-3 concise options with the recommended option first; the UI also permits free-form feedback.`:``;return[`Work autonomously in deep mode. After every tool result, compare the evidence against the user objective and all constraints; continue until gaps are closed.`,`Do not treat a plausible draft as completion. When the work is actually complete, call ${c.complete} with a summary and concrete evidence, then provide the final answer.`,`Put verification summaries and evidence in the self-check tool call. Deliver the current user or assigned task's requested answer or artifact in its requested format, including exact text or JSON. Add verification commentary only when that format permits it.`,n,r,`Never reveal private chain-of-thought. Use concise user-visible commentary for intent, progress, observations, and decisions.`].filter(Boolean).join(` `)}function E(...e){return e.filter(e=>e!==void 0&&e.length>0).join(`
|
|
1
|
+
import{detachedFrozen as e}from"../../primitives/snapshot.js";import{waitForSettlement as t}from"../../async/settlement.js";import{createMessage as n,createUserMessage as r}from"../../message/message.js";import{defineTool as i}from"../tool/definition.js";import{readSpillTool as a}from"../tool/output-budget.js";import{AwaitedEventQueue as o}from"../loop/queue.js";import{runTurn as s}from"../loop/run-turn.js";const c=Object.freeze({complete:`submit_result`,requestUserInput:`request_user_input`}),l=`<<deep-mode:answer-unchanged>>`;function u(n){return{async*[Symbol.asyncIterator](){let r=new o,i=new AbortController,a=M(n.teardownTimeoutMs??3e4,`teardownTimeoutMs`),s=n.signal===void 0?i.signal:AbortSignal.any([n.signal,i.signal]),c=Promise.resolve(),l=d(n,s,t=>{let n=c.then(()=>r.push(e(t)));return c=n.catch(()=>void 0),n}).then(async()=>{await c,r.close()},async e=>{await c,r.fail(e)});try{for(;;){let e=await r.take();if(e.done)break;yield e.value}await l}finally{if(i.abort(Error(`agent event consumer stopped`)),r.close(),!await t(l,a)){let e=Error(`agent producer ignored cancellation for more than ${a}ms`,{cause:i.signal.reason});throw e.code=`AGENT_TEARDOWN_TIMEOUT`,e}}}}}async function d(e,t,n){let r=e.mode??`basic`;if(![`basic`,`deep`,`deep-human-in-loop`].includes(r))throw RangeError(`unsupported agent mode "${String(r)}"`);let i=`userInput`in e?e.userInput:void 0;if(r===`deep-human-in-loop`&&(i===void 0||typeof i.request!=`function`))throw TypeError(`deep-human-in-loop mode requires a UserInputBroker`);let o=e.maxTurns??16;if(o!==`auto`&&(!Number.isSafeInteger(o)||o<1))throw RangeError(`maxTurns must be a positive safe integer or 'auto'`);await n({type:`agent-start`,mode:r,maxTurns:o});let l={completion:void 0,userAborted:!1,unverifiedAnswers:0,completionInvalidated:!1,draftAnswer:void 0,orphanMarkerNudged:!1,markerCut:!1,markerReply:!1},u=r!==`basic`,d=e.mode===`deep`||e.mode===`deep-human-in-loop`?i:void 0,b=[];e.spillStore!==void 0&&b.push(a(e.spillStore)),u&&b.push(_(l)),d!==void 0&&r!==`basic`&&b.push(v(r,d,l,n,e.accounting));let w=b.length===0?e.tools:x(e.tools,b),T=u?y(e.hooks,e.history,l,o):e.hooks,E={registry:e.registry,config:e.config,history:e.history,...w===void 0?{}:{tools:w},...e.nativeTools===void 0?{}:{nativeTools:e.nativeTools},...e.toolChoice===void 0?{}:{toolChoice:e.toolChoice},...e.imagePolicy===void 0?{}:{imagePolicy:e.imagePolicy},...e.documentPolicy===void 0?{}:{documentPolicy:e.documentPolicy},...e.validateOutput===void 0?{}:{validateOutput:e.validateOutput},...e.outputFormat===void 0?{}:{outputFormat:e.outputFormat},system:k(e.system,O(r,d!==void 0)),...e.interceptors===void 0?{}:{interceptors:S(e.interceptors)},...e.approvals===void 0?{}:{approvals:e.approvals},bounds:{...e.bounds,maxSteps:o},...T===void 0?{}:{hooks:T},signal:t,...e.logger===void 0?{}:{logger:e.logger},commentary:e.commentary??`auto`,teardownTimeoutMs:e.teardownTimeoutMs??3e4,...e.modelTimeoutMs===void 0?{}:{modelTimeoutMs:e.modelTimeoutMs},...e.maxModelRequestBytes===void 0?{}:{maxModelRequestBytes:e.maxModelRequestBytes},...e.maxModelResponseBytes===void 0?{}:{maxModelResponseBytes:e.maxModelResponseBytes},...e.maxModelStreamEvents===void 0?{}:{maxModelStreamEvents:e.maxModelStreamEvents},...e.hookTimeoutMs===void 0?{}:{hookTimeoutMs:e.hookTimeoutMs},...e.hookTeardownTimeoutMs===void 0?{}:{hookTeardownTimeoutMs:e.hookTeardownTimeoutMs},...e.trace===void 0?{}:{trace:e.trace},...e.accounting===void 0?{}:{accounting:e.accounting},...e.spillStore===void 0?{}:{spillStore:e.spillStore},...e.experimentalPrograms===void 0?{}:{experimentalPrograms:e.experimentalPrograms},...e.contextSections===void 0?{}:{contextSections:e.contextSections}},D,A=[],j,M=!1,N=``,P=[],F,I,L=!1,R=async()=>{let e=P;P=[];for(let t of e)await n(t)},z=async()=>{let e=P;P=[];for(let t of e)t.type!==`text-delta`&&t.type!==`text-end`&&await n(t)},B=async t=>{if(I===void 0||t.type!==`assistant-text`||t.messageId!==I){if(F!==void 0&&t.type===`assistant-reasoning`&&t.messageId===F.from){await n({...t,messageId:F.message.id});return}if(F!==void 0&&t.type===`assistant-text`&&t.messageId===F.from){let e=F.message.content.find(e=>e.type===`text`);await n({...t,messageId:F.message.id,text:e?.type===`text`?e.text:t.text});return}if(t.type===`step-start`&&(F=void 0,I=void 0,L=!1,l.markerCut=!1,l.markerReply=!1,await R(),M=l.completion!==void 0,N=``),M&&(t.type===`text-delta`||t.type===`text-end`)){N=t.type===`text-end`?t.text:N+t.text,P.push(t),p(N)?t.type===`text-end`&&t.incomplete&&(l.markerCut=!0):(M=!1,await R());return}if(M&&t.type===`assistant-message`){let r=t.message.content,i=l.draftAnswer,a=f(r),o=a!==void 0&&(a.trim()===`<<deep-mode:answer-unchanged>>`||l.markerCut&&p(a));if(M=!1,o){l.markerReply=!0,F={from:t.message.id,message:h(i??``,r)},g(e.history,F.message,l.markerCut),L=!0,i===void 0&&(I=t.message.id),await z(),await n({...t,message:F.message});return}l.markerCut=!1,await R()}else if(P.length>0){if(t.type===`turn-end`&&M&&p(N))M=!1,l.markerCut=!0,await z();else if(t.type===`turn-end`||t.type===`tool-call`)M=!1,await R();else{P.push(t);return}}await n(t)}};for await(let t of s(E)){if(t.type===`step-start`?(A=[],j=void 0):t.type===`tool-call`?(A.push(t.call.toolName),t.call.toolName!==c.complete&&w?.get(t.call.toolName)?.completionExempt!==!0&&(l.completion!==void 0&&(l.completionInvalidated=!0),l.completion=void 0,l.unverifiedAnswers=0)):t.type===`tool-result`&&t.call.toolName===c.complete&&!t.result.isError?j=C(t.result.value):t.type===`step-end`&&j!==void 0&&A.filter(e=>e===c.complete).length===1&&A.every(e=>e===c.complete||w?.get(e)?.completionExempt===!0)&&(l.completion=j,l.completionInvalidated=!1),t.type===`turn-end`){M&&P.length>0&&p(N)&&(l.markerCut=!0),D=m(t.outcome,l),D!==t.outcome&&l.draftAnswer!==void 0&&!L&&g(e.history,F?.message??h(D.text),l.markerCut),await B({...t,outcome:D});continue}await B(t)}if(D===void 0)throw Error(`runTurn ended without a turn-end event`);let V=r===`basic`?D.reason.kind===`completed`||D.reason.kind===`concluded-by-tool`:l.completion!==void 0&&!l.userAborted&&(D.reason.kind===`completed`||D.reason.kind===`concluded-by-tool`||D.reason.kind===`budget-exhausted`&&D.reason.forcedFinalAnswer)&&D.text.trim()!==``;await n({type:`agent-end`,outcome:{...D,mode:r,completed:V,...l.completion===void 0?{}:{completion:l.completion}}})}function f(e){let t=e.filter(e=>e.type!==`reasoning`);return t.length===1&&t[0]?.type===`text`?t[0].text:void 0}function p(e){let t=e.trim();return t.length===0||l.startsWith(t)}function m(e,t){return t.completion===void 0||!t.markerReply&&!t.markerCut||!(t.markerCut&&e.text.trim()!==``&&p(e.text))&&e.text.trim()!==`<<deep-mode:answer-unchanged>>`?e:{...e,text:t.draftAnswer??``}}function h(e,t){return n({role:`assistant`,content:t===void 0?[{type:`text`,text:e,phase:`final-answer`}]:t.flatMap(t=>t.type===`reasoning`?[t]:e===``?[]:[{type:`text`,text:e,phase:`final-answer`}]),source:{kind:`app`,producer:`deep-mode-kept-answer`}})}function g(e,t,n=!1){let r=e.entries(),i;for(let e=r.length-1;e>=0;e--){let t=r[e];if(t?.event.kind===`assistant`){i=t;break}}let a=i?.event.kind===`assistant`?f(i.event.message.content):void 0;i!==void 0&&a!==void 0&&(a.trim()!==`<<deep-mode:answer-unchanged>>`&&!(n&&a.trim()!==``&&p(a))||e.append({kind:`assistant`,message:t},{op:`replace`,from:i.seq,to:i.seq}))}function _(e){return i({name:c.complete,description:`Submit the self-check only when the user objective and constraints are fully satisfied. After acceptance, give the user the final answer.`,budgetExempt:!0,parameters:{type:`object`,properties:{summary:{type:`string`,description:`Concise statement of what was completed.`},evidence:{type:`array`,items:{type:`string`},description:`Concrete checks or tool results showing the objective is satisfied.`}},required:[`summary`,`evidence`],additionalProperties:!1},parse:T,execute:t=>({accepted:!0,summary:t.summary,evidence:[...t.evidence],instruction:e.draftAnswer===void 0?`This self-check is accepted for the current run. Now deliver the answer or artifact requested by the current user or assigned task, preserving its requested content and format. For exact text, only JSON, only a number, or another constrained format, return only the requested output. The summary and evidence in this tool result are verification metadata; keep them out of the final answer unless the task requests them. If the task requests a report, provide the substantive findings or changes, supporting evidence or sources, and relevant limitations. Do not merely say the self-check passed or refer to an earlier message. Do not call submit_result again in this run unless you perform new substantive tool work that invalidates this submission. A later user request or worker follow-up starts a new run and needs its own self-check.`:`This self-check is accepted for the current run. You already gave the user a complete answer earlier in this run, before this check. If that answer is still correct and complete, reply with exactly ${l} and nothing else — no summary, no reference to it, no repeating it; the earlier answer is kept as the final answer. Only if this check found something to correct or add, give the complete corrected answer in full, as if the earlier one did not exist: never summarize it, point back to it, or say the self-check passed. Do not call submit_result again in this run unless you perform new substantive tool work that invalidates this submission. A later user request or worker follow-up starts a new run and needs its own self-check.`})})}function v(e,t,n,r,a){return i({name:c.requestUserInput,budgetExempt:!0,description:e===`deep-human-in-loop`?`Ask the user one to three short questions when a material choice or missing fact requires human input, then wait for the response. Provide 2-3 mutually exclusive suggestions; free-form input is added by the client.`:`Ask the user one to three short clarification questions only when blocked, then wait for the response. Provide suggested choices; free-form input is added by the client.`,parameters:D(),parse:E,execute:async({questions:e},i)=>{let o=a?.startOperation(`user-input`,{toolCallId:i.callId,data:{questionCount:e.length}}),s={requestId:i.callId,callId:i.callId,turn:i.turn,step:i.step,questions:e,isBlocking:!0};try{let c=t.request(s,i.signal);await r({type:`user-input-request`,request:s});let l=await c;return await r({type:`user-input-response`,request:s,response:l}),l===`abort`?(n.userAborted=!0,i.concludeTurn(),o!==void 0&&a?.endOperation(o,`aborted`),{aborted:!0}):(o!==void 0&&a?.endOperation(o,`success`),w(l,e))}catch(e){throw o!==void 0&&a?.endOperation(o,i.signal.aborted?`aborted`:`error`,{error:e}),e}}})}function y(e,t,n,i){return{...e,onTurnEnd:async a=>{let o=m(a.outcome,n);if(await e?.onTurnEnd?.(o===a.outcome?a:{...a,outcome:o}),a.outcome.reason.kind===`completed`&&a.canContinue&&n.completion!==void 0&&n.draftAnswer===void 0&&!n.orphanMarkerNudged&&n.markerReply&&a.outcome.text.trim()===`<<deep-mode:answer-unchanged>>`){n.orphanMarkerNudged=!0,t.append({kind:`user`,message:r({source:{kind:`app`,producer:`deep-mode-self-check`},content:[{type:`text`,text:`There is no earlier answer in this run for ${l} to keep: that reply applies only after an answer was given before the check in the same run. Reply with the answer itself now, in the requested format.`}]})});return}a.outcome.reason.kind!==`completed`||i!==`auto`&&a.outcome.steps>=i||n.completion!==void 0||n.userAborted||(n.unverifiedAnswers++,!(n.unverifiedAnswers>=3)&&(a.outcome.text.trim()!==``&&a.outcome.text.trim()!==`<<deep-mode:answer-unchanged>>`&&(n.draftAnswer=a.outcome.text),t.append({kind:`user`,message:r({source:{kind:`app`,producer:`deep-mode-self-check`},content:[{type:`text`,text:(n.completionInvalidated?`Your previously accepted submission is no longer current because you called another substantive tool afterwards. Review the later tool results and call ${c.complete} again when complete; the old instruction not to resubmit no longer applies. `:``)+`Self-check required: this run has no accepted current self-check. Acceptance recorded in an earlier run does not complete this request or follow-up; an earlier instruction not to resubmit applied only to that earlier run. Compare the current result against the user's objective and every constraint. If anything is missing, continue with tools. If blocked and request_user_input is available, ask the user. Only when the work is actually complete, call ${c.complete}. Keep verification in that tool call and then deliver the current user or assigned task's requested output in its original format. This reminder does not change the task or request a process report. Rephrasing a completion claim without submitting does not satisfy this gate.`}]})})))}}}var b=class{definitions;constructor(e,t){let n=new Map;for(let t of e?.names()??[]){let r=e?.get(t);r!==void 0&&n.set(t,r)}for(let e of t){if(n.has(e.name))throw Error(`tool name "${e.name}" is reserved by the selected agent mode`);n.set(e.name,e)}this.definitions=n}get(e){return this.definitions.get(e)}has(e){return this.definitions.has(e)}names(){return[...this.definitions.keys()]}schemas(){return[...this.definitions.values()].map(({name:e,description:t,parameters:n})=>({name:e,description:t,parameters:structuredClone(n)}))}executionMode(e,t){let n=this.definitions.get(e);if(n===void 0)return`exclusive`;try{return n.isConcurrencySafe?.(t)===!0?`parallel`:`exclusive`}catch{return`exclusive`}}};function x(e,t){return new b(e,t)}function S(e){let t=new Set(Object.values(c));return e.map(e=>({name:e.name,...e.before===void 0?{}:{before:(n,r)=>t.has(n.toolName)?r():e.before(n,r)},...e.around===void 0?{}:{around:(n,r)=>t.has(n.toolName)?r():e.around(n,r)},...e.after===void 0?{}:{after:(n,r,i)=>t.has(n.toolName)?i():e.after(n,r,i)}}))}function C(e){let t=A(e,`submit_result result`);return T({summary:t.summary,evidence:t.evidence})}function w(e,t){let n=new Set(t.map(e=>e.id));for(let t of n){let n=e.answers[t];if(n===void 0||!Array.isArray(n.answers)||n.answers.length===0||n.answers.some(e=>typeof e!=`string`||e.trim().length===0))throw Error(`the user-input broker returned no valid answer for "${t}"`)}for(let t of Object.keys(e.answers))if(!n.has(t))throw Error(`the user-input broker returned an answer for unknown question "${t}"`);return e}function T(e){let t=A(e,`submit_result arguments`);if(typeof t.summary!=`string`||t.summary.trim().length===0)throw Error(`summary must be a non-empty string`);if(!Array.isArray(t.evidence)||t.evidence.some(e=>typeof e!=`string`||e.trim().length===0))throw Error(`evidence must be an array of non-empty strings`);return{summary:t.summary,evidence:t.evidence}}function E(e){let t=A(e,`request_user_input arguments`);if(!Array.isArray(t.questions)||t.questions.length<1||t.questions.length>3)throw Error(`questions must contain one to three items`);let n=new Set,r=t.questions.map((e,t)=>{let r=A(e,`questions[${t}]`),i=j(r.id,`questions[${t}].id`);if(!/^[a-z][a-z0-9_]*$/.test(i))throw Error(`questions[${t}].id must be snake_case`);if(n.has(i))throw Error(`question id "${i}" is duplicated`);n.add(i);let a=j(r.header,`questions[${t}].header`),o=j(r.question,`questions[${t}].question`);if(!Array.isArray(r.options)||r.options.length<2||r.options.length>3)throw Error(`questions[${t}].options must contain two or three choices`);let s=r.options.map((e,n)=>{let r=A(e,`questions[${t}].options[${n}]`);return{label:j(r.label,`questions[${t}].options[${n}].label`),description:j(r.description,`questions[${t}].options[${n}].description`)}});return Object.freeze({id:i,header:a,question:o,options:Object.freeze(s),allowFreeForm:!0})});return{questions:Object.freeze(r)}}function D(){return{type:`object`,properties:{questions:{type:`array`,minItems:1,maxItems:3,description:`Questions to show the user. Prefer one and do not exceed three.`,items:{type:`object`,additionalProperties:!1,properties:{id:{type:`string`,description:`Stable snake_case answer key.`},header:{type:`string`,description:`Short UI label, ideally 12 characters or fewer.`},question:{type:`string`,description:`Single-sentence question.`},options:{type:`array`,minItems:2,maxItems:3,description:`Mutually exclusive choices. Put the recommended choice first and suffix its label with "(Recommended)". Do not add Other; the client supplies free-form input.`,items:{type:`object`,additionalProperties:!1,properties:{label:{type:`string`,description:`User-facing label, one to five words.`},description:{type:`string`,description:`One sentence explaining impact or trade-off.`}},required:[`label`,`description`]}}},required:[`id`,`header`,`question`,`options`]}}},required:[`questions`],additionalProperties:!1}}function O(e,t){if(e===`basic`)return[`Work as a bounded tool-using agent. Use available tools proactively when they materially improve correctness.`,`Stay within the configured iteration budget, then give the best final answer supported by the gathered results.`].join(` `);let n=t?`If a missing fact or material user choice blocks correct progress, call ${c.requestUserInput} and continue after the answer.`:`If blocked by missing user input, state that limitation plainly in the final response.`,r=e===`deep-human-in-loop`?`For material choices, surface 2-3 concise options with the recommended option first; the UI also permits free-form feedback.`:``;return[`Work autonomously in deep mode. After every tool result, compare the evidence against the user objective and all constraints; continue until gaps are closed.`,`Do not treat a plausible draft as completion. When the work is actually complete, call ${c.complete} with a summary and concrete evidence, then provide the final answer.`,`Put verification summaries and evidence in the self-check tool call. Deliver the current user or assigned task's requested answer or artifact in its requested format, including exact text or JSON. Add verification commentary only when that format permits it.`,n,r,`Never reveal private chain-of-thought. Use concise user-visible commentary for intent, progress, observations, and decisions.`].filter(Boolean).join(` `)}function k(...e){return e.filter(e=>e!==void 0&&e.length>0).join(`
|
|
2
2
|
|
|
3
|
-
`)}function
|
|
3
|
+
`)}function A(e,t){if(typeof e!=`object`||!e||Array.isArray(e))throw Error(`${t} must be an object`);return e}function j(e,t){if(typeof e!=`string`||e.trim().length===0)throw Error(`${t} must be a non-empty string`);return e}function M(e,t){if(!Number.isFinite(e)||e<=0)throw RangeError(`${t} must be a positive finite number`);return e}export{c as AGENT_CONTROL_TOOLS,l as UNCHANGED_ANSWER_MARKER,u as runAgent};
|
|
4
4
|
//# sourceMappingURL=run-agent.js.map
|