@alvin0/ai-agent-sdk-core 0.1.4 → 0.1.5
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +13 -1
- package/dist/agent/define/definition.d.ts +1 -1
- package/dist/agent/define/definition.js +1 -1
- package/dist/agent/define/definition.js.map +1 -1
- package/dist/agent/define/session/types.d.ts +6 -0
- package/dist/agent/define/session/types.d.ts.map +1 -1
- package/dist/agent/define/session.d.ts +25 -2
- package/dist/agent/define/session.d.ts.map +1 -1
- package/dist/agent/define/session.js +1 -1
- package/dist/agent/define/session.js.map +1 -1
- package/dist/agent/loop/admission.js +2 -0
- package/dist/agent/loop/admission.js.map +1 -0
- package/dist/agent/loop/events.d.ts +4 -0
- package/dist/agent/loop/events.d.ts.map +1 -1
- package/dist/agent/loop/program.js +2 -0
- package/dist/agent/loop/program.js.map +1 -0
- package/dist/agent/loop/run-turn.d.ts.map +1 -1
- package/dist/agent/loop/run-turn.js +1 -1
- package/dist/agent/loop/run-turn.js.map +1 -1
- package/dist/agent/loop/schedule.d.ts.map +1 -1
- package/dist/agent/loop/schedule.js +2 -2
- package/dist/agent/loop/schedule.js.map +1 -1
- package/dist/agent/loop/tool-call-support.js +2 -0
- package/dist/agent/loop/tool-call-support.js.map +1 -0
- package/dist/agent/loop/turn/hooks.js +1 -1
- package/dist/agent/loop/turn/hooks.js.map +1 -1
- package/dist/agent/loop/turn/model-request-boundary.js +2 -0
- package/dist/agent/loop/turn/model-request-boundary.js.map +1 -0
- package/dist/agent/loop/turn/model-round.js +1 -1
- package/dist/agent/loop/turn/model-round.js.map +1 -1
- package/dist/agent/loop/turn/step-projection.js +2 -0
- package/dist/agent/loop/turn/step-projection.js.map +1 -0
- package/dist/agent/loop/turn/types.d.ts +6 -0
- package/dist/agent/loop/turn/types.d.ts.map +1 -1
- package/dist/agent/memory/context-optimizer.d.ts +61 -0
- package/dist/agent/memory/context-optimizer.d.ts.map +1 -0
- package/dist/agent/memory/context-optimizer.js +4 -0
- package/dist/agent/memory/context-optimizer.js.map +1 -0
- package/dist/agent/memory/memory.js +1 -1
- package/dist/agent/memory/memory.js.map +1 -1
- package/dist/agent/mode/run-agent.d.ts +15 -1
- package/dist/agent/mode/run-agent.d.ts.map +1 -1
- package/dist/agent/mode/run-agent.js +2 -2
- package/dist/agent/mode/run-agent.js.map +1 -1
- package/dist/agent/skill/provider/snapshot.js +1 -1
- package/dist/agent/team/managed.d.ts +33 -64
- package/dist/agent/team/managed.d.ts.map +1 -1
- package/dist/agent/team/managed.js +6 -3
- package/dist/agent/team/managed.js.map +1 -1
- package/dist/agent/team/team.d.ts +2 -0
- package/dist/agent/team/team.d.ts.map +1 -1
- package/dist/agent/team/team.js +1 -1
- package/dist/agent/team/team.js.map +1 -1
- package/dist/agent/team/types.d.ts +1 -0
- package/dist/agent/team/types.d.ts.map +1 -1
- package/dist/agent/tool/action-fusion.d.ts +30 -0
- package/dist/agent/tool/action-fusion.d.ts.map +1 -0
- package/dist/agent/tool/action-fusion.js +2 -0
- package/dist/agent/tool/action-fusion.js.map +1 -0
- package/dist/agent/tool/capture.js +1 -1
- package/dist/agent/tool/capture.js.map +1 -1
- package/dist/agent/tool/definition.d.ts +8 -0
- package/dist/agent/tool/definition.d.ts.map +1 -1
- package/dist/agent/tool/definition.js.map +1 -1
- package/dist/agent/tool/evidence-reducer.d.ts +41 -0
- package/dist/agent/tool/evidence-reducer.d.ts.map +1 -0
- package/dist/agent/tool/evidence-reducer.js +7 -0
- package/dist/agent/tool/evidence-reducer.js.map +1 -0
- package/dist/agent/tool/nested.d.ts +117 -0
- package/dist/agent/tool/nested.d.ts.map +1 -0
- package/dist/agent/tool/nested.js +2 -0
- package/dist/agent/tool/nested.js.map +1 -0
- package/dist/agent/tool/output-budget.d.ts.map +1 -1
- package/dist/agent/tool/output-budget.js +2 -2
- package/dist/agent/tool/output-budget.js.map +1 -1
- package/dist/agent/tool/output-schema.js +2 -0
- package/dist/agent/tool/output-schema.js.map +1 -0
- package/dist/agent/tool/pipeline.d.ts +7 -0
- package/dist/agent/tool/pipeline.d.ts.map +1 -1
- package/dist/agent/tool/pipeline.js +2 -2
- package/dist/agent/tool/pipeline.js.map +1 -1
- package/dist/agent/tool/program-results.js +2 -0
- package/dist/agent/tool/program-results.js.map +1 -0
- package/dist/agent.d.ts +6 -2
- package/dist/agent.js +1 -1
- package/dist/composition/agent/definition.js +1 -1
- package/dist/composition/agent/options.js +1 -1
- package/dist/composition/agent/options.js.map +1 -1
- package/dist/composition/agent/session.js +1 -1
- package/dist/composition/agent/session.js.map +1 -1
- package/dist/composition/agent/types.d.ts +6 -0
- package/dist/composition/agent/types.d.ts.map +1 -1
- package/dist/composition/tool-source/snapshot.js +1 -1
- package/dist/index.d.ts +2 -1
- package/dist/index.js +1 -1
- package/dist/memory.d.ts +2 -1
- package/dist/memory.js +1 -1
- package/dist/observability/bus.js +1 -1
- package/dist/primitives/version.d.ts +1 -1
- package/dist/primitives/version.js +1 -1
- package/dist/primitives/version.js.map +1 -1
- package/dist/runtime/registry.js +1 -1
- package/dist/tools.d.ts +4 -1
- package/dist/tools.js +1 -1
- package/package.json +1 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"session.js","names":[],"sources":["../../../src/agent/define/session.ts"],"sourcesContent":["import { contentHasDocument, contentHasImage } from '../../message/projection.ts'\nimport { ModelError } from '../../errors/model-error.ts'\nimport { type ToolCatalog } from '../tool/registry.ts'\nimport { History } from '../history/history.ts'\nimport { normalizeToolPairing } from '../history/normalize.ts'\nimport type { TurnHooks } from '../loop/types.ts'\nimport { ContextCompactor, type CompactionResult } from '../memory/compaction.ts'\nimport { bindCompactionAccounting } from '../memory/accounting-binding.ts'\nimport { resolveCompactionConfig } from '../memory/compaction-config.ts'\nimport { AgentMemory } from '../memory/memory.ts'\nimport { captureContextSections } from '../context/section.ts'\nimport type { ContextSection } from '../context/types.ts'\nimport { runAgent, type AgentRunEvent, type AgentRunOutcome } from '../mode/run-agent.ts'\nimport type { UserInputBroker } from '../mode/user-input.ts'\nimport { waitForSettlement } from '../../async/index.ts'\nimport type { OperationStatus } from '../../observation/index.ts'\nimport { RunEventBuffer } from '../accounting/event-buffer.ts'\nimport { AgentRunError, AGENT_ACCOUNTING_ERROR_CODES } from '../accounting/error.ts'\nimport type { RunAccountingPort } from '../accounting/contracts.ts'\nimport type { LegacyRunReport } from '../accounting/report.ts'\nimport type { RunReport } from '../accounting/delivery-types.ts'\nimport { createRunTerminalRecord, withTerminalDelivery } from '../accounting/delivery/terminal.ts'\nimport { SkillCatalog, createSkillTools, renderSkillCatalog, type SkillLookupOptions } from '../skill/index.ts'\nimport type { AgentDefinition } from './definition.ts'\nimport {\n type AgentInput, type AgentRuntimeLimits, type AgentSessionOptions, type AgentSessionSnapshot,\n type AgentSessionActivatedSkillSnapshot, type AgentResumeSessionOptions,\n type AgentInvocationOptions, type AgentResponse, type AgentRunHandle,\n} from './session/types.ts'\nimport { validateSessionSnapshot } from './session/validation.ts'\nimport { resolveRuntimeLimits } from './session/config.ts'\nimport {\n conversationId, newConversationId, userMessage, deferred, messageOf, errorCodeOf,\n toolCatalog,\n} from './session/common.ts'\nimport { captureResumedSkillActivations, prepareSkills } from './session/skills.ts'\nimport { appendRunInstructions } from './instructions.ts'\nimport type { ToolSourceRunReference } from '../tool/source-types.ts'\nimport { accountTraceEvent } from './session/trace-accounting.ts'\nimport {\n captureResumedObjective, commitRuntimeMemory, loadRuntimeMemory, renderRuntimeMemory,\n} from './session/runtime-memory.ts'\nimport { attachRuntimeSession, runtimeSessionConfiguration } from './session/runtime-binding.ts'\nimport { bindSkillProviderLogger } from '../skill/provider/context.ts'\nimport { createSessionLedger } from './session/accounting.ts'\nimport { runRuntimeCompaction } from './session/runtime-compaction.ts'\nimport { sessionCallConfig } from './session/model-config.ts'\nimport { consumeSessionEvents } from './session/observer.ts'\nimport { sealRuntimeRun } from './session/run-seal.ts'\n\nexport class AgentSession {\n readonly definition: AgentDefinition\n private readonly options: AgentSessionOptions\n private readonly catalog: ToolCatalog | undefined\n private activeRuntimeCatalog: ToolCatalog | undefined\n private readonly skillCatalog: SkillCatalog | undefined\n private readonly runtimeLimits: Readonly<AgentRuntimeLimits>\n /** Definition sections first, then session sections; duplicate ids are rejected. */\n private readonly contextSections: readonly ContextSection[] | undefined\n private currentHistory: History\n private currentMemory: AgentMemory\n private currentConversationId: string\n private compactor: ContextCompactor | undefined\n private pendingSkillActivations: readonly AgentSessionActivatedSkillSnapshot[] = Object.freeze([])\n private active = false\n private activeAdditionalInstructions: string | undefined\n /** The overlay of the run that owns the session, so maintenance follows the same model. */\n private activeInvocation: AgentInvocationOptions | undefined\n private readonly idleWaiters = new Set<() => void>()\n\n constructor(definition: AgentDefinition, options: AgentSessionOptions) {\n if (definition.mode === 'deep-human-in-loop' && options.userInput === undefined) {\n throw new TypeError(`agent '${definition.id}' requires a userInput broker in deep-human-in-loop mode`)\n }\n this.definition = definition\n const historyLimits = options.historyLimits === undefined\n ? undefined\n : Object.freeze({ ...options.historyLimits })\n // Validate reset-time policy even when the initial History was supplied by\n // the host, and detach mutable option containers from the caller.\n if (options.history !== undefined && historyLimits !== undefined) void new History(historyLimits)\n const compaction = options.compaction === undefined || options.compaction === false\n ? options.compaction\n : Object.freeze({ ...options.compaction })\n const trace = options.trace === undefined ? undefined : Object.freeze({ ...options.trace })\n const team = options.team === undefined ? undefined : Object.freeze({ ...options.team })\n const ledgerLimits = options.ledgerLimits === undefined ? undefined : Object.freeze({ ...options.ledgerLimits })\n const eventBufferLimits = options.eventBufferLimits === undefined\n ? undefined\n : Object.freeze({ ...options.eventBufferLimits })\n this.options = Object.freeze({\n ...options,\n ...(historyLimits === undefined ? {} : { historyLimits }),\n ...(compaction === undefined ? {} : { compaction }),\n ...(trace === undefined ? {} : { trace }),\n ...(team === undefined ? {} : { team }),\n ...(ledgerLimits === undefined ? {} : { ledgerLimits }),\n ...(eventBufferLimits === undefined ? {} : { eventBufferLimits }),\n ...(options.skills === undefined ? {} : { skills: Object.freeze([...options.skills]) }),\n ...(Array.isArray(options.tools) ? { tools: Object.freeze([...options.tools]) } : {}),\n ...(options.interceptors === undefined ? {} : { interceptors: Object.freeze([...options.interceptors]) }),\n })\n this.runtimeLimits = resolveRuntimeLimits(options.runtimeLimits)\n // A session may replace a definition section by reusing its id: the\n // definition describes the agent, the session describes where it is\n // running, and the more specific one wins in place. Two sections with one\n // id inside the *same* list stays an error — a single live surface node\n // cannot have two owners.\n const overrides = captureContextSections(options.contextSections) ?? []\n const base = captureContextSections(definition.contextSections) ?? []\n const merged = [\n ...base.map(section => overrides.find(override => override.id === section.id) ?? section),\n ...overrides.filter(override => !base.some(section => section.id === override.id)),\n ]\n this.contextSections = merged.length === 0 ? undefined : Object.freeze(merged)\n this.currentConversationId = conversationId(options.conversationId)\n this.currentHistory = options.history ?? new History(historyLimits)\n const skillSources = [...definition.skills, ...options.skills ?? []]\n const skillRuntimeDisabled = definition.skillIds?.length === 0\n const skillRuntimeConfigured = skillSources.length > 0 || (definition.skillIds?.length ?? 0) > 0\n this.skillCatalog = skillRuntimeDisabled || !skillRuntimeConfigured\n ? undefined\n : new SkillCatalog(skillSources, {\n ...(definition.skillIds === undefined ? {} : { allowedSkillIds: definition.skillIds }),\n maxSkills: definition.skillOptions.maxSkills,\n maxCatalogBytes: definition.skillOptions.maxDiscoveryBytes,\n })\n const skillTools = this.skillCatalog === undefined ? [] : createSkillTools(\n this.skillCatalog,\n definition.skillOptions,\n () => this.skillLookup(),\n )\n const teamAccess = options.team?.tools === 'reporting' ? 'reporting' as const : 'full' as const\n const teamTools = options.team?.tools === false\n ? []\n : options.team?.team.toolsFor(options.team.name ?? definition.id, teamAccess) ?? []\n this.catalog = toolCatalog(definition.tools, options.tools, [...skillTools, ...teamTools])\n this.currentMemory = options.memory instanceof AgentMemory\n ? options.memory\n : options.memory === undefined\n ? new AgentMemory(definition.memory.seed, definition.memory)\n : AgentMemory.fromSnapshot(options.memory, definition.memory)\n captureResumedObjective(this.currentMemory, this.currentHistory, this.definition.memory.autoCaptureObjective)\n this.compactor = this.createCompactor()\n attachRuntimeSession(this, (input, invocation, additionalInstructions) =>\n this.createRunHandle(input, invocation, additionalInstructions), invocation =>\n this.createRunHandle(undefined, invocation), invocation =>\n this.compactForRuntime(invocation), () => {\n this.compactor = this.createCompactor()\n })\n options.team?.team.attach(this, {\n ...(options.team.name === undefined ? {} : { name: options.team.name }),\n ...(options.team.description === undefined ? {} : { description: options.team.description }),\n ...(options.team.instructions === undefined ? {} : { instructions: options.team.instructions }),\n ...(options.team.role === undefined ? {} : { role: options.team.role }),\n ...(options.team.tools === undefined ? {} : { tools: options.team.tools }),\n })\n }\n\n /** Restore a JSON-round-tripped session snapshot with fresh runtime dependencies. */\n static fromSnapshot(\n definition: AgentDefinition,\n options: AgentResumeSessionOptions,\n ): AgentSession {\n const { snapshot, ...runtime } = options\n validateSessionSnapshot(snapshot, definition.id, definition.skillOptions.maxSkills)\n const session = new AgentSession(definition, {\n ...runtime,\n conversationId: snapshot.conversationId,\n history: History.fromSnapshot(snapshot.history, runtime.historyLimits),\n memory: AgentMemory.fromSnapshot(snapshot.memory, definition.memory),\n })\n session.pendingSkillActivations = captureResumedSkillActivations(snapshot.skills, session.skillCatalog)\n return session\n }\n\n /** Stable identity for persistence keys, URLs, logs, and GUI trace grouping. */\n get conversationId(): string { return this.currentConversationId }\n\n /** Mutable append-only history owned by this conversation. */\n get history(): History { return this.currentHistory }\n\n /** Durable task facts injected into every request outside compactable history. */\n get memory(): AgentMemory { return this.currentMemory }\n\n /** Refreshable skill catalog for host UIs and explicit user invocation surfaces. */\n get skills(): SkillCatalog | undefined { return this.skillCatalog }\n\n /** Whether a model/tool turn currently owns this session. */\n get isRunning(): boolean { return this.active }\n\n /** Capture one JSON-safe envelope that can be passed to `agent.resumeSession()`. */\n snapshot(): AgentSessionSnapshot {\n const activated = this.activationSnapshot()\n return Object.freeze({\n version: 1 as const,\n conversationId: this.currentConversationId,\n agentId: this.definition.id,\n history: this.currentHistory.snapshot(),\n memory: this.currentMemory.snapshot(),\n ...runtimeSessionConfiguration(this)?.memory === undefined ? {} : {\n memoryBindingId: runtimeSessionConfiguration(this)!.memory!.bindingId,\n },\n ...activated.length === 0 ? {} : {\n skills: Object.freeze({ activated }),\n },\n })\n }\n\n /** Start a fresh conversation without rebuilding provider/tool configuration. */\n reset(): void {\n if (this.active) throw new Error('cannot reset an agent session while a run is active')\n this.currentConversationId = newConversationId()\n this.currentHistory = new History(this.options.historyLimits)\n this.currentMemory = new AgentMemory(this.definition.memory.seed, this.definition.memory)\n this.pendingSkillActivations = Object.freeze([])\n this.skillCatalog?.clearActivations()\n this.compactor = this.createCompactor()\n }\n\n /** Create one explicit context checkpoint while the session is idle. */\n async compact(invocation: AgentInvocationOptions = {}): Promise<CompactionResult | null> {\n if (this.active) throw new Error('cannot compact an agent session while a run is active')\n this.active = true\n this.activeInvocation = invocation\n try {\n await this.prepareSkills(invocation.signal)\n return await this.compactor?.compactNow(invocation.signal) ?? null\n } finally {\n this.releaseRun()\n }\n }\n\n private async compactForRuntime(invocation: AgentInvocationOptions): Promise<{\n readonly result: CompactionResult | null\n readonly report: LegacyRunReport\n readonly failure?: unknown\n }> {\n if (this.active) throw new Error('cannot compact an agent session while a run is active')\n const ledger = this.createLedger()\n this.active = true\n this.activeInvocation = invocation\n if (this.compactor !== undefined) bindCompactionAccounting(this.compactor, ledger)\n if (this.skillCatalog !== undefined) bindSkillProviderLogger(this.skillCatalog, ledger.modelInvocation.logger)\n try { return await runRuntimeCompaction({\n ...(this.compactor === undefined ? {} : { compactor: this.compactor }),\n invocation,\n accounting: ledger,\n prepare: () => this.prepareSkills(invocation.signal, ledger),\n }) } finally { this.releaseRun() }\n }\n\n /**\n * Append attributed context without starting a turn.\n *\n * A2A quiet delivery uses this primitive. The returned history sequence is a\n * delivery receipt and lets wake-up schedulers coalesce messages safely.\n */\n inject(input: AgentInput): number {\n const message = userMessage(input)\n this.currentHistory.append({ kind: 'user', message })\n return this.currentHistory.entries().length\n }\n\n /** Resolve after the current run releases the session. */\n whenIdle(signal?: AbortSignal): Promise<void> {\n if (!this.active) return Promise.resolve()\n if (signal?.aborted) return Promise.reject(signal.reason)\n return new Promise<void>((resolve, reject) => {\n let settled = false\n const finish = (): void => {\n if (settled) return\n settled = true\n this.idleWaiters.delete(finish)\n signal?.removeEventListener('abort', abort)\n resolve()\n }\n const abort = (): void => {\n if (settled) return\n settled = true\n this.idleWaiters.delete(finish)\n reject(signal?.reason)\n }\n this.idleWaiters.add(finish)\n signal?.addEventListener('abort', abort, { once: true })\n if (!this.active) finish()\n })\n }\n\n /** Start an eager run and expose both public events and its canonical terminal report. */\n stream(input: AgentInput, invocation: AgentInvocationOptions = {}): AgentRunHandle {\n return this.createRunHandle(input, invocation)\n }\n\n /** Process context already appended with {@link inject} without duplicating it. */\n streamPending(invocation: AgentInvocationOptions = {}): AgentRunHandle {\n return this.createRunHandle(undefined, invocation)\n }\n\n /** Run one user turn and return the terminal response. */\n async run(input: AgentInput, invocation: AgentInvocationOptions = {}): Promise<AgentResponse> {\n const handle = this.stream(input, invocation)\n await consumeSessionEvents(handle, invocation.onEvent, this.runtimeLimits.observerTimeoutMs ?? 30_000)\n return await handle.result\n }\n\n /** Run one turn over already-injected context and return its terminal response. */\n async runPending(invocation: AgentInvocationOptions = {}): Promise<AgentResponse> {\n const handle = this.streamPending(invocation)\n await consumeSessionEvents(handle, invocation.onEvent, this.runtimeLimits.observerTimeoutMs ?? 30_000)\n return await handle.result\n }\n\n private createRunHandle(\n input: AgentInput | undefined,\n invocation: AgentInvocationOptions,\n additionalInstructions?: string,\n ): AgentRunHandle {\n if (this.active) throw new Error(`agent session '${this.definition.id}' is already running`)\n const firstTurnSeq = this.currentHistory.entries().length + 1\n const owned = new AbortController()\n let terminal = false\n const signal = invocation.signal === undefined\n ? owned.signal\n : AbortSignal.any([invocation.signal, owned.signal])\n const buffer = new RunEventBuffer<AgentRunEvent>(\n this.options.eventBufferLimits?.maxEvents,\n this.options.eventBufferLimits?.maxBytes,\n )\n const reportDeferred = deferred<RunReport>()\n const resultDeferred = deferred<AgentResponse>()\n const toolSourcesDeferred = deferred<readonly ToolSourceRunReference[]>()\n const ledger = this.createLedger()\n let toolSourceReferences: readonly ToolSourceRunReference[] = Object.freeze([])\n if (this.compactor !== undefined) bindCompactionAccounting(this.compactor, ledger)\n if (this.skillCatalog !== undefined) {\n bindSkillProviderLogger(this.skillCatalog, ledger.modelInvocation.logger)\n }\n this.active = true\n this.activeAdditionalInstructions = additionalInstructions\n this.activeInvocation = invocation\n const spanOperations = new Map<string, string>()\n const task = (async (): Promise<void> => {\n let failure: unknown\n let outcome: AgentRunOutcome | undefined\n let memoryState: Awaited<ReturnType<typeof loadRuntimeMemory>>['state'] | undefined\n try {\n const runtime = runtimeSessionConfiguration(this)\n if (runtime?.memory !== undefined) {\n const prepared = await loadRuntimeMemory(\n runtime.memory, this.currentConversationId, this.definition.memory, signal, ledger,\n )\n memoryState = prepared.state\n if (prepared.memory !== undefined) this.currentMemory = prepared.memory\n }\n if (runtime?.prepareTools !== undefined) {\n const logger = ledger.modelInvocation.logger\n if (logger === undefined) throw new Error('runtime tool source logger is unavailable')\n const generation = runtime.prepareTools(signal, logger, [...this.catalog?.names() ?? [], ...this.definition.nativeTools.map(tool => tool.name)])\n this.activeRuntimeCatalog = toolCatalog([], this.catalog, generation.tools)\n toolSourceReferences = generation.references\n }\n toolSourcesDeferred.resolve(toolSourceReferences)\n await this.prepareSkills(signal, ledger)\n if (input !== undefined) {\n const message = userMessage(input)\n if (this.definition.memory.autoCaptureObjective) {\n const operation = ledger.startOperation('memory', { data: { action: 'capture-objective' } })\n try {\n this.currentMemory.captureOriginalObjective(message)\n ledger.endOperation(operation, 'success')\n } catch (error) {\n ledger.endOperation(operation, 'error', { error })\n throw error\n }\n }\n this.currentHistory.append({ kind: 'user', message })\n }\n // Preflight before compaction can turn a required image into a summary.\n if (invocation.imagePolicy === 'strict' && this.history.messages().some(message => contentHasImage(message.content))) {\n const config = this.callConfig(invocation)\n const model = await this.options.registry.resolveModelInfo(config.provider, config.model, signal)\n if (model.inputModalities !== undefined && !model.inputModalities.includes('image')) {\n throw new ModelError(`model ${model.id} does not support required image input`, 'UNSUPPORTED_IMAGE_INPUT')\n }\n }\n // Same preflight for documents, for the same reason.\n if (invocation.documentPolicy === 'strict' && this.history.messages().some(message => contentHasDocument(message.content))) {\n const config = this.callConfig(invocation)\n const model = await this.options.registry.resolveModelInfo(config.provider, config.model, signal)\n if (model.inputModalities !== undefined && !model.inputModalities.includes('document')) {\n throw new ModelError(`model ${model.id} does not support required document input`, 'UNSUPPORTED_DOCUMENT_INPUT')\n }\n }\n for await (const event of this.runDefinition({ ...invocation, signal }, ledger)) {\n accountTraceEvent(ledger, spanOperations, event)\n if (event.type === 'agent-end') outcome = event.outcome\n buffer.push(event)\n }\n if (outcome === undefined) {\n throw new Error(`agent session '${this.definition.id}' ended without agent-end`)\n }\n if (signal.aborted) throw signal.reason ?? new Error('agent run was aborted')\n if (outcome.reason.kind === 'error' && outcome.reason.failure.code === 'USAGE_REQUIRED') {\n const error = new Error(outcome.reason.failure.message) as Error & { code: string }\n error.code = 'USAGE_REQUIRED'\n throw error\n }\n if (runtime?.memory !== undefined && memoryState !== undefined && memoryState.status !== 'disabled') {\n await commitRuntimeMemory(\n runtime.memory, this.currentConversationId, this.currentMemory.snapshot(),\n memoryState, signal, ledger,\n )\n }\n } catch (error: unknown) {\n failure = error\n toolSourcesDeferred.resolve(toolSourceReferences)\n }\n\n let report: RunReport\n try {\n const status: OperationStatus = signal.aborted || outcome?.reason.kind === 'aborted'\n ? 'aborted'\n : failure !== undefined || outcome?.reason.kind === 'error'\n ? 'error'\n : 'success'\n const ledgerReport = await ledger.finalize(status, outcome?.completed ?? false, failure)\n report = withTerminalDelivery(createRunTerminalRecord(ledgerReport), ledgerReport.delivery)\n reportDeferred.resolve(report)\n } catch (finalizeError: unknown) {\n reportDeferred.reject(finalizeError)\n resultDeferred.reject(finalizeError)\n buffer.fail(finalizeError)\n terminal = true\n this.releaseRun()\n return\n }\n if (terminal) return\n\n if (failure === undefined && ledger.terminalAuditFailure) {\n const error = new Error('audit observation checkpoint failed after run finalization') as Error & { code: string }\n error.code = 'OBSERVABILITY_AUDIT_UNAVAILABLE'\n failure = error\n }\n if (failure !== undefined) {\n const error = new AgentRunError(\n messageOf(failure),\n errorCodeOf(failure) ?? AGENT_ACCOUNTING_ERROR_CODES.RUN_FAILED,\n report,\n { cause: failure },\n )\n resultDeferred.reject(error)\n buffer.fail(error)\n } else {\n const terminal = outcome as AgentRunOutcome\n const historyEvent = [...this.currentHistory.entries()].reverse()\n .find(entry => entry.seq >= firstTurnSeq && entry.event.kind === 'assistant')\n ?.event\n const assistantMessage = historyEvent?.kind === 'assistant' ? historyEvent.message : undefined\n const response: AgentResponse = Object.freeze({\n text: terminal.text,\n outcome: terminal,\n report,\n ...assistantMessage === undefined ? {} : { message: assistantMessage },\n })\n resultDeferred.resolve(response)\n buffer.close()\n }\n terminal = true\n this.releaseRun()\n })()\n void task.catch(error => {\n if (terminal) return\n reportDeferred.reject(error)\n resultDeferred.reject(error)\n buffer.fail(error)\n terminal = true\n this.releaseRun()\n })\n void resultDeferred.promise.catch(() => undefined)\n void reportDeferred.promise.catch(() => undefined)\n let iterated = false\n return Object.freeze({\n runId: ledger.runId,\n traceId: ledger.traceId,\n toolSourceSnapshots: toolSourcesDeferred.promise,\n eventsSettled: task.then(() => undefined, () => undefined),\n result: resultDeferred.promise,\n report: reportDeferred.promise,\n seal: () => sealRuntimeRun({ ledger, buffer, report: reportDeferred, result: resultDeferred,\n toolSources: toolSourcesDeferred, currentToolSources: () => toolSourceReferences, isTerminal: () => terminal,\n markTerminal: () => { terminal = true }, abort: () => owned.abort(new Error('Agent run was sealed')),\n release: () => this.releaseRun() }),\n abort(_reason?: unknown): void {\n if (!terminal && !owned.signal.aborted) owned.abort(new Error('Agent run was aborted'))\n },\n [Symbol.asyncIterator](): AsyncIterator<AgentRunEvent> {\n if (iterated) return (async function* () { throw new Error('an agent run handle can only be iterated once') })()\n iterated = true\n return (async function* () {\n let exhausted = false\n try {\n while (true) {\n const item = await buffer.take()\n if (item.done) { exhausted = true; break }\n yield item.value\n }\n } finally {\n if (!exhausted) {\n owned.abort(new Error('agent event consumer stopped'))\n buffer.stop()\n await waitForSettlement(task, 30_000)\n }\n }\n })()\n },\n })\n }\n\n private releaseRun(): void {\n this.active = false\n this.activeAdditionalInstructions = undefined\n this.activeInvocation = undefined\n this.activeRuntimeCatalog = undefined\n if (this.skillCatalog !== undefined) bindSkillProviderLogger(this.skillCatalog, undefined)\n if (this.compactor !== undefined) bindCompactionAccounting(this.compactor, undefined)\n const waiters = [...this.idleWaiters]\n this.idleWaiters.clear()\n for (const resolve of waiters) resolve()\n }\n\n private createLedger() {\n const runtime = runtimeSessionConfiguration(this)\n return createSessionLedger({\n definition: this.definition,\n options: this.options,\n runtimeLimits: this.runtimeLimits,\n conversationId: this.currentConversationId,\n ...(runtime === undefined ? {} : { runtime }),\n })\n }\n\n private runDefinition(\n invocation: AgentInvocationOptions,\n accounting?: RunAccountingPort,\n ): AsyncIterable<AgentRunEvent> {\n const definition = this.definition\n const hooks = this.combinedHooks(accounting)\n const catalog = this.effectiveCatalog()\n const outputFormat = invocation.outputFormat ?? definition.outputFormat\n const common = {\n registry: this.options.registry,\n config: this.callConfig(invocation),\n history: this.history,\n ...catalog === undefined ? {} : { tools: catalog },\n ...definition.nativeTools.length === 0 ? {} : { nativeTools: definition.nativeTools },\n ...definition.toolChoice === undefined ? {} : { toolChoice: definition.toolChoice },\n ...invocation.imagePolicy === undefined ? {} : { imagePolicy: invocation.imagePolicy },\n ...invocation.documentPolicy === undefined ? {} : { documentPolicy: invocation.documentPolicy },\n ...outputFormat === undefined ? {} : { outputFormat },\n ...(invocation.validateOutput === undefined ? {} : { validateOutput: invocation.validateOutput }),\n system: this.systemInstructions(this.activeAdditionalInstructions),\n maxTurns: definition.maxTurns,\n bounds: {\n maxToolCalls: definition.maxToolCalls,\n ...this.runtimeLimits.maxParallelToolCalls === undefined\n ? {}\n : { maxParallel: this.runtimeLimits.maxParallelToolCalls },\n ...this.runtimeLimits.maxConsecutiveToolErrors === undefined\n ? {}\n : { maxConsecutiveToolErrors: this.runtimeLimits.maxConsecutiveToolErrors },\n ...this.runtimeLimits.repeatToolWarningAt === undefined\n ? {}\n : { repeatToolWarningAt: this.runtimeLimits.repeatToolWarningAt },\n ...this.runtimeLimits.repeatToolLimit === undefined\n ? {}\n : { repeatToolLimit: this.runtimeLimits.repeatToolLimit },\n ...this.runtimeLimits.toolCycleWarningAt === undefined\n ? {}\n : { toolCycleWarningAt: this.runtimeLimits.toolCycleWarningAt },\n ...this.runtimeLimits.toolCycleLimit === undefined\n ? {}\n : { toolCycleLimit: this.runtimeLimits.toolCycleLimit },\n ...this.runtimeLimits.onExhausted === undefined\n ? {}\n : { onExhausted: this.runtimeLimits.onExhausted },\n ...this.runtimeLimits.maxToolResultTokens === undefined\n ? {}\n : { maxToolResultTokens: this.runtimeLimits.maxToolResultTokens },\n ...this.runtimeLimits.toolResultOverflow === undefined\n ? {}\n : { toolResultOverflow: this.runtimeLimits.toolResultOverflow },\n ...this.runtimeLimits.maxToolCycleLength === undefined\n ? {}\n : { maxToolCycleLength: this.runtimeLimits.maxToolCycleLength },\n ...this.runtimeLimits.finalReportReserveTokens === undefined ? {} : {\n finalReportReserveTokens: this.runtimeLimits.finalReportReserveTokens,\n },\n ...this.runtimeLimits.maxTotalTokens === undefined\n ? {}\n : { maxTotalTokens: this.runtimeLimits.maxTotalTokens },\n ...this.runtimeLimits.maxToolResultBytes === undefined\n ? {}\n : { maxToolResultBytes: this.runtimeLimits.maxToolResultBytes },\n ...this.runtimeLimits.maxToolDurationMs === undefined\n ? {}\n : { maxToolDurationMs: this.runtimeLimits.maxToolDurationMs },\n ...this.runtimeLimits.toolTeardownTimeoutMs === undefined\n ? {}\n : { toolTeardownTimeoutMs: this.runtimeLimits.toolTeardownTimeoutMs },\n },\n commentary: definition.commentary,\n ...this.runtimeLimits.teardownTimeoutMs === undefined ? {} : { teardownTimeoutMs: this.runtimeLimits.teardownTimeoutMs },\n ...this.runtimeLimits.modelTimeoutMs === undefined ? {} : { modelTimeoutMs: this.runtimeLimits.modelTimeoutMs },\n ...this.runtimeLimits.maxModelRequestBytes === undefined ? {} : { maxModelRequestBytes: this.runtimeLimits.maxModelRequestBytes },\n ...this.runtimeLimits.maxModelResponseBytes === undefined ? {} : { maxModelResponseBytes: this.runtimeLimits.maxModelResponseBytes },\n ...this.runtimeLimits.maxModelStreamEvents === undefined ? {} : { maxModelStreamEvents: this.runtimeLimits.maxModelStreamEvents },\n ...this.runtimeLimits.hookTimeoutMs === undefined ? {} : { hookTimeoutMs: this.runtimeLimits.hookTimeoutMs },\n ...this.runtimeLimits.hookTeardownTimeoutMs === undefined ? {} : { hookTeardownTimeoutMs: this.runtimeLimits.hookTeardownTimeoutMs },\n ...this.options.approvals === undefined ? {} : { approvals: this.options.approvals },\n ...this.options.spillStore === undefined ? {} : { spillStore: this.options.spillStore },\n ...this.options.interceptors === undefined ? {} : { interceptors: this.options.interceptors },\n ...this.contextSections === undefined ? {} : { contextSections: this.contextSections },\n ...hooks === undefined ? {} : { hooks },\n ...invocation.signal === undefined ? {} : { signal: invocation.signal },\n ...accounting === undefined ? {} : { accounting },\n ...accounting?.modelInvocation.logger === undefined ? {} : { logger: accounting.modelInvocation.logger },\n trace: {\n ...this.options.trace,\n conversationId: this.currentConversationId,\n agentId: definition.id,\n agentName: definition.name,\n },\n }\n if (definition.mode === 'deep-human-in-loop') {\n return runAgent({\n ...common, mode: definition.mode, userInput: this.options.userInput as UserInputBroker,\n })\n }\n if (definition.mode === 'deep') {\n return runAgent({\n ...common, mode: definition.mode,\n ...this.options.userInput === undefined ? {} : { userInput: this.options.userInput },\n })\n }\n return runAgent({ ...common, mode: 'basic' })\n }\n\n private createCompactor(): ContextCompactor | undefined {\n const configured = this.options.compaction === false\n ? false\n : this.options.compaction === undefined\n ? this.definition.compaction\n : resolveCompactionConfig(this.options.compaction)\n if (configured === false) return undefined\n return new ContextCompactor({\n registry: this.options.registry,\n config: () => this.callConfig(this.activeInvocation),\n history: () => this.currentHistory,\n system: () => this.systemInstructions(this.activeAdditionalInstructions),\n pinnedMessages: () => renderRuntimeMemory(\n this.currentMemory, this.definition.memory.maxInjectedChars,\n ),\n tools: () => [\n ...this.effectiveCatalog()?.schemas() ?? [],\n ...this.definition.nativeTools,\n ],\n policy: configured,\n })\n }\n\n private effectiveCatalog(): ToolCatalog | undefined {\n return this.activeRuntimeCatalog ?? this.catalog\n }\n\n private combinedHooks(accounting?: RunAccountingPort): TurnHooks | undefined {\n const user = this.options.hooks\n if (this.compactor === undefined\n && user === undefined\n && this.currentMemory.items().length === 0) return undefined\n return {\n ...user,\n beforeStep: async context => {\n const generation = this.currentHistory.generation()\n if (this.compactor !== undefined) bindCompactionAccounting(this.compactor, accounting)\n await this.compactor?.beforeStep(context)\n if (accounting?.usageStop !== undefined) return { kind: 'proceed' as const }\n const refreshed = this.currentHistory.generation() === generation\n ? context\n : {\n ...context,\n messages: normalizeToolPairing(this.currentHistory.messages()),\n snapshot: this.currentHistory.snapshot(),\n }\n const memory = renderRuntimeMemory(\n this.currentMemory, this.definition.memory.maxInjectedChars, accounting,\n )\n const current = memory.length === 0\n ? refreshed\n : { ...refreshed, messages: Object.freeze([...memory, ...refreshed.messages]) }\n const decision = await user?.beforeStep?.(current) ?? { kind: 'proceed' as const }\n if (decision.kind === 'reject') return decision\n const prepend = [...memory, ...decision.prepend ?? []]\n return prepend.length === 0 ? decision : { kind: 'proceed' as const, prepend }\n },\n onRequestError: async context => {\n if (this.compactor !== undefined) bindCompactionAccounting(this.compactor, accounting)\n const recovery = await this.compactor?.onRequestError(context)\n if (accounting?.usageStop !== undefined) return 'fail'\n if (recovery === 'retry') return 'retry'\n return await user?.onRequestError?.(context) ?? 'fail'\n },\n }\n }\n\n private callConfig(invocation?: AgentInvocationOptions) {\n return sessionCallConfig(this.definition, runtimeSessionConfiguration(this), invocation)\n }\n\n private systemInstructions(additionalInstructions?: string): string {\n const base = this.skillCatalog === undefined\n ? this.definition.instructions\n : renderSkillCatalog(\n this.definition.instructions,\n this.skillCatalog.summaries(),\n this.definition.skillOptions,\n )\n const team = this.options.team\n const composed = team === undefined\n ? base\n : `${base}\\n\\n${team.team.instructionsFor(team.name ?? this.definition.id)}`\n return appendRunInstructions(composed, additionalInstructions)\n }\n\n private skillLookup(signal?: AbortSignal): SkillLookupOptions {\n return {\n ...(this.options.skillCwd === undefined ? {} : { cwd: this.options.skillCwd }),\n ...(signal === undefined ? {} : { signal }),\n }\n }\n\n private activationSnapshot(): readonly AgentSessionActivatedSkillSnapshot[] {\n const activated = new Map<string, AgentSessionActivatedSkillSnapshot>()\n for (const entry of this.pendingSkillActivations) activated.set(entry.id, entry)\n for (const reference of this.skillCatalog?.activatedSkillReferences() ?? []) {\n activated.set(reference.id, reference)\n }\n for (const summary of this.skillCatalog?.activatedSummaries() ?? []) {\n if (activated.has(summary.id)) continue\n activated.set(summary.id, Object.freeze({\n id: summary.id, provider: summary.provider, source: summary.source,\n ...summary.resourceBase === undefined ? {} : {\n resourceBase: Object.freeze({ ...summary.resourceBase }),\n },\n }))\n }\n return Object.freeze([...activated.values()].sort((left, right) => left.id.localeCompare(right.id)))\n }\n\n private async prepareSkills(signal?: AbortSignal, accounting?: RunAccountingPort): Promise<void> {\n await prepareSkills(\n this.definition, this.skillCatalog, this.pendingSkillActivations,\n signal => this.skillLookup(signal),\n () => { this.pendingSkillActivations = Object.freeze([]) }, signal, accounting,\n )\n }\n}\n\nexport { configureRuntimeSessionModel, streamRuntimeSession } from './session/runtime-binding.ts'\nexport type {\n AgentInput, AgentRuntimeLimits, AgentSessionOptions, AgentTeamMemberOptions,\n AgentSessionSnapshot, AgentSessionActivatedSkillSnapshot, AgentResumeSessionOptions,\n AgentInvocationOptions, AgentResponse, AgentRunHandle,\n} from './session/types.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Q,GAAI,OAAO,OAAO,CACtC,GAAI,EAAQ,GAAI,SAAU,EAAQ,SAAU,OAAQ,EAAQ,OAC5D,GAAG,EAAQ,eAAiB,IAAA,GAAY,CAAC,EAAI,CAC3C,aAAc,OAAO,OAAO,CAAE,GAAG,EAAQ,YAAa,CAAC,CACzD,CACF,CAAC,CAAC,EAEJ,OAAO,OAAO,OAAO,CAAC,GAAG,EAAU,OAAO,CAAC,CAAC,CAAC,MAAM,EAAM,IAAU,EAAK,GAAG,cAAc,EAAM,EAAE,CAAC,CAAC,CACrG,CAEA,MAAc,cAAc,EAAsB,EAA+C,CAC/F,MAAM,EACJ,KAAK,WAAY,KAAK,aAAc,KAAK,wBACzC,GAAU,KAAK,YAAY,CAAM,MAC3B,CAAE,KAAK,wBAA0B,OAAO,OAAO,CAAC,CAAC,CAAE,EAAG,EAAQ,CACtE,CACF,CACF"}
|
|
1
|
+
{"version":3,"file":"session.js","names":[],"sources":["../../../src/agent/define/session.ts"],"sourcesContent":["import { contentHasDocument, contentHasImage } from '../../message/projection.ts'\nimport { ModelError } from '../../errors/model-error.ts'\nimport { type ToolCatalog } from '../tool/registry.ts'\nimport { History } from '../history/history.ts'\nimport { bindModelRequestBoundary } from '../loop/turn/model-request-boundary.ts'\nimport { bindStepProjectionSources } from '../loop/turn/step-projection.ts'\nimport { normalizeToolPairing } from '../history/normalize.ts'\nimport type { TurnHooks } from '../loop/types.ts'\nimport { ContextCompactor, type CompactionResult } from '../memory/compaction.ts'\nimport { bindCompactionAccounting } from '../memory/accounting-binding.ts'\nimport { resolveCompactionConfig } from '../memory/compaction-config.ts'\nimport { AgentMemory } from '../memory/memory.ts'\nimport { captureContextSections } from '../context/section.ts'\nimport type { ContextSection } from '../context/types.ts'\nimport { runAgent, type AgentRunEvent, type AgentRunOutcome } from '../mode/run-agent.ts'\nimport type { UserInputBroker } from '../mode/user-input.ts'\nimport { waitForSettlement } from '../../async/index.ts'\nimport type { OperationStatus } from '../../observation/index.ts'\nimport { RunEventBuffer } from '../accounting/event-buffer.ts'\nimport { AgentRunError, AGENT_ACCOUNTING_ERROR_CODES } from '../accounting/error.ts'\nimport type { RunAccountingPort } from '../accounting/contracts.ts'\nimport type { LegacyRunReport } from '../accounting/report.ts'\nimport type { RunReport } from '../accounting/delivery-types.ts'\nimport { createRunTerminalRecord, withTerminalDelivery } from '../accounting/delivery/terminal.ts'\nimport { SkillCatalog, createSkillTools, renderSkillCatalog, type SkillLookupOptions } from '../skill/index.ts'\nimport type { AgentDefinition } from './definition.ts'\nimport {\n type AgentInput, type AgentRuntimeLimits, type AgentSessionOptions, type AgentSessionSnapshot,\n type AgentSessionActivatedSkillSnapshot, type AgentResumeSessionOptions,\n type AgentInvocationOptions, type AgentResponse, type AgentRunHandle,\n} from './session/types.ts'\nimport { validateSessionSnapshot } from './session/validation.ts'\nimport { resolveRuntimeLimits } from './session/config.ts'\nimport {\n conversationId, newConversationId, userMessage, deferred, messageOf, errorCodeOf,\n toolCatalog,\n} from './session/common.ts'\nimport { captureResumedSkillActivations, prepareSkills } from './session/skills.ts'\nimport { appendRunInstructions } from './instructions.ts'\nimport type { ToolSourceRunReference } from '../tool/source-types.ts'\nimport { accountTraceEvent } from './session/trace-accounting.ts'\nimport {\n captureResumedObjective, commitRuntimeMemory, loadRuntimeMemory, renderRuntimeMemory,\n} from './session/runtime-memory.ts'\nimport { attachRuntimeSession, runtimeSessionConfiguration } from './session/runtime-binding.ts'\nimport { bindSkillProviderLogger } from '../skill/provider/context.ts'\nimport { createSessionLedger } from './session/accounting.ts'\nimport { runRuntimeCompaction } from './session/runtime-compaction.ts'\nimport { sessionCallConfig } from './session/model-config.ts'\nimport { consumeSessionEvents } from './session/observer.ts'\nimport { sealRuntimeRun } from './session/run-seal.ts'\n\nexport class AgentSession {\n readonly definition: AgentDefinition\n private readonly options: AgentSessionOptions\n private readonly catalog: ToolCatalog | undefined\n private activeRuntimeCatalog: ToolCatalog | undefined\n private readonly skillCatalog: SkillCatalog | undefined\n private readonly runtimeLimits: Readonly<AgentRuntimeLimits>\n /** Definition sections first, then session sections; duplicate ids are rejected. */\n private readonly contextSections: readonly ContextSection[] | undefined\n private currentHistory: History\n private currentMemory: AgentMemory\n private currentConversationId: string\n private compactor: ContextCompactor | undefined\n private pendingSkillActivations: readonly AgentSessionActivatedSkillSnapshot[] = Object.freeze([])\n private active = false\n private activeAdditionalInstructions: string | undefined\n /** The overlay of the run that owns the session, so maintenance follows the same model. */\n private activeInvocation: AgentInvocationOptions | undefined\n private readonly idleWaiters = new Set<() => void>()\n /**\n * Messages injected while a run is in flight, waiting for the next model\n * request. Appending them at once put them AHEAD of the assistant output of\n * the round already streaming, a round that never saw them; the next round\n * then read \"steer, then the work that ignored it\" as work that answered it.\n */\n private pendingInjections: History | undefined\n /**\n * A model request has been built and its output is not yet fully recorded.\n * Only then is an injection held: hooks and team notices that inject between\n * rounds still append at once, as they always have.\n */\n private roundInFlight = false\n\n constructor(definition: AgentDefinition, options: AgentSessionOptions) {\n if (definition.mode === 'deep-human-in-loop' && options.userInput === undefined) {\n throw new TypeError(`agent '${definition.id}' requires a userInput broker in deep-human-in-loop mode`)\n }\n this.definition = definition\n const historyLimits = options.historyLimits === undefined\n ? undefined\n : Object.freeze({ ...options.historyLimits })\n // Validate reset-time policy even when the initial History was supplied by\n // the host, and detach mutable option containers from the caller.\n if (options.history !== undefined && historyLimits !== undefined) void new History(historyLimits)\n const compaction = options.compaction === undefined || options.compaction === false\n ? options.compaction\n : Object.freeze({ ...options.compaction })\n const trace = options.trace === undefined ? undefined : Object.freeze({ ...options.trace })\n const team = options.team === undefined ? undefined : Object.freeze({ ...options.team })\n const ledgerLimits = options.ledgerLimits === undefined ? undefined : Object.freeze({ ...options.ledgerLimits })\n const eventBufferLimits = options.eventBufferLimits === undefined\n ? undefined\n : Object.freeze({ ...options.eventBufferLimits })\n this.options = Object.freeze({\n ...options,\n ...(historyLimits === undefined ? {} : { historyLimits }),\n ...(compaction === undefined ? {} : { compaction }),\n ...(trace === undefined ? {} : { trace }),\n ...(team === undefined ? {} : { team }),\n ...(ledgerLimits === undefined ? {} : { ledgerLimits }),\n ...(eventBufferLimits === undefined ? {} : { eventBufferLimits }),\n ...(options.skills === undefined ? {} : { skills: Object.freeze([...options.skills]) }),\n ...(Array.isArray(options.tools) ? { tools: Object.freeze([...options.tools]) } : {}),\n ...(options.interceptors === undefined ? {} : { interceptors: Object.freeze([...options.interceptors]) }),\n })\n this.runtimeLimits = resolveRuntimeLimits(options.runtimeLimits)\n // A session may replace a definition section by reusing its id: the\n // definition describes the agent, the session describes where it is\n // running, and the more specific one wins in place. Two sections with one\n // id inside the *same* list stays an error — a single live surface node\n // cannot have two owners.\n const overrides = captureContextSections(options.contextSections) ?? []\n const base = captureContextSections(definition.contextSections) ?? []\n const merged = [\n ...base.map(section => overrides.find(override => override.id === section.id) ?? section),\n ...overrides.filter(override => !base.some(section => section.id === override.id)),\n ]\n this.contextSections = merged.length === 0 ? undefined : Object.freeze(merged)\n this.currentConversationId = conversationId(options.conversationId)\n this.currentHistory = options.history ?? new History(historyLimits)\n const skillSources = [...definition.skills, ...options.skills ?? []]\n const skillRuntimeDisabled = definition.skillIds?.length === 0\n const skillRuntimeConfigured = skillSources.length > 0 || (definition.skillIds?.length ?? 0) > 0\n this.skillCatalog = skillRuntimeDisabled || !skillRuntimeConfigured\n ? undefined\n : new SkillCatalog(skillSources, {\n ...(definition.skillIds === undefined ? {} : { allowedSkillIds: definition.skillIds }),\n maxSkills: definition.skillOptions.maxSkills,\n maxCatalogBytes: definition.skillOptions.maxDiscoveryBytes,\n })\n const skillTools = this.skillCatalog === undefined ? [] : createSkillTools(\n this.skillCatalog,\n definition.skillOptions,\n () => this.skillLookup(),\n )\n const teamAccess = options.team?.tools === 'reporting' ? 'reporting' as const : 'full' as const\n const teamTools = options.team?.tools === false\n ? []\n : options.team?.team.toolsFor(options.team.name ?? definition.id, teamAccess) ?? []\n this.catalog = toolCatalog(definition.tools, options.tools, [...skillTools, ...teamTools])\n this.currentMemory = options.memory instanceof AgentMemory\n ? options.memory\n : options.memory === undefined\n ? new AgentMemory(definition.memory.seed, definition.memory)\n : AgentMemory.fromSnapshot(options.memory, definition.memory)\n captureResumedObjective(this.currentMemory, this.currentHistory, this.definition.memory.autoCaptureObjective)\n this.compactor = this.createCompactor()\n attachRuntimeSession(this, (input, invocation, additionalInstructions) =>\n this.createRunHandle(input, invocation, additionalInstructions), invocation =>\n this.createRunHandle(undefined, invocation), invocation =>\n this.compactForRuntime(invocation), () => {\n this.compactor = this.createCompactor()\n })\n options.team?.team.attach(this, {\n ...(options.team.name === undefined ? {} : { name: options.team.name }),\n ...(options.team.description === undefined ? {} : { description: options.team.description }),\n ...(options.team.instructions === undefined ? {} : { instructions: options.team.instructions }),\n ...(options.team.role === undefined ? {} : { role: options.team.role }),\n ...(options.team.tools === undefined ? {} : { tools: options.team.tools }),\n })\n }\n\n /** Restore a JSON-round-tripped session snapshot with fresh runtime dependencies. */\n static fromSnapshot(\n definition: AgentDefinition,\n options: AgentResumeSessionOptions,\n ): AgentSession {\n const { snapshot, ...runtime } = options\n validateSessionSnapshot(snapshot, definition.id, definition.skillOptions.maxSkills)\n const session = new AgentSession(definition, {\n ...runtime,\n conversationId: snapshot.conversationId,\n history: History.fromSnapshot(snapshot.history, runtime.historyLimits),\n memory: AgentMemory.fromSnapshot(snapshot.memory, definition.memory),\n })\n session.pendingSkillActivations = captureResumedSkillActivations(snapshot.skills, session.skillCatalog)\n return session\n }\n\n /** Stable identity for persistence keys, URLs, logs, and GUI trace grouping. */\n get conversationId(): string { return this.currentConversationId }\n\n /** Mutable append-only history owned by this conversation. */\n get history(): History { return this.currentHistory }\n\n /** Durable task facts injected into every request outside compactable history. */\n get memory(): AgentMemory { return this.currentMemory }\n\n /** Refreshable skill catalog for host UIs and explicit user invocation surfaces. */\n get skills(): SkillCatalog | undefined { return this.skillCatalog }\n\n /** Whether a model/tool turn currently owns this session. */\n get isRunning(): boolean { return this.active }\n\n /** Capture one JSON-safe envelope that can be passed to `agent.resumeSession()`. */\n snapshot(): AgentSessionSnapshot {\n const activated = this.activationSnapshot()\n const history = this.currentHistory.snapshot()\n const pending = this.pendingInjections?.entries() ?? []\n // An accepted input must survive a snapshot taken before its model round\n // finishes. Project pending inputs at the known tail without delivering\n // them early to the live model or changing the persisted v1 schema.\n const persistedHistory = pending.length === 0 ? history : Object.freeze({\n version: 1 as const,\n entries: Object.freeze([...history.entries, ...pending.map((entry, index) => Object.freeze({\n ...entry, seq: history.entries.length + index + 1,\n }))]),\n })\n return Object.freeze({\n version: 1 as const,\n conversationId: this.currentConversationId,\n agentId: this.definition.id,\n history: persistedHistory,\n memory: this.currentMemory.snapshot(),\n ...runtimeSessionConfiguration(this)?.memory === undefined ? {} : {\n memoryBindingId: runtimeSessionConfiguration(this)!.memory!.bindingId,\n },\n ...activated.length === 0 ? {} : {\n skills: Object.freeze({ activated }),\n },\n })\n }\n\n /** Start a fresh conversation without rebuilding provider/tool configuration. */\n reset(): void {\n if (this.active) throw new Error('cannot reset an agent session while a run is active')\n this.currentConversationId = newConversationId()\n this.currentHistory = new History(this.options.historyLimits)\n this.currentMemory = new AgentMemory(this.definition.memory.seed, this.definition.memory)\n this.pendingInjections = undefined\n this.pendingSkillActivations = Object.freeze([])\n this.skillCatalog?.clearActivations()\n this.compactor = this.createCompactor()\n }\n\n /** Create one explicit context checkpoint while the session is idle. */\n async compact(invocation: AgentInvocationOptions = {}): Promise<CompactionResult | null> {\n if (this.active) throw new Error('cannot compact an agent session while a run is active')\n this.active = true\n this.activeInvocation = invocation\n try {\n await this.prepareSkills(invocation.signal)\n return await this.compactor?.compactNow(invocation.signal) ?? null\n } finally {\n this.releaseRun()\n }\n }\n\n private async compactForRuntime(invocation: AgentInvocationOptions): Promise<{\n readonly result: CompactionResult | null\n readonly report: LegacyRunReport\n readonly failure?: unknown\n }> {\n if (this.active) throw new Error('cannot compact an agent session while a run is active')\n const ledger = this.createLedger()\n this.active = true\n this.activeInvocation = invocation\n if (this.compactor !== undefined) bindCompactionAccounting(this.compactor, ledger)\n if (this.skillCatalog !== undefined) bindSkillProviderLogger(this.skillCatalog, ledger.modelInvocation.logger)\n try { return await runRuntimeCompaction({\n ...(this.compactor === undefined ? {} : { compactor: this.compactor }),\n invocation,\n accounting: ledger,\n prepare: () => this.prepareSkills(invocation.signal, ledger),\n }) } finally { this.releaseRun() }\n }\n\n /**\n * Append attributed context without starting a turn.\n *\n * A2A quiet delivery uses this primitive. The returned count includes queued\n * inputs and lets wake-up schedulers coalesce messages safely; a mid-round\n * receipt is provisional rather than the eventual persisted entry sequence.\n */\n inject(input: AgentInput): number {\n const message = userMessage(input)\n // Mid-run, hold the message until the next model request is built, so it\n // lands after every entry the model has actually answered. Bound pending\n // inputs with the same guards as history instead of an unbounded array.\n if (this.active && this.roundInFlight) {\n const pending = this.pendingInjections ??= new History(this.options.historyLimits)\n pending.append({ kind: 'user', message })\n return this.currentHistory.entries().length + pending.entries().length\n }\n this.drainInjections()\n this.currentHistory.append({ kind: 'user', message })\n return this.currentHistory.entries().length\n }\n\n /**\n * Close the in-flight window once a round's output is fully recorded: after\n * its tool results (`step-end`), after a final answer with no tool calls, or\n * when the turn ends. The loop waits on this consumer, so held messages land\n * exactly there, never between a tool call and its result.\n */\n private observeRoundBoundary(event: { readonly type: string; readonly kind?: string; readonly message?: { readonly content: readonly { readonly type: string }[] } }): void {\n // The chat request is now fixed. beforeStep hooks still run outside this\n // window, so their injections can be included in that request's refresh.\n if (event.type === 'span-start' && event.kind === 'chat') {\n this.roundInFlight = true\n return\n }\n if (!this.roundInFlight) return\n const finalAnswer = event.type === 'assistant-message'\n && event.message?.content.every(block => block.type !== 'tool-call') === true\n if (event.type === 'step-end' || event.type === 'turn-end' || event.type === 'agent-end' || finalAnswer) {\n this.roundInFlight = false\n this.drainInjections()\n }\n }\n\n /** Deliver held injections, in arrival order, at the chronological tail. */\n private drainInjections(): void {\n if (this.pendingInjections === undefined) return\n const pending = this.pendingInjections\n // Atomic: a full history must not consume only the first queued input and\n // silently lose the rest. Keep the buffer available to snapshot/recovery.\n this.currentHistory.appendBatch(pending.entries().map(entry => ({ event: entry.event })))\n this.pendingInjections = undefined\n }\n\n /** Resolve after the current run releases the session. */\n whenIdle(signal?: AbortSignal): Promise<void> {\n if (!this.active) return Promise.resolve()\n if (signal?.aborted) return Promise.reject(signal.reason)\n return new Promise<void>((resolve, reject) => {\n let settled = false\n const finish = (): void => {\n if (settled) return\n settled = true\n this.idleWaiters.delete(finish)\n signal?.removeEventListener('abort', abort)\n resolve()\n }\n const abort = (): void => {\n if (settled) return\n settled = true\n this.idleWaiters.delete(finish)\n reject(signal?.reason)\n }\n this.idleWaiters.add(finish)\n signal?.addEventListener('abort', abort, { once: true })\n if (!this.active) finish()\n })\n }\n\n /** Start an eager run and expose both public events and its canonical terminal report. */\n stream(input: AgentInput, invocation: AgentInvocationOptions = {}): AgentRunHandle {\n return this.createRunHandle(input, invocation)\n }\n\n /** Process context already appended with {@link inject} without duplicating it. */\n streamPending(invocation: AgentInvocationOptions = {}): AgentRunHandle {\n return this.createRunHandle(undefined, invocation)\n }\n\n /** Run one user turn and return the terminal response. */\n async run(input: AgentInput, invocation: AgentInvocationOptions = {}): Promise<AgentResponse> {\n const handle = this.stream(input, invocation)\n await consumeSessionEvents(handle, invocation.onEvent, this.runtimeLimits.observerTimeoutMs ?? 30_000)\n return await handle.result\n }\n\n /** Run one turn over already-injected context and return its terminal response. */\n async runPending(invocation: AgentInvocationOptions = {}): Promise<AgentResponse> {\n const handle = this.streamPending(invocation)\n await consumeSessionEvents(handle, invocation.onEvent, this.runtimeLimits.observerTimeoutMs ?? 30_000)\n return await handle.result\n }\n\n private createRunHandle(\n input: AgentInput | undefined,\n invocation: AgentInvocationOptions,\n additionalInstructions?: string,\n ): AgentRunHandle {\n if (this.active) throw new Error(`agent session '${this.definition.id}' is already running`)\n this.drainInjections()\n const firstTurnSeq = this.currentHistory.entries().length + 1\n const owned = new AbortController()\n let terminal = false\n const signal = invocation.signal === undefined\n ? owned.signal\n : AbortSignal.any([invocation.signal, owned.signal])\n const buffer = new RunEventBuffer<AgentRunEvent>(\n this.options.eventBufferLimits?.maxEvents,\n this.options.eventBufferLimits?.maxBytes,\n )\n const reportDeferred = deferred<RunReport>()\n const resultDeferred = deferred<AgentResponse>()\n const toolSourcesDeferred = deferred<readonly ToolSourceRunReference[]>()\n const ledger = this.createLedger()\n let toolSourceReferences: readonly ToolSourceRunReference[] = Object.freeze([])\n if (this.compactor !== undefined) bindCompactionAccounting(this.compactor, ledger)\n if (this.skillCatalog !== undefined) {\n bindSkillProviderLogger(this.skillCatalog, ledger.modelInvocation.logger)\n }\n this.active = true\n bindModelRequestBoundary(this.currentHistory, inFlight => {\n this.roundInFlight = inFlight\n if (!inFlight) this.drainInjections()\n })\n this.activeAdditionalInstructions = additionalInstructions\n this.activeInvocation = invocation\n const spanOperations = new Map<string, string>()\n const task = (async (): Promise<void> => {\n let failure: unknown\n let outcome: AgentRunOutcome | undefined\n let memoryState: Awaited<ReturnType<typeof loadRuntimeMemory>>['state'] | undefined\n try {\n const runtime = runtimeSessionConfiguration(this)\n if (runtime?.memory !== undefined) {\n const prepared = await loadRuntimeMemory(\n runtime.memory, this.currentConversationId, this.definition.memory, signal, ledger,\n )\n memoryState = prepared.state\n if (prepared.memory !== undefined) this.currentMemory = prepared.memory\n }\n if (runtime?.prepareTools !== undefined) {\n const logger = ledger.modelInvocation.logger\n if (logger === undefined) throw new Error('runtime tool source logger is unavailable')\n const generation = runtime.prepareTools(signal, logger, [...this.catalog?.names() ?? [], ...this.definition.nativeTools.map(tool => tool.name)])\n this.activeRuntimeCatalog = toolCatalog([], this.catalog, generation.tools)\n toolSourceReferences = generation.references\n }\n toolSourcesDeferred.resolve(toolSourceReferences)\n await this.prepareSkills(signal, ledger)\n if (input !== undefined) {\n const message = userMessage(input)\n if (this.definition.memory.autoCaptureObjective) {\n const operation = ledger.startOperation('memory', { data: { action: 'capture-objective' } })\n try {\n this.currentMemory.captureOriginalObjective(message)\n ledger.endOperation(operation, 'success')\n } catch (error) {\n ledger.endOperation(operation, 'error', { error })\n throw error\n }\n }\n this.currentHistory.append({ kind: 'user', message })\n }\n // Preflight before compaction can turn a required image into a summary.\n if (invocation.imagePolicy === 'strict' && this.history.messages().some(message => contentHasImage(message.content))) {\n const config = this.callConfig(invocation)\n const model = await this.options.registry.resolveModelInfo(config.provider, config.model, signal)\n if (model.inputModalities !== undefined && !model.inputModalities.includes('image')) {\n throw new ModelError(`model ${model.id} does not support required image input`, 'UNSUPPORTED_IMAGE_INPUT')\n }\n }\n // Same preflight for documents, for the same reason.\n if (invocation.documentPolicy === 'strict' && this.history.messages().some(message => contentHasDocument(message.content))) {\n const config = this.callConfig(invocation)\n const model = await this.options.registry.resolveModelInfo(config.provider, config.model, signal)\n if (model.inputModalities !== undefined && !model.inputModalities.includes('document')) {\n throw new ModelError(`model ${model.id} does not support required document input`, 'UNSUPPORTED_DOCUMENT_INPUT')\n }\n }\n for await (const event of this.runDefinition({ ...invocation, signal }, ledger)) {\n this.observeRoundBoundary(event)\n accountTraceEvent(ledger, spanOperations, event)\n if (event.type === 'agent-end') outcome = event.outcome\n buffer.push(event)\n }\n if (outcome === undefined) {\n throw new Error(`agent session '${this.definition.id}' ended without agent-end`)\n }\n if (signal.aborted) throw signal.reason ?? new Error('agent run was aborted')\n if (outcome.reason.kind === 'error' && outcome.reason.failure.code === 'USAGE_REQUIRED') {\n const error = new Error(outcome.reason.failure.message) as Error & { code: string }\n error.code = 'USAGE_REQUIRED'\n throw error\n }\n if (runtime?.memory !== undefined && memoryState !== undefined && memoryState.status !== 'disabled') {\n await commitRuntimeMemory(\n runtime.memory, this.currentConversationId, this.currentMemory.snapshot(),\n memoryState, signal, ledger,\n )\n }\n } catch (error: unknown) {\n failure = error\n toolSourcesDeferred.resolve(toolSourceReferences)\n }\n\n try { this.drainInjections() } catch (error) { failure ??= error }\n\n let report: RunReport\n try {\n const status: OperationStatus = signal.aborted || outcome?.reason.kind === 'aborted'\n ? 'aborted'\n : failure !== undefined || outcome?.reason.kind === 'error'\n ? 'error'\n : 'success'\n const ledgerReport = await ledger.finalize(status, outcome?.completed ?? false, failure)\n report = withTerminalDelivery(createRunTerminalRecord(ledgerReport), ledgerReport.delivery)\n reportDeferred.resolve(report)\n } catch (finalizeError: unknown) {\n reportDeferred.reject(finalizeError)\n resultDeferred.reject(finalizeError)\n buffer.fail(finalizeError)\n terminal = true\n this.releaseRun()\n return\n }\n if (terminal) return\n\n if (failure === undefined && ledger.terminalAuditFailure) {\n const error = new Error('audit observation checkpoint failed after run finalization') as Error & { code: string }\n error.code = 'OBSERVABILITY_AUDIT_UNAVAILABLE'\n failure = error\n }\n if (failure !== undefined) {\n const error = new AgentRunError(\n messageOf(failure),\n errorCodeOf(failure) ?? AGENT_ACCOUNTING_ERROR_CODES.RUN_FAILED,\n report,\n { cause: failure },\n )\n resultDeferred.reject(error)\n buffer.fail(error)\n } else {\n const terminal = outcome as AgentRunOutcome\n const historyEvent = [...this.currentHistory.entries()].reverse()\n .find(entry => entry.seq >= firstTurnSeq && entry.event.kind === 'assistant')\n ?.event\n const assistantMessage = historyEvent?.kind === 'assistant' ? historyEvent.message : undefined\n const response: AgentResponse = Object.freeze({\n text: terminal.text,\n outcome: terminal,\n report,\n ...assistantMessage === undefined ? {} : { message: assistantMessage },\n })\n resultDeferred.resolve(response)\n buffer.close()\n }\n terminal = true\n this.releaseRun()\n })()\n void task.catch(error => {\n if (terminal) return\n reportDeferred.reject(error)\n resultDeferred.reject(error)\n buffer.fail(error)\n terminal = true\n this.releaseRun()\n })\n void resultDeferred.promise.catch(() => undefined)\n void reportDeferred.promise.catch(() => undefined)\n let iterated = false\n return Object.freeze({\n runId: ledger.runId,\n traceId: ledger.traceId,\n toolSourceSnapshots: toolSourcesDeferred.promise,\n eventsSettled: task.then(() => undefined, () => undefined),\n result: resultDeferred.promise,\n report: reportDeferred.promise,\n seal: () => sealRuntimeRun({ ledger, buffer, report: reportDeferred, result: resultDeferred,\n toolSources: toolSourcesDeferred, currentToolSources: () => toolSourceReferences, isTerminal: () => terminal,\n markTerminal: () => { terminal = true }, abort: () => owned.abort(new Error('Agent run was sealed')),\n release: () => this.releaseRun() }),\n abort(_reason?: unknown): void {\n if (!terminal && !owned.signal.aborted) owned.abort(new Error('Agent run was aborted'))\n },\n [Symbol.asyncIterator](): AsyncIterator<AgentRunEvent> {\n if (iterated) return (async function* () { throw new Error('an agent run handle can only be iterated once') })()\n iterated = true\n return (async function* () {\n let exhausted = false\n try {\n while (true) {\n const item = await buffer.take()\n if (item.done) { exhausted = true; break }\n yield item.value\n }\n } finally {\n if (!exhausted) {\n owned.abort(new Error('agent event consumer stopped'))\n buffer.stop()\n await waitForSettlement(task, 30_000)\n }\n }\n })()\n },\n })\n }\n\n private releaseRun(): void {\n // A message that arrived during the final model round is still delivered,\n // so the next run (or a waiting scheduler) reads it.\n try { this.drainInjections() } finally {\n bindModelRequestBoundary(this.currentHistory)\n this.roundInFlight = false\n this.active = false\n this.activeAdditionalInstructions = undefined\n this.activeInvocation = undefined\n this.activeRuntimeCatalog = undefined\n if (this.skillCatalog !== undefined) bindSkillProviderLogger(this.skillCatalog, undefined)\n if (this.compactor !== undefined) bindCompactionAccounting(this.compactor, undefined)\n const waiters = [...this.idleWaiters]\n this.idleWaiters.clear()\n for (const resolve of waiters) resolve()\n }\n }\n\n private createLedger() {\n const runtime = runtimeSessionConfiguration(this)\n return createSessionLedger({\n definition: this.definition,\n options: this.options,\n runtimeLimits: this.runtimeLimits,\n conversationId: this.currentConversationId,\n ...(runtime === undefined ? {} : { runtime }),\n })\n }\n\n private runDefinition(\n invocation: AgentInvocationOptions,\n accounting?: RunAccountingPort,\n ): AsyncIterable<AgentRunEvent> {\n const definition = this.definition\n const hooks = this.combinedHooks(accounting)\n const catalog = this.effectiveCatalog()\n const outputFormat = invocation.outputFormat ?? definition.outputFormat\n const common = {\n registry: this.options.registry,\n config: this.callConfig(invocation),\n history: this.history,\n ...catalog === undefined ? {} : { tools: catalog },\n ...definition.nativeTools.length === 0 ? {} : { nativeTools: definition.nativeTools },\n ...definition.toolChoice === undefined ? {} : { toolChoice: definition.toolChoice },\n ...invocation.imagePolicy === undefined ? {} : { imagePolicy: invocation.imagePolicy },\n ...invocation.documentPolicy === undefined ? {} : { documentPolicy: invocation.documentPolicy },\n ...outputFormat === undefined ? {} : { outputFormat },\n ...(invocation.validateOutput === undefined ? {} : { validateOutput: invocation.validateOutput }),\n system: this.systemInstructions(this.activeAdditionalInstructions),\n maxTurns: definition.maxTurns,\n bounds: {\n maxToolCalls: definition.maxToolCalls,\n ...this.runtimeLimits.maxParallelToolCalls === undefined\n ? {}\n : { maxParallel: this.runtimeLimits.maxParallelToolCalls },\n ...this.runtimeLimits.maxConsecutiveToolErrors === undefined\n ? {}\n : { maxConsecutiveToolErrors: this.runtimeLimits.maxConsecutiveToolErrors },\n ...this.runtimeLimits.repeatToolWarningAt === undefined\n ? {}\n : { repeatToolWarningAt: this.runtimeLimits.repeatToolWarningAt },\n ...this.runtimeLimits.repeatToolLimit === undefined\n ? {}\n : { repeatToolLimit: this.runtimeLimits.repeatToolLimit },\n ...this.runtimeLimits.toolCycleWarningAt === undefined\n ? {}\n : { toolCycleWarningAt: this.runtimeLimits.toolCycleWarningAt },\n ...this.runtimeLimits.toolCycleLimit === undefined\n ? {}\n : { toolCycleLimit: this.runtimeLimits.toolCycleLimit },\n ...this.runtimeLimits.onExhausted === undefined\n ? {}\n : { onExhausted: this.runtimeLimits.onExhausted },\n ...this.runtimeLimits.maxToolResultTokens === undefined\n ? {}\n : { maxToolResultTokens: this.runtimeLimits.maxToolResultTokens },\n ...this.runtimeLimits.toolResultOverflow === undefined\n ? {}\n : { toolResultOverflow: this.runtimeLimits.toolResultOverflow },\n ...this.runtimeLimits.maxToolCycleLength === undefined\n ? {}\n : { maxToolCycleLength: this.runtimeLimits.maxToolCycleLength },\n ...this.runtimeLimits.finalReportReserveTokens === undefined ? {} : {\n finalReportReserveTokens: this.runtimeLimits.finalReportReserveTokens,\n },\n ...this.runtimeLimits.maxTotalTokens === undefined\n ? {}\n : { maxTotalTokens: this.runtimeLimits.maxTotalTokens },\n ...this.runtimeLimits.maxToolResultBytes === undefined\n ? {}\n : { maxToolResultBytes: this.runtimeLimits.maxToolResultBytes },\n ...this.runtimeLimits.maxToolDurationMs === undefined\n ? {}\n : { maxToolDurationMs: this.runtimeLimits.maxToolDurationMs },\n ...this.runtimeLimits.toolTeardownTimeoutMs === undefined\n ? {}\n : { toolTeardownTimeoutMs: this.runtimeLimits.toolTeardownTimeoutMs },\n },\n commentary: definition.commentary,\n ...this.runtimeLimits.teardownTimeoutMs === undefined ? {} : { teardownTimeoutMs: this.runtimeLimits.teardownTimeoutMs },\n ...this.runtimeLimits.modelTimeoutMs === undefined ? {} : { modelTimeoutMs: this.runtimeLimits.modelTimeoutMs },\n ...this.runtimeLimits.maxModelRequestBytes === undefined ? {} : { maxModelRequestBytes: this.runtimeLimits.maxModelRequestBytes },\n ...this.runtimeLimits.maxModelResponseBytes === undefined ? {} : { maxModelResponseBytes: this.runtimeLimits.maxModelResponseBytes },\n ...this.runtimeLimits.maxModelStreamEvents === undefined ? {} : { maxModelStreamEvents: this.runtimeLimits.maxModelStreamEvents },\n ...this.runtimeLimits.hookTimeoutMs === undefined ? {} : { hookTimeoutMs: this.runtimeLimits.hookTimeoutMs },\n ...this.runtimeLimits.hookTeardownTimeoutMs === undefined ? {} : { hookTeardownTimeoutMs: this.runtimeLimits.hookTeardownTimeoutMs },\n ...this.options.approvals === undefined ? {} : { approvals: this.options.approvals },\n ...this.options.spillStore === undefined ? {} : { spillStore: this.options.spillStore },\n ...this.options.experimentalPrograms === undefined ? {} : { experimentalPrograms: this.options.experimentalPrograms },\n ...this.options.interceptors === undefined ? {} : { interceptors: this.options.interceptors },\n ...this.contextSections === undefined ? {} : { contextSections: this.contextSections },\n ...hooks === undefined ? {} : { hooks },\n ...invocation.signal === undefined ? {} : { signal: invocation.signal },\n ...accounting === undefined ? {} : { accounting },\n ...accounting?.modelInvocation.logger === undefined ? {} : { logger: accounting.modelInvocation.logger },\n trace: {\n ...this.options.trace,\n conversationId: this.currentConversationId,\n agentId: definition.id,\n agentName: definition.name,\n },\n }\n if (definition.mode === 'deep-human-in-loop') {\n return runAgent({\n ...common, mode: definition.mode, userInput: this.options.userInput as UserInputBroker,\n })\n }\n if (definition.mode === 'deep') {\n return runAgent({\n ...common, mode: definition.mode,\n ...this.options.userInput === undefined ? {} : { userInput: this.options.userInput },\n })\n }\n return runAgent({ ...common, mode: 'basic' })\n }\n\n private createCompactor(): ContextCompactor | undefined {\n const configured = this.options.compaction === false\n ? false\n : this.options.compaction === undefined\n ? this.definition.compaction\n : resolveCompactionConfig(this.options.compaction)\n if (configured === false) return undefined\n return new ContextCompactor({\n registry: this.options.registry,\n config: () => this.callConfig(this.activeInvocation),\n history: () => this.currentHistory,\n system: () => this.systemInstructions(this.activeAdditionalInstructions),\n pinnedMessages: () => renderRuntimeMemory(\n this.currentMemory, this.definition.memory.maxInjectedChars,\n ),\n tools: () => [\n ...this.effectiveCatalog()?.schemas() ?? [],\n ...this.definition.nativeTools,\n ],\n policy: configured,\n })\n }\n\n private effectiveCatalog(): ToolCatalog | undefined {\n return this.activeRuntimeCatalog ?? this.catalog\n }\n\n private combinedHooks(accounting?: RunAccountingPort): TurnHooks | undefined {\n const user = this.options.hooks\n return {\n ...user,\n beforeStep: async context => {\n // Before anything reads history for this request: model-round refreshes\n // its messages when entries changed, so delivered input is included.\n const generation = this.currentHistory.generation()\n const entries = this.currentHistory.entries().length\n this.drainInjections()\n const prepared = this.currentHistory.entries().length === entries\n ? context\n : { ...context, messages: normalizeToolPairing(this.currentHistory.messages()), snapshot: this.currentHistory.snapshot() }\n if (this.compactor !== undefined) bindCompactionAccounting(this.compactor, accounting)\n await this.compactor?.beforeStep(prepared)\n if (accounting?.usageStop !== undefined) return { kind: 'proceed' as const }\n const refreshed = this.currentHistory.generation() === generation && this.currentHistory.entries().length === entries\n ? context\n : {\n ...context,\n messages: normalizeToolPairing(this.currentHistory.messages()),\n snapshot: this.currentHistory.snapshot(),\n }\n const memory = renderRuntimeMemory(\n this.currentMemory, this.definition.memory.maxInjectedChars, accounting,\n )\n const current = memory.length === 0\n ? refreshed\n : { ...refreshed, messages: Object.freeze([...memory, ...refreshed.messages]) }\n const decision = await user?.beforeStep?.(current) ?? { kind: 'proceed' as const }\n if (decision.kind === 'reject') return decision\n // A projection sees injected memory already; do not inject it twice.\n const prepend = [...decision.messages === undefined ? memory : [], ...decision.prepend ?? []]\n return bindStepProjectionSources(prepend.length === 0 ? decision : { ...decision, prepend }, refreshed.messages)\n },\n onRequestError: async context => {\n if (this.compactor !== undefined) bindCompactionAccounting(this.compactor, accounting)\n const recovery = await this.compactor?.onRequestError(context)\n if (accounting?.usageStop !== undefined) return 'fail'\n if (recovery === 'retry') return 'retry'\n return await user?.onRequestError?.(context) ?? 'fail'\n },\n }\n }\n\n private callConfig(invocation?: AgentInvocationOptions) {\n return sessionCallConfig(this.definition, runtimeSessionConfiguration(this), invocation)\n }\n\n private systemInstructions(additionalInstructions?: string): string {\n const base = this.skillCatalog === undefined\n ? this.definition.instructions\n : renderSkillCatalog(\n this.definition.instructions,\n this.skillCatalog.summaries(),\n this.definition.skillOptions,\n )\n const team = this.options.team\n const composed = team === undefined\n ? base\n : `${base}\\n\\n${team.team.instructionsFor(team.name ?? this.definition.id)}`\n return appendRunInstructions(composed, additionalInstructions)\n }\n\n private skillLookup(signal?: AbortSignal): SkillLookupOptions {\n return {\n ...(this.options.skillCwd === undefined ? {} : { cwd: this.options.skillCwd }),\n ...(signal === undefined ? {} : { signal }),\n }\n }\n\n private activationSnapshot(): readonly AgentSessionActivatedSkillSnapshot[] {\n const activated = new Map<string, AgentSessionActivatedSkillSnapshot>()\n for (const entry of this.pendingSkillActivations) activated.set(entry.id, entry)\n for (const reference of this.skillCatalog?.activatedSkillReferences() ?? []) {\n activated.set(reference.id, reference)\n }\n for (const summary of this.skillCatalog?.activatedSummaries() ?? []) {\n if (activated.has(summary.id)) continue\n activated.set(summary.id, Object.freeze({\n id: summary.id, provider: summary.provider, source: summary.source,\n ...summary.resourceBase === undefined ? {} : {\n resourceBase: Object.freeze({ ...summary.resourceBase }),\n },\n }))\n }\n return Object.freeze([...activated.values()].sort((left, right) => left.id.localeCompare(right.id)))\n }\n\n private async prepareSkills(signal?: AbortSignal, accounting?: RunAccountingPort): Promise<void> {\n await prepareSkills(\n this.definition, this.skillCatalog, this.pendingSkillActivations,\n signal => this.skillLookup(signal),\n () => { this.pendingSkillActivations = Object.freeze([]) }, signal, accounting,\n )\n }\n}\n\nexport { configureRuntimeSessionModel, streamRuntimeSession } from './session/runtime-binding.ts'\nexport type {\n AgentInput, AgentRuntimeLimits, AgentSessionOptions, AgentTeamMemberOptions,\n AgentSessionSnapshot, AgentSessionActivatedSkillSnapshot, AgentResumeSessionOptions,\n AgentInvocationOptions, AgentResponse, AgentRunHandle,\n} from './session/types.ts'\n"],"mappings":"o2EAoDA,IAAa,EAAb,MAAa,CAAa,CACxB,WACA,QACA,QACA,qBACA,aACA,cAEA,gBACA,eACA,cACA,sBACA,UACA,wBAAiF,OAAO,OAAO,CAAC,CAAC,EACjG,OAAiB,GACjB,6BAEA,iBACA,YAA+B,IAAI,IAOnC,kBAMA,cAAwB,GAExB,YAAY,EAA6B,EAA8B,CACrE,GAAI,EAAW,OAAS,sBAAwB,EAAQ,YAAc,IAAA,GACpE,MAAU,UAAU,UAAU,EAAW,GAAG,yDAAyD,EAEvG,KAAK,WAAa,EAClB,IAAM,EAAgB,EAAQ,gBAAkB,IAAA,GAC5C,IAAA,GACA,OAAO,OAAO,CAAE,GAAG,EAAQ,aAAc,CAAC,EAG1C,EAAQ,UAAY,IAAA,IAAa,IAAkB,IAAA,IAAW,IAAS,EAAQ,CAAa,EAChG,IAAM,EAAa,EAAQ,aAAe,IAAA,IAAa,EAAQ,aAAe,GAC1E,EAAQ,WACR,OAAO,OAAO,CAA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AAQ,SAAU,OAAQ,EAAQ,OAC5D,GAAG,EAAQ,eAAiB,IAAA,GAAY,CAAC,EAAI,CAC3C,aAAc,OAAO,OAAO,CAAE,GAAG,EAAQ,YAAa,CAAC,CACzD,CACF,CAAC,CAAC,EAEJ,OAAO,OAAO,OAAO,CAAC,GAAG,EAAU,OAAO,CAAC,CAAC,CAAC,MAAM,EAAM,IAAU,EAAK,GAAG,cAAc,EAAM,EAAE,CAAC,CAAC,CACrG,CAEA,MAAc,cAAc,EAAsB,EAA+C,CAC/F,MAAM,EACJ,KAAK,WAAY,KAAK,aAAc,KAAK,wBACzC,GAAU,KAAK,YAAY,CAAM,MAC3B,CAAE,KAAK,wBAA0B,OAAO,OAAO,CAAC,CAAC,CAAE,EAAG,EAAQ,CACtE,CACF,CACF"}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
function e(e){let t=e===`unbounded`?1/0:Math.max(0,e),n=0,r=0;return{reserve(e){if(!e&&n+r>=t)return;e||r++;let i=!1;return{budgeted:!e,confirm(){i||(i=!0,e||(r--,n++))},release(){i||(i=!0,e||r--)}}},get budgeted(){return n}}}export{e as createToolAdmission};
|
|
2
|
+
//# sourceMappingURL=admission.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"admission.js","names":[],"sources":["../../../src/agent/loop/admission.ts"],"sourcesContent":["/**\n * The one owner of a step's tool-call budget.\n *\n * Every dispatch in a step — a model-issued call or a call a program makes on\n * the model's behalf — reserves here before authorization and confirms only\n * when its body actually starts. A second counter anywhere else is how a nested\n * caller ends up running ten bodies against a budget of three.\n */\nexport interface ToolAdmission {\n /**\n * Reserve room for one call about to be authorized.\n * @param exempt - Whether the tool is `budgetExempt`; exempt calls never spend budget.\n * @returns A ticket, or `undefined` when the budget declines the call.\n */\n reserve(exempt: boolean): AdmissionTicket | undefined\n /** Dispatched calls that spent budget; exempt tools are excluded. */\n readonly budgeted: number\n}\n\n/** One reservation. Exactly one of `confirm` or `release` takes effect. */\nexport interface AdmissionTicket {\n /** Whether confirming this ticket spends budget. */\n readonly budgeted: boolean\n /** The body is starting: the reservation becomes spent budget. */\n confirm(): void\n /** The call will not run: return the reservation. */\n release(): void\n}\n\n/**\n * @param limit - Budgeted dispatches this step may still make, or `unbounded`\n * when the budget is a notice rather than a wall.\n * @returns A fresh admission for one step.\n */\nexport function createToolAdmission(limit: number | 'unbounded'): ToolAdmission {\n const ceiling = limit === 'unbounded' ? Number.POSITIVE_INFINITY : Math.max(0, limit)\n let spent = 0\n let reserved = 0\n return {\n reserve(exempt) {\n if (!exempt && spent + reserved >= ceiling) return undefined\n if (!exempt) reserved++\n let settled = false\n return {\n budgeted: !exempt,\n confirm() {\n if (settled) return\n settled = true\n if (!exempt) { reserved--; spent++ }\n },\n release() {\n if (settled) return\n settled = true\n if (!exempt) reserved--\n },\n }\n },\n get budgeted() { return spent },\n }\n}\n"],"mappings":"AAkCA,SAAgB,EAAoB,EAA4C,CAC9E,IAAM,EAAU,IAAU,YAAc,IAA2B,KAAK,IAAI,EAAG,CAAK,EAChF,EAAQ,EACR,EAAW,EACf,MAAO,CACL,QAAQ,EAAQ,CACd,GAAI,CAAC,GAAU,EAAQ,GAAY,EAAS,OACvC,GAAQ,IACb,IAAI,EAAU,GACd,MAAO,CACL,SAAU,CAAC,EACX,SAAU,CACJ,IACJ,EAAU,GACL,IAAU,IAAY,KAC7B,EACA,SAAU,CACJ,IACJ,EAAU,GACL,GAAQ,IACf,CACF,CACF,EACA,IAAI,UAAW,CAAE,OAAO,CAAM,CAChC,CACF"}
|
|
@@ -175,6 +175,8 @@ interface BeforeStepContext {
|
|
|
175
175
|
type StepDecision = {
|
|
176
176
|
readonly kind: 'proceed';
|
|
177
177
|
readonly prepend?: readonly Message[];
|
|
178
|
+
/** Model-only projection. Raw history and checkpoint snapshots remain unchanged. */
|
|
179
|
+
readonly messages?: readonly Message[];
|
|
178
180
|
} | {
|
|
179
181
|
readonly kind: 'reject';
|
|
180
182
|
readonly reason: string;
|
|
@@ -198,6 +200,8 @@ type CheckpointContext = {
|
|
|
198
200
|
readonly kind: 'before-tool-dispatch';
|
|
199
201
|
readonly call: ToolCallRequest;
|
|
200
202
|
readonly snapshot: HistorySnapshot;
|
|
203
|
+
/** Set when a program tool made this call; the id of that outer call. */
|
|
204
|
+
readonly parentCallId?: ToolCallRequest['callId'];
|
|
201
205
|
readonly signal?: AbortSignal;
|
|
202
206
|
readonly logger?: SdkLogger;
|
|
203
207
|
};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"events.d.ts","names":[],"sources":["../../../src/agent/loop/events.ts"],"mappings":";;;;;;;;;;;;;;;KAgBY;;;;;;;;KAcA,oBAAoB;KAEpB;WACG;;WACA;WAAoC;;WACpC;WAAmC,QAAQ;WAA0B;;WAErE;;WACA;;WACA;WAAoC;;WACpC;;WACA;WAAwB,SAAS;;UAE/B;WACN,QAAQ;WACR;WACA;;WAEA,QAAQ;;WAER,aAAa;WACb;WACA;;UAGD;WAAkB,OAAO;;KACvB;KACA,6BAA6B;KAC7B;KACA;WAEC;WACA;WACA,SAAS;WACT;;WAGA;WACA;WACA,SAAS;WACT;WACA;WACA;WACA;WACA;WACA;WACA,gBAAgB;WAChB;WACA;WACA;WACA,QAAQ;;KAET,aAAa,cACpB,wBAAwB;WACb;WAA6B;IAAiB;WAC9C;WAA6B;WAAuB;WAAuB;IAAuB;WAClG;WAA6B;WAAwB;WAAuB,OAAO;IAA+B;;;;;WAIlH;WAA2B;WAAwB;WAAuB,OAAO;WAA6B;IAAsB;WACpI;WAAkC;WAAwB;IAAiB;WAE9E;WACA;WACA;WACA,WAAW;WACX;IACP;WACU;WAAoC,SAAS;IAAY;WAE5D;WACA,WAAW;WACX;WACA,OAAO;WACP,QAAQ;WACR,sBAAsB;WACtB,2BAA2B;IAClC;WAEO;WACA,WAAW;WACX,MAAM;IACb;;WAGO;WACA,WAAW;WACX;WACA,QAAQ;WACR,sBAAsB;WACtB,2BAA2B;IAClC;WACU;WAA4B,MAAM;IAAoB;WACtD;WAA8B,MAAM;WAA0B,QAAQ;IAAwB;WAC9F;WAAmC,SAAS;IAAoB;WAChE;WAAwB,OAAO;IAAe;WAC9C;WAAiC,OADa;WACuD;IAAuB;WAC5H;WAA2B;WAAuB;IAAiB;WACnE;WAA2B,SAAS;IAAgB;UAEnD;WACN;WACA;WACA,mBAAmB;WACnB,UAAU;WACV,QAAQ;WACR,SAAS;EAClB,KAAK,OAAO,wBAAwB;;KAE1B;WACG;WAA0B,mBAAmB;;
|
|
1
|
+
{"version":3,"file":"events.d.ts","names":[],"sources":["../../../src/agent/loop/events.ts"],"mappings":";;;;;;;;;;;;;;;KAgBY;;;;;;;;KAcA,oBAAoB;KAEpB;WACG;;WACA;WAAoC;;WACpC;WAAmC,QAAQ;WAA0B;;WAErE;;WACA;;WACA;WAAoC;;WACpC;;WACA;WAAwB,SAAS;;UAE/B;WACN,QAAQ;WACR;WACA;;WAEA,QAAQ;;WAER,aAAa;WACb;WACA;;UAGD;WAAkB,OAAO;;KACvB;KACA,6BAA6B;KAC7B;KACA;WAEC;WACA;WACA,SAAS;WACT;;WAGA;WACA;WACA,SAAS;WACT;WACA;WACA;WACA;WACA;WACA;WACA,gBAAgB;WAChB;WACA;WACA;WACA,QAAQ;;KAET,aAAa,cACpB,wBAAwB;WACb;WAA6B;IAAiB;WAC9C;WAA6B;WAAuB;WAAuB;IAAuB;WAClG;WAA6B;WAAwB;WAAuB,OAAO;IAA+B;;;;;WAIlH;WAA2B;WAAwB;WAAuB,OAAO;WAA6B;IAAsB;WACpI;WAAkC;WAAwB;IAAiB;WAE9E;WACA;WACA;WACA,WAAW;WACX;IACP;WACU;WAAoC,SAAS;IAAY;WAE5D;WACA,WAAW;WACX;WACA,OAAO;WACP,QAAQ;WACR,sBAAsB;WACtB,2BAA2B;IAClC;WAEO;WACA,WAAW;WACX,MAAM;IACb;;WAGO;WACA,WAAW;WACX;WACA,QAAQ;WACR,sBAAsB;WACtB,2BAA2B;IAClC;WACU;WAA4B,MAAM;IAAoB;WACtD;WAA8B,MAAM;WAA0B,QAAQ;IAAwB;WAC9F;WAAmC,SAAS;IAAoB;WAChE;WAAwB,OAAO;IAAe;WAC9C;WAAiC,OADa;WACuD;IAAuB;WAC5H;WAA2B;WAAuB;IAAiB;WACnE;WAA2B,SAAS;IAAgB;UAEnD;WACN;WACA;WACA,mBAAmB;WACnB,UAAU;WACV,QAAQ;WACR,SAAS;EAClB,KAAK,OAAO,wBAAwB;;KAE1B;WACG;WAA0B,mBAAmB;;WAE7C,oBAAoB;;WACpB;WAAyB;;UACvB;WACN;WACA;WACA,SAAS;WACT,UAAU;WACV,QAAQ;WACR,SAAS;EAClB,KAAK,OAAO,wBAAwB;;KAE1B;WACG;WAAuC,SAAS;WAA0B,UAAU;WACpF,SAAS;WAAsB,SAAS;;WACxC;WAAuC,MAAM;WAA0B,UAAU;;WAEjF,eAAe;WACf,SAAS;WAAsB,SAAS;;UACtC;WACN,SAAS;WACT,UAAU;;WAEV;;UAEM;WACN,cAAc,KAAK,sBAAsB,QAAQ,gBAAgB;WACjE,kBAAkB,KAAK,wBAAwB;WAC/C,cAAc,KAAK,sBAAsB;WACzC,aAAa,KAAK,mBAAmB"}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{ToolCallId as e}from"../../primitives/brand.js";import{waitForSettlement as t}from"../../async/settlement.js";import{createSpanId as n}from"../../observation/context.js";import{snapshotJsonValue as r}from"../../primitives/json-snapshot.js";import{TOOL_ERROR_CODES as i,ToolError as a}from"../tool/errors.js";import{NESTED_TOOL_ERROR_CODES as o}from"../tool/nested.js";import{authorizeToolCall as s,dispatchAuthorizedToolCall as c,finalizeToolCall as l,prepareToolCall as u,toolFailure as d}from"../tool/pipeline.js";import{emitEvent as f,errorCode as p,immutableResult as m,messageOf as h,now as g,raceWithSignal as _,teardownFailure as v,withApprovalEvents as y}from"./tool-call-support.js";import{checkOutputSchema as b,outputSchemaSupported as x}from"../tool/output-schema.js";const S=65536,C=Object.freeze({maxBytes:S,maxDepth:64,maxNodes:32768,maxArrayItems:16384,maxObjectFields:16384,maxKeyBytes:S});function w(e){let t=new Map;for(let[n,r]of e??[]){if(!Number.isSafeInteger(r.maxCalls)||r.maxCalls<1)throw RangeError(`program "${n}" maxCalls must be a positive safe integer`);let i=Object.freeze([...new Set(r.allow)]);for(let t of i){if(typeof t!=`string`||t.length===0)throw TypeError(`program "${n}" grants an invalid tool name`);if(e?.has(t)===!0)throw RangeError(`program "${n}" may not call program "${t}"`)}t.set(n,Object.freeze({allow:i,maxCalls:r.maxCalls}))}return t}var T=class{options;step;grant;outer;port;fatal;closedCode;closedMessage=``;shutdown=new AbortController;inFlight;requests=0;sequence=0;unbindExecutionSignal;captured;constructor(e,t,n,r){this.options=e,this.step=t,this.grant=n,this.outer=r,this.captured=new Map(n.allow.map(t=>[t,e.catalog.get(t)]));let i=Object.freeze(n.allow.flatMap(e=>{let t=this.captured.get(e);return t===void 0?[]:[E(t)]}));this.port=Object.freeze({call:(e,t,n)=>this.request(e,t,n?.retain===!0),catalog:()=>i,load:e=>this.load(e),release:e=>this.step.programResults?.release(e,this.outer.call.toolName)===!0})}async close(e){this.unbindExecutionSignal?.(),this.latch(o.CLOSED,`the program has ended`),this.shutdown.abort(Error(`program closed`));let n=this.inFlight;return n===void 0||await t(n,e)}abort(e){this.unbindExecutionSignal?.(),this.latch(o.CLOSED,`the program was cancelled`),this.shutdown.abort(e)}bindExecutionSignal(e){this.unbindExecutionSignal?.();let t=()=>this.abort(e.reason);this.unbindExecutionSignal=()=>{e.removeEventListener(`abort`,t),this.unbindExecutionSignal=void 0},e.aborted?t():e.addEventListener(`abort`,t,{once:!0})}load(e){let t=this.step.programResults;if(typeof e!=`string`||t===void 0||this.fatal!==void 0||this.closedCode!==void 0)return D(o.RESULT_UNAVAILABLE,`no retained result is available`);let n;try{n=t.load(e,this.outer.call.toolName,e=>this.options.catalog.get(e))}catch(e){throw this.fatal??=a.fatal(h(e),p(e),{cause:e}),this.latch(o.CLOSED,`retained-result authority could not be checked`),this.fatal}return n.kind===`unavailable`?D(o.RESULT_UNAVAILABLE,`the retained result is ${n.reason===`unknown`?`not available to this program`:n.reason}`):Object.freeze({ok:!0,value:n.value,schema:n.schema,provenance:n.provenance})}async request(e,t,n=!1){if(this.fatal!==void 0||this.closedCode!==void 0)return this.refusal();if(this.inFlight!==void 0)return D(o.CALL_IN_FLIGHT,`a program may run one tool call at a time`);if(this.requests++,this.requests>this.grant.maxCalls)return this.latch(o.CALL_CAP,`the program reached its limit of ${this.grant.maxCalls} tool calls`),this.refusal();let r,i,s=new Promise((e,t)=>{r=e,i=t});this.inFlight=s,this.run(e,t,n).then(r,e=>{this.fatal??=a.fatal(h(e),p(e),{cause:e}),this.latch(o.CLOSED,`an earlier tool call failed fatally`),i(e)});try{return await s}finally{this.inFlight=void 0}}async run(t,s,c){if(!this.captured.has(t))return D(o.NOT_ALLOWED,`the program may not call "${t}"`);if(!this.current(t))return this.stale(t);let l=this.captured.get(t);if(l===void 0)return D(i.UNKNOWN_TOOL,`no tool named "${t}" is available`);let u;try{u=JSON.stringify(r(s,C))}catch{u=void 0}if(u===void 0||new TextEncoder().encode(u).byteLength>65536)return D(o.INVALID_ARGUMENTS,`tool arguments must be JSON within the size limit`);let _=Object.freeze({callId:e(`${this.outer.call.callId}:${String(++this.sequence)}`),toolName:t,rawArguments:u}),v={traceId:this.outer.trace.traceId,spanId:n(),parentSpanId:this.outer.trace.spanId},y=AbortSignal.any([this.outer.signal,this.shutdown.signal]);await f(this.options,{type:`span-start`,trace:v,at:g(),name:`execute_tool ${t}`,kind:`execute_tool`,attributes:{"gen_ai.operation.name":`execute_tool`,"gen_ai.tool.name":t,"gen_ai.tool.call.id":_.callId,"sdk.tool.parent_call_id":this.outer.call.callId},input:u});let x;try{x=m(await this.execute(_,l,v,y),this.step.maxResultBytes)}catch(e){this.fatal??=a.fatal(h(e),p(e),{cause:e}),this.latch(o.CLOSED,`an earlier tool call failed fatally`),x=d(h(e),p(e))}let S=this.current(t)&&!y.aborted;if(this.current(t)||this.latch(o.STALE_CATALOG,`"${t}" changed while the program was running`),await f(this.options,{type:`span-end`,trace:v,at:g(),status:y.aborted?`aborted`:x.isError?`error`:`success`,...x.isError?{error:{type:`ToolError`,message:x.error.message,code:x.error.code}}:{}}),!S)return this.refusal();if(x.isError)return D(x.error.code,x.error.message);if(x.value===void 0)return D(o.STRUCTURED_OUTPUT_UNAVAILABLE,`"${t}" returned no structured value the program may read`);let w=l.experimentalOutputSchema,T=w===void 0?`unsupported`:b(w,x.value);if(T===`invalid`)return D(o.OUTPUT_SCHEMA_MISMATCH,`"${t}" returned a value outside its declared output schema`);let E=T===`valid`?`validated`:`unchecked`;if(!c)return Object.freeze({ok:!0,value:x.value,schema:E});let O=this.step.programResults?.save({owner:this.outer.call.toolName,value:x.value,definition:l,schema:E,provenance:{toolName:t,callId:String(_.callId),parentCallId:String(this.outer.call.callId)}})??{refused:`closed`};return Object.freeze({ok:!0,value:x.value,schema:E,...`handle`in O?{handle:O.handle}:{retainRefused:O.refused}})}async execute(e,n,r,f){let{teardownTimeoutMs:p}=this.step,m=u({catalog:this.options.catalog,call:e,position:this.options.position,signal:f,teardownTimeoutMs:p,parentCallId:this.outer.call.callId,...this.options.logger===void 0?{}:{logger:this.options.logger},...this.options.interceptors===void 0?{}:{interceptors:this.options.interceptors},...this.options.approvals===void 0?{}:{approvals:this.options.approvals}}),g=this.step.admission.reserve(n.budgetExempt===!0);if(g===void 0){let e=`the turn has spent its tool-call budget`;return this.latch(o.BUDGET_EXHAUSTED,e),d(e,o.BUDGET_EXHAUSTED)}try{let n=s(y(this.options,m,r)),u;try{u=await _(n,f)}catch(r){if(!f.aborted)throw r;if(!await t(n,p))throw v(e.toolName,`authorization`,p,r);return d(`the call was cancelled`,i.ABORTED)}if(u.kind===`final`)return u.result;try{let n=Promise.resolve(this.options.checkpoint?.({kind:`before-tool-dispatch`,call:e,parentCallId:this.outer.call.callId,snapshot:this.options.history.snapshot(),signal:f,...this.options.logger===void 0?{}:{logger:this.options.logger}}));try{await _(n,f)}catch(r){if(!f.aborted)throw r;if(!await t(n,p))throw v(e.toolName,`checkpoint`,p,r)}}catch(e){if(e instanceof a&&e.code===i.TEARDOWN_TIMEOUT)throw e;return d(`history checkpoint failed: ${h(e)}`,i.CHECKPOINT_FAILED)}if(!this.current(e.toolName)){let t=`"${e.toolName}" changed while the program was running`;return this.latch(o.STALE_CATALOG,t),d(t,o.STALE_CATALOG)}if(this.fatal!==void 0||f.aborted)return d(`the program was cancelled`,i.ABORTED);g.confirm();let b=c(u.call);b.catch(()=>void 0);let x=await O(b,f,p,e.toolName,`execution`);return await O(l(u.call,x),f,p,e.toolName,`finalization`)}finally{g.release()}}current(e){return this.options.catalog.get(e)===this.captured.get(e)}stale(e){return this.latch(o.STALE_CATALOG,`"${e}" changed after the program started`),this.refusal()}latch(e,t){this.closedCode===void 0&&(this.closedCode=e,this.closedMessage=t)}refusal(){return D(this.closedCode??o.CLOSED,this.closedMessage||`the program is closed`)}};function E(e){let t=e.experimentalOutputSchema;return Object.freeze({name:e.name,description:e.description,parameters:e.parameters,output:t===void 0?`unknown`:x(t)?`declared`:`unsupported`,...t===void 0?{}:{outputSchema:t}})}function D(e,t){return Object.freeze({ok:!1,code:e,message:t})}async function O(e,n,r,a,o){try{return await _(e,n)}catch(s){if(!n.aborted)throw s;if(!await t(e,r))throw v(a,o,r,s);return d(`the call was cancelled`,i.ABORTED)}}export{S as MAX_NESTED_ARGUMENT_BYTES,T as ProgramRun,E as describe,D as refuse,O as settleWithin,w as validPrograms};
|
|
2
|
+
//# sourceMappingURL=program.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"program.js","names":[],"sources":["../../../src/agent/loop/program.ts"],"sourcesContent":["/** Programs: the scheduler-granted port through which one tool calls others. Internal to the loop. */\nimport type { ToolAdmission } from './admission.ts'\nimport {\n emitEvent, errorCode, immutableResult, messageOf, now, raceWithSignal, teardownFailure, withApprovalEvents,\n type ToolCallHost,\n} from './tool-call-support.ts'\nimport { waitForSettlement } from '../../async/index.ts'\nimport { ToolCallId, type JsonValue } from '../../primitives/index.ts'\nimport { snapshotJsonValue } from '../../primitives/json-snapshot.ts'\nimport type { ToolDefinition, ToolExecutionResult } from '../tool/definition.ts'\nimport { TOOL_ERROR_CODES, ToolError } from '../tool/errors.ts'\nimport {\n NESTED_TOOL_ERROR_CODES,\n type NestedCallOptions, type NestedLoadResult, type NestedToolDescriptor, type NestedToolPort,\n type NestedToolResult, type ProgramGrant,\n} from '../tool/nested.ts'\nimport { checkOutputSchema, outputSchemaSupported } from '../tool/output-schema.ts'\nimport {\n authorizeToolCall, dispatchAuthorizedToolCall, finalizeToolCall, prepareToolCall, toolFailure,\n type ToolCallRequest,\n} from '../tool/pipeline.ts'\nimport type { ProgramResultStore } from '../tool/program-results.ts'\nimport { createSpanId, type TraceRef } from '../trace/trace.ts'\n\n/** What every slot of one step shares. */\nexport interface StepRuntime {\n readonly admission: ToolAdmission\n readonly maxDurationMs: number\n readonly teardownTimeoutMs: number\n readonly maxResultBytes: number\n readonly programs: ReadonlyMap<string, ProgramGrant>\n readonly programResults: ProgramResultStore | undefined\n}\n\n/** Largest serialized argument object a program may send to one child. */\nexport const MAX_NESTED_ARGUMENT_BYTES = 64 * 1024\nconst ARGUMENT_LIMITS = Object.freeze({\n maxBytes: MAX_NESTED_ARGUMENT_BYTES, maxDepth: 64, maxNodes: 32_768,\n maxArrayItems: 16_384, maxObjectFields: 16_384, maxKeyBytes: MAX_NESTED_ARGUMENT_BYTES,\n})\n\nexport function validPrograms(programs: ReadonlyMap<string, ProgramGrant> | undefined): ReadonlyMap<string, ProgramGrant> {\n const valid = new Map<string, ProgramGrant>()\n for (const [name, grant] of programs ?? []) {\n if (!Number.isSafeInteger(grant.maxCalls) || grant.maxCalls < 1) {\n throw new RangeError(`program \"${name}\" maxCalls must be a positive safe integer`)\n }\n const allow = Object.freeze([...new Set(grant.allow)])\n for (const target of allow) {\n if (typeof target !== 'string' || target.length === 0) throw new TypeError(`program \"${name}\" grants an invalid tool name`)\n // No recursion and no program-in-program: nested admission is one level.\n if (programs?.has(target) === true) throw new RangeError(`program \"${name}\" may not call program \"${target}\"`)\n }\n valid.set(name, Object.freeze({ allow, maxCalls: grant.maxCalls }))\n }\n return valid\n}\n\n/**\n * One running program: the port its body calls, and the latch that outlives\n * whatever the program does with a refusal.\n *\n * A child goes through the same reservation, policy, approval, checkpoint,\n * execution, post-policy and byte bound as a model-issued call. What it does\n * NOT do is enter history or spill: the program's own result is what the model\n * reads, and that result is bounded like any other.\n */\nexport class ProgramRun {\n readonly port: NestedToolPort\n /** A fatal child failure, rethrown as the outer call's own. */\n fatal: unknown\n private closedCode: string | undefined\n private closedMessage = ''\n private readonly shutdown = new AbortController()\n private inFlight: Promise<NestedToolResult> | undefined\n private requests = 0\n private sequence = 0\n private unbindExecutionSignal: (() => void) | undefined\n /** Definition identity per granted name, captured when the program started. */\n private readonly captured: ReadonlyMap<string, ToolDefinition | undefined>\n\n constructor(\n private readonly options: ToolCallHost,\n private readonly step: StepRuntime,\n private readonly grant: ProgramGrant,\n private readonly outer: { readonly call: ToolCallRequest; readonly trace: TraceRef; readonly signal: AbortSignal },\n ) {\n this.captured = new Map(grant.allow.map(name => [name, options.catalog.get(name)]))\n const descriptors = Object.freeze(grant.allow.flatMap(name => {\n const definition = this.captured.get(name)\n return definition === undefined ? [] : [describe(definition)]\n }))\n this.port = Object.freeze({\n call: (toolName: string, args: JsonValue, callOptions?: NestedCallOptions) => this.request(toolName, args, callOptions?.retain === true),\n catalog: () => descriptors,\n load: (handle: string) => this.load(handle),\n release: (handle: string) => this.step.programResults?.release(handle, this.outer.call.toolName) === true,\n })\n }\n\n /** Stop admitting children and wait for the one in flight, if any. */\n async close(teardownTimeoutMs: number): Promise<boolean> {\n this.unbindExecutionSignal?.()\n this.latch(NESTED_TOOL_ERROR_CODES.CLOSED, 'the program has ended')\n this.shutdown.abort(new Error('program closed'))\n const inFlight = this.inFlight\n return inFlight === undefined || await waitForSettlement(inFlight, teardownTimeoutMs)\n }\n\n /** Stop without waiting; the outer call is already failing. */\n abort(reason: unknown): void {\n this.unbindExecutionSignal?.()\n this.latch(NESTED_TOOL_ERROR_CODES.CLOSED, 'the program was cancelled')\n this.shutdown.abort(reason)\n }\n\n /** The body signal also carries the program tool's own timeout. */\n bindExecutionSignal(signal: AbortSignal): void {\n this.unbindExecutionSignal?.()\n const abort = () => this.abort(signal.reason)\n this.unbindExecutionSignal = () => {\n signal.removeEventListener('abort', abort)\n this.unbindExecutionSignal = undefined\n }\n if (signal.aborted) abort()\n else signal.addEventListener('abort', abort, { once: true })\n }\n\n private load(handle: string): NestedLoadResult {\n const store = this.step.programResults\n if (typeof handle !== 'string' || store === undefined || this.fatal !== undefined || this.closedCode !== undefined) {\n return refuse(NESTED_TOOL_ERROR_CODES.RESULT_UNAVAILABLE, 'no retained result is available')\n }\n // The owner is the program tool, never anything the program says it is.\n let loaded: ReturnType<ProgramResultStore['load']>\n try { loaded = store.load(handle, this.outer.call.toolName, name => this.options.catalog.get(name)) } catch (error) {\n this.fatal ??= ToolError.fatal(messageOf(error), errorCode(error), { cause: error })\n this.latch(NESTED_TOOL_ERROR_CODES.CLOSED, 'retained-result authority could not be checked')\n throw this.fatal\n }\n if (loaded.kind === 'unavailable') {\n return refuse(NESTED_TOOL_ERROR_CODES.RESULT_UNAVAILABLE, `the retained result is ${loaded.reason === 'unknown' ? 'not available to this program' : loaded.reason}`)\n }\n return Object.freeze({ ok: true, value: loaded.value, schema: loaded.schema, provenance: loaded.provenance })\n }\n\n private async request(toolName: string, args: JsonValue, retain = false): Promise<NestedToolResult> {\n if (this.fatal !== undefined || this.closedCode !== undefined) return this.refusal()\n if (this.inFlight !== undefined) {\n return refuse(NESTED_TOOL_ERROR_CODES.CALL_IN_FLIGHT, 'a program may run one tool call at a time')\n }\n this.requests++\n if (this.requests > this.grant.maxCalls) {\n this.latch(NESTED_TOOL_ERROR_CODES.CALL_CAP, `the program reached its limit of ${this.grant.maxCalls} tool calls`)\n return this.refusal()\n }\n let resolve!: (result: NestedToolResult) => void\n let reject!: (error: unknown) => void\n const pending = new Promise<NestedToolResult>((done, fail) => { resolve = done; reject = fail })\n // Hold the port before run() can synchronously call catalog/observation code.\n // Start run synchronously too: arguments are still captured at call time.\n this.inFlight = pending\n void this.run(toolName, args, retain).then(resolve, error => {\n this.fatal ??= ToolError.fatal(messageOf(error), errorCode(error), { cause: error })\n this.latch(NESTED_TOOL_ERROR_CODES.CLOSED, 'an earlier tool call failed fatally')\n reject(error)\n })\n try { return await pending } finally { this.inFlight = undefined }\n }\n\n private async run(toolName: string, args: JsonValue, retain: boolean): Promise<NestedToolResult> {\n if (!this.captured.has(toolName)) {\n return refuse(NESTED_TOOL_ERROR_CODES.NOT_ALLOWED, `the program may not call \"${toolName}\"`)\n }\n if (!this.current(toolName)) return this.stale(toolName)\n const definition = this.captured.get(toolName)\n if (definition === undefined) {\n return refuse(TOOL_ERROR_CODES.UNKNOWN_TOOL, `no tool named \"${toolName}\" is available`)\n }\n let rawArguments: string | undefined\n try { rawArguments = JSON.stringify(snapshotJsonValue(args, ARGUMENT_LIMITS)) } catch { rawArguments = undefined }\n if (rawArguments === undefined || new TextEncoder().encode(rawArguments).byteLength > MAX_NESTED_ARGUMENT_BYTES) {\n return refuse(NESTED_TOOL_ERROR_CODES.INVALID_ARGUMENTS, 'tool arguments must be JSON within the size limit')\n }\n const call: ToolCallRequest = Object.freeze({\n callId: ToolCallId(`${this.outer.call.callId}:${String(++this.sequence)}`), toolName, rawArguments,\n })\n const trace: TraceRef = { traceId: this.outer.trace.traceId, spanId: createSpanId(), parentSpanId: this.outer.trace.spanId }\n const signal = AbortSignal.any([this.outer.signal, this.shutdown.signal])\n await emitEvent(this.options, {\n type: 'span-start', trace, at: now(), name: `execute_tool ${toolName}`, kind: 'execute_tool',\n attributes: {\n 'gen_ai.operation.name': 'execute_tool', 'gen_ai.tool.name': toolName, 'gen_ai.tool.call.id': call.callId,\n 'sdk.tool.parent_call_id': this.outer.call.callId,\n },\n input: rawArguments,\n })\n let result: ToolExecutionResult\n try {\n result = immutableResult(await this.execute(call, definition, trace, signal), this.step.maxResultBytes)\n } catch (error: unknown) {\n // Tool bodies already become results inside the pipeline. What escapes\n // here — a throwing interceptor, a teardown timeout, a fatal ToolError —\n // fails a model-issued call's whole turn, so it fails the program too.\n this.fatal ??= ToolError.fatal(messageOf(error), errorCode(error), { cause: error })\n this.latch(NESTED_TOOL_ERROR_CODES.CLOSED, 'an earlier tool call failed fatally')\n result = toolFailure(messageOf(error), errorCode(error))\n }\n // Authority is checked again at publication: a result produced under a\n // grant that changed while it ran is not handed to the program.\n const publishable = this.current(toolName) && !signal.aborted\n if (!this.current(toolName)) this.latch(NESTED_TOOL_ERROR_CODES.STALE_CATALOG, `\"${toolName}\" changed while the program was running`)\n await emitEvent(this.options, {\n type: 'span-end', trace, at: now(),\n status: signal.aborted ? 'aborted' : result.isError ? 'error' : 'success',\n ...result.isError ? { error: { type: 'ToolError', message: result.error.message, code: result.error.code } } : {},\n })\n if (!publishable) return this.refusal()\n if (result.isError) return refuse(result.error.code, result.error.message)\n // Policy may have removed the value. Rendered text is for the model and is\n // never parsed back into data the policy chose not to release.\n if (result.value === undefined) {\n return refuse(NESTED_TOOL_ERROR_CODES.STRUCTURED_OUTPUT_UNAVAILABLE, `\"${toolName}\" returned no structured value the program may read`)\n }\n const schema = definition.experimentalOutputSchema\n const verdict = schema === undefined ? 'unsupported' : checkOutputSchema(schema, result.value)\n if (verdict === 'invalid') {\n return refuse(NESTED_TOOL_ERROR_CODES.OUTPUT_SCHEMA_MISMATCH, `\"${toolName}\" returned a value outside its declared output schema`)\n }\n const checked = verdict === 'valid' ? 'validated' as const : 'unchecked' as const\n if (!retain) return Object.freeze({ ok: true, value: result.value, schema: checked })\n const saved = this.step.programResults?.save({\n owner: this.outer.call.toolName, value: result.value, definition, schema: checked,\n provenance: { toolName, callId: String(call.callId), parentCallId: String(this.outer.call.callId) },\n }) ?? { refused: 'closed' as const }\n return Object.freeze({\n ok: true, value: result.value, schema: checked,\n ...'handle' in saved ? { handle: saved.handle } : { retainRefused: saved.refused },\n })\n }\n\n private async execute(\n call: ToolCallRequest,\n definition: ToolDefinition,\n trace: TraceRef,\n signal: AbortSignal,\n ): Promise<ToolExecutionResult> {\n const { teardownTimeoutMs } = this.step\n const prepared = prepareToolCall({\n catalog: this.options.catalog, call, position: this.options.position, signal, teardownTimeoutMs,\n parentCallId: this.outer.call.callId,\n ...(this.options.logger === undefined ? {} : { logger: this.options.logger }),\n ...this.options.interceptors === undefined ? {} : { interceptors: this.options.interceptors },\n ...this.options.approvals === undefined ? {} : { approvals: this.options.approvals },\n })\n const ticket = this.step.admission.reserve(definition.budgetExempt === true)\n if (ticket === undefined) {\n const message = 'the turn has spent its tool-call budget'\n this.latch(NESTED_TOOL_ERROR_CODES.BUDGET_EXHAUSTED, message)\n return toolFailure(message, NESTED_TOOL_ERROR_CODES.BUDGET_EXHAUSTED)\n }\n try {\n const authorizing = authorizeToolCall(withApprovalEvents(this.options, prepared, trace))\n let authorization: Awaited<typeof authorizing>\n try {\n authorization = await raceWithSignal(authorizing, signal)\n } catch (error: unknown) {\n if (!signal.aborted) throw error\n if (!await waitForSettlement(authorizing, teardownTimeoutMs)) {\n throw teardownFailure(call.toolName, 'authorization', teardownTimeoutMs, error)\n }\n return toolFailure('the call was cancelled', TOOL_ERROR_CODES.ABORTED)\n }\n if (authorization.kind === 'final') return authorization.result\n try {\n const checkpointing = Promise.resolve(this.options.checkpoint?.({\n kind: 'before-tool-dispatch', call, parentCallId: this.outer.call.callId,\n snapshot: this.options.history.snapshot(), signal,\n ...(this.options.logger === undefined ? {} : { logger: this.options.logger }),\n }))\n try { await raceWithSignal(checkpointing, signal) }\n catch (error: unknown) {\n if (!signal.aborted) throw error\n if (!await waitForSettlement(checkpointing, teardownTimeoutMs)) {\n throw teardownFailure(call.toolName, 'checkpoint', teardownTimeoutMs, error)\n }\n }\n } catch (error: unknown) {\n if (error instanceof ToolError && error.code === TOOL_ERROR_CODES.TEARDOWN_TIMEOUT) throw error\n return toolFailure(`history checkpoint failed: ${messageOf(error)}`, TOOL_ERROR_CODES.CHECKPOINT_FAILED)\n }\n // Approval and checkpoint both await. Whatever changed meanwhile decides.\n if (!this.current(call.toolName)) {\n const message = `\"${call.toolName}\" changed while the program was running`\n this.latch(NESTED_TOOL_ERROR_CODES.STALE_CATALOG, message)\n return toolFailure(message, NESTED_TOOL_ERROR_CODES.STALE_CATALOG)\n }\n if (this.fatal !== undefined || signal.aborted) return toolFailure('the program was cancelled', TOOL_ERROR_CODES.ABORTED)\n ticket.confirm()\n const executing = dispatchAuthorizedToolCall(authorization.call)\n void executing.catch(() => undefined)\n const executed = await settleWithin(executing, signal, teardownTimeoutMs, call.toolName, 'execution')\n const finalized = await settleWithin(\n finalizeToolCall(authorization.call, executed), signal, teardownTimeoutMs, call.toolName, 'finalization',\n )\n return finalized\n } finally {\n ticket.release()\n }\n }\n\n private current(toolName: string): boolean {\n return this.options.catalog.get(toolName) === this.captured.get(toolName)\n }\n\n private stale(toolName: string): NestedToolResult {\n this.latch(NESTED_TOOL_ERROR_CODES.STALE_CATALOG, `\"${toolName}\" changed after the program started`)\n return this.refusal()\n }\n\n private latch(code: string, message: string): void {\n if (this.closedCode !== undefined) return\n this.closedCode = code\n this.closedMessage = message\n }\n\n private refusal(): NestedToolResult {\n return refuse(this.closedCode ?? NESTED_TOOL_ERROR_CODES.CLOSED, this.closedMessage || 'the program is closed')\n }\n}\n\nexport function describe(definition: ToolDefinition): NestedToolDescriptor {\n const schema = definition.experimentalOutputSchema\n return Object.freeze({\n name: definition.name, description: definition.description, parameters: definition.parameters,\n output: schema === undefined ? 'unknown' : outputSchemaSupported(schema) ? 'declared' : 'unsupported',\n ...schema === undefined ? {} : { outputSchema: schema },\n })\n}\n\nexport function refuse(code: string, message: string): { readonly ok: false; readonly code: string; readonly message: string } {\n return Object.freeze({ ok: false, code, message })\n}\n\n/** Wait for one stage; on cancellation, give it the teardown allowance to settle. */\nexport async function settleWithin(\n pending: Promise<ToolExecutionResult>,\n signal: AbortSignal,\n teardownTimeoutMs: number,\n toolName: string,\n stage: string,\n): Promise<ToolExecutionResult> {\n try {\n return await raceWithSignal(pending, signal)\n } catch (error: unknown) {\n if (!signal.aborted) throw error\n if (!await waitForSettlement(pending, teardownTimeoutMs)) throw teardownFailure(toolName, stage, teardownTimeoutMs, error)\n return toolFailure('the call was cancelled', TOOL_ERROR_CODES.ABORTED)\n }\n}\n"],"mappings":"mxBAmCA,MAAa,EAA4B,MACnC,EAAkB,OAAO,OAAO,CACpC,SAAU,EAA2B,SAAU,GAAI,SAAU,MAC7D,cAAe,MAAQ,gBAAiB,MAAQ,YAAa,CAC/D,CAAC,EAED,SAAgB,EAAc,EAA4F,CACxH,IAAM,EAAQ,IAAI,IAClB,IAAK,GAAM,CAAC,EAAM,KAAU,GAAY,CAAC,EAAG,CAC1C,GAAI,CAAC,OAAO,cAAc,EAAM,QAAQ,GAAK,EAAM,SAAW,EAC5D,MAAU,WAAW,YAAY,EAAK,2CAA2C,EAEnF,IAAM,EAAQ,OAAO,OAAO,CAAC,GAAG,IAAI,IAAI,EAAM,KAAK,CAAC,CAAC,EACrD,IAAK,IAAM,KAAU,EAAO,CAC1B,GAAI,OAAO,GAAW,UAAY,EAAO,SAAW,EAAG,MAAU,UAAU,YAAY,EAAK,8BAA8B,EAE1H,GAAI,GAAU,IAAI,CAAM,IAAM,GAAM,MAAU,WAAW,YAAY,EAAK,0BAA0B,EAAO,EAAE,CAC/G,CACA,EAAM,IAAI,EAAM,OAAO,OAAO,CAAE,QAAO,SAAU,EAAM,QAAS,CAAC,CAAC,CACpE,CACA,OAAO,CACT,CAWA,IAAa,EAAb,KAAwB,CAeH,QACA,KACA,MACA,MAjBnB,KAEA,MACA,WACA,cAAwB,GACxB,SAA4B,IAAI,gBAChC,SACA,SAAmB,EACnB,SAAmB,EACnB,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ACzH,OAAO,EAAY,yBAA0B,EAAiB,OAAO,CACvE,CACF"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"run-turn.d.ts","names":[],"sources":["../../../src/agent/loop/run-turn.ts"],"mappings":";;;;
|
|
1
|
+
{"version":3,"file":"run-turn.d.ts","names":[],"sources":["../../../src/agent/loop/run-turn.ts"],"mappings":";;;;iBA4BgB,QAAQ,SAAS,iBAAiB,cAAc"}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{detachedFrozen as e}from"../../primitives/snapshot.js";import{waitForSettlement as t}from"../../async/settlement.js";import{createSpanId as n,createTraceId as r}from"../../observation/context.js";import{createUserMessage as i}from"../../message/message.js";import{authoritativeTokenUsage as a,budgetTokenTotal as o,summarizeModelCallUsage as s}from"../accounting/usage.js";import{ContextSectionRuntime as c}from"../context/section.js";import{AwaitedEventQueue as l}from"./queue.js";import{runToolCalls as ee}from"./schedule.js";import{positiveFinite as u,resolveBounds as d,snapshotRunTurnOptions as f}from"./turn/config.js";import{codedRuntimeError as p,errorCodeOf as m,messageOf as h,now as g}from"./turn/common.js";import{runHook as te,runOptionalHook as ne}from"./turn/hooks.js";import{emitAssistantContent as _,maintenanceEmitter as v,textOf as y}from"./turn/content.js";import{repeatKey as b,repeatedSuffixCycle as re,toolActionPattern as ie}from"./turn/repetition.js";import{accountingUsageStop as x}from"./turn/usage-stop.js";import{modelRound as S}from"./turn/model-round.js";function C(e){return e.toolChoice===`none`?!1:(e.tools?.names().length??0)>0||(e.nativeTools?.length??0)>0}function w(n){return{async*[Symbol.asyncIterator](){let r=f(n),i=new l,a=new AbortController,o=u(r.teardownTimeoutMs??3e4,`teardownTimeoutMs`),s=T(r,r.signal===void 0?a.signal:AbortSignal.any([r.signal,a.signal]),t=>i.push(e(t))).then(()=>i.close(),e=>i.fail(e));try{for(;;){let e=await i.take();if(e.done)break;yield e.value}await s}finally{if(a.abort(Error(`turn event consumer stopped`)),i.close(),!await t(s,o))throw p(`turn producer ignored cancellation for more than ${o}ms`,`TURN_TEARDOWN_TIMEOUT`,a.signal.reason)}}}}async function T(e,t,l){let u=d(e.bounds),f=u.maxTotalTokens===`auto`?1/0:u.maxTotalTokens,p=u.maxSteps===`auto`?1/0:u.maxSteps,w=e.trace?.traceId??r(),T={traceId:w,spanId:n(),parentSpanId:e.trace?.parentSpanId??null},E=Math.max(1,e.history.entries().filter(e=>e.event.kind===`user`&&e.event.message.source.kind===`user`).length),D=g(),O=0,k=0,ae=[...u.toolBudgetRemindAt].filter(e=>e>0&&e<u.maxToolCalls).sort((e,t)=>t-e),A=0,j=0,M,N=!1,P=0,F=0,I=``,L=[],R,z,B,V=[],H=v(l,T),oe=t=>{let n=i({source:{kind:`app`,producer:`tool-loop-budget-guard`},content:[{type:`text`,text:t}]}),r=M;if(r!==void 0)try{M=e.history.append({kind:`user`,message:n},{op:`replace`,from:r,to:r,targets:[r]}).seq;return}catch{M=void 0}M=e.history.append({kind:`user`,message:n}).seq},U=e.contextSections===void 0||e.contextSections.length===0?void 0:new c({sections:e.contextSections,history:e.history,...e.logger===void 0?{}:{logger:e.logger},guard:(n,r)=>te(n,e,t,r),scope:{agentId:e.trace?.agentId,conversationId:e.trace?.conversationId}}),W=[],G=!1,K=!1,q=C(e),se=e.outputFormat?.type===`json_schema`&&q,J=e.accounting?.startOperation(`turn`,{data:{turn:E,model:e.config.model}}),Y=!1,X,Z=()=>{if(t.aborted)return{kind:`aborted`};let n=x(e.accounting);if(n!==void 0)return n;if(X!==void 0)return X;let r=o(s(L));return r!==void 0&&r>=f?{kind:`budget-exhausted`,budget:`tokens`,forcedFinalAnswer:!1}:void 0};try{await l({type:`span-start`,trace:T,at:D,name:`invoke_agent ${e.trace?.agentId??`agent`}`,kind:`invoke_agent`,attributes:{"gen_ai.operation.name":`invoke_agent`,"gen_ai.agent.id":e.trace?.agentId??`agent`,"gen_ai.agent.name":e.trace?.agentName??e.trace?.agentId??`agent`,"gen_ai.request.model":e.config.model,...e.trace?.conversationId===void 0?{}:{"gen_ai.conversation.id":e.trace.conversationId}}}),G=!0,await l({type:`turn-start`,turn:E,trace:T});turnLifecycle:for(;;){for(;R===void 0&&O<p&&!t.aborted&&(R=Z(),R===void 0);){let n=o(s(L));if(u.maxTotalTokens!==`auto`&&n!==void 0){let t=[.5,.75,.9].filter(e=>n>=f*e).length;if(t>P){P=t;let r=Math.max(0,f-n);e.history.append({kind:`user`,message:i({source:{kind:`app`,producer:`tool-loop-token-guard`},content:[{type:`text`,text:`Token budget: ${r} of ${u.maxTotalTokens} aggregate tokens remain. Each request also spends input tokens on the accumulated context. `+(t>=2?`Stop broad exploration. `:`Prioritize outstanding verification and reporting. `)+`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&&O>0&&p-O<=2&&(N=!0,e.history.append({kind:`user`,message:i({source:{kind:`app`,producer:`tool-loop-step-guard`},content:[{type:`text`,text:`${p-O} 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.`}]})})),U!==void 0&&(await U.reconcile(O,W,t),W=[]);let r=O+1,a=await S(e,t,l,H,T,E,r,se?`process`:e.outputFormat?.type===`json_schema`?`final`:`standard`);if(O++,a.report!==void 0&&L.push(a.report),a.message!==void 0&&(e.history.append({kind:`assistant`,message:a.message,...a.finish.kind===`aborted`?{interrupted:!0}:{},...a.usage===void 0?{}:{usage:a.usage}}),await l({type:`assistant-message`,message:a.message,trace:a.trace}),await _(a,l),I=y(a.message.content)),X=x(e.accounting)??(a.usageRequired?{kind:`error`,failure:{message:`provider usage is required by the configured run policy`,code:`USAGE_REQUIRED`}}:a.usageUnavailable?{kind:`usage-unavailable`,modelCallId:a.report?.modelCallId??`unknown`}:void 0),t.aborted||a.finish.kind===`aborted`){R={kind:`aborted`};break}if(a.finish.kind===`error`&&X!==void 0){R={kind:`error`,failure:a.finish.failure};break}if(a.usageRequired&&(a.calls.length===0||e.tools===void 0)){R=X;break}if(a.finish.kind===`error`&&!a.usageRequired){if(R=Z(),R!==void 0)break;let n=await ne(e.hooks?.onRequestError,[{turn:E,step:r,failure:a.finish.failure,snapshot:e.history.snapshot(),signal:t,...e.logger===void 0?{}:{logger:e.logger},emit:H}],e,t,`onRequestError`),i=x(e.accounting);if(i!==void 0){R=t.aborted?{kind:`aborted`}:i;break}if(n===`retry`&&O<p)continue;R={kind:`error`,failure:a.finish.failure};break}if(a.finish.kind===`max-tokens`&&!a.usageRequired){R={kind:`max-tokens`};break}if(a.calls.length===0&&a.usageUnavailable){R=x(e.accounting)??{kind:`usage-unavailable`,modelCallId:a.report?.modelCallId??`unknown`};break}if(a.calls.length===0&&se){if(R=Z(),R!==void 0)break;e.history.append({kind:`user`,message:i({source:{kind:`app`,producer:`structured-output-finalizer`},content:[{type:`text`,text:`The process phase is complete. Return the final answer now in the requested output format. Do not call tools.`}]})});let n=await S(e,t,l,H,T,E,O+1,`final`);O++,n.report!==void 0&&L.push(n.report),n.message!==void 0&&(e.history.append({kind:`assistant`,message:n.message,...n.usage===void 0?{}:{usage:n.usage}}),await l({type:`assistant-message`,message:n.message,trace:n.trace}),await _(n,l),I=y(n.message.content)),R=n.finish.kind===`aborted`?{kind:`aborted`}:n.finish.kind===`error`?{kind:`error`,failure:n.finish.failure}:n.finish.kind===`max-tokens`?{kind:`max-tokens`}:n.usageRequired?{kind:`error`,failure:{message:`provider usage is required by the configured run policy`,code:`USAGE_REQUIRED`}}:n.usageUnavailable?x(e.accounting)??{kind:`usage-unavailable`,modelCallId:n.report?.modelCallId??`unknown`}:{kind:`completed`};break}if(a.droppedDuplicateCalls!==void 0&&e.history.append({kind:`user`,message:i({source:{kind:`app`,producer:`tool-loop-duplicate-guard`},content:[{type:`text`,text:`You reused the tool-call id ${a.droppedDuplicateCalls.map(e=>`'${e}'`).join(`, `)}. A result pairs to exactly one call, so the repeat was not run and only the first call of that id has a result. Give every call its own id, and call again if you still need what the dropped one would have done.`}]})}),a.calls.length===0||e.tools===void 0){R={kind:`completed`};break}let c=a.calls.filter(t=>e.tools?.get(t.toolName)?.budgetExempt!==!0).length,d=Math.max(0,u.maxToolCalls-k),m=B,h=a.calls.map(e=>{let t=b(e),n=m?.key===t?m.count+1:1;return m={key:t,count:n},n}).some(e=>e>=u.repeatToolLimit),g=ie(a.calls),v=re([...V,g],u.maxToolCycleLength),C=v!==void 0&&v.repetitions>=u.toolCycleLimit,w=s(L),D=o(w),M=D!==void 0&&D>=f,z=h||C||M||a.usageRequired,G=M?`tokens`:C?`tool-call-cycle`:h?`repeated-tool-call`:a.usageRequired?`usage-required`:`tool-calls`,K=u.onExhausted!==`continue`,q=await ee({calls:a.calls,catalog:e.tools,history:e.history,position:{turn:E,step:r,...e.accounting===void 0?{}:{runId:e.accounting.runId},...e.trace?.conversationId===void 0?{}:{conversationId:e.trace.conversationId}},signal:t,parentTrace:T,maxParallel:u.maxParallel,dispatchLimit:z?0:K?d:a.calls.length,declineReason:G,maxResultBytes:u.maxToolResultBytes,maxResultTokens:u.maxToolResultTokens,resultOverflow:u.toolResultOverflow,...e.spillStore===void 0?{}:{spillStore:e.spillStore},maxDurationMs:u.maxToolDurationMs,teardownTimeoutMs:u.toolTeardownTimeoutMs,...e.logger===void 0?{}:{logger:e.logger},...e.interceptors===void 0?{}:{interceptors:e.interceptors},...e.approvals===void 0?{}:{approvals:e.approvals},...e.accounting===void 0?{}:{accounting:e.accounting},emit:l,...e.hooks?.checkpoint===void 0?{}:{checkpoint:n=>te(Promise.resolve(e.hooks?.checkpoint?.(n)),e,t,`checkpoint`)}});U!==void 0&&q.results.length===a.calls.length&&W.push(...a.calls.map((e,t)=>({toolName:e.toolName,rawArguments:e.rawArguments,failed:q.results[t]?.isError??!0}))),k+=q.budgeted;let J=Math.max(0,u.maxToolCalls-k),Y=ae.filter(e=>J<=e).length;if(Y>A&&J>0&&(A=Y,oe(`Tool budget: ${J} of ${u.maxToolCalls} calls remain in this turn. Stop broad exploration, make the necessary edits, and reserve calls for`+(K?` verification. When the budget runs out no further work call will run, so finish with what you can still verify.`:` verification. Past the budget you are expected to be wrapping up, not opening new lines of work.`))),!K&&J===0){let e=Math.floor(k/u.maxToolCalls);e>j&&(j=e,oe(`Tool budget spent: ${k} calls made against a budget of ${u.maxToolCalls}. Do not start new substantive work. Finish what is in flight, verify what you can, and answer — stating plainly what is unverified or unfinished.`))}await l({type:`step-end`,turn:E,step:r,trace:a.trace}),V.push(g);let ce=h;for(let t=0;t<a.calls.length;t++){let n=a.calls[t],r=q.results[t];if(n===void 0||r===void 0)continue;F=r.isError?F+1:0;let o=b(n),s=B?.key===o?B.count+1:1;B={key:o,count:s},s===u.repeatToolWarningAt&&e.history.append({kind:`user`,message:i({source:{kind:`app`,producer:`tool-loop-repeat-guard`},content:[{type:`text`,text:`You have called ${n.toolName} with the same arguments ${s} consecutive times. Reassess before repeating it.`}]})}),s>=u.repeatToolLimit&&(ce=!0)}if(v?.repetitions===u.toolCycleWarningAt&&e.history.append({kind:`user`,message:i({source:{kind:`app`,producer:`tool-loop-cycle-guard`},content:[{type:`text`,text:`Tool-use pattern repeated ${v.repetitions} times across ${v.period} step(s). Reassess the approach and identify concrete new evidence before continuing.`}]})}),q.concluded){R={kind:`concluded-by-tool`,toolName:q.concludedBy??`unknown`};break}if(t.aborted){R={kind:`aborted`};break}if(a.usageRequired){R=X;break}if(a.usageUnavailable){R=x(e.accounting)??{kind:`usage-unavailable`,modelCallId:a.report?.modelCallId??`unknown`};break}let Q,$=u.maxTotalTokens!==`auto`&&u.finalReportReserveTokens>0&&D!==void 0&&D>=f-u.finalReportReserveTokens;if(M||$?Q=`tokens`:C?Q=`tool-call-cycle`:K&&c>d?Q=`tool-calls`:F>=u.maxConsecutiveToolErrors?Q=`consecutive-tool-errors`:ce?Q=`repeated-tool-call`:O>=p&&(Q=`steps`),Q!==void 0){let n=(Q!==`tokens`||$&&!M)&&u.onExhausted!==`stop`&&Z()===void 0;if(n){let n=await S(e,t,l,H,T,E,O+1,`forced-final`);if(O++,n.report!==void 0&&L.push(n.report),n.message!==void 0&&(e.history.append({kind:`assistant`,message:n.message,...n.usage===void 0?{}:{usage:n.usage}}),await l({type:`assistant-message`,message:n.message,trace:n.trace}),await _(n,l),I=y(n.message.content)),n.finish.kind===`aborted`){R={kind:`aborted`};break}if(n.finish.kind===`error`){R={kind:`error`,failure:n.finish.failure};break}if(n.finish.kind===`max-tokens`){R={kind:`max-tokens`};break}if(n.usageRequired){R={kind:`error`,failure:{message:`provider usage is required by the configured run policy`,code:`USAGE_REQUIRED`}};break}if(n.usageUnavailable){R=x(e.accounting)??{kind:`usage-unavailable`,modelCallId:n.report?.modelCallId??`unknown`};break}}R={kind:`budget-exhausted`,budget:Q,forcedFinalAnswer:n,...Q===`tokens`&&$&&!M?{trigger:`report-reserve`}:{}}}}R===void 0&&(R=t.aborted?{kind:`aborted`}:{kind:`budget-exhausted`,budget:`steps`,forcedFinalAnswer:!1});let n=s(L),r=a(n),c={reason:R,text:I,steps:O,usageReport:n,toolCalls:k,traceId:w,...r===void 0?{}:{usage:r}},d=e.history.entries().length,m=R.kind===`completed`&&O<p&&Z()===void 0;if(await ne(e.hooks?.onTurnEnd,[{outcome:c,snapshot:e.history.snapshot(),canContinue:m}],e,t,`onTurnEnd`),m&&e.history.entries().length>d&&!t.aborted){R=void 0;continue turnLifecycle}z=c;break}await l({type:`span-end`,trace:T,at:g(),status:z.reason.kind===`error`?`error`:z.reason.kind===`aborted`?`aborted`:`success`,output:{reason:z.reason,text:I},...z.usage===void 0?{}:{usage:z.usage},...z.reason.kind===`error`?{error:{type:`ModelError`,message:z.reason.failure.message,code:z.reason.failure.code}}:{}}),K=!0,J!==void 0&&(e.accounting?.endOperation(J,z.reason.kind===`error`?`error`:z.reason.kind===`aborted`?`aborted`:`success`,{data:{reason:z.reason.kind,steps:O,toolCalls:k}}),Y=!0),await l({type:`turn-end`,outcome:z,trace:T})}catch(n){let r=m(n);throw G&&!K&&await l({type:`span-end`,trace:T,at:g(),status:t.aborted?`aborted`:`error`,error:{type:n instanceof Error?n.name:`RuntimeError`,message:h(n),...r===void 0?{}:{code:r}}}).catch(()=>void 0),J!==void 0&&!Y&&(e.accounting?.endOperation(J,t.aborted?`aborted`:`error`,{error:n}),Y=!0),n}}export{w as runTurn};
|
|
1
|
+
import{detachedFrozen as e}from"../../primitives/snapshot.js";import{waitForSettlement as t}from"../../async/settlement.js";import{createSpanId as n,createTraceId as r}from"../../observation/context.js";import{createUserMessage as i}from"../../message/message.js";import{authoritativeTokenUsage as a,budgetTokenTotal as o,summarizeModelCallUsage as s}from"../accounting/usage.js";import{ContextSectionRuntime as c}from"../context/section.js";import{AwaitedEventQueue as l}from"./queue.js";import{captureProgramGrants as u}from"../tool/nested.js";import{scheduleToolCalls as ee}from"./schedule.js";import{ProgramResultStore as d}from"../tool/program-results.js";import{positiveFinite as f,resolveBounds as p,snapshotRunTurnOptions as m}from"./turn/config.js";import{codedRuntimeError as h,errorCodeOf as g,messageOf as _,now as v}from"./turn/common.js";import{runHook as y,runOptionalHook as te}from"./turn/hooks.js";import{emitAssistantContent as b,maintenanceEmitter as ne,textOf as x}from"./turn/content.js";import{repeatKey as re,repeatedSuffixCycle as ie,toolActionPattern as ae}from"./turn/repetition.js";import{accountingUsageStop as S}from"./turn/usage-stop.js";import{modelRound as C}from"./turn/model-round.js";function w(e){return e.toolChoice===`none`?!1:(e.tools?.names().length??0)>0||(e.nativeTools?.length??0)>0}function T(n){return{async*[Symbol.asyncIterator](){let r=m(n),i=new l,a=new AbortController,o=f(r.teardownTimeoutMs??3e4,`teardownTimeoutMs`),s=E(r,r.signal===void 0?a.signal:AbortSignal.any([r.signal,a.signal]),t=>i.push(e(t))).then(()=>i.close(),e=>i.fail(e));try{for(;;){let e=await i.take();if(e.done)break;yield e.value}await s}finally{if(a.abort(Error(`turn event consumer stopped`)),i.close(),!await t(s,o))throw h(`turn producer ignored cancellation for more than ${o}ms`,`TURN_TEARDOWN_TIMEOUT`,a.signal.reason)}}}}async function E(e,t,l){let f=p(e.bounds),m=f.maxTotalTokens===`auto`?1/0:f.maxTotalTokens,h=f.maxSteps===`auto`?1/0:f.maxSteps,T=e.trace?.traceId??r(),E={traceId:T,spanId:n(),parentSpanId:e.trace?.parentSpanId??null},D=Math.max(1,e.history.entries().filter(e=>e.event.kind===`user`&&e.event.message.source.kind===`user`).length),O=v(),k=0,A=0,oe=[...f.toolBudgetRemindAt].filter(e=>e>0&&e<f.maxToolCalls).sort((e,t)=>t-e),se=0,j=0,M,N=!1,P=0,F=0,I=``,L=[],R,z,B,ce=[],V=ne(l,E),le=t=>{let n=i({source:{kind:`app`,producer:`tool-loop-budget-guard`},content:[{type:`text`,text:t}]}),r=M;if(r!==void 0)try{M=e.history.append({kind:`user`,message:n},{op:`replace`,from:r,to:r,targets:[r]}).seq;return}catch{M=void 0}M=e.history.append({kind:`user`,message:n}).seq},H=e.contextSections===void 0||e.contextSections.length===0?void 0:new c({sections:e.contextSections,history:e.history,...e.logger===void 0?{}:{logger:e.logger},guard:(n,r)=>y(n,e,t,r),scope:{agentId:e.trace?.agentId,conversationId:e.trace?.conversationId}}),U=[],W=!1,G=!1,K=w(e),q=e.experimentalPrograms===void 0?void 0:u(e.experimentalPrograms),J=q===void 0?void 0:new d,ue=e.outputFormat?.type===`json_schema`&&K,Y=e.accounting?.startOperation(`turn`,{data:{turn:D,model:e.config.model}}),X=!1,Z,Q=()=>{if(t.aborted)return{kind:`aborted`};let n=S(e.accounting);if(n!==void 0)return n;if(Z!==void 0)return Z;let r=o(s(L));return r!==void 0&&r>=m?{kind:`budget-exhausted`,budget:`tokens`,forcedFinalAnswer:!1}:void 0};try{await l({type:`span-start`,trace:E,at:O,name:`invoke_agent ${e.trace?.agentId??`agent`}`,kind:`invoke_agent`,attributes:{"gen_ai.operation.name":`invoke_agent`,"gen_ai.agent.id":e.trace?.agentId??`agent`,"gen_ai.agent.name":e.trace?.agentName??e.trace?.agentId??`agent`,"gen_ai.request.model":e.config.model,...e.trace?.conversationId===void 0?{}:{"gen_ai.conversation.id":e.trace.conversationId}}}),W=!0,await l({type:`turn-start`,turn:D,trace:E});turnLifecycle:for(;;){for(;R===void 0&&k<h&&!t.aborted&&(R=Q(),R===void 0);){let n=o(s(L));if(f.maxTotalTokens!==`auto`&&n!==void 0){let t=[.5,.75,.9].filter(e=>n>=m*e).length;if(t>P){P=t;let r=Math.max(0,m-n);e.history.append({kind:`user`,message:i({source:{kind:`app`,producer:`tool-loop-token-guard`},content:[{type:`text`,text:`Token budget: ${r} of ${f.maxTotalTokens} aggregate tokens remain. Each request also spends input tokens on the accumulated context. `+(t>=2?`Stop broad exploration. `:`Prioritize outstanding verification and reporting. `)+`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&&k>0&&h-k<=2&&(N=!0,e.history.append({kind:`user`,message:i({source:{kind:`app`,producer:`tool-loop-step-guard`},content:[{type:`text`,text:`${h-k} 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.`}]})})),H!==void 0&&(await H.reconcile(k,U,t),U=[]);let r=k+1,a=await C(e,t,l,V,E,D,r,ue?`process`:e.outputFormat?.type===`json_schema`?`final`:`standard`);if(k++,a.report!==void 0&&L.push(a.report),a.message!==void 0&&(e.history.append({kind:`assistant`,message:a.message,...a.finish.kind===`aborted`?{interrupted:!0}:{},...a.usage===void 0?{}:{usage:a.usage}}),await l({type:`assistant-message`,message:a.message,trace:a.trace}),await b(a,l),I=x(a.message.content)),Z=S(e.accounting)??(a.usageRequired?{kind:`error`,failure:{message:`provider usage is required by the configured run policy`,code:`USAGE_REQUIRED`}}:a.usageUnavailable?{kind:`usage-unavailable`,modelCallId:a.report?.modelCallId??`unknown`}:void 0),t.aborted||a.finish.kind===`aborted`){R={kind:`aborted`};break}if(a.finish.kind===`error`&&Z!==void 0){R={kind:`error`,failure:a.finish.failure};break}if(a.usageRequired&&(a.calls.length===0||e.tools===void 0)){R=Z;break}if(a.finish.kind===`error`&&!a.usageRequired){if(R=Q(),R!==void 0)break;let n=await te(e.hooks?.onRequestError,[{turn:D,step:r,failure:a.finish.failure,snapshot:e.history.snapshot(),signal:t,...e.logger===void 0?{}:{logger:e.logger},emit:V}],e,t,`onRequestError`),i=S(e.accounting);if(i!==void 0){R=t.aborted?{kind:`aborted`}:i;break}if(n===`retry`&&k<h)continue;R={kind:`error`,failure:a.finish.failure};break}if(a.finish.kind===`max-tokens`&&!a.usageRequired){R={kind:`max-tokens`};break}if(a.calls.length===0&&a.usageUnavailable){R=S(e.accounting)??{kind:`usage-unavailable`,modelCallId:a.report?.modelCallId??`unknown`};break}if(a.calls.length===0&&ue){if(R=Q(),R!==void 0)break;e.history.append({kind:`user`,message:i({source:{kind:`app`,producer:`structured-output-finalizer`},content:[{type:`text`,text:`The process phase is complete. Return the final answer now in the requested output format. Do not call tools.`}]})});let n=await C(e,t,l,V,E,D,k+1,`final`);k++,n.report!==void 0&&L.push(n.report),n.message!==void 0&&(e.history.append({kind:`assistant`,message:n.message,...n.usage===void 0?{}:{usage:n.usage}}),await l({type:`assistant-message`,message:n.message,trace:n.trace}),await b(n,l),I=x(n.message.content)),R=n.finish.kind===`aborted`?{kind:`aborted`}:n.finish.kind===`error`?{kind:`error`,failure:n.finish.failure}:n.finish.kind===`max-tokens`?{kind:`max-tokens`}:n.usageRequired?{kind:`error`,failure:{message:`provider usage is required by the configured run policy`,code:`USAGE_REQUIRED`}}:n.usageUnavailable?S(e.accounting)??{kind:`usage-unavailable`,modelCallId:n.report?.modelCallId??`unknown`}:{kind:`completed`};break}if(a.droppedDuplicateCalls!==void 0&&e.history.append({kind:`user`,message:i({source:{kind:`app`,producer:`tool-loop-duplicate-guard`},content:[{type:`text`,text:`You reused the tool-call id ${a.droppedDuplicateCalls.map(e=>`'${e}'`).join(`, `)}. A result pairs to exactly one call, so the repeat was not run and only the first call of that id has a result. Give every call its own id, and call again if you still need what the dropped one would have done.`}]})}),a.calls.length===0||e.tools===void 0){R={kind:`completed`};break}let c=a.calls.filter(t=>e.tools?.get(t.toolName)?.budgetExempt!==!0).length,u=Math.max(0,f.maxToolCalls-A),d=B,p=a.calls.map(e=>{let t=re(e),n=d?.key===t?d.count+1:1;return d={key:t,count:n},n}).some(e=>e>=f.repeatToolLimit),g=ae(a.calls),_=ie([...ce,g],f.maxToolCycleLength),v=_!==void 0&&_.repetitions>=f.toolCycleLimit,ne=s(L),w=o(ne),T=w!==void 0&&w>=m,O=p||v||T||a.usageRequired,M=T?`tokens`:v?`tool-call-cycle`:p?`repeated-tool-call`:a.usageRequired?`usage-required`:`tool-calls`,z=f.onExhausted!==`continue`,W=await ee({calls:a.calls,catalog:e.tools,history:e.history,position:{turn:D,step:r,...e.accounting===void 0?{}:{runId:e.accounting.runId},...e.trace?.conversationId===void 0?{}:{conversationId:e.trace.conversationId}},signal:t,parentTrace:E,maxParallel:f.maxParallel,dispatchLimit:O?0:z?u:a.calls.length,declineReason:M,maxResultBytes:f.maxToolResultBytes,maxResultTokens:f.maxToolResultTokens,resultOverflow:f.toolResultOverflow,...e.spillStore===void 0?{}:{spillStore:e.spillStore},maxDurationMs:f.maxToolDurationMs,teardownTimeoutMs:f.toolTeardownTimeoutMs,...e.logger===void 0?{}:{logger:e.logger},...e.interceptors===void 0?{}:{interceptors:e.interceptors},...e.approvals===void 0?{}:{approvals:e.approvals},...e.accounting===void 0?{}:{accounting:e.accounting},emit:l,...e.hooks?.checkpoint===void 0?{}:{checkpoint:n=>y(Promise.resolve(e.hooks?.checkpoint?.(n)),e,t,`checkpoint`)}},{admissionLimit:O?0:z?u:`unbounded`,...q===void 0?{}:{programs:q},...J===void 0?{}:{programResults:J}});H!==void 0&&W.results.length===a.calls.length&&U.push(...a.calls.map((e,t)=>({toolName:e.toolName,rawArguments:e.rawArguments,failed:W.results[t]?.isError??!0}))),A+=W.budgeted;let G=Math.max(0,f.maxToolCalls-A),K=oe.filter(e=>G<=e).length;if(K>se&&G>0&&(se=K,le(`Tool budget: ${G} of ${f.maxToolCalls} calls remain in this turn. Stop broad exploration, make the necessary edits, and reserve calls for`+(z?` verification. When the budget runs out no further work call will run, so finish with what you can still verify.`:` verification. Past the budget you are expected to be wrapping up, not opening new lines of work.`))),!z&&G===0){let e=Math.floor(A/f.maxToolCalls);e>j&&(j=e,le(`Tool budget spent: ${A} calls made against a budget of ${f.maxToolCalls}. Do not start new substantive work. Finish what is in flight, verify what you can, and answer — stating plainly what is unverified or unfinished.`))}await l({type:`step-end`,turn:D,step:r,trace:a.trace}),ce.push(g);let Y=p;for(let t=0;t<a.calls.length;t++){let n=a.calls[t],r=W.results[t];if(n===void 0||r===void 0)continue;F=r.isError?F+1:0;let o=re(n),s=B?.key===o?B.count+1:1;B={key:o,count:s},s===f.repeatToolWarningAt&&e.history.append({kind:`user`,message:i({source:{kind:`app`,producer:`tool-loop-repeat-guard`},content:[{type:`text`,text:`You have called ${n.toolName} with the same arguments ${s} consecutive times. Reassess before repeating it.`}]})}),s>=f.repeatToolLimit&&(Y=!0)}if(_?.repetitions===f.toolCycleWarningAt&&e.history.append({kind:`user`,message:i({source:{kind:`app`,producer:`tool-loop-cycle-guard`},content:[{type:`text`,text:`Tool-use pattern repeated ${_.repetitions} times across ${_.period} step(s). Reassess the approach and identify concrete new evidence before continuing.`}]})}),W.concluded){R={kind:`concluded-by-tool`,toolName:W.concludedBy??`unknown`};break}if(t.aborted){R={kind:`aborted`};break}if(a.usageRequired){R=Z;break}if(a.usageUnavailable){R=S(e.accounting)??{kind:`usage-unavailable`,modelCallId:a.report?.modelCallId??`unknown`};break}let X,$=f.maxTotalTokens!==`auto`&&f.finalReportReserveTokens>0&&w!==void 0&&w>=m-f.finalReportReserveTokens;if(T||$?X=`tokens`:v?X=`tool-call-cycle`:z&&c>u?X=`tool-calls`:F>=f.maxConsecutiveToolErrors?X=`consecutive-tool-errors`:Y?X=`repeated-tool-call`:k>=h&&(X=`steps`),X!==void 0){let n=(X!==`tokens`||$&&!T)&&f.onExhausted!==`stop`&&Q()===void 0;if(n){let n=await C(e,t,l,V,E,D,k+1,`forced-final`);if(k++,n.report!==void 0&&L.push(n.report),n.message!==void 0&&(e.history.append({kind:`assistant`,message:n.message,...n.usage===void 0?{}:{usage:n.usage}}),await l({type:`assistant-message`,message:n.message,trace:n.trace}),await b(n,l),I=x(n.message.content)),n.finish.kind===`aborted`){R={kind:`aborted`};break}if(n.finish.kind===`error`){R={kind:`error`,failure:n.finish.failure};break}if(n.finish.kind===`max-tokens`){R={kind:`max-tokens`};break}if(n.usageRequired){R={kind:`error`,failure:{message:`provider usage is required by the configured run policy`,code:`USAGE_REQUIRED`}};break}if(n.usageUnavailable){R=S(e.accounting)??{kind:`usage-unavailable`,modelCallId:n.report?.modelCallId??`unknown`};break}}R={kind:`budget-exhausted`,budget:X,forcedFinalAnswer:n,...X===`tokens`&&$&&!T?{trigger:`report-reserve`}:{}}}}R===void 0&&(R=t.aborted?{kind:`aborted`}:{kind:`budget-exhausted`,budget:`steps`,forcedFinalAnswer:!1});let n=s(L),r=a(n),c={reason:R,text:I,steps:k,usageReport:n,toolCalls:A,traceId:T,...r===void 0?{}:{usage:r}},u=e.history.entries().length,d=R.kind===`completed`&&k<h&&Q()===void 0;if(await te(e.hooks?.onTurnEnd,[{outcome:c,snapshot:e.history.snapshot(),canContinue:d}],e,t,`onTurnEnd`),d&&e.history.entries().length>u&&!t.aborted){R=void 0;continue turnLifecycle}z=c;break}z.reason.kind===`aborted`&&e.history.append({kind:`user`,message:i({source:{kind:`app`,producer:`turn-interrupted`},content:[{type:`text`,text:`The previous request was interrupted before it finished. Use the next message to determine what to do next.`}]})}),await l({type:`span-end`,trace:E,at:v(),status:z.reason.kind===`error`?`error`:z.reason.kind===`aborted`?`aborted`:`success`,output:{reason:z.reason,text:I},...z.usage===void 0?{}:{usage:z.usage},...z.reason.kind===`error`?{error:{type:`ModelError`,message:z.reason.failure.message,code:z.reason.failure.code}}:{}}),G=!0,Y!==void 0&&(e.accounting?.endOperation(Y,z.reason.kind===`error`?`error`:z.reason.kind===`aborted`?`aborted`:`success`,{data:{reason:z.reason.kind,steps:k,toolCalls:A}}),X=!0),await l({type:`turn-end`,outcome:z,trace:E})}catch(n){let r=g(n);throw W&&!G&&await l({type:`span-end`,trace:E,at:v(),status:t.aborted?`aborted`:`error`,error:{type:n instanceof Error?n.name:`RuntimeError`,message:_(n),...r===void 0?{}:{code:r}}}).catch(()=>void 0),Y!==void 0&&!X&&(e.accounting?.endOperation(Y,t.aborted?`aborted`:`error`,{error:n}),X=!0),n}finally{J?.close()}}export{T as runTurn};
|
|
2
2
|
//# sourceMappingURL=run-turn.js.map
|