@alvin0/ai-agent-sdk-core 0.1.4 → 0.1.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (107) hide show
  1. package/README.md +13 -1
  2. package/dist/agent/define/definition.d.ts +1 -1
  3. package/dist/agent/define/definition.js +1 -1
  4. package/dist/agent/define/definition.js.map +1 -1
  5. package/dist/agent/define/session/types.d.ts +6 -0
  6. package/dist/agent/define/session/types.d.ts.map +1 -1
  7. package/dist/agent/define/session.d.ts +39 -2
  8. package/dist/agent/define/session.d.ts.map +1 -1
  9. package/dist/agent/define/session.js +1 -1
  10. package/dist/agent/define/session.js.map +1 -1
  11. package/dist/agent/loop/admission.js +2 -0
  12. package/dist/agent/loop/admission.js.map +1 -0
  13. package/dist/agent/loop/events.d.ts +4 -0
  14. package/dist/agent/loop/events.d.ts.map +1 -1
  15. package/dist/agent/loop/program.js +2 -0
  16. package/dist/agent/loop/program.js.map +1 -0
  17. package/dist/agent/loop/run-turn.d.ts.map +1 -1
  18. package/dist/agent/loop/run-turn.js +1 -1
  19. package/dist/agent/loop/run-turn.js.map +1 -1
  20. package/dist/agent/loop/schedule.d.ts.map +1 -1
  21. package/dist/agent/loop/schedule.js +2 -2
  22. package/dist/agent/loop/schedule.js.map +1 -1
  23. package/dist/agent/loop/tool-call-support.js +2 -0
  24. package/dist/agent/loop/tool-call-support.js.map +1 -0
  25. package/dist/agent/loop/turn/hooks.js +1 -1
  26. package/dist/agent/loop/turn/hooks.js.map +1 -1
  27. package/dist/agent/loop/turn/model-request-boundary.js +2 -0
  28. package/dist/agent/loop/turn/model-request-boundary.js.map +1 -0
  29. package/dist/agent/loop/turn/model-round.js +1 -1
  30. package/dist/agent/loop/turn/model-round.js.map +1 -1
  31. package/dist/agent/loop/turn/step-projection.js +2 -0
  32. package/dist/agent/loop/turn/step-projection.js.map +1 -0
  33. package/dist/agent/loop/turn/types.d.ts +6 -0
  34. package/dist/agent/loop/turn/types.d.ts.map +1 -1
  35. package/dist/agent/memory/context-optimizer.d.ts +61 -0
  36. package/dist/agent/memory/context-optimizer.d.ts.map +1 -0
  37. package/dist/agent/memory/context-optimizer.js +4 -0
  38. package/dist/agent/memory/context-optimizer.js.map +1 -0
  39. package/dist/agent/memory/memory.js +1 -1
  40. package/dist/agent/memory/memory.js.map +1 -1
  41. package/dist/agent/mode/run-agent.d.ts +15 -1
  42. package/dist/agent/mode/run-agent.d.ts.map +1 -1
  43. package/dist/agent/mode/run-agent.js +2 -2
  44. package/dist/agent/mode/run-agent.js.map +1 -1
  45. package/dist/agent/skill/provider/snapshot.js +1 -1
  46. package/dist/agent/team/contracts.d.ts +5 -0
  47. package/dist/agent/team/contracts.d.ts.map +1 -1
  48. package/dist/agent/team/managed.d.ts +33 -64
  49. package/dist/agent/team/managed.d.ts.map +1 -1
  50. package/dist/agent/team/managed.js +6 -3
  51. package/dist/agent/team/managed.js.map +1 -1
  52. package/dist/agent/team/team.d.ts +2 -0
  53. package/dist/agent/team/team.d.ts.map +1 -1
  54. package/dist/agent/team/team.js +1 -1
  55. package/dist/agent/team/team.js.map +1 -1
  56. package/dist/agent/team/types.d.ts +1 -0
  57. package/dist/agent/team/types.d.ts.map +1 -1
  58. package/dist/agent/tool/action-fusion.d.ts +30 -0
  59. package/dist/agent/tool/action-fusion.d.ts.map +1 -0
  60. package/dist/agent/tool/action-fusion.js +2 -0
  61. package/dist/agent/tool/action-fusion.js.map +1 -0
  62. package/dist/agent/tool/capture.js +1 -1
  63. package/dist/agent/tool/capture.js.map +1 -1
  64. package/dist/agent/tool/definition.d.ts +8 -0
  65. package/dist/agent/tool/definition.d.ts.map +1 -1
  66. package/dist/agent/tool/definition.js.map +1 -1
  67. package/dist/agent/tool/evidence-reducer.d.ts +41 -0
  68. package/dist/agent/tool/evidence-reducer.d.ts.map +1 -0
  69. package/dist/agent/tool/evidence-reducer.js +7 -0
  70. package/dist/agent/tool/evidence-reducer.js.map +1 -0
  71. package/dist/agent/tool/nested.d.ts +117 -0
  72. package/dist/agent/tool/nested.d.ts.map +1 -0
  73. package/dist/agent/tool/nested.js +2 -0
  74. package/dist/agent/tool/nested.js.map +1 -0
  75. package/dist/agent/tool/output-budget.d.ts.map +1 -1
  76. package/dist/agent/tool/output-budget.js +2 -2
  77. package/dist/agent/tool/output-budget.js.map +1 -1
  78. package/dist/agent/tool/output-schema.js +2 -0
  79. package/dist/agent/tool/output-schema.js.map +1 -0
  80. package/dist/agent/tool/pipeline.d.ts +7 -0
  81. package/dist/agent/tool/pipeline.d.ts.map +1 -1
  82. package/dist/agent/tool/pipeline.js +2 -2
  83. package/dist/agent/tool/pipeline.js.map +1 -1
  84. package/dist/agent/tool/program-results.js +2 -0
  85. package/dist/agent/tool/program-results.js.map +1 -0
  86. package/dist/agent.d.ts +6 -2
  87. package/dist/agent.js +1 -1
  88. package/dist/composition/agent/definition.js +1 -1
  89. package/dist/composition/agent/options.js +1 -1
  90. package/dist/composition/agent/options.js.map +1 -1
  91. package/dist/composition/agent/session.js +1 -1
  92. package/dist/composition/agent/session.js.map +1 -1
  93. package/dist/composition/agent/types.d.ts +6 -0
  94. package/dist/composition/agent/types.d.ts.map +1 -1
  95. package/dist/composition/tool-source/snapshot.js +1 -1
  96. package/dist/index.d.ts +2 -1
  97. package/dist/index.js +1 -1
  98. package/dist/memory.d.ts +2 -1
  99. package/dist/memory.js +1 -1
  100. package/dist/observability/bus.js +1 -1
  101. package/dist/primitives/version.d.ts +1 -1
  102. package/dist/primitives/version.js +1 -1
  103. package/dist/primitives/version.js.map +1 -1
  104. package/dist/runtime/registry.js +1 -1
  105. package/dist/tools.d.ts +4 -1
  106. package/dist/tools.js +1 -1
  107. package/package.json +1 -1
@@ -1 +1 @@
1
- {"version":3,"file":"session.js","names":[],"sources":["../../../src/composition/agent/session.ts"],"sourcesContent":["import { publicMessage } from './public-message.ts'\nimport type { AgentInput } from '../../agent/define/session/types.ts'\nimport { isJsonValue, detachedFrozen, type JsonValue } from '../../primitives/index.ts'\nimport { freezeMessage } from '../../message/index.ts'\nimport { AgentRunError } from '../../agent/accounting/error.ts'\nimport type { RunReport } from '../exporter/delivery-types.ts'\nimport { configureRuntimeSessionModel, streamRuntimeSession, type AgentSession } from '../../agent/define/session.ts'\nimport {\n compactRuntimeSession, streamPendingRuntimeSession, type RuntimeSessionRunHandle,\n} from '../../agent/define/session/runtime-binding.ts'\nimport type { AgentRunHandle as LegacyRunHandle } from '../../agent/define/session/types.ts'\nimport type { AgentRunEvent } from '../../agent/mode/run-agent.ts'\nimport type { ToolExecutionResult } from '../../agent/tool/definition.ts'\nimport { TOOL_ERROR_CODES } from '../../agent/tool/errors.ts'\nimport { AgentSdkError } from '../../errors/agent-sdk-error.ts'\nimport type { ModelRegistry } from '../../runtime/registry.ts'\nimport type { ProviderSelection } from '../provider/types.ts'\nimport { atDeadline } from '../lifecycle/bounded.ts'\nimport type { RuntimeOperations } from '../lifecycle/operations.ts'\nimport type { RuntimeObservationPort } from '../observation/port.ts'\nimport { createRunTerminalRecord } from '../delivery/terminal.ts'\nimport { finalizeRuntimeRunReport, type RuntimeRunReport } from '../observation/final-report.ts'\nimport type { RuntimeObservationResource } from '../delivery/resource.ts'\nimport type { RuntimeResources } from '../../platform/resources.ts'\nimport { snapshotToolSources } from '../tool-source/snapshot.ts'\nimport { capabilityIdentityError, inheritCapabilityIdentityConflict } from '../identity/error.ts'\nimport type { CapturedToolSource } from '../tool-source/types.ts'\nimport type { ToolSourceRunReference } from '../tool-source/types.ts'\nimport { createRuntimeMemoryPersistence } from '../memory/run.ts'\nimport { validateMemoryResumeBinding } from '../memory/resume.ts'\nimport type { BoundRuntimeAgentDefinition } from './definition.ts'\nimport { captureInvocationOptions, captureRuntimeSessionOptions, type CapturedInvocationOptions } from './options.ts'\nimport { projectNativeToolEvent } from './native-event.ts'\nimport type {\n RuntimeAgent, RuntimeAgentInvocationOptions, RuntimeAgentResponse, RuntimeAgentRunEvent,\n RuntimeAgentRunHandle, RuntimeAgentSession, RuntimeAgentSessionOptions, RuntimeAgentSessionSnapshot,\n} from './types.ts'\nimport type { CompactionResult } from '../../agent/memory/compaction.ts'\nimport type { AgentTeamMemberOptions } from '../../agent/define/session/types.ts'\nimport type { TeamSessionPort } from '../../agent/team/contracts.ts'\nimport { assertAgentIdentitySnapshot } from '../identity/agent.ts'\n\nexport interface RuntimeAgentHost {\n readonly registry: ModelRegistry\n /**\n * The runtime's captured provider routes.\n *\n * Held so a per-invocation model override resolves against exactly the same\n * configuration the agent binding used, rather than a second view of it.\n */\n readonly selection: ProviderSelection\n readonly operations: RuntimeOperations\n readonly observation: RuntimeObservationPort\n readonly resource: RuntimeObservationResource\n readonly resources: RuntimeResources\n}\n\ninterface RuntimeAgentBinding {\n readonly host: RuntimeAgentHost\n readonly definition: BoundRuntimeAgentDefinition\n}\n\nconst runtimeAgentBindings = new WeakMap<RuntimeAgent, RuntimeAgentBinding>()\n\nexport function createRuntimeAgent(host: RuntimeAgentHost, definition: BoundRuntimeAgentDefinition): RuntimeAgent {\n const agent = Object.freeze({\n model: definition.model,\n generate(input: AgentInput, options?: RuntimeAgentInvocationOptions) { return createRuntimeSession(host, definition).run(input, options) },\n stream(input: AgentInput, options?: RuntimeAgentInvocationOptions) { return createRuntimeSession(host, definition).stream(input, options) },\n createSession(options?: RuntimeAgentSessionOptions) { return createRuntimeSession(host, definition, options) },\n resumeSession(snapshot: RuntimeAgentSessionSnapshot, options?: RuntimeAgentSessionOptions) {\n return createRuntimeSession(host, definition, options, snapshot)\n },\n })\n runtimeAgentBindings.set(agent, Object.freeze({ host, definition }))\n return agent\n}\n\nexport function createRuntimeTeamMemberSession(\n host: RuntimeAgentHost,\n agent: RuntimeAgent,\n options: RuntimeAgentSessionOptions,\n team: AgentTeamMemberOptions,\n ownerSignal: AbortSignal,\n): { readonly view: RuntimeAgentSession; readonly port: TeamSessionPort } {\n const binding = runtimeAgentBindings.get(agent)\n if (binding?.host !== host) throw new AgentSdkError(\n 'Runtime team members must be agents from the same runtime', 'TEAM_AGENT_OWNERSHIP_INVALID',\n )\n const view = createRuntimeSession(host, binding.definition, options, undefined, team, ownerSignal)\n return Object.freeze({ view, port: view.teamPort })\n}\n\nexport function preflightRuntimeTeamMember(\n host: RuntimeAgentHost,\n agent: RuntimeAgent,\n options: RuntimeAgentSessionOptions,\n additionalToolNames: readonly string[],\n): void {\n const binding = runtimeAgentBindings.get(agent)\n if (binding?.host !== host) throw new AgentSdkError(\n 'Runtime team members must be agents from the same runtime', 'TEAM_AGENT_OWNERSHIP_INVALID',\n )\n assertAgentIdentitySnapshot({\n tools: [...binding.definition.legacy.tools, ...options.tools ?? []],\n nativeTools: binding.definition.legacy.nativeTools,\n skills: [...binding.definition.legacy.skills, ...options.skills ?? []] as never,\n ...(binding.definition.legacy.skillIds === undefined ? {} : {\n allowedSkillIds: binding.definition.legacy.skillIds,\n }),\n additionalToolNames,\n })\n}\n\nexport function runtimeOwnsAgent(host: RuntimeAgentHost, agent: unknown): agent is RuntimeAgent {\n return typeof agent === 'object' && agent !== null && runtimeAgentBindings.get(agent as RuntimeAgent)?.host === host\n}\n\nclass RuntimeAgentSessionValue implements RuntimeAgentSession {\n private active: SessionOperation | undefined\n private readonly observerTimeoutMs: number\n readonly teamPort: TeamSessionPort\n\n constructor(\n private readonly host: RuntimeAgentHost,\n private readonly session: AgentSession,\n private readonly nativeProvider: string,\n definitionId: string,\n observerTimeoutMs = 30_000,\n private readonly ownerSignal?: AbortSignal,\n ) {\n this.observerTimeoutMs = observerTimeoutMs\n const owner = this\n this.teamPort = Object.freeze({\n definition: Object.freeze({ id: definitionId }),\n get conversationId() { return owner.conversationId },\n get isRunning() { return owner.isRunning },\n inject(input: Parameters<TeamSessionPort['inject']>[0]) { return owner.injectForTeam(input) },\n whenIdle(signal?: AbortSignal) { return owner.whenIdle(signal) },\n runPending(invocation = {}) { return owner.runPendingForTeam(invocation) },\n })\n }\n\n get conversationId(): string { return this.session.conversationId }\n get isRunning(): boolean { return this.active !== undefined }\n\n stream(input: AgentInput, rawOptions?: RuntimeAgentInvocationOptions): RuntimeAgentRunHandle {\n if (typeof input !== 'string') {\n if (input === null || typeof input !== 'object' || input.role !== 'user') throw new TypeError('Runtime input must be text or a user message')\n input = freezeMessage(input)\n }\n const options = captureInvocationOptions(rawOptions, this.host.selection)\n const started = this.start(input, options)\n return runtimeHandle(started.legacy, started.report, started.result, this.nativeProvider, options.includeTraceEvents === true)\n }\n\n private start(input: AgentInput | undefined, options: CapturedInvocationOptions): StartedRuntimeRun {\n const operation = this.beginOperation()\n let lease: ReturnType<RuntimeOperations['acquire']>\n try {\n const signal = this.ownerSignal === undefined\n ? options.signal\n : options.signal === undefined ? this.ownerSignal : AbortSignal.any([options.signal, this.ownerSignal])\n lease = this.host.operations.acquire('agent-run', {\n ...(signal === undefined ? {} : { signal }),\n })\n } catch (error) { this.finishOperation(operation); throw error }\n let output: JsonValue | undefined\n const structured = options.structuredOutput\n let legacy: RuntimeSessionRunHandle\n try {\n legacy = input === undefined\n ? streamPendingRuntimeSession(this.session, { signal: lease.signal, ...modelOverlay(options) })\n : streamRuntimeSession(this.session, input, { signal: lease.signal, ...modelOverlay(options),\n ...(structured === undefined ? {} : {\n outputFormat: { type: 'json_schema' as const, name: structured.name, schema: structured.schema.jsonSchema },\n validateOutput: (value: unknown) => {\n const parsed = structured.schema.parse(value)\n if (!isJsonValue(parsed)) throw new TypeError('structured output parser must return lossless JSON synchronously')\n output = detachedFrozen(parsed)\n },\n }), ...(options.imagePolicy === undefined ? {} : { imagePolicy: options.imagePolicy }),\n ...(options.documentPolicy === undefined ? {} : { documentPolicy: options.documentPolicy }) }, options.additionalInstructions)\n } catch (error) { lease.settle(); this.finishOperation(operation); throw error }\n const abort = (): void => legacy.abort()\n lease.signal.addEventListener('abort', abort, { once: true })\n if (lease.signal.aborted) abort()\n void lease.whenSealed.then(() => legacy.seal()).catch(() => undefined)\n const report = this.runtimeReport(legacy.report, legacy.toolSourceSnapshots, lease.signal)\n const internalResult = this.runtimeResult(legacy.result, report, () => output)\n const eventsSettled = Promise.race([legacy.eventsSettled, lease.whenSealed])\n const released = Promise.allSettled([eventsSettled, internalResult, report]).then(() => {\n lease.signal.removeEventListener('abort', abort)\n lease.settle()\n this.finishOperation(operation)\n })\n const result = released.then(() => internalResult)\n void result.catch(() => undefined)\n void report.catch(() => undefined)\n return Object.freeze({ legacy, report, result })\n }\n\n async run(input: AgentInput, rawOptions?: RuntimeAgentInvocationOptions): Promise<RuntimeAgentResponse> {\n const options = captureInvocationOptions(rawOptions, this.host.selection)\n const handle = this.stream(input, options)\n try {\n for await (const event of handle) {\n if (options.onEvent !== undefined) {\n try { await this.observe(options.onEvent, event, handle) }\n catch (error) {\n handle.abort()\n const report = await handle.report\n throw runtimeFailure(error, report, 'RUN_EVENT_OBSERVER_FAILED')\n }\n }\n }\n } catch (error) { if (codeOf(error) === 'RUN_EVENT_OBSERVER_FAILED') throw error; return await handle.result }\n return await handle.result\n }\n\n inject(input: AgentInput): number {\n this.host.operations.assertActive()\n this.assertOwnerActive()\n if (this.active !== undefined) throw new Error('Cannot inject while a runtime session is active')\n return this.session.inject(input)\n }\n\n private injectForTeam(input: Parameters<TeamSessionPort['inject']>[0]): number {\n this.host.operations.assertActive()\n this.assertOwnerActive()\n return this.session.inject(input)\n }\n\n snapshot(): RuntimeAgentSessionSnapshot { return this.session.snapshot() }\n\n compact(rawOptions?: RuntimeAgentInvocationOptions): Promise<CompactionResult | null> {\n const options = captureInvocationOptions(rawOptions, this.host.selection)\n const operation = this.beginOperation()\n let pending: Promise<CompactionResult | null>\n try {\n pending = this.host.operations.execute('manual-compaction', {\n ...(this.ownerSignal === undefined\n ? options.signal === undefined ? {} : { signal: options.signal }\n : { signal: options.signal === undefined ? this.ownerSignal : AbortSignal.any([options.signal, this.ownerSignal]) }),\n }, async lease => {\n const outcome = await compactRuntimeSession(this.session, { signal: lease.signal, ...modelOverlay(options) })\n const record = createRunTerminalRecord(outcome.report)\n const terminal = await this.host.observation.checkpointTerminal(record, lease.signal)\n const report = finalizeRuntimeRunReport(record, outcome.report.delivery, terminal,\n this.host.observation.mode, this.host.observation.requiredBoundary)\n if (outcome.failure !== undefined) throw runtimeFailure(\n outcome.failure,\n report,\n report.errors.at(-1)?.code ?? codeOf(outcome.failure),\n )\n return outcome.result === null ? null : Object.freeze({ ...outcome.result, status: 'completed' as const, report })\n })\n } catch (error) { this.finishOperation(operation); throw error }\n return pending.finally(() => this.finishOperation(operation))\n }\n\n reset(): void {\n this.host.operations.assertActive()\n this.assertOwnerActive()\n if (this.active !== undefined) throw new Error('Cannot reset while a runtime session is active')\n this.session.reset()\n }\n\n whenIdle(signal?: AbortSignal): Promise<void> {\n const pending = this.active?.done\n if (pending === undefined) return Promise.resolve()\n if (signal?.aborted) return Promise.reject(new AgentSdkError('Runtime idle wait was aborted', 'RUNTIME_OPERATION_ABORTED'))\n return new Promise((resolve, reject) => {\n let release = (): void => undefined\n const finish = (error?: Error): void => { release(); error === undefined ? resolve() : reject(error) }\n if (signal !== undefined) release = this.host.resources.onAbort(signal,\n () => finish(new AgentSdkError('Runtime idle wait was aborted', 'RUNTIME_OPERATION_ABORTED')))\n void pending.then(() => finish())\n })\n }\n\n private async runPendingForTeam(invocation: {\n readonly signal?: AbortSignal\n readonly onEvent?: (event: AgentRunEvent) => void | Promise<void>\n }): Promise<unknown> {\n const started = this.start(undefined, {\n ...(invocation.signal === undefined ? {} : { signal: invocation.signal }),\n })\n try {\n for await (const event of started.legacy) await invocation.onEvent?.(event)\n } catch (error) {\n started.legacy.abort()\n await started.result.catch(() => undefined)\n throw error\n }\n return await started.result\n }\n\n private beginOperation(): SessionOperation {\n this.assertOwnerActive()\n if (this.active !== undefined) throw new Error('Cannot start while a runtime session is active')\n let resolve!: () => void\n const operation: SessionOperation = { done: new Promise(done => { resolve = done }), resolve }\n this.active = operation\n return operation\n }\n\n private finishOperation(operation: SessionOperation): void {\n if (this.active !== operation) return\n this.active = undefined\n operation.resolve()\n }\n\n private assertOwnerActive(): void {\n if (this.ownerSignal?.aborted === true) {\n throw new AgentSdkError('Runtime team session is closed', 'TEAM_CLOSED')\n }\n }\n\n private async runtimeReport(\n legacy: Promise<RunReport>,\n sourceSnapshots: Promise<readonly ToolSourceRunReference[]>,\n signal: AbortSignal,\n ): Promise<RuntimeRunReport> {\n const [previous, sources] = await Promise.all([legacy, sourceSnapshots])\n const record = createRunTerminalRecord(previous, sources)\n const terminal = await this.host.observation.checkpointTerminal(record, signal)\n return finalizeRuntimeRunReport(record, previous.delivery, terminal,\n this.host.observation.mode, this.host.observation.requiredBoundary)\n }\n\n private async runtimeResult(\n legacy: Promise<Awaited<LegacyRunHandle['result']>>,\n report: Promise<RuntimeRunReport>,\n output: () => JsonValue | undefined,\n ): Promise<RuntimeAgentResponse> {\n try {\n const response = await legacy\n const final = await report\n if (final.status !== 'success') {\n throw runtimeFailure(undefined, final, final.errors.at(-1)?.code ?? 'AGENT_RUN_FAILED')\n }\n const parsedOutput = output()\n return Object.freeze({ runId: final.runId, traceId: final.traceId,\n completed: response.outcome.completed, stopReason: response.outcome.reason.kind,\n text: response.text, ...(parsedOutput === undefined ? {} : { output: parsedOutput }),\n ...(response.message === undefined ? {} : { message: publicMessage(response.message) }),\n usage: final.usage, report: final })\n } catch (error) {\n const final = await report\n throw runtimeFailure(error, final, codeOf(error))\n }\n }\n\n private async observe(\n observer: NonNullable<RuntimeAgentInvocationOptions['onEvent']>,\n event: RuntimeAgentRunEvent,\n handle: RuntimeAgentRunHandle,\n ): Promise<void> {\n const deadlineAt = this.host.resources.platform.monotonicNow() + this.observerTimeoutMs\n try { await atDeadline(this.host.resources, deadlineAt, () => observer(event), undefined) }\n catch { handle.abort(); throw new AgentSdkError('Runtime event observer did not complete', 'RUN_EVENT_OBSERVER_FAILED') }\n }\n}\n\nfunction createRuntimeSession(\n host: RuntimeAgentHost,\n definition: BoundRuntimeAgentDefinition,\n options: RuntimeAgentSessionOptions = {},\n snapshot?: RuntimeAgentSessionSnapshot,\n team?: AgentTeamMemberOptions,\n ownerSignal?: AbortSignal,\n): RuntimeAgentSessionValue {\n host.operations.assertActive()\n options = captureRuntimeSessionOptions(options)\n assertAgentIdentitySnapshot({\n tools: [...definition.legacy.tools, ...options.tools ?? []],\n nativeTools: definition.legacy.nativeTools,\n skills: [...definition.legacy.skills, ...options.skills ?? []] as never,\n ...(definition.legacy.skillIds === undefined ? {} : { allowedSkillIds: definition.legacy.skillIds }),\n })\n const memory = options.memory === false ? undefined : options.memory ?? definition.memory\n if (snapshot !== undefined) validateMemoryResumeBinding(snapshot, memory)\n const toolSources = combineToolSources(definition.toolSources, options.toolSources ?? [])\n const limits = options.runtimeLimits\n const { maxSteps: _maxSteps, maxToolCalls: _maxToolCalls, ...agentRuntimeLimits } = limits ?? {}\n const selected = limits?.maxSteps === undefined && limits?.maxToolCalls === undefined\n ? definition.legacy : definition.legacy.with({\n ...(limits.maxSteps === undefined ? {} : { maxTurns: limits.maxSteps }),\n ...(limits.maxToolCalls === undefined ? {} : { maxToolCalls: limits.maxToolCalls }),\n })\n const shared = { registry: host.registry, observation: host.observation, observationResource: host.resource,\n ...(options.tools === undefined ? {} : { tools: options.tools }),\n ...(options.skills === undefined ? {} : { skills: options.skills as never }),\n ...(options.skillCwd === undefined ? {} : { skillCwd: options.skillCwd }),\n ...(options.userInput === undefined ? {} : { userInput: options.userInput }),\n ...(options.approvals === undefined ? {} : { approvals: options.approvals }),\n ...(options.spillStore === undefined ? {} : { spillStore: options.spillStore }),\n ...(options.interceptors === undefined ? {} : { interceptors: options.interceptors }),\n ...(options.contextSections === undefined ? {} : { contextSections: options.contextSections }),\n ...(options.hooks === undefined ? {} : { hooks: options.hooks }),\n ...(options.usagePolicy === undefined ? {} : { usagePolicy: options.usagePolicy }),\n ...(options.historyLimits === undefined ? {} : { historyLimits: options.historyLimits }),\n ...(options.ledgerLimits === undefined ? {} : { ledgerLimits: options.ledgerLimits }),\n ...(options.eventBufferLimits === undefined ? {} : { eventBufferLimits: options.eventBufferLimits }),\n ...(options.compaction === undefined ? {} : { compaction: options.compaction }),\n ...(team === undefined ? {} : { team }),\n ...(Object.keys(agentRuntimeLimits).length === 0 ? {} : { runtimeLimits: agentRuntimeLimits }),\n }\n const session = snapshot === undefined\n ? selected.createSession({ ...shared, ...(options.conversationId === undefined ? {} : { conversationId: options.conversationId }) })\n : selected.resumeSession({ ...shared, snapshot })\n configureRuntimeSessionModel(session, { provider: definition.model.provider, model: definition.model.id,\n ...(definition.effort === undefined ? {} : { reasoningEffort: definition.effort }),\n ...(definition.maxTokens === undefined ? {} : { maxTokens: definition.maxTokens }),\n logger: correlation => host.observation.correlatedLogger(correlation, { scope: 'sdk.agent.run' }),\n ...(toolSources.length === 0 ? {} : {\n prepareTools: (signal, logger, occupiedNames) => snapshotToolSources(\n toolSources, signal, logger, occupiedNames,\n ),\n }),\n ...(memory === undefined ? {} : {\n memory: createRuntimeMemoryPersistence(\n memory,\n definition.legacy.id,\n agentRuntimeLimits.memoryOperationTimeoutMs,\n ),\n }),\n })\n return new RuntimeAgentSessionValue(\n host, session, definition.model.provider, definition.legacy.id, limits?.observerTimeoutMs, ownerSignal,\n )\n}\n\n/** Project one captured invocation onto the low-level per-run model overlay. */\nfunction modelOverlay(options: CapturedInvocationOptions): {\n readonly model?: { readonly provider: string; readonly model: string }\n readonly maxTokens?: number\n} {\n return {\n ...(options.model === undefined ? {} : { model: { provider: options.model.provider, model: options.model.id } }),\n ...(options.maxTokens === undefined ? {} : { maxTokens: options.maxTokens }),\n }\n}\n\ninterface SessionOperation {\n readonly done: Promise<void>\n readonly resolve: () => void\n}\n\ninterface StartedRuntimeRun {\n readonly legacy: RuntimeSessionRunHandle\n readonly report: Promise<RuntimeRunReport>\n readonly result: Promise<RuntimeAgentResponse>\n}\n\nfunction combineToolSources(\n defined: readonly CapturedToolSource[],\n additional: readonly CapturedToolSource[],\n): readonly CapturedToolSource[] {\n const all = [...defined, ...additional]\n const seen = new Map<string, number>()\n for (const [index, source] of all.entries()) {\n const first = seen.get(source.id)\n if (first !== undefined) throw capabilityIdentityError(\n 'TOOL_SOURCE_ID_CONFLICT', 'tool-source-id', first, index,\n )\n seen.set(source.id, index)\n }\n return Object.freeze(all)\n}\n\nfunction runtimeHandle(\n source: LegacyRunHandle & { readonly traceId: string; abort(reason?: unknown): void },\n report: Promise<RuntimeRunReport>, result: Promise<RuntimeAgentResponse>, nativeProvider: string,\n includeTraceEvents: boolean,\n): RuntimeAgentRunHandle {\n let iterated = false\n return Object.freeze({ runId: source.runId, report, result, abort: () => source.abort(),\n [Symbol.asyncIterator](): AsyncIterator<RuntimeAgentRunEvent> {\n if (iterated) return (async function* () { throw new Error('A runtime run handle can only be iterated once') })()\n iterated = true\n return projectEvents(source, report, nativeProvider, includeTraceEvents)\n } })\n}\n\nasync function* projectEvents(\n source: LegacyRunHandle & { readonly traceId: string; abort(reason?: unknown): void },\n report: Promise<RuntimeRunReport>,\n nativeProvider: string,\n includeTraceEvents: boolean,\n): AsyncGenerator<RuntimeAgentRunEvent> {\n let sequence = 0, completed = false\n const context = () => ({ runId: source.runId, traceId: source.traceId, sequence: ++sequence, schemaVersion: 1 as const })\n try {\n for await (const event of source) {\n const projected = projectEvent(event, nativeProvider, includeTraceEvents)\n if (projected !== undefined) yield Object.freeze({ ...context(), ...projected }) as RuntimeAgentRunEvent\n }\n const terminal = await report\n if (terminal.status === 'success') {\n yield Object.freeze({ ...context(), type: 'usage', usage: terminal.usage, report: terminal })\n } else {\n const error = terminal.errors.at(-1) ?? fallbackError(terminal)\n yield Object.freeze({ ...context(), type: 'error', error, report: terminal })\n }\n completed = true\n } catch {\n const terminal = await report\n const error = terminal.errors.at(-1) ?? fallbackError(terminal)\n yield Object.freeze({ ...context(), type: 'error', error, report: terminal })\n completed = true\n } finally { if (!completed) source.abort() }\n}\n\ntype WithoutEventContext<T> = T extends unknown ? Omit<T, 'runId' | 'traceId' | 'sequence' | 'schemaVersion'> : never\ntype ProjectedEvent = WithoutEventContext<RuntimeAgentRunEvent>\n\nfunction projectEvent(event: AgentRunEvent, nativeProvider: string, includeTraceEvents: boolean): ProjectedEvent | undefined {\n if (event.type === 'usage-progress') return { type: 'usage-progress', usage: event.usage,\n ...(event.attemptId === undefined ? {} : { attemptId: event.attemptId }) }\n // Runtime consumers such as Edge hosts may persist an execution trace. Keep\n // the SDK's span lifecycle intact; unlike transcript events, spans carry the\n // identity and nesting needed to reconstruct the call tree.\n if (includeTraceEvents && (event.type === 'span-start' || event.type === 'span-end')) return event\n if (event.type === 'text-delta') return {\n type: event.phase === 'commentary' ? 'commentary-delta' : 'assistant-delta',\n text: event.text, index: event.index, phase: event.phase, blockId: `${event.trace.spanId}:${event.index}`,\n }\n if (event.type === 'assistant-message') return { type: 'assistant-message', message: publicMessage(event.message) }\n if (event.type === 'text-end' || event.type === 'reasoning-delta') {\n const { trace, ...content } = event\n return { ...content, blockId: `${trace.spanId}:${event.index}` }\n }\n if (event.type === 'image-delta') {\n const { trace, ...content } = event\n return { ...content, blockId: `${trace.spanId}:${event.itemId}` }\n }\n if (event.type === 'compaction-start' || event.type === 'compaction-end'\n || event.type === 'turn-start' || event.type === 'step-start' || event.type === 'step-end'\n || event.type === 'assistant-text' || event.type === 'assistant-reasoning') {\n const { trace: _trace, ...content } = event\n return content\n }\n if (event.type === 'tool-call') return { type: 'tool-call', callId: event.call.callId,\n name: event.call.toolName, input: parseInput(event.call.rawArguments) }\n if (event.type === 'tool-result') return { type: 'tool-result', callId: event.call.callId,\n name: event.call.toolName, status: toolResultStatus(event.result), output: event.result }\n if (event.type === 'assistant-native-tool') return projectNativeToolEvent(event.call, nativeProvider)\n if (event.type === 'approval-request') return { type: 'approval-request', request: event.request }\n if (event.type === 'user-input-request') return { type: 'user-input-request', request: event.request }\n if (event.type === 'user-input-response') return { type: 'user-input-response', requestId: event.request.requestId,\n response: event.response }\n return undefined\n}\n\nfunction toolResultStatus(\n result: ToolExecutionResult,\n): 'completed' | 'failed' | 'aborted' | 'rejected' | 'declined' {\n // A call the loop refused to run is neither success nor failure: nothing\n // broke, and nothing was done. Reporting it as either misleads a UI — and a\n // red row for a budget decision is what makes a finished run look crashed.\n if (!result.isError) return result.meta?.['declined'] === true ? 'declined' : 'completed'\n if (result.error.code === TOOL_ERROR_CODES.ABORTED\n || result.error.code === TOOL_ERROR_CODES.ABORTED_BEFORE_DISPATCH) return 'aborted'\n if (result.error.code === TOOL_ERROR_CODES.UNKNOWN_TOOL\n || result.error.code === TOOL_ERROR_CODES.INVALID_ARGUMENTS\n || result.error.code === TOOL_ERROR_CODES.MALFORMED_ARGUMENTS\n || result.error.code === TOOL_ERROR_CODES.DENIED\n || result.error.code === TOOL_ERROR_CODES.BUDGET_EXHAUSTED\n || result.error.code === TOOL_ERROR_CODES.CHECKPOINT_FAILED) return 'rejected'\n return 'failed'\n}\n\nfunction parseInput(value: string): unknown { try { return JSON.parse(value) as unknown } catch { return value } }\nfunction codeOf(value: unknown): string {\n return value instanceof AgentSdkError ? value.code : 'AGENT_RUN_FAILED'\n}\nfunction runtimeFailure(value: unknown, report: RuntimeRunReport, code: string): AgentRunError {\n return inheritCapabilityIdentityConflict(\n new AgentRunError('Agent run did not complete', code, report as never), value,\n )\n}\nfunction fallbackError(report: RuntimeRunReport): RuntimeRunReport['errors'][number] {\n return Object.freeze({ code: 'AGENT_RUN_FAILED', stage: 'agent-run', message: 'Agent operation failed',\n usageCoverage: report.usage.coverage,\n possiblyBilledAttemptsWithoutUsage: report.usage.coverage.possiblyBilledAttemptsWithoutUsage })\n}\n"],"mappings":"0zCA8DA,MAAM,EAAuB,IAAI,QAEjC,SAAgB,EAAmB,EAAwB,EAAuD,CAChH,IAAM,EAAQ,OAAO,OAAO,CAC1B,MAAO,EAAW,MAClB,SAAS,EAAmB,EAAyC,CAAE,OAAO,EAAqB,EAAM,CAAU,CAAC,CAAC,IAAI,EAAO,CAAO,CAAE,EACzI,OAAO,EAAmB,EAAyC,CAAE,OAAO,EAAqB,EAAM,CAAU,CAAC,CAAC,OAAO,EAAO,CAAO,CAAE,EAC1I,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AAO,CAAE,KAAM,sBAAuB,UAAW,EAAM,QAAQ,UACvG,SAAU,EAAM,QAAS,CAE7B,CAEA,SAAS,EACP,EAC8D,CAa9D,OATK,EAAO,QACR,EAAO,MAAM,OAAS,EAAiB,SACtC,EAAO,MAAM,OAAS,EAAiB,wBAAgC,UACxE,EAAO,MAAM,OAAS,EAAiB,cACtC,EAAO,MAAM,OAAS,EAAiB,mBACvC,EAAO,MAAM,OAAS,EAAiB,qBACvC,EAAO,MAAM,OAAS,EAAiB,QACvC,EAAO,MAAM,OAAS,EAAiB,kBACvC,EAAO,MAAM,OAAS,EAAiB,kBAA0B,WAC/D,SATqB,EAAO,MAAO,WAAgB,GAAO,WAAa,WAUhF,CAEA,SAAS,EAAW,EAAwB,CAAE,GAAI,CAAE,OAAO,KAAK,MAAM,CAAK,CAAa,MAAQ,CAAE,OAAO,CAAM,CAAE,CACjH,SAAS,EAAO,EAAwB,CACtC,OAAO,aAAiB,EAAgB,EAAM,KAAO,kBACvD,CACA,SAAS,EAAe,EAAgB,EAA0B,EAA6B,CAC7F,OAAO,EACL,IAAI,EAAc,6BAA8B,EAAM,CAAe,EAAG,CAC1E,CACF,CACA,SAAS,EAAc,EAA8D,CACnF,OAAO,OAAO,OAAO,CAAE,KAAM,mBAAoB,MAAO,YAAa,QAAS,yBAC5E,cAAe,EAAO,MAAM,SAC5B,mCAAoC,EAAO,MAAM,SAAS,kCAAmC,CAAC,CAClG"}
1
+ {"version":3,"file":"session.js","names":[],"sources":["../../../src/composition/agent/session.ts"],"sourcesContent":["import { publicMessage } from './public-message.ts'\nimport type { AgentInput } from '../../agent/define/session/types.ts'\nimport { isJsonValue, detachedFrozen, type JsonValue } from '../../primitives/index.ts'\nimport { freezeMessage } from '../../message/index.ts'\nimport { AgentRunError } from '../../agent/accounting/error.ts'\nimport type { RunReport } from '../exporter/delivery-types.ts'\nimport { configureRuntimeSessionModel, streamRuntimeSession, type AgentSession } from '../../agent/define/session.ts'\nimport {\n compactRuntimeSession, streamPendingRuntimeSession, type RuntimeSessionRunHandle,\n} from '../../agent/define/session/runtime-binding.ts'\nimport type { AgentRunHandle as LegacyRunHandle } from '../../agent/define/session/types.ts'\nimport type { AgentRunEvent } from '../../agent/mode/run-agent.ts'\nimport type { ToolExecutionResult } from '../../agent/tool/definition.ts'\nimport { TOOL_ERROR_CODES } from '../../agent/tool/errors.ts'\nimport { AgentSdkError } from '../../errors/agent-sdk-error.ts'\nimport type { ModelRegistry } from '../../runtime/registry.ts'\nimport type { ProviderSelection } from '../provider/types.ts'\nimport { atDeadline } from '../lifecycle/bounded.ts'\nimport type { RuntimeOperations } from '../lifecycle/operations.ts'\nimport type { RuntimeObservationPort } from '../observation/port.ts'\nimport { createRunTerminalRecord } from '../delivery/terminal.ts'\nimport { finalizeRuntimeRunReport, type RuntimeRunReport } from '../observation/final-report.ts'\nimport type { RuntimeObservationResource } from '../delivery/resource.ts'\nimport type { RuntimeResources } from '../../platform/resources.ts'\nimport { snapshotToolSources } from '../tool-source/snapshot.ts'\nimport { capabilityIdentityError, inheritCapabilityIdentityConflict } from '../identity/error.ts'\nimport type { CapturedToolSource } from '../tool-source/types.ts'\nimport type { ToolSourceRunReference } from '../tool-source/types.ts'\nimport { createRuntimeMemoryPersistence } from '../memory/run.ts'\nimport { validateMemoryResumeBinding } from '../memory/resume.ts'\nimport type { BoundRuntimeAgentDefinition } from './definition.ts'\nimport { captureInvocationOptions, captureRuntimeSessionOptions, type CapturedInvocationOptions } from './options.ts'\nimport { projectNativeToolEvent } from './native-event.ts'\nimport type {\n RuntimeAgent, RuntimeAgentInvocationOptions, RuntimeAgentResponse, RuntimeAgentRunEvent,\n RuntimeAgentRunHandle, RuntimeAgentSession, RuntimeAgentSessionOptions, RuntimeAgentSessionSnapshot,\n} from './types.ts'\nimport type { CompactionResult } from '../../agent/memory/compaction.ts'\nimport type { AgentTeamMemberOptions } from '../../agent/define/session/types.ts'\nimport type { TeamSessionPort } from '../../agent/team/contracts.ts'\nimport { assertAgentIdentitySnapshot } from '../identity/agent.ts'\n\nexport interface RuntimeAgentHost {\n readonly registry: ModelRegistry\n /**\n * The runtime's captured provider routes.\n *\n * Held so a per-invocation model override resolves against exactly the same\n * configuration the agent binding used, rather than a second view of it.\n */\n readonly selection: ProviderSelection\n readonly operations: RuntimeOperations\n readonly observation: RuntimeObservationPort\n readonly resource: RuntimeObservationResource\n readonly resources: RuntimeResources\n}\n\ninterface RuntimeAgentBinding {\n readonly host: RuntimeAgentHost\n readonly definition: BoundRuntimeAgentDefinition\n}\n\nconst runtimeAgentBindings = new WeakMap<RuntimeAgent, RuntimeAgentBinding>()\n\nexport function createRuntimeAgent(host: RuntimeAgentHost, definition: BoundRuntimeAgentDefinition): RuntimeAgent {\n const agent = Object.freeze({\n model: definition.model,\n generate(input: AgentInput, options?: RuntimeAgentInvocationOptions) { return createRuntimeSession(host, definition).run(input, options) },\n stream(input: AgentInput, options?: RuntimeAgentInvocationOptions) { return createRuntimeSession(host, definition).stream(input, options) },\n createSession(options?: RuntimeAgentSessionOptions) { return createRuntimeSession(host, definition, options) },\n resumeSession(snapshot: RuntimeAgentSessionSnapshot, options?: RuntimeAgentSessionOptions) {\n return createRuntimeSession(host, definition, options, snapshot)\n },\n })\n runtimeAgentBindings.set(agent, Object.freeze({ host, definition }))\n return agent\n}\n\nexport function createRuntimeTeamMemberSession(\n host: RuntimeAgentHost,\n agent: RuntimeAgent,\n options: RuntimeAgentSessionOptions,\n team: AgentTeamMemberOptions,\n ownerSignal: AbortSignal,\n): { readonly view: RuntimeAgentSession; readonly port: TeamSessionPort } {\n const binding = runtimeAgentBindings.get(agent)\n if (binding?.host !== host) throw new AgentSdkError(\n 'Runtime team members must be agents from the same runtime', 'TEAM_AGENT_OWNERSHIP_INVALID',\n )\n const view = createRuntimeSession(host, binding.definition, options, undefined, team, ownerSignal)\n return Object.freeze({ view, port: view.teamPort })\n}\n\nexport function preflightRuntimeTeamMember(\n host: RuntimeAgentHost,\n agent: RuntimeAgent,\n options: RuntimeAgentSessionOptions,\n additionalToolNames: readonly string[],\n): void {\n const binding = runtimeAgentBindings.get(agent)\n if (binding?.host !== host) throw new AgentSdkError(\n 'Runtime team members must be agents from the same runtime', 'TEAM_AGENT_OWNERSHIP_INVALID',\n )\n assertAgentIdentitySnapshot({\n tools: [...binding.definition.legacy.tools, ...options.tools ?? []],\n nativeTools: binding.definition.legacy.nativeTools,\n skills: [...binding.definition.legacy.skills, ...options.skills ?? []] as never,\n ...(binding.definition.legacy.skillIds === undefined ? {} : {\n allowedSkillIds: binding.definition.legacy.skillIds,\n }),\n additionalToolNames,\n })\n}\n\nexport function runtimeOwnsAgent(host: RuntimeAgentHost, agent: unknown): agent is RuntimeAgent {\n return typeof agent === 'object' && agent !== null && runtimeAgentBindings.get(agent as RuntimeAgent)?.host === host\n}\n\nclass RuntimeAgentSessionValue implements RuntimeAgentSession {\n private active: SessionOperation | undefined\n private readonly observerTimeoutMs: number\n readonly teamPort: TeamSessionPort\n\n constructor(\n private readonly host: RuntimeAgentHost,\n private readonly session: AgentSession,\n private readonly nativeProvider: string,\n definitionId: string,\n observerTimeoutMs = 30_000,\n private readonly ownerSignal?: AbortSignal,\n ) {\n this.observerTimeoutMs = observerTimeoutMs\n const owner = this\n this.teamPort = Object.freeze({\n definition: Object.freeze({ id: definitionId }),\n get conversationId() { return owner.conversationId },\n get isRunning() { return owner.isRunning },\n inject(input: Parameters<TeamSessionPort['inject']>[0]) { return owner.injectForTeam(input) },\n whenIdle(signal?: AbortSignal) { return owner.whenIdle(signal) },\n hasUnansweredInput() { return owner.session.hasUnansweredInput() },\n runPending(invocation = {}) { return owner.runPendingForTeam(invocation) },\n })\n }\n\n get conversationId(): string { return this.session.conversationId }\n get isRunning(): boolean { return this.active !== undefined }\n\n stream(input: AgentInput, rawOptions?: RuntimeAgentInvocationOptions): RuntimeAgentRunHandle {\n if (typeof input !== 'string') {\n if (input === null || typeof input !== 'object' || input.role !== 'user') throw new TypeError('Runtime input must be text or a user message')\n input = freezeMessage(input)\n }\n const options = captureInvocationOptions(rawOptions, this.host.selection)\n const started = this.start(input, options)\n return runtimeHandle(started.legacy, started.report, started.result, this.nativeProvider, options.includeTraceEvents === true)\n }\n\n private start(input: AgentInput | undefined, options: CapturedInvocationOptions): StartedRuntimeRun {\n const operation = this.beginOperation()\n let lease: ReturnType<RuntimeOperations['acquire']>\n try {\n const signal = this.ownerSignal === undefined\n ? options.signal\n : options.signal === undefined ? this.ownerSignal : AbortSignal.any([options.signal, this.ownerSignal])\n lease = this.host.operations.acquire('agent-run', {\n ...(signal === undefined ? {} : { signal }),\n })\n } catch (error) { this.finishOperation(operation); throw error }\n let output: JsonValue | undefined\n const structured = options.structuredOutput\n let legacy: RuntimeSessionRunHandle\n try {\n legacy = input === undefined\n ? streamPendingRuntimeSession(this.session, { signal: lease.signal, ...modelOverlay(options) })\n : streamRuntimeSession(this.session, input, { signal: lease.signal, ...modelOverlay(options),\n ...(structured === undefined ? {} : {\n outputFormat: { type: 'json_schema' as const, name: structured.name, schema: structured.schema.jsonSchema },\n validateOutput: (value: unknown) => {\n const parsed = structured.schema.parse(value)\n if (!isJsonValue(parsed)) throw new TypeError('structured output parser must return lossless JSON synchronously')\n output = detachedFrozen(parsed)\n },\n }), ...(options.imagePolicy === undefined ? {} : { imagePolicy: options.imagePolicy }),\n ...(options.documentPolicy === undefined ? {} : { documentPolicy: options.documentPolicy }) }, options.additionalInstructions)\n } catch (error) { lease.settle(); this.finishOperation(operation); throw error }\n const abort = (): void => legacy.abort()\n lease.signal.addEventListener('abort', abort, { once: true })\n if (lease.signal.aborted) abort()\n void lease.whenSealed.then(() => legacy.seal()).catch(() => undefined)\n const report = this.runtimeReport(legacy.report, legacy.toolSourceSnapshots, lease.signal)\n const internalResult = this.runtimeResult(legacy.result, report, () => output)\n const eventsSettled = Promise.race([legacy.eventsSettled, lease.whenSealed])\n const released = Promise.allSettled([eventsSettled, internalResult, report]).then(() => {\n lease.signal.removeEventListener('abort', abort)\n lease.settle()\n this.finishOperation(operation)\n })\n const result = released.then(() => internalResult)\n void result.catch(() => undefined)\n void report.catch(() => undefined)\n return Object.freeze({ legacy, report, result })\n }\n\n async run(input: AgentInput, rawOptions?: RuntimeAgentInvocationOptions): Promise<RuntimeAgentResponse> {\n const options = captureInvocationOptions(rawOptions, this.host.selection)\n const handle = this.stream(input, options)\n try {\n for await (const event of handle) {\n if (options.onEvent !== undefined) {\n try { await this.observe(options.onEvent, event, handle) }\n catch (error) {\n handle.abort()\n const report = await handle.report\n throw runtimeFailure(error, report, 'RUN_EVENT_OBSERVER_FAILED')\n }\n }\n }\n } catch (error) { if (codeOf(error) === 'RUN_EVENT_OBSERVER_FAILED') throw error; return await handle.result }\n return await handle.result\n }\n\n inject(input: AgentInput): number {\n this.host.operations.assertActive()\n this.assertOwnerActive()\n // A run in flight is the case steering exists for. The underlying session\n // holds the message until the round that could not see it has finished,\n // then delivers it in arrival order. Refusing here left the runtime\n // surface unable to steer at all, while the same call on a bare session\n // (and injectForTeam below) is accepted.\n return this.session.inject(input)\n }\n\n private injectForTeam(input: Parameters<TeamSessionPort['inject']>[0]): number {\n this.host.operations.assertActive()\n this.assertOwnerActive()\n return this.session.inject(input)\n }\n\n snapshot(): RuntimeAgentSessionSnapshot { return this.session.snapshot() }\n\n compact(rawOptions?: RuntimeAgentInvocationOptions): Promise<CompactionResult | null> {\n const options = captureInvocationOptions(rawOptions, this.host.selection)\n const operation = this.beginOperation()\n let pending: Promise<CompactionResult | null>\n try {\n pending = this.host.operations.execute('manual-compaction', {\n ...(this.ownerSignal === undefined\n ? options.signal === undefined ? {} : { signal: options.signal }\n : { signal: options.signal === undefined ? this.ownerSignal : AbortSignal.any([options.signal, this.ownerSignal]) }),\n }, async lease => {\n const outcome = await compactRuntimeSession(this.session, { signal: lease.signal, ...modelOverlay(options) })\n const record = createRunTerminalRecord(outcome.report)\n const terminal = await this.host.observation.checkpointTerminal(record, lease.signal)\n const report = finalizeRuntimeRunReport(record, outcome.report.delivery, terminal,\n this.host.observation.mode, this.host.observation.requiredBoundary)\n if (outcome.failure !== undefined) throw runtimeFailure(\n outcome.failure,\n report,\n report.errors.at(-1)?.code ?? codeOf(outcome.failure),\n )\n return outcome.result === null ? null : Object.freeze({ ...outcome.result, status: 'completed' as const, report })\n })\n } catch (error) { this.finishOperation(operation); throw error }\n return pending.finally(() => this.finishOperation(operation))\n }\n\n reset(): void {\n this.host.operations.assertActive()\n this.assertOwnerActive()\n if (this.active !== undefined) throw new Error('Cannot reset while a runtime session is active')\n this.session.reset()\n }\n\n whenIdle(signal?: AbortSignal): Promise<void> {\n const pending = this.active?.done\n if (pending === undefined) return Promise.resolve()\n if (signal?.aborted) return Promise.reject(new AgentSdkError('Runtime idle wait was aborted', 'RUNTIME_OPERATION_ABORTED'))\n return new Promise((resolve, reject) => {\n let release = (): void => undefined\n const finish = (error?: Error): void => { release(); error === undefined ? resolve() : reject(error) }\n if (signal !== undefined) release = this.host.resources.onAbort(signal,\n () => finish(new AgentSdkError('Runtime idle wait was aborted', 'RUNTIME_OPERATION_ABORTED')))\n void pending.then(() => finish())\n })\n }\n\n private async runPendingForTeam(invocation: {\n readonly signal?: AbortSignal\n readonly onEvent?: (event: AgentRunEvent) => void | Promise<void>\n }): Promise<unknown> {\n const started = this.start(undefined, {\n ...(invocation.signal === undefined ? {} : { signal: invocation.signal }),\n })\n try {\n for await (const event of started.legacy) await invocation.onEvent?.(event)\n } catch (error) {\n started.legacy.abort()\n await started.result.catch(() => undefined)\n throw error\n }\n return await started.result\n }\n\n private beginOperation(): SessionOperation {\n this.assertOwnerActive()\n if (this.active !== undefined) throw new Error('Cannot start while a runtime session is active')\n let resolve!: () => void\n const operation: SessionOperation = { done: new Promise(done => { resolve = done }), resolve }\n this.active = operation\n return operation\n }\n\n private finishOperation(operation: SessionOperation): void {\n if (this.active !== operation) return\n this.active = undefined\n operation.resolve()\n }\n\n private assertOwnerActive(): void {\n if (this.ownerSignal?.aborted === true) {\n throw new AgentSdkError('Runtime team session is closed', 'TEAM_CLOSED')\n }\n }\n\n private async runtimeReport(\n legacy: Promise<RunReport>,\n sourceSnapshots: Promise<readonly ToolSourceRunReference[]>,\n signal: AbortSignal,\n ): Promise<RuntimeRunReport> {\n const [previous, sources] = await Promise.all([legacy, sourceSnapshots])\n const record = createRunTerminalRecord(previous, sources)\n const terminal = await this.host.observation.checkpointTerminal(record, signal)\n return finalizeRuntimeRunReport(record, previous.delivery, terminal,\n this.host.observation.mode, this.host.observation.requiredBoundary)\n }\n\n private async runtimeResult(\n legacy: Promise<Awaited<LegacyRunHandle['result']>>,\n report: Promise<RuntimeRunReport>,\n output: () => JsonValue | undefined,\n ): Promise<RuntimeAgentResponse> {\n try {\n const response = await legacy\n const final = await report\n if (final.status !== 'success') {\n throw runtimeFailure(undefined, final, final.errors.at(-1)?.code ?? 'AGENT_RUN_FAILED')\n }\n const parsedOutput = output()\n return Object.freeze({ runId: final.runId, traceId: final.traceId,\n completed: response.outcome.completed, stopReason: response.outcome.reason.kind,\n text: response.text, ...(parsedOutput === undefined ? {} : { output: parsedOutput }),\n ...(response.message === undefined ? {} : { message: publicMessage(response.message) }),\n usage: final.usage, report: final })\n } catch (error) {\n const final = await report\n throw runtimeFailure(error, final, codeOf(error))\n }\n }\n\n private async observe(\n observer: NonNullable<RuntimeAgentInvocationOptions['onEvent']>,\n event: RuntimeAgentRunEvent,\n handle: RuntimeAgentRunHandle,\n ): Promise<void> {\n const deadlineAt = this.host.resources.platform.monotonicNow() + this.observerTimeoutMs\n try { await atDeadline(this.host.resources, deadlineAt, () => observer(event), undefined) }\n catch { handle.abort(); throw new AgentSdkError('Runtime event observer did not complete', 'RUN_EVENT_OBSERVER_FAILED') }\n }\n}\n\nfunction createRuntimeSession(\n host: RuntimeAgentHost,\n definition: BoundRuntimeAgentDefinition,\n options: RuntimeAgentSessionOptions = {},\n snapshot?: RuntimeAgentSessionSnapshot,\n team?: AgentTeamMemberOptions,\n ownerSignal?: AbortSignal,\n): RuntimeAgentSessionValue {\n host.operations.assertActive()\n options = captureRuntimeSessionOptions(options)\n assertAgentIdentitySnapshot({\n tools: [...definition.legacy.tools, ...options.tools ?? []],\n nativeTools: definition.legacy.nativeTools,\n skills: [...definition.legacy.skills, ...options.skills ?? []] as never,\n ...(definition.legacy.skillIds === undefined ? {} : { allowedSkillIds: definition.legacy.skillIds }),\n })\n const memory = options.memory === false ? undefined : options.memory ?? definition.memory\n if (snapshot !== undefined) validateMemoryResumeBinding(snapshot, memory)\n const toolSources = combineToolSources(definition.toolSources, options.toolSources ?? [])\n const limits = options.runtimeLimits\n const { maxSteps: _maxSteps, maxToolCalls: _maxToolCalls, ...agentRuntimeLimits } = limits ?? {}\n const selected = limits?.maxSteps === undefined && limits?.maxToolCalls === undefined\n ? definition.legacy : definition.legacy.with({\n ...(limits.maxSteps === undefined ? {} : { maxTurns: limits.maxSteps }),\n ...(limits.maxToolCalls === undefined ? {} : { maxToolCalls: limits.maxToolCalls }),\n })\n const shared = { registry: host.registry, observation: host.observation, observationResource: host.resource,\n ...(options.tools === undefined ? {} : { tools: options.tools }),\n ...(options.skills === undefined ? {} : { skills: options.skills as never }),\n ...(options.skillCwd === undefined ? {} : { skillCwd: options.skillCwd }),\n ...(options.userInput === undefined ? {} : { userInput: options.userInput }),\n ...(options.approvals === undefined ? {} : { approvals: options.approvals }),\n ...(options.spillStore === undefined ? {} : { spillStore: options.spillStore }),\n ...(options.experimentalPrograms === undefined ? {} : { experimentalPrograms: options.experimentalPrograms }),\n ...(options.interceptors === undefined ? {} : { interceptors: options.interceptors }),\n ...(options.contextSections === undefined ? {} : { contextSections: options.contextSections }),\n ...(options.hooks === undefined ? {} : { hooks: options.hooks }),\n ...(options.usagePolicy === undefined ? {} : { usagePolicy: options.usagePolicy }),\n ...(options.historyLimits === undefined ? {} : { historyLimits: options.historyLimits }),\n ...(options.ledgerLimits === undefined ? {} : { ledgerLimits: options.ledgerLimits }),\n ...(options.eventBufferLimits === undefined ? {} : { eventBufferLimits: options.eventBufferLimits }),\n ...(options.compaction === undefined ? {} : { compaction: options.compaction }),\n ...(team === undefined ? {} : { team }),\n ...(Object.keys(agentRuntimeLimits).length === 0 ? {} : { runtimeLimits: agentRuntimeLimits }),\n }\n const session = snapshot === undefined\n ? selected.createSession({ ...shared, ...(options.conversationId === undefined ? {} : { conversationId: options.conversationId }) })\n : selected.resumeSession({ ...shared, snapshot })\n configureRuntimeSessionModel(session, { provider: definition.model.provider, model: definition.model.id,\n ...(definition.effort === undefined ? {} : { reasoningEffort: definition.effort }),\n ...(definition.maxTokens === undefined ? {} : { maxTokens: definition.maxTokens }),\n logger: correlation => host.observation.correlatedLogger(correlation, { scope: 'sdk.agent.run' }),\n ...(toolSources.length === 0 ? {} : {\n prepareTools: (signal, logger, occupiedNames) => snapshotToolSources(\n toolSources, signal, logger, occupiedNames,\n ),\n }),\n ...(memory === undefined ? {} : {\n memory: createRuntimeMemoryPersistence(\n memory,\n definition.legacy.id,\n agentRuntimeLimits.memoryOperationTimeoutMs,\n ),\n }),\n })\n return new RuntimeAgentSessionValue(\n host, session, definition.model.provider, definition.legacy.id, limits?.observerTimeoutMs, ownerSignal,\n )\n}\n\n/** Project one captured invocation onto the low-level per-run model overlay. */\nfunction modelOverlay(options: CapturedInvocationOptions): {\n readonly model?: { readonly provider: string; readonly model: string }\n readonly maxTokens?: number\n} {\n return {\n ...(options.model === undefined ? {} : { model: { provider: options.model.provider, model: options.model.id } }),\n ...(options.maxTokens === undefined ? {} : { maxTokens: options.maxTokens }),\n }\n}\n\ninterface SessionOperation {\n readonly done: Promise<void>\n readonly resolve: () => void\n}\n\ninterface StartedRuntimeRun {\n readonly legacy: RuntimeSessionRunHandle\n readonly report: Promise<RuntimeRunReport>\n readonly result: Promise<RuntimeAgentResponse>\n}\n\nfunction combineToolSources(\n defined: readonly CapturedToolSource[],\n additional: readonly CapturedToolSource[],\n): readonly CapturedToolSource[] {\n const all = [...defined, ...additional]\n const seen = new Map<string, number>()\n for (const [index, source] of all.entries()) {\n const first = seen.get(source.id)\n if (first !== undefined) throw capabilityIdentityError(\n 'TOOL_SOURCE_ID_CONFLICT', 'tool-source-id', first, index,\n )\n seen.set(source.id, index)\n }\n return Object.freeze(all)\n}\n\nfunction runtimeHandle(\n source: LegacyRunHandle & { readonly traceId: string; abort(reason?: unknown): void },\n report: Promise<RuntimeRunReport>, result: Promise<RuntimeAgentResponse>, nativeProvider: string,\n includeTraceEvents: boolean,\n): RuntimeAgentRunHandle {\n let iterated = false\n return Object.freeze({ runId: source.runId, report, result, abort: () => source.abort(),\n [Symbol.asyncIterator](): AsyncIterator<RuntimeAgentRunEvent> {\n if (iterated) return (async function* () { throw new Error('A runtime run handle can only be iterated once') })()\n iterated = true\n return projectEvents(source, report, nativeProvider, includeTraceEvents)\n } })\n}\n\nasync function* projectEvents(\n source: LegacyRunHandle & { readonly traceId: string; abort(reason?: unknown): void },\n report: Promise<RuntimeRunReport>,\n nativeProvider: string,\n includeTraceEvents: boolean,\n): AsyncGenerator<RuntimeAgentRunEvent> {\n let sequence = 0, completed = false\n const context = () => ({ runId: source.runId, traceId: source.traceId, sequence: ++sequence, schemaVersion: 1 as const })\n try {\n for await (const event of source) {\n const projected = projectEvent(event, nativeProvider, includeTraceEvents)\n if (projected !== undefined) yield Object.freeze({ ...context(), ...projected }) as RuntimeAgentRunEvent\n }\n const terminal = await report\n if (terminal.status === 'success') {\n yield Object.freeze({ ...context(), type: 'usage', usage: terminal.usage, report: terminal })\n } else {\n const error = terminal.errors.at(-1) ?? fallbackError(terminal)\n yield Object.freeze({ ...context(), type: 'error', error, report: terminal })\n }\n completed = true\n } catch {\n const terminal = await report\n const error = terminal.errors.at(-1) ?? fallbackError(terminal)\n yield Object.freeze({ ...context(), type: 'error', error, report: terminal })\n completed = true\n } finally { if (!completed) source.abort() }\n}\n\ntype WithoutEventContext<T> = T extends unknown ? Omit<T, 'runId' | 'traceId' | 'sequence' | 'schemaVersion'> : never\ntype ProjectedEvent = WithoutEventContext<RuntimeAgentRunEvent>\n\nfunction projectEvent(event: AgentRunEvent, nativeProvider: string, includeTraceEvents: boolean): ProjectedEvent | undefined {\n if (event.type === 'usage-progress') return { type: 'usage-progress', usage: event.usage,\n ...(event.attemptId === undefined ? {} : { attemptId: event.attemptId }) }\n // Runtime consumers such as Edge hosts may persist an execution trace. Keep\n // the SDK's span lifecycle intact; unlike transcript events, spans carry the\n // identity and nesting needed to reconstruct the call tree.\n if (includeTraceEvents && (event.type === 'span-start' || event.type === 'span-end')) return event\n if (event.type === 'text-delta') return {\n type: event.phase === 'commentary' ? 'commentary-delta' : 'assistant-delta',\n text: event.text, index: event.index, phase: event.phase, blockId: `${event.trace.spanId}:${event.index}`,\n }\n if (event.type === 'assistant-message') return { type: 'assistant-message', message: publicMessage(event.message) }\n if (event.type === 'text-end' || event.type === 'reasoning-delta') {\n const { trace, ...content } = event\n return { ...content, blockId: `${trace.spanId}:${event.index}` }\n }\n if (event.type === 'image-delta') {\n const { trace, ...content } = event\n return { ...content, blockId: `${trace.spanId}:${event.itemId}` }\n }\n if (event.type === 'compaction-start' || event.type === 'compaction-end'\n || event.type === 'turn-start' || event.type === 'step-start' || event.type === 'step-end'\n || event.type === 'assistant-text' || event.type === 'assistant-reasoning') {\n const { trace: _trace, ...content } = event\n return content\n }\n if (event.type === 'tool-call') return { type: 'tool-call', callId: event.call.callId,\n name: event.call.toolName, input: parseInput(event.call.rawArguments) }\n if (event.type === 'tool-result') return { type: 'tool-result', callId: event.call.callId,\n name: event.call.toolName, status: toolResultStatus(event.result), output: event.result }\n if (event.type === 'assistant-native-tool') return projectNativeToolEvent(event.call, nativeProvider)\n if (event.type === 'approval-request') return { type: 'approval-request', request: event.request }\n if (event.type === 'user-input-request') return { type: 'user-input-request', request: event.request }\n if (event.type === 'user-input-response') return { type: 'user-input-response', requestId: event.request.requestId,\n response: event.response }\n return undefined\n}\n\nfunction toolResultStatus(\n result: ToolExecutionResult,\n): 'completed' | 'failed' | 'aborted' | 'rejected' | 'declined' {\n // A call the loop refused to run is neither success nor failure: nothing\n // broke, and nothing was done. Reporting it as either misleads a UI — and a\n // red row for a budget decision is what makes a finished run look crashed.\n if (!result.isError) return result.meta?.['declined'] === true ? 'declined' : 'completed'\n if (result.error.code === TOOL_ERROR_CODES.ABORTED\n || result.error.code === TOOL_ERROR_CODES.ABORTED_BEFORE_DISPATCH) return 'aborted'\n if (result.error.code === TOOL_ERROR_CODES.UNKNOWN_TOOL\n || result.error.code === TOOL_ERROR_CODES.INVALID_ARGUMENTS\n || result.error.code === TOOL_ERROR_CODES.MALFORMED_ARGUMENTS\n || result.error.code === TOOL_ERROR_CODES.DENIED\n || result.error.code === TOOL_ERROR_CODES.BUDGET_EXHAUSTED\n || result.error.code === TOOL_ERROR_CODES.CHECKPOINT_FAILED) return 'rejected'\n return 'failed'\n}\n\nfunction parseInput(value: string): unknown { try { return JSON.parse(value) as unknown } catch { return value } }\nfunction codeOf(value: unknown): string {\n return value instanceof AgentSdkError ? value.code : 'AGENT_RUN_FAILED'\n}\nfunction runtimeFailure(value: unknown, report: RuntimeRunReport, code: string): AgentRunError {\n return inheritCapabilityIdentityConflict(\n new AgentRunError('Agent run did not complete', code, report as never), value,\n )\n}\nfunction fallbackError(report: RuntimeRunReport): RuntimeRunReport['errors'][number] {\n return Object.freeze({ code: 'AGENT_RUN_FAILED', stage: 'agent-run', message: 'Agent operation failed',\n usageCoverage: report.usage.coverage,\n possiblyBilledAttemptsWithoutUsage: report.usage.coverage.possiblyBilledAttemptsWithoutUsage })\n}\n"],"mappings":"0zCA8DA,MAAM,EAAuB,IAAI,QAEjC,SAAgB,EAAmB,EAAwB,EAAuD,CAChH,IAAM,EAAQ,OAAO,OAAO,CAC1B,MAAO,EAAW,MAClB,SAAS,EAAmB,EAAyC,CAAE,OAAO,EAAqB,EAAM,CAAU,CAAC,CAAC,IAAI,EAAO,CAAO,CAAE,EACzI,OAAO,EAAmB,EAAyC,CAAE,OAAO,EAAqB,EAAM,CAAU,CAAC,CAAC,OAAO,EAAO,CAAO,CAAE,EAC1I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sB,MAAO,CAAE,KAAM,qBAAsB,QAAS,EAAM,OAAQ,EACrG,GAAI,EAAM,OAAS,sBAAuB,MAAO,CAAE,KAAM,sBAAuB,UAAW,EAAM,QAAQ,UACvG,SAAU,EAAM,QAAS,CAE7B,CAEA,SAAS,EACP,EAC8D,CAa9D,OATK,EAAO,QACR,EAAO,MAAM,OAAS,EAAiB,SACtC,EAAO,MAAM,OAAS,EAAiB,wBAAgC,UACxE,EAAO,MAAM,OAAS,EAAiB,cACtC,EAAO,MAAM,OAAS,EAAiB,mBACvC,EAAO,MAAM,OAAS,EAAiB,qBACvC,EAAO,MAAM,OAAS,EAAiB,QACvC,EAAO,MAAM,OAAS,EAAiB,kBACvC,EAAO,MAAM,OAAS,EAAiB,kBAA0B,WAC/D,SATqB,EAAO,MAAO,WAAgB,GAAO,WAAa,WAUhF,CAEA,SAAS,EAAW,EAAwB,CAAE,GAAI,CAAE,OAAO,KAAK,MAAM,CAAK,CAAa,MAAQ,CAAE,OAAO,CAAM,CAAE,CACjH,SAAS,EAAO,EAAwB,CACtC,OAAO,aAAiB,EAAgB,EAAM,KAAO,kBACvD,CACA,SAAS,EAAe,EAAgB,EAA0B,EAA6B,CAC7F,OAAO,EACL,IAAI,EAAc,6BAA8B,EAAM,CAAe,EAAG,CAC1E,CACF,CACA,SAAS,EAAc,EAA8D,CACnF,OAAO,OAAO,OAAO,CAAE,KAAM,mBAAoB,MAAO,YAAa,QAAS,yBAC5E,cAAe,EAAO,MAAM,SAC5B,mCAAoC,EAAO,MAAM,SAAS,kCAAmC,CAAC,CAClG"}
@@ -11,6 +11,7 @@ import { ApprovalBroker, ApprovalRequest } from "../../agent/tool/approval.js";
11
11
  import { ToolInterceptor } from "../../agent/tool/pipeline.js";
12
12
  import { RunLedgerLimits, UsagePolicy } from "../../agent/accounting/report.js";
13
13
  import { StreamedAssistantTextPhase, TurnEndReason, TurnHooks } from "../../agent/loop/events.js";
14
+ import { ExperimentalProgramGrant } from "../../agent/tool/nested.js";
14
15
  import { ContextSection } from "../../agent/context/types.js";
15
16
  import { UserInputBroker, UserInputDecision, UserInputRequest } from "../../agent/mode/user-input.js";
16
17
  import { AgentRunEvent } from "../../agent/mode/run-agent.js";
@@ -91,6 +92,11 @@ interface RuntimeAgentSessionOptions {
91
92
  * truncate, and gives the model `read_tool_output` to read the rest back.
92
93
  */
93
94
  readonly spillStore?: SpillStore;
95
+ /**
96
+ * Experimental: program tools and the tools each may call. Off by default.
97
+ * Child calls spend this turn's tool budget and never enter model history.
98
+ */
99
+ readonly experimentalPrograms?: readonly ExperimentalProgramGrant[];
94
100
  readonly interceptors?: readonly ToolInterceptor[];
95
101
  /**
96
102
  * Model-visible context recomputed before every model round.
@@ -1 +1 @@
1
- {"version":3,"file":"types.d.ts","names":[],"sources":["../../../src/composition/agent/types.ts"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;UAyBiB;WACN;WACA;WACA;WACA,OAAO;WACP;WACA;WACA;;WAEA;;WAEA,2BAA2B;WAC3B;WACA,iBAAiB;WACjB,uBAAuB;WACvB,aAAa;WACb,eAAe;WACf,uBAAuB;WACvB,kBAAkB;WAClB;WACA,SAAS;;;;;;;;WAQT,2BAA2B;WAC3B,aAAa;;WAEb;WACA;WACA;;WAEA;aACE,UAAU,SAAS;aACnB,OAAO,SAAS;;;UAIZ,+BAA+B;UAE/B,iCAAiC,KAAK;WAC5C;aAAmB;aAA2B;;;UAGxC,2BAA2B;WACjC;WACA;;UAGM;WACN;WACA,iBAAiB;WACjB,uBAAuB;WACvB,kBAAkB;WAClB,SAAS;WACT;WACA,YAAY;WACZ,YAAY;;;;;;;WAOZ,aAAa;WACb,wBAAwB;;;;;;;WAOxB,2BAA2B;WAC3B,QAAQ;WACR,cAAc;;WAEd,gBAAgB;;WAEhB,eAAe;;WAEf,oBAAoB;WACpB,gBAAgB;WAChB,aAAa;;UAGP;;;;;;;;;;;;;;;;WAgBN;aAAmB;aAA2B;;;WAE9C;;WAEA;aACE;aACA,QAA2D,cAA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AO;WAAoC,QAAQ;;WAC3E;WAAiC,OAD0C;WAC0B;;WACrG;WAAwB,OAAO;WAA6C,QAAQ;;UAGlF;;WAEN;;WAEA,YAJM;WAKN;WACA;WACA;WACA,SAAS;WACT,UAAU;WACV,OAAO;WACP,QAAQ;;UAGF,8BAA8B,cAAc;WAClD;;WAEA,QAAQ,QAAQ;WAChB,QAAQ,QAAQ;EACzB,MAAM;;UAGS,oCAAoC;WAC1C;;UAGM;WACN;WACA;EACT,IAAI,OAAO,YAAY,UAAU,gCAAgC,QAAQ;EACzE,OAAO,OAAO,YAAY,UAAU,gCAAgC;EACpE,OAAO,OAAO;EACd,YAAY;EACZ,QAAQ,UAAU,gCAAgC,QAAQ;EAC1D;EACA,SAAS,SAAS,cAAc;;UAGjB;WACN,OAAO;EAChB,SAAS,OAAO,YAAY,UAAU,gCAAgC,QAAQ;EAC9E,OAAO,OAAO,YAAY,UAAU,gCAAgC;EACpE,cAAc,UAAU,6BAA6B;EACrD,cAAc,UAAU,6BAA6B,UAAU,6BAA6B"}
@@ -1,2 +1,2 @@
1
- import{AgentSdkError as e}from"../../errors/agent-sdk-error.js";import{boundedText as t,objectValue as n,ownData as r}from"../../capability/common/data.js";import{capabilityIdentityError as i,isCapabilityIdentityError as a}from"../../errors/capability-identity.js";import{beginCoreCapabilityOperation as o}from"../../platform/capability-operation.js";import{captureToolDefinitions as s}from"../../agent/tool/capture.js";import{TOOL_SOURCE_ERROR_CODES as c,TOOL_SOURCE_LIMITS as l}from"./config.js";function u(u,f,p,m=[]){let h=[],g=[],_=new Map(m.map((e,t)=>[e,t])),v=0;for(let y of u){let u=p.child({toolSourceId:y.id}),b=o(u,`core-tool-source`,`snapshot`);if(f.aborted)throw b.abort(),new e(`Tool source snapshot was aborted`,c.ABORTED);let x;try{x=y.snapshot({signal:f,logger:u})}catch(t){throw f.aborted?b.abort():b.fail(t),f.aborted?new e(`Tool source snapshot was aborted`,c.ABORTED,{cause:t}):new e(`Tool source snapshot failed`,c.SNAPSHOT_FAILED,{cause:t})}if(x instanceof Promise)throw x.catch(()=>void 0),b.fail(new e(`Tool source snapshot must be synchronous`,c.SNAPSHOT_INVALID)),new e(`Tool source snapshot must be synchronous`,c.SNAPSHOT_INVALID);try{let e=n(x),a=t(r(e,`revision`),l.revisionBytes),o=s(r(e,`tools`));if(h.length+o.length>l.catalogTools)throw TypeError(`Tool catalog count exceeds its bound`);if(v+=d(o),v>l.catalogBytes)throw TypeError(`Tool catalog bytes exceed their bound`);for(let e of o){let t=m.length+h.length,n=_.get(e.name);if(n!==void 0)throw i(c.NAME_CONFLICT,`tool-name`,n,t);_.set(e.name,t),h.push(e)}g.push(Object.freeze({sourceId:y.id,revision:a})),b.success()}catch(t){throw b.fail(t),a(t)?t:new e(`Tool source snapshot is invalid`,c.SNAPSHOT_INVALID)}}return Object.freeze({tools:Object.freeze(h),references:Object.freeze(g)})}function d(e){let t=e.map(e=>({name:e.name,description:e.description,parameters:e.parameters,...e.timeoutMs===void 0?{}:{timeoutMs:e.timeoutMs}}));return new TextEncoder().encode(JSON.stringify(t)).byteLength}export{u as snapshotToolSources};
1
+ import{AgentSdkError as e}from"../../errors/agent-sdk-error.js";import{captureToolDefinitions as t}from"../../agent/tool/capture.js";import{boundedText as n,objectValue as r,ownData as i}from"../../capability/common/data.js";import{capabilityIdentityError as a,isCapabilityIdentityError as o}from"../../errors/capability-identity.js";import{beginCoreCapabilityOperation as s}from"../../platform/capability-operation.js";import{TOOL_SOURCE_ERROR_CODES as c,TOOL_SOURCE_LIMITS as l}from"./config.js";function u(u,f,p,m=[]){let h=[],g=[],_=new Map(m.map((e,t)=>[e,t])),v=0;for(let y of u){let u=p.child({toolSourceId:y.id}),b=s(u,`core-tool-source`,`snapshot`);if(f.aborted)throw b.abort(),new e(`Tool source snapshot was aborted`,c.ABORTED);let x;try{x=y.snapshot({signal:f,logger:u})}catch(t){throw f.aborted?b.abort():b.fail(t),f.aborted?new e(`Tool source snapshot was aborted`,c.ABORTED,{cause:t}):new e(`Tool source snapshot failed`,c.SNAPSHOT_FAILED,{cause:t})}if(x instanceof Promise)throw x.catch(()=>void 0),b.fail(new e(`Tool source snapshot must be synchronous`,c.SNAPSHOT_INVALID)),new e(`Tool source snapshot must be synchronous`,c.SNAPSHOT_INVALID);try{let e=r(x),o=n(i(e,`revision`),l.revisionBytes),s=t(i(e,`tools`));if(h.length+s.length>l.catalogTools)throw TypeError(`Tool catalog count exceeds its bound`);if(v+=d(s),v>l.catalogBytes)throw TypeError(`Tool catalog bytes exceed their bound`);for(let e of s){let t=m.length+h.length,n=_.get(e.name);if(n!==void 0)throw a(c.NAME_CONFLICT,`tool-name`,n,t);_.set(e.name,t),h.push(e)}g.push(Object.freeze({sourceId:y.id,revision:o})),b.success()}catch(t){throw b.fail(t),o(t)?t:new e(`Tool source snapshot is invalid`,c.SNAPSHOT_INVALID)}}return Object.freeze({tools:Object.freeze(h),references:Object.freeze(g)})}function d(e){let t=e.map(e=>({name:e.name,description:e.description,parameters:e.parameters,...e.timeoutMs===void 0?{}:{timeoutMs:e.timeoutMs}}));return new TextEncoder().encode(JSON.stringify(t)).byteLength}export{u as snapshotToolSources};
2
2
  //# sourceMappingURL=snapshot.js.map
package/dist/index.d.ts CHANGED
@@ -48,6 +48,7 @@ import { AgentInput } from "./agent/define/session/types.js";
48
48
  import { MemoryBinding, MemoryCommitInput, MemoryCommitResult, MemoryLoadResult, MemoryScope, MemoryStore, MemoryStoreDefinition, MemoryStoreOptions } from "./agent/memory/persistence-types.js";
49
49
  import { estimateContextTokens, estimateMessageTokens } from "./agent/memory/token-estimator.js";
50
50
  import { selectCompactablePrefix } from "./agent/memory/surface-compaction.js";
51
+ import { ContextMilestone, ContextOptimizationMetrics, ContextOptimizerOptions, createContextOptimizer } from "./agent/memory/context-optimizer.js";
51
52
  import { RuntimeSchema, defineToolFromSchema } from "./agent/tool/schema.js";
52
53
  import { ToolExecutionBackend, ToolExecutionCapabilities, ToolExecutionRequest, ToolExecutionStore, ToolOperation, ToolOperationClaim, createToolExecutionInterceptor, localToolExecutionBackend } from "./agent/tool/execution.js";
53
54
  import { RuntimeProviderInfo } from "./composition/provider/types.js";
@@ -70,4 +71,4 @@ import { defineMemoryStore } from "./composition/memory/definition.js";
70
71
  import { defineSkillProviderPlugin } from "./agent/skill/provider/definition.js";
71
72
  import { defineObservationExporter } from "./composition/exporter/definition.js";
72
73
  import { CONTEXT_SECTION_ID_PATTERN, CONTEXT_SECTION_INVALID, MAX_CONTEXT_SECTION_TEXT_BYTES, defineContextSection } from "./agent/context/section.js";
73
- export { type A2AMessageSource, APP_IDENTITY, type ActivatedSkillSnapshot, type AdapterRegistrationHandle, type AgentCompactionConfig, type AgentCompactionOptions, type AgentDefinition, type AgentDefinitionInput, type AgentDefinitionOverrides, type AgentInput, AgentMemory, type AgentMemoryConfig, type AgentMemoryConfigInput, type AgentMemoryItem, type AgentMemoryKind, type AgentMemorySeed, type AgentMemorySnapshot, type AgentMessageSource, type AgentRuntime, type AgentRuntimeOptions, AgentSdkError, type AgentSkillOptions, type AgentTeamMemberInput, type AlwaysRetryPolicyConfig, type ApiKeyCheck, type ApiKeyRejection, type AppIdentity, type ApprovalBroker, type ApprovalDecision, type ApprovalRequest, type ApprovalStateStore, type AssistantMessage, type AssistantProvenance, type AssistantTextPhase, type AttemptUsageReport, type BackoffConfig, BlockAssembler, type Branded, COMPACTION_INSTRUCTION, CONTEXT_SECTION_ID_PATTERN, CONTEXT_SECTION_INVALID, CONTEXT_WINDOW_EXCEEDED_CODE, type CallConfig, type CallConfigAdapterDefaults, type CapabilityIdentityConflict, type CaptureReceipt, type CloneAgentOverrides, type CompactionResult, type ContentBlock, type ContentBlockMap, type ContentBlockType, ContextCompactor, type ContextCompactorOptions, type ContextSection, type ContextSectionResolveInput, type ContextSectionScope, type ContextSectionState, type ContextToolTouch, type CorrelationContext, type DefinedAgent, type DeliveryMode, type DiagnosticSnapshot, type DispatchState, type DocumentBlock, type DocumentMediaType, type DocumentSource, EMPTY_RESPONSE_CODE, type EmbeddingManyResult, type EmbeddingModelHandle, type EmbeddingModelOptions, type EmbeddingResult, type EmbeddingUsageReport, type EndProviderAttemptInput, type FinishReason, type FinishReasonMap, type GenerateOptions, INVALID_CREDENTIAL_CODE, type ImageBlock, type ImageDetail, type ImageMediaType, type ImageSource, type InteractiveApprovalBroker, type InteractiveApprovalBrokerOptions, type InteractiveUserInputBroker, type InteractiveUserInputBrokerOptions, type JsonObject, type JsonSchemaOutputFormat, type JsonValue, type LogLevel, MAX_CONTEXT_SECTION_TEXT_BYTES, MAX_SKILL_DESCRIPTION_CHARS, MAX_SKILL_ID_CHARS, MAX_SKILL_INSTRUCTIONS_CHARS, MAX_SKILL_NAME_CHARS, MAX_SKILL_RESOURCE_CHARS, MAX_SKILL_RESOURCE_PATH_CHARS, MAX_TIMER_DELAY_MS, MEMORY_ERROR_CODES, MEMORY_STORE_API_VERSION, MISSING_CREDENTIAL_CODE, MODEL_ERROR_CODES, type MemoryBinding, type MemoryCommitInput, type MemoryCommitResult, type MemoryLoadResult, type MemoryScope, type MemoryStore, type MemoryStoreDefinition, type MemoryStoreOptions, type Message, MessageId, type MessageSource, type MessageSourceMap, ModelAdapter, type ModelCallHandle, ModelCallObservationError, type ModelCallReport, type ModelCatalogOptions, type ModelCatalogSnapshot, type ModelCatalogState, type ModelContext, ModelError, type ModelErrorOptions, type ModelFailure, type ModelInfo, type ModelInvocationContext, type ModelMessageSource, type ModelModality, type ModelModalityMap, type ModelOutputFormat, type ModelProviderPlugin, type ModelProviderRegistrar, type ModelReasoningInfo, ModelRegistry, type ModelRegistryOptions, type ModelToolSchema, NOOP_OBSERVATION_PORT, type NativeImageGenerationTool, type NativeToolCallBlock, type NativeToolName, type NativeToolSchema, type NativeToolSchemaMap, type NativeWebSearchTool, type NormalRetryPolicyConfig, OBSERVATION_ERROR_CODES, OBSERVATION_EXPORTER_API_VERSION, type ObservationBoundary, type ObservationDeliveryAck, type ObservationDeliveryBatch, type ObservationDeliverySummary, type ObservationEvent, type ObservationEventName, type ObservationExportItem, type ObservationExporterPlugin, type ObservationExporterPluginDefinition, type ObservationPhase, type ObservationPort, type ObservationPriority, type ObservationResource, type ObservationResourceInput, type ObservationRunScope, type ObservationSpan, type ObservationSpanName, type OpenObservationSpanInput, type OperationStatus, PLUGIN_ERROR_CODES, PluginError, type PluginRegistrationHandle, type PreparedAdapterCall, type PreparedCall, type ProviderAttemptHandle, type ProviderInfo, ProviderRequestId, type ProviderRetryScheduledInput, QUOTA_EXCEEDED_CODE, REGISTRY_ERROR_CODES, type ReasoningBlock, ReasoningEffortId, type ReasoningEffortInfo, type ReplayEnvelope, type ResolvedAgentSkillOptions, type ResolvedAlwaysRetryPolicy, type ResolvedModelInfo, type ResolvedNormalRetryPolicy, type ResolvedRetryBackoff, type ResolvedRetryPolicy, type RetryAttempt, type RetryPolicyConfig, type RunReport, type RunTerminalRecord, type RuntimeAgent, type RuntimeAgentBindingInput, type RuntimeAgentDefinition, type RuntimeAgentDefinitionInput, type RuntimeAgentInvocationOptions, type RuntimeAgentLimits, type RuntimeAgentResponse, type RuntimeAgentRunEvent, type RuntimeAgentRunEventContext, type RuntimeAgentRunHandle, type RuntimeAgentSession, type RuntimeAgentSessionOptions, type RuntimeAgentSessionSnapshot, type RuntimeAgentTeam, type RuntimeAgentTeamEvent, type RuntimeAgentTeamOptions, type RuntimeCloseReport, type RuntimeDefaults, type RuntimeModelCatalogSnapshot, type RuntimeObservationExporterRegistration, type RuntimeObservationResourceInput, type RuntimeOwnerObservabilityOptions, type RuntimeProviderInfo, type RuntimeSchema, type RuntimeSkillCandidate, type RuntimeSkillLookupOptions, type RuntimeSkillSource, SDK_VERSION, SKILL_ERROR_CODES, SKILL_ID_PATTERN, SKILL_PROVIDER_API_VERSION, SKILL_TOOL_NAMES, type SafeErrorRecord, type SdkLogger, type SkillCandidate, SkillCatalog, type SkillCatalogOptions, type SkillCatalogSnapshot, type SkillDefinition, type SkillDefinitionInput, type SkillInvocationPolicy, type SkillLookupOptions, type SkillProvider, type SkillProviderDefinition, type SkillProviderListOptions, type SkillProviderPlugin, type SkillProviderPluginDefinition, type SkillReference, type SkillResourceBase, type SkillResourceSummary, type SkillSource, type SkillSummary, type SpanId, type StartProviderAttemptInput, type StreamChunk, type StreamMiddleware, type SupportSafeError, type TextAnnotation, type TextAnnotationMap, type TextBlock, type TextOutputFormat, type TokenUsage, type ToolCallBlock, ToolCallId, type ToolChoice, type ToolDefinition, type ToolExecutionBackend, type ToolExecutionCapabilities, type ToolExecutionRequest, type ToolExecutionStore, type ToolMessageSource, type ToolOperation, type ToolOperationClaim, type ToolResultBlock, type ToolResultMessage, type ToolResultMessageInput, type ToolRunContext, type ToolSchema, type TraceId, type UrlCitationAnnotation, type UsageAdditionResult, type UsageCounters, type UsageCoverage, type UsageValidationResult, type UserInputAnswer, type UserInputBroker, type UserInputDecision, type UserInputOption, type UserInputQuestion, type UserInputRequest, type UserInputResponse, type UserMessage, type WebSearchLocation, type WithRetryOptions, addUsageCounters, assertNever, assertUsableApiKey, attributionHeaders, backoffDelayMs, callConfigEquals, classifyUsageCoverage, cloneAgent, contentHasDocument, contentHasImage, createAgentRuntime, createApprovalBroker, createApprovalRequest, createAssistantMessage, createCoreSpan, createMessage, createObservationRunScope, createOperationId, createSkillTools, createSpanId, createTextMessage, createToolExecutionInterceptor, createToolResultMessage, createTraceId, createUserInputBroker, createUserMessage, deepFreeze, defineAgent, defineContextSection, defineMemoryStore, defineObservationExporter, defineSkill, defineSkillProvider, defineSkillProviderPlugin, defineTool, defineToolFromSchema, detachedFrozen, disabledDeliverySummary, errorChain, estimateContextTokens, estimateMessageTokens, fixedApprovalBroker, fixedUserInputBroker, freezeCorrelation, freezeMessage, hasUsageCounters, isAgentSdkError, isContextWindowExceededError, isJsonValue, isNativeToolSchema, isQuotaExceededError, isRetryable, isSpanId, isTraceId, localToolExecutionBackend, normalizeApiKey, normalizeModelFailure, possiblyBilledAttemptsWithoutUsage, projectDocumentsForTextModel, projectImagesForTextModel, renderSkillCatalog, resolveCompactionConfig, resolveMemoryConfig, resolveRetryPolicy, resolveSkillOptions, safeErrorRecord, selectCompactablePrefix, snapshotObservationSpan, textOnlyDocumentText, textOnlyImageText, traceparent, userAgent, validObservationSpan, validateCandidate, validateCaptureReceipt, validateSkillId, validateSkillResourcePath, validateSkillSource, validateUsageCounters, waitForSettlement, withApprovalPersistence, withIdleTimeout, withRetry };
74
+ export { type A2AMessageSource, APP_IDENTITY, type ActivatedSkillSnapshot, type AdapterRegistrationHandle, type AgentCompactionConfig, type AgentCompactionOptions, type AgentDefinition, type AgentDefinitionInput, type AgentDefinitionOverrides, type AgentInput, AgentMemory, type AgentMemoryConfig, type AgentMemoryConfigInput, type AgentMemoryItem, type AgentMemoryKind, type AgentMemorySeed, type AgentMemorySnapshot, type AgentMessageSource, type AgentRuntime, type AgentRuntimeOptions, AgentSdkError, type AgentSkillOptions, type AgentTeamMemberInput, type AlwaysRetryPolicyConfig, type ApiKeyCheck, type ApiKeyRejection, type AppIdentity, type ApprovalBroker, type ApprovalDecision, type ApprovalRequest, type ApprovalStateStore, type AssistantMessage, type AssistantProvenance, type AssistantTextPhase, type AttemptUsageReport, type BackoffConfig, BlockAssembler, type Branded, COMPACTION_INSTRUCTION, CONTEXT_SECTION_ID_PATTERN, CONTEXT_SECTION_INVALID, CONTEXT_WINDOW_EXCEEDED_CODE, type CallConfig, type CallConfigAdapterDefaults, type CapabilityIdentityConflict, type CaptureReceipt, type CloneAgentOverrides, type CompactionResult, type ContentBlock, type ContentBlockMap, type ContentBlockType, ContextCompactor, type ContextCompactorOptions, type ContextMilestone, type ContextOptimizationMetrics, type ContextOptimizerOptions, type ContextSection, type ContextSectionResolveInput, type ContextSectionScope, type ContextSectionState, type ContextToolTouch, type CorrelationContext, type DefinedAgent, type DeliveryMode, type DiagnosticSnapshot, type DispatchState, type DocumentBlock, type DocumentMediaType, type DocumentSource, EMPTY_RESPONSE_CODE, type EmbeddingManyResult, type EmbeddingModelHandle, type EmbeddingModelOptions, type EmbeddingResult, type EmbeddingUsageReport, type EndProviderAttemptInput, type FinishReason, type FinishReasonMap, type GenerateOptions, INVALID_CREDENTIAL_CODE, type ImageBlock, type ImageDetail, type ImageMediaType, type ImageSource, type InteractiveApprovalBroker, type InteractiveApprovalBrokerOptions, type InteractiveUserInputBroker, type InteractiveUserInputBrokerOptions, type JsonObject, type JsonSchemaOutputFormat, type JsonValue, type LogLevel, MAX_CONTEXT_SECTION_TEXT_BYTES, MAX_SKILL_DESCRIPTION_CHARS, MAX_SKILL_ID_CHARS, MAX_SKILL_INSTRUCTIONS_CHARS, MAX_SKILL_NAME_CHARS, MAX_SKILL_RESOURCE_CHARS, MAX_SKILL_RESOURCE_PATH_CHARS, MAX_TIMER_DELAY_MS, MEMORY_ERROR_CODES, MEMORY_STORE_API_VERSION, MISSING_CREDENTIAL_CODE, MODEL_ERROR_CODES, type MemoryBinding, type MemoryCommitInput, type MemoryCommitResult, type MemoryLoadResult, type MemoryScope, type MemoryStore, type MemoryStoreDefinition, type MemoryStoreOptions, type Message, MessageId, type MessageSource, type MessageSourceMap, ModelAdapter, type ModelCallHandle, ModelCallObservationError, type ModelCallReport, type ModelCatalogOptions, type ModelCatalogSnapshot, type ModelCatalogState, type ModelContext, ModelError, type ModelErrorOptions, type ModelFailure, type ModelInfo, type ModelInvocationContext, type ModelMessageSource, type ModelModality, type ModelModalityMap, type ModelOutputFormat, type ModelProviderPlugin, type ModelProviderRegistrar, type ModelReasoningInfo, ModelRegistry, type ModelRegistryOptions, type ModelToolSchema, NOOP_OBSERVATION_PORT, type NativeImageGenerationTool, type NativeToolCallBlock, type NativeToolName, type NativeToolSchema, type NativeToolSchemaMap, type NativeWebSearchTool, type NormalRetryPolicyConfig, OBSERVATION_ERROR_CODES, OBSERVATION_EXPORTER_API_VERSION, type ObservationBoundary, type ObservationDeliveryAck, type ObservationDeliveryBatch, type ObservationDeliverySummary, type ObservationEvent, type ObservationEventName, type ObservationExportItem, type ObservationExporterPlugin, type ObservationExporterPluginDefinition, type ObservationPhase, type ObservationPort, type ObservationPriority, type ObservationResource, type ObservationResourceInput, type ObservationRunScope, type ObservationSpan, type ObservationSpanName, type OpenObservationSpanInput, type OperationStatus, PLUGIN_ERROR_CODES, PluginError, type PluginRegistrationHandle, type PreparedAdapterCall, type PreparedCall, type ProviderAttemptHandle, type ProviderInfo, ProviderRequestId, type ProviderRetryScheduledInput, QUOTA_EXCEEDED_CODE, REGISTRY_ERROR_CODES, type ReasoningBlock, ReasoningEffortId, type ReasoningEffortInfo, type ReplayEnvelope, type ResolvedAgentSkillOptions, type ResolvedAlwaysRetryPolicy, type ResolvedModelInfo, type ResolvedNormalRetryPolicy, type ResolvedRetryBackoff, type ResolvedRetryPolicy, type RetryAttempt, type RetryPolicyConfig, type RunReport, type RunTerminalRecord, type RuntimeAgent, type RuntimeAgentBindingInput, type RuntimeAgentDefinition, type RuntimeAgentDefinitionInput, type RuntimeAgentInvocationOptions, type RuntimeAgentLimits, type RuntimeAgentResponse, type RuntimeAgentRunEvent, type RuntimeAgentRunEventContext, type RuntimeAgentRunHandle, type RuntimeAgentSession, type RuntimeAgentSessionOptions, type RuntimeAgentSessionSnapshot, type RuntimeAgentTeam, type RuntimeAgentTeamEvent, type RuntimeAgentTeamOptions, type RuntimeCloseReport, type RuntimeDefaults, type RuntimeModelCatalogSnapshot, type RuntimeObservationExporterRegistration, type RuntimeObservationResourceInput, type RuntimeOwnerObservabilityOptions, type RuntimeProviderInfo, type RuntimeSchema, type RuntimeSkillCandidate, type RuntimeSkillLookupOptions, type RuntimeSkillSource, SDK_VERSION, SKILL_ERROR_CODES, SKILL_ID_PATTERN, SKILL_PROVIDER_API_VERSION, SKILL_TOOL_NAMES, type SafeErrorRecord, type SdkLogger, type SkillCandidate, SkillCatalog, type SkillCatalogOptions, type SkillCatalogSnapshot, type SkillDefinition, type SkillDefinitionInput, type SkillInvocationPolicy, type SkillLookupOptions, type SkillProvider, type SkillProviderDefinition, type SkillProviderListOptions, type SkillProviderPlugin, type SkillProviderPluginDefinition, type SkillReference, type SkillResourceBase, type SkillResourceSummary, type SkillSource, type SkillSummary, type SpanId, type StartProviderAttemptInput, type StreamChunk, type StreamMiddleware, type SupportSafeError, type TextAnnotation, type TextAnnotationMap, type TextBlock, type TextOutputFormat, type TokenUsage, type ToolCallBlock, ToolCallId, type ToolChoice, type ToolDefinition, type ToolExecutionBackend, type ToolExecutionCapabilities, type ToolExecutionRequest, type ToolExecutionStore, type ToolMessageSource, type ToolOperation, type ToolOperationClaim, type ToolResultBlock, type ToolResultMessage, type ToolResultMessageInput, type ToolRunContext, type ToolSchema, type TraceId, type UrlCitationAnnotation, type UsageAdditionResult, type UsageCounters, type UsageCoverage, type UsageValidationResult, type UserInputAnswer, type UserInputBroker, type UserInputDecision, type UserInputOption, type UserInputQuestion, type UserInputRequest, type UserInputResponse, type UserMessage, type WebSearchLocation, type WithRetryOptions, addUsageCounters, assertNever, assertUsableApiKey, attributionHeaders, backoffDelayMs, callConfigEquals, classifyUsageCoverage, cloneAgent, contentHasDocument, contentHasImage, createAgentRuntime, createApprovalBroker, createApprovalRequest, createAssistantMessage, createContextOptimizer, createCoreSpan, createMessage, createObservationRunScope, createOperationId, createSkillTools, createSpanId, createTextMessage, createToolExecutionInterceptor, createToolResultMessage, createTraceId, createUserInputBroker, createUserMessage, deepFreeze, defineAgent, defineContextSection, defineMemoryStore, defineObservationExporter, defineSkill, defineSkillProvider, defineSkillProviderPlugin, defineTool, defineToolFromSchema, detachedFrozen, disabledDeliverySummary, errorChain, estimateContextTokens, estimateMessageTokens, fixedApprovalBroker, fixedUserInputBroker, freezeCorrelation, freezeMessage, hasUsageCounters, isAgentSdkError, isContextWindowExceededError, isJsonValue, isNativeToolSchema, isQuotaExceededError, isRetryable, isSpanId, isTraceId, localToolExecutionBackend, normalizeApiKey, normalizeModelFailure, possiblyBilledAttemptsWithoutUsage, projectDocumentsForTextModel, projectImagesForTextModel, renderSkillCatalog, resolveCompactionConfig, resolveMemoryConfig, resolveRetryPolicy, resolveSkillOptions, safeErrorRecord, selectCompactablePrefix, snapshotObservationSpan, textOnlyDocumentText, textOnlyImageText, traceparent, userAgent, validObservationSpan, validateCandidate, validateCaptureReceipt, validateSkillId, validateSkillResourcePath, validateSkillSource, validateUsageCounters, waitForSettlement, withApprovalPersistence, withIdleTimeout, withRetry };
package/dist/index.js CHANGED
@@ -1 +1 @@
1
- import{MessageId as e,ProviderRequestId as t,ReasoningEffortId as n,ToolCallId as r}from"./primitives/brand.js";import{deepFreeze as i}from"./primitives/freeze.js";import{isJsonValue as a}from"./primitives/json.js";import{assertNever as o}from"./primitives/never.js";import{detachedFrozen as s}from"./primitives/snapshot.js";import{SDK_VERSION as c}from"./primitives/version.js";import{waitForSettlement as l}from"./async/settlement.js";import{createObservationRunScope as u,createOperationId as d,createSpanId as f,createTraceId as p,freezeCorrelation as m,isSpanId as h,isTraceId as g,traceparent as _}from"./observation/context.js";import{safeErrorRecord as v}from"./observation/event.js";import{NOOP_OBSERVATION_PORT as y,createCoreSpan as b,disabledDeliverySummary as x,snapshotObservationSpan as S,validObservationSpan as C,validateCaptureReceipt as w}from"./observation/port.js";import{AgentSdkError as T,CONTEXT_WINDOW_EXCEEDED_CODE as E,EMPTY_RESPONSE_CODE as D,INVALID_CREDENTIAL_CODE as O,MISSING_CREDENTIAL_CODE as k,QUOTA_EXCEEDED_CODE as A,errorChain as j,isAgentSdkError as M,isContextWindowExceededError as N,isQuotaExceededError as P}from"./errors/agent-sdk-error.js";import{ModelCallObservationError as F,OBSERVATION_ERROR_CODES as I}from"./observation/report.js";import{addUsageCounters as L,classifyUsageCoverage as R,hasUsageCounters as z,possiblyBilledAttemptsWithoutUsage as B,validateUsageCounters as V}from"./observation/usage.js";import{PLUGIN_ERROR_CODES as H,PluginError as U}from"./plugin/provider-plugin.js";import{MODEL_ERROR_CODES as W,ModelError as G,REGISTRY_ERROR_CODES as K}from"./errors/model-error.js";import{normalizeModelFailure as q}from"./errors/failure.js";import{createAssistantMessage as J,createMessage as Y,createTextMessage as X,createToolResultMessage as Z,createUserMessage as Q,freezeMessage as $}from"./message/message.js";import{contentHasDocument as ee,contentHasImage as te,projectDocumentsForTextModel as ne,projectImagesForTextModel as re,textOnlyDocumentText as ie,textOnlyImageText as ae}from"./message/projection.js";import{BlockAssembler as oe}from"./stream/assembler.js";import{withIdleTimeout as se}from"./stream/idle-timeout.js";import{ModelAdapter as ce}from"./contract/adapter.js";import{callConfigEquals as le}from"./contract/call-config.js";import{MAX_TIMER_DELAY_MS as ue,backoffDelayMs as de,isRetryable as fe,resolveRetryPolicy as pe}from"./contract/retry-policy.js";import{isNativeToolSchema as me}from"./contract/tool.js";import{ModelRegistry as he}from"./runtime/registry.js";import{withRetry as ge}from"./runtime/with-retry.js";import{assertUsableApiKey as _e,normalizeApiKey as ve}from"./http/api-key.js";import{APP_IDENTITY as ye,attributionHeaders as be,userAgent as xe}from"./http/attribution.js";import{AgentMemory as Se,resolveMemoryConfig as Ce}from"./agent/memory/memory.js";import{estimateContextTokens as we,estimateMessageTokens as Te}from"./agent/memory/token-estimator.js";import{selectCompactablePrefix as Ee}from"./agent/memory/surface-compaction.js";import{COMPACTION_INSTRUCTION as De,ContextCompactor as Oe}from"./agent/memory/compaction.js";import{resolveCompactionConfig as ke}from"./agent/memory/compaction-config.js";import{MEMORY_ERROR_CODES as Ae,MEMORY_STORE_API_VERSION as je}from"./composition/memory/config.js";import{defineMemoryStore as Me}from"./composition/memory/definition.js";import{MAX_SKILL_DESCRIPTION_CHARS as Ne,MAX_SKILL_ID_CHARS as Pe,MAX_SKILL_INSTRUCTIONS_CHARS as Fe,MAX_SKILL_NAME_CHARS as Ie,MAX_SKILL_RESOURCE_CHARS as Le,MAX_SKILL_RESOURCE_PATH_CHARS as Re,SKILL_ID_PATTERN as ze,defineSkill as Be,defineSkillProvider as Ve,validateCandidate as He,validateSkillId as Ue,validateSkillResourcePath as We,validateSkillSource as Ge}from"./agent/skill/definition.js";import{SKILL_ERROR_CODES as Ke,SKILL_PROVIDER_API_VERSION as qe}from"./agent/skill/provider/config.js";import{defineSkillProviderPlugin as Je}from"./agent/skill/provider/definition.js";import{SkillCatalog as Ye}from"./agent/skill/catalog.js";import{defineTool as Xe}from"./agent/tool/definition.js";import{SKILL_TOOL_NAMES as Ze,createSkillTools as Qe,renderSkillCatalog as $e,resolveSkillOptions as et}from"./agent/skill/tools.js";import{OBSERVATION_EXPORTER_API_VERSION as tt}from"./composition/exporter/types.js";import{CONTEXT_SECTION_ID_PATTERN as nt,CONTEXT_SECTION_INVALID as rt,MAX_CONTEXT_SECTION_TEXT_BYTES as it,defineContextSection as at}from"./agent/context/section.js";import{createApprovalBroker as ot,createApprovalRequest as st,fixedApprovalBroker as ct,withApprovalPersistence as lt}from"./agent/tool/approval.js";import{createAgentRuntime as ut}from"./composition/runtime/public.js";import{cloneAgent as dt,defineAgent as ft}from"./composition/agent/author.js";import{defineObservationExporter as pt}from"./composition/exporter/definition.js";import{createUserInputBroker as mt,fixedUserInputBroker as ht}from"./agent/mode/user-input.js";import{defineToolFromSchema as gt}from"./agent/tool/schema.js";import{createToolExecutionInterceptor as _t,localToolExecutionBackend as vt}from"./agent/tool/execution.js";export{ye as APP_IDENTITY,Se as AgentMemory,T as AgentSdkError,oe as BlockAssembler,De as COMPACTION_INSTRUCTION,nt as CONTEXT_SECTION_ID_PATTERN,rt as CONTEXT_SECTION_INVALID,E as CONTEXT_WINDOW_EXCEEDED_CODE,Oe as ContextCompactor,D as EMPTY_RESPONSE_CODE,O as INVALID_CREDENTIAL_CODE,it as MAX_CONTEXT_SECTION_TEXT_BYTES,Ne as MAX_SKILL_DESCRIPTION_CHARS,Pe as MAX_SKILL_ID_CHARS,Fe as MAX_SKILL_INSTRUCTIONS_CHARS,Ie as MAX_SKILL_NAME_CHARS,Le as MAX_SKILL_RESOURCE_CHARS,Re as MAX_SKILL_RESOURCE_PATH_CHARS,ue as MAX_TIMER_DELAY_MS,Ae as MEMORY_ERROR_CODES,je as MEMORY_STORE_API_VERSION,k as MISSING_CREDENTIAL_CODE,W as MODEL_ERROR_CODES,e as MessageId,ce as ModelAdapter,F as ModelCallObservationError,G as ModelError,he as ModelRegistry,y as NOOP_OBSERVATION_PORT,I as OBSERVATION_ERROR_CODES,tt as OBSERVATION_EXPORTER_API_VERSION,H as PLUGIN_ERROR_CODES,U as PluginError,t as ProviderRequestId,A as QUOTA_EXCEEDED_CODE,K as REGISTRY_ERROR_CODES,n as ReasoningEffortId,c as SDK_VERSION,Ke as SKILL_ERROR_CODES,ze as SKILL_ID_PATTERN,qe as SKILL_PROVIDER_API_VERSION,Ze as SKILL_TOOL_NAMES,Ye as SkillCatalog,r as ToolCallId,L as addUsageCounters,o as assertNever,_e as assertUsableApiKey,be as attributionHeaders,de as backoffDelayMs,le as callConfigEquals,R as classifyUsageCoverage,dt as cloneAgent,ee as contentHasDocument,te as contentHasImage,ut as createAgentRuntime,ot as createApprovalBroker,st as createApprovalRequest,J as createAssistantMessage,b as createCoreSpan,Y as createMessage,u as createObservationRunScope,d as createOperationId,Qe as createSkillTools,f as createSpanId,X as createTextMessage,_t as createToolExecutionInterceptor,Z as createToolResultMessage,p as createTraceId,mt as createUserInputBroker,Q as createUserMessage,i as deepFreeze,ft as defineAgent,at as defineContextSection,Me as defineMemoryStore,pt as defineObservationExporter,Be as defineSkill,Ve as defineSkillProvider,Je as defineSkillProviderPlugin,Xe as defineTool,gt as defineToolFromSchema,s as detachedFrozen,x as disabledDeliverySummary,j as errorChain,we as estimateContextTokens,Te as estimateMessageTokens,ct as fixedApprovalBroker,ht as fixedUserInputBroker,m as freezeCorrelation,$ as freezeMessage,z as hasUsageCounters,M as isAgentSdkError,N as isContextWindowExceededError,a as isJsonValue,me as isNativeToolSchema,P as isQuotaExceededError,fe as isRetryable,h as isSpanId,g as isTraceId,vt as localToolExecutionBackend,ve as normalizeApiKey,q as normalizeModelFailure,B as possiblyBilledAttemptsWithoutUsage,ne as projectDocumentsForTextModel,re as projectImagesForTextModel,$e as renderSkillCatalog,ke as resolveCompactionConfig,Ce as resolveMemoryConfig,pe as resolveRetryPolicy,et as resolveSkillOptions,v as safeErrorRecord,Ee as selectCompactablePrefix,S as snapshotObservationSpan,ie as textOnlyDocumentText,ae as textOnlyImageText,_ as traceparent,xe as userAgent,C as validObservationSpan,He as validateCandidate,w as validateCaptureReceipt,Ue as validateSkillId,We as validateSkillResourcePath,Ge as validateSkillSource,V as validateUsageCounters,l as waitForSettlement,lt as withApprovalPersistence,se as withIdleTimeout,ge as withRetry};
1
+ import{MessageId as e,ProviderRequestId as t,ReasoningEffortId as n,ToolCallId as r}from"./primitives/brand.js";import{deepFreeze as i}from"./primitives/freeze.js";import{isJsonValue as a}from"./primitives/json.js";import{assertNever as o}from"./primitives/never.js";import{detachedFrozen as s}from"./primitives/snapshot.js";import{SDK_VERSION as c}from"./primitives/version.js";import{waitForSettlement as l}from"./async/settlement.js";import{createObservationRunScope as u,createOperationId as d,createSpanId as f,createTraceId as p,freezeCorrelation as m,isSpanId as h,isTraceId as g,traceparent as _}from"./observation/context.js";import{safeErrorRecord as v}from"./observation/event.js";import{NOOP_OBSERVATION_PORT as y,createCoreSpan as b,disabledDeliverySummary as x,snapshotObservationSpan as S,validObservationSpan as C,validateCaptureReceipt as w}from"./observation/port.js";import{AgentSdkError as T,CONTEXT_WINDOW_EXCEEDED_CODE as E,EMPTY_RESPONSE_CODE as D,INVALID_CREDENTIAL_CODE as O,MISSING_CREDENTIAL_CODE as k,QUOTA_EXCEEDED_CODE as A,errorChain as j,isAgentSdkError as M,isContextWindowExceededError as N,isQuotaExceededError as P}from"./errors/agent-sdk-error.js";import{ModelCallObservationError as F,OBSERVATION_ERROR_CODES as I}from"./observation/report.js";import{addUsageCounters as L,classifyUsageCoverage as R,hasUsageCounters as z,possiblyBilledAttemptsWithoutUsage as B,validateUsageCounters as V}from"./observation/usage.js";import{PLUGIN_ERROR_CODES as H,PluginError as U}from"./plugin/provider-plugin.js";import{MODEL_ERROR_CODES as W,ModelError as G,REGISTRY_ERROR_CODES as K}from"./errors/model-error.js";import{normalizeModelFailure as q}from"./errors/failure.js";import{createAssistantMessage as J,createMessage as Y,createTextMessage as X,createToolResultMessage as Z,createUserMessage as Q,freezeMessage as $}from"./message/message.js";import{contentHasDocument as ee,contentHasImage as te,projectDocumentsForTextModel as ne,projectImagesForTextModel as re,textOnlyDocumentText as ie,textOnlyImageText as ae}from"./message/projection.js";import{BlockAssembler as oe}from"./stream/assembler.js";import{withIdleTimeout as se}from"./stream/idle-timeout.js";import{ModelAdapter as ce}from"./contract/adapter.js";import{callConfigEquals as le}from"./contract/call-config.js";import{MAX_TIMER_DELAY_MS as ue,backoffDelayMs as de,isRetryable as fe,resolveRetryPolicy as pe}from"./contract/retry-policy.js";import{isNativeToolSchema as me}from"./contract/tool.js";import{ModelRegistry as he}from"./runtime/registry.js";import{withRetry as ge}from"./runtime/with-retry.js";import{assertUsableApiKey as _e,normalizeApiKey as ve}from"./http/api-key.js";import{APP_IDENTITY as ye,attributionHeaders as be,userAgent as xe}from"./http/attribution.js";import{AgentMemory as Se,resolveMemoryConfig as Ce}from"./agent/memory/memory.js";import{estimateContextTokens as we,estimateMessageTokens as Te}from"./agent/memory/token-estimator.js";import{selectCompactablePrefix as Ee}from"./agent/memory/surface-compaction.js";import{COMPACTION_INSTRUCTION as De,ContextCompactor as Oe}from"./agent/memory/compaction.js";import{resolveCompactionConfig as ke}from"./agent/memory/compaction-config.js";import{defineTool as Ae}from"./agent/tool/definition.js";import{createContextOptimizer as je}from"./agent/memory/context-optimizer.js";import{MEMORY_ERROR_CODES as Me,MEMORY_STORE_API_VERSION as Ne}from"./composition/memory/config.js";import{defineMemoryStore as Pe}from"./composition/memory/definition.js";import{MAX_SKILL_DESCRIPTION_CHARS as Fe,MAX_SKILL_ID_CHARS as Ie,MAX_SKILL_INSTRUCTIONS_CHARS as Le,MAX_SKILL_NAME_CHARS as Re,MAX_SKILL_RESOURCE_CHARS as ze,MAX_SKILL_RESOURCE_PATH_CHARS as Be,SKILL_ID_PATTERN as Ve,defineSkill as He,defineSkillProvider as Ue,validateCandidate as We,validateSkillId as Ge,validateSkillResourcePath as Ke,validateSkillSource as qe}from"./agent/skill/definition.js";import{SKILL_ERROR_CODES as Je,SKILL_PROVIDER_API_VERSION as Ye}from"./agent/skill/provider/config.js";import{defineSkillProviderPlugin as Xe}from"./agent/skill/provider/definition.js";import{SkillCatalog as Ze}from"./agent/skill/catalog.js";import{SKILL_TOOL_NAMES as Qe,createSkillTools as $e,renderSkillCatalog as et,resolveSkillOptions as tt}from"./agent/skill/tools.js";import{OBSERVATION_EXPORTER_API_VERSION as nt}from"./composition/exporter/types.js";import{CONTEXT_SECTION_ID_PATTERN as rt,CONTEXT_SECTION_INVALID as it,MAX_CONTEXT_SECTION_TEXT_BYTES as at,defineContextSection as ot}from"./agent/context/section.js";import{createApprovalBroker as st,createApprovalRequest as ct,fixedApprovalBroker as lt,withApprovalPersistence as ut}from"./agent/tool/approval.js";import{createAgentRuntime as dt}from"./composition/runtime/public.js";import{cloneAgent as ft,defineAgent as pt}from"./composition/agent/author.js";import{defineObservationExporter as mt}from"./composition/exporter/definition.js";import{createUserInputBroker as ht,fixedUserInputBroker as gt}from"./agent/mode/user-input.js";import{defineToolFromSchema as _t}from"./agent/tool/schema.js";import{createToolExecutionInterceptor as vt,localToolExecutionBackend as yt}from"./agent/tool/execution.js";export{ye as APP_IDENTITY,Se as AgentMemory,T as AgentSdkError,oe as BlockAssembler,De as COMPACTION_INSTRUCTION,rt as CONTEXT_SECTION_ID_PATTERN,it as CONTEXT_SECTION_INVALID,E as CONTEXT_WINDOW_EXCEEDED_CODE,Oe as ContextCompactor,D as EMPTY_RESPONSE_CODE,O as INVALID_CREDENTIAL_CODE,at as MAX_CONTEXT_SECTION_TEXT_BYTES,Fe as MAX_SKILL_DESCRIPTION_CHARS,Ie as MAX_SKILL_ID_CHARS,Le as MAX_SKILL_INSTRUCTIONS_CHARS,Re as MAX_SKILL_NAME_CHARS,ze as MAX_SKILL_RESOURCE_CHARS,Be as MAX_SKILL_RESOURCE_PATH_CHARS,ue as MAX_TIMER_DELAY_MS,Me as MEMORY_ERROR_CODES,Ne as MEMORY_STORE_API_VERSION,k as MISSING_CREDENTIAL_CODE,W as MODEL_ERROR_CODES,e as MessageId,ce as ModelAdapter,F as ModelCallObservationError,G as ModelError,he as ModelRegistry,y as NOOP_OBSERVATION_PORT,I as OBSERVATION_ERROR_CODES,nt as OBSERVATION_EXPORTER_API_VERSION,H as PLUGIN_ERROR_CODES,U as PluginError,t as ProviderRequestId,A as QUOTA_EXCEEDED_CODE,K as REGISTRY_ERROR_CODES,n as ReasoningEffortId,c as SDK_VERSION,Je as SKILL_ERROR_CODES,Ve as SKILL_ID_PATTERN,Ye as SKILL_PROVIDER_API_VERSION,Qe as SKILL_TOOL_NAMES,Ze as SkillCatalog,r as ToolCallId,L as addUsageCounters,o as assertNever,_e as assertUsableApiKey,be as attributionHeaders,de as backoffDelayMs,le as callConfigEquals,R as classifyUsageCoverage,ft as cloneAgent,ee as contentHasDocument,te as contentHasImage,dt as createAgentRuntime,st as createApprovalBroker,ct as createApprovalRequest,J as createAssistantMessage,je as createContextOptimizer,b as createCoreSpan,Y as createMessage,u as createObservationRunScope,d as createOperationId,$e as createSkillTools,f as createSpanId,X as createTextMessage,vt as createToolExecutionInterceptor,Z as createToolResultMessage,p as createTraceId,ht as createUserInputBroker,Q as createUserMessage,i as deepFreeze,pt as defineAgent,ot as defineContextSection,Pe as defineMemoryStore,mt as defineObservationExporter,He as defineSkill,Ue as defineSkillProvider,Xe as defineSkillProviderPlugin,Ae as defineTool,_t as defineToolFromSchema,s as detachedFrozen,x as disabledDeliverySummary,j as errorChain,we as estimateContextTokens,Te as estimateMessageTokens,lt as fixedApprovalBroker,gt as fixedUserInputBroker,m as freezeCorrelation,$ as freezeMessage,z as hasUsageCounters,M as isAgentSdkError,N as isContextWindowExceededError,a as isJsonValue,me as isNativeToolSchema,P as isQuotaExceededError,fe as isRetryable,h as isSpanId,g as isTraceId,yt as localToolExecutionBackend,ve as normalizeApiKey,q as normalizeModelFailure,B as possiblyBilledAttemptsWithoutUsage,ne as projectDocumentsForTextModel,re as projectImagesForTextModel,et as renderSkillCatalog,ke as resolveCompactionConfig,Ce as resolveMemoryConfig,pe as resolveRetryPolicy,tt as resolveSkillOptions,v as safeErrorRecord,Ee as selectCompactablePrefix,S as snapshotObservationSpan,ie as textOnlyDocumentText,ae as textOnlyImageText,_ as traceparent,xe as userAgent,C as validObservationSpan,We as validateCandidate,w as validateCaptureReceipt,Ge as validateSkillId,Ke as validateSkillResourcePath,qe as validateSkillSource,V as validateUsageCounters,l as waitForSettlement,ut as withApprovalPersistence,se as withIdleTimeout,ge as withRetry};
package/dist/memory.d.ts CHANGED
@@ -5,6 +5,7 @@ import { AgentMemory, AgentMemoryConfig, AgentMemoryConfigInput, AgentMemoryItem
5
5
  import { MemoryBinding, MemoryCommitInput, MemoryCommitResult, MemoryLoadResult, MemoryScope, MemoryStore, MemoryStoreDefinition, MemoryStoreOptions } from "./agent/memory/persistence-types.js";
6
6
  import { estimateContextTokens, estimateMessageTokens } from "./agent/memory/token-estimator.js";
7
7
  import { selectCompactablePrefix } from "./agent/memory/surface-compaction.js";
8
+ import { ContextMilestone, ContextOptimizationMetrics, ContextOptimizerOptions, createContextOptimizer } from "./agent/memory/context-optimizer.js";
8
9
  import { MEMORY_ERROR_CODES, MEMORY_STORE_API_VERSION } from "./composition/memory/config.js";
9
10
  import { defineMemoryStore } from "./composition/memory/definition.js";
10
- export { type AgentCompactionConfig, type AgentCompactionOptions, AgentMemory, type AgentMemoryConfig, type AgentMemoryConfigInput, type AgentMemoryItem, type AgentMemoryKind, type AgentMemorySeed, type AgentMemorySnapshot, COMPACTION_INSTRUCTION, type CompactionResult, ContextCompactor, type ContextCompactorOptions, MEMORY_ERROR_CODES, MEMORY_STORE_API_VERSION, type MemoryBinding, type MemoryCommitInput, type MemoryCommitResult, type MemoryLoadResult, type MemoryScope, type MemoryStore, type MemoryStoreDefinition, type MemoryStoreOptions, type SdkLogger, defineMemoryStore, estimateContextTokens, estimateMessageTokens, resolveCompactionConfig, resolveMemoryConfig, selectCompactablePrefix };
11
+ export { type AgentCompactionConfig, type AgentCompactionOptions, AgentMemory, type AgentMemoryConfig, type AgentMemoryConfigInput, type AgentMemoryItem, type AgentMemoryKind, type AgentMemorySeed, type AgentMemorySnapshot, COMPACTION_INSTRUCTION, type CompactionResult, ContextCompactor, type ContextCompactorOptions, type ContextMilestone, type ContextOptimizationMetrics, type ContextOptimizerOptions, MEMORY_ERROR_CODES, MEMORY_STORE_API_VERSION, type MemoryBinding, type MemoryCommitInput, type MemoryCommitResult, type MemoryLoadResult, type MemoryScope, type MemoryStore, type MemoryStoreDefinition, type MemoryStoreOptions, type SdkLogger, createContextOptimizer, defineMemoryStore, estimateContextTokens, estimateMessageTokens, resolveCompactionConfig, resolveMemoryConfig, selectCompactablePrefix };
package/dist/memory.js CHANGED
@@ -1 +1 @@
1
- import{AgentMemory as e,resolveMemoryConfig as t}from"./agent/memory/memory.js";import{estimateContextTokens as n,estimateMessageTokens as r}from"./agent/memory/token-estimator.js";import{selectCompactablePrefix as i}from"./agent/memory/surface-compaction.js";import{COMPACTION_INSTRUCTION as a,ContextCompactor as o}from"./agent/memory/compaction.js";import{resolveCompactionConfig as s}from"./agent/memory/compaction-config.js";import{MEMORY_ERROR_CODES as c,MEMORY_STORE_API_VERSION as l}from"./composition/memory/config.js";import{defineMemoryStore as u}from"./composition/memory/definition.js";export{e as AgentMemory,a as COMPACTION_INSTRUCTION,o as ContextCompactor,c as MEMORY_ERROR_CODES,l as MEMORY_STORE_API_VERSION,u as defineMemoryStore,n as estimateContextTokens,r as estimateMessageTokens,s as resolveCompactionConfig,t as resolveMemoryConfig,i as selectCompactablePrefix};
1
+ import{AgentMemory as e,resolveMemoryConfig as t}from"./agent/memory/memory.js";import{estimateContextTokens as n,estimateMessageTokens as r}from"./agent/memory/token-estimator.js";import{selectCompactablePrefix as i}from"./agent/memory/surface-compaction.js";import{COMPACTION_INSTRUCTION as a,ContextCompactor as o}from"./agent/memory/compaction.js";import{resolveCompactionConfig as s}from"./agent/memory/compaction-config.js";import{createContextOptimizer as c}from"./agent/memory/context-optimizer.js";import{MEMORY_ERROR_CODES as l,MEMORY_STORE_API_VERSION as u}from"./composition/memory/config.js";import{defineMemoryStore as d}from"./composition/memory/definition.js";export{e as AgentMemory,a as COMPACTION_INSTRUCTION,o as ContextCompactor,l as MEMORY_ERROR_CODES,u as MEMORY_STORE_API_VERSION,c as createContextOptimizer,d as defineMemoryStore,n as estimateContextTokens,r as estimateMessageTokens,s as resolveCompactionConfig,t as resolveMemoryConfig,i as selectCompactablePrefix};
@@ -1,2 +1,2 @@
1
- import{deepFreeze as e}from"../primitives/freeze.js";import"../primitives/version.js";import{createObservationRunScope as t,createOperationId as n}from"../observation/context.js";import{safeErrorRecord as r}from"../observation/event.js";import{createCoreSpan as i,snapshotObservationSpan as a}from"../observation/port.js";import{sanitizeObservationEvent as o,serializedEventBytes as s}from"../observation/privacy.js";import{createBusLogger as c}from"./logger.js";const l={none:0,"local-durable":1,"remote-acknowledged":2},u=new Set([`ABORT_ERR`,`ECONNREFUSED`,`ECONNRESET`,`EHOSTUNREACH`,`ENETUNREACH`,`ETIMEDOUT`,`OBSERVABILITY_EXPORT_FAILED`,`OBSERVABILITY_FLUSH_TIMEOUT`,`OBSERVABILITY_PROCESSOR_FAILED`,`OTEL_PROVIDER_UNCONFIGURED`]),d=/^[A-Za-z0-9](?:[A-Za-z0-9._-]{0,63})$/,f=new Set([`none`,`metadata`,`redacted`,`full`]),p=new Set([`trace`,`debug`,`info`,`warn`,`error`,`fatal`]);function m(e,t){if(!Number.isSafeInteger(e)||e<1)throw RangeError(`${t} must be a positive safe integer`);return e}function h(t,n){let i=r(t);return e({type:[`AbortError`,`Error`,`RangeError`,`TypeError`].includes(i.type)?i.type:`Error`,message:n,...i.code!==void 0&&u.has(i.code)?{code:i.code}:{},...i.retryable===void 0?{}:{retryable:i.retryable},...i.status===void 0?{}:{status:i.status}})}function g(e,t,n=`none`,r){return Object.freeze({eventId:e,status:t,durable:t===`accepted`&&n!==`none`,boundary:n,...r===void 0?{}:{reason:r}})}function _(e){try{let t=Reflect.get(e,`eventId`);return typeof t==`string`&&t.length>0?t:n()}catch{return n()}}function v(e){let t=`none`;for(let n of e)n.requirement===`required`&&l[n.boundary]>l[t]&&(t=n.boundary);return t}function y(e,t){let n=new Set;for(let r of t){let t=r.exporter?.id;if(typeof t!=`string`||!d.test(t))throw TypeError(`observation exporter id must be a safe 1-64 character identifier`);if(n.has(t))throw TypeError(`duplicate observation exporter id: ${t}`);if(n.add(t),r.requirement!==`required`&&r.requirement!==`best-effort`)throw TypeError(`observation exporter ${t} has an invalid requirement`);if(!(r.boundary in l))throw TypeError(`observation exporter ${t} has an invalid boundary`);let i=r.exporter.supportedBoundaries??[`none`];if(typeof r.exporter.export!=`function`)throw TypeError(`observation exporter ${t} has no export function`);if(!i.includes(r.boundary))throw TypeError(`observation exporter ${t} does not support ${r.boundary}`);if(e===`operational`&&r.requirement===`required`)throw TypeError(`operational observation exporters must be best-effort`)}if(e!==`operational`&&!t.some(e=>e.requirement===`required`&&e.boundary!==`none`))throw TypeError(`${e} observability requires a durable required exporter`);return Object.freeze(t.map(e=>Object.freeze({...e})))}function b(e,t){let n=new AbortController,r=setTimeout(()=>n.abort(new DOMException(`observation deadline exceeded`,`TimeoutError`)),e),i=()=>n.abort(t?.reason??new DOMException(`observation aborted`,`AbortError`));return t?.aborted===!0?i():t?.addEventListener(`abort`,i,{once:!0}),{signal:n.signal,clear(){clearTimeout(r),t?.removeEventListener(`abort`,i)}}}function x(e,t){return t.aborted?Promise.reject(t.reason??Error(`observation aborted`)):new Promise((n,r)=>{let i=()=>{a(),r(t.reason??Error(`observation aborted`))},a=()=>t.removeEventListener(`abort`,i);t.addEventListener(`abort`,i,{once:!0}),e.then(e=>{a(),n(e)},e=>{a(),r(e)})})}function S(e){try{let t=e.reason;return typeof t==`object`&&!!t&&Reflect.get(t,`name`)===`TimeoutError`}catch{return!1}}function C(e){return Object.freeze({complete:e.complete,exportedEvents:e.exportedEvents,pendingEvents:e.pendingEvents,rejectedCritical:e.rejectedCritical,timedOut:e.timedOut})}function w(e,t){return e.eventId===t.eventId&&e.sequence===t.sequence&&e.name===t.name&&e.phase===t.phase&&e.occurredAt===t.occurredAt&&e.monotonicMs===t.monotonicMs&&e.priority===t.priority&&JSON.stringify(e.resource)===JSON.stringify(t.resource)&&JSON.stringify(e.correlation)===JSON.stringify(t.correlation)}var T=class{mode;resource;registrations;processors;options;queue=[];queueBytes=0;closing=!1;closed=!1;shutdownPromise;flushChain=Promise.resolve();protectedFailures=new Set;healthScope=t();healthRunId=n();healthCorrelation=i({name:`sdk.integration.request`,runId:this.healthRunId,startedAt:new Date().toISOString(),monotonicMs:this.healthScope.monotonicMs()}).correlation;counters={accepted:0,exported:0,droppedVerbose:0,droppedNormal:0,criticalRejected:0,processorFailures:0,exporterFailures:0,flushTimeouts:0,requiredFailure:!1};constructor(t){if(this.mode=t.mode??`operational`,![`operational`,`reliable`,`audit`].includes(this.mode))throw TypeError(`invalid observation mode`);this.resource=e({sdkName:`ai-agent-sdk`,sdkVersion:t.resource?.sdkVersion??`0.1.4`,...t.resource?.serviceName===void 0?{}:{serviceName:t.resource.serviceName},...t.resource?.serviceVersion===void 0?{}:{serviceVersion:t.resource.serviceVersion},runtime:t.resource?.runtime??`unknown`}),this.registrations=y(this.mode,t.exporters??[]);let n=new Set;for(let e of t.processors??[]){if(typeof e.id!=`string`||!d.test(e.id))throw TypeError(`processor id must be a safe 1-64 character identifier`);if(n.has(e.id))throw TypeError(`duplicate observation processor id: ${e.id}`);if(typeof e.transform!=`function`)throw TypeError(`observation processor ${e.id} is invalid`);n.add(e.id)}if(this.processors=Object.freeze([...t.processors??[]]),!f.has(t.content??`none`))throw TypeError(`invalid observation content policy`);if(!p.has(t.minimumLogLevel??`info`))throw TypeError(`invalid minimum log level`);let r=new Set;for(let e of t.redactors??[]){if(typeof e.id!=`string`||!d.test(e.id)||typeof e.redact!=`function`)throw TypeError(`invalid observation content redactor`);if(r.has(e.id))throw TypeError(`duplicate observation redactor id: ${e.id}`);r.add(e.id)}this.options={content:t.content??`none`,includeErrorStacks:t.includeErrorStacks??!1,minimumLogLevel:t.minimumLogLevel??`info`,maxQueueEvents:m(t.maxQueueEvents??1e4,`maxQueueEvents`),maxQueueBytes:m(t.maxQueueBytes??16777216,`maxQueueBytes`),maxBatchEvents:m(t.maxBatchEvents??256,`maxBatchEvents`),maxBatchBytes:m(t.maxBatchBytes??524288,`maxBatchBytes`),flushTimeoutMs:m(t.flushTimeoutMs??1e4,`flushTimeoutMs`),shutdownTimeoutMs:m(t.shutdownTimeoutMs??3e4,`shutdownTimeoutMs`),redactors:Object.freeze([...t.redactors??[]]),...t.onHealthChange===void 0?{}:{onHealthChange:t.onHealthChange},...t.openSpan===void 0?{}:{openSpan:t.openSpan}}}openSpan(e){let t=this.options.openSpan;if(t===void 0)return i(e);try{let n=a(t(e));if(n!==void 0)return n;this.counters.processorFailures++,this.recordFailure(`span:invalid`,TypeError(`invalid span`),`observation span backend returned an invalid span`,!1)}catch(e){this.counters.processorFailures++,this.recordFailure(`span:throw`,e,`observation span backend failed`,!1)}return i(e)}capture(e){let t=_(e);if(this.closing||this.closed)return g(t,`rejected`,`none`,`closed`);let n;try{n=this.prepareEvent(e,!1)}catch(e){return this.counters.processorFailures++,this.counters.lastFailure=h(e,`observation processor failed`),this.notifyHealth(),this.recordFailure(`processor:capture`,e,`observation processor failed`,!0),g(t,`rejected`,`none`,`processor-failed`)}let r=this.enqueue(n,!1);return r.status===`accepted`?this.stageExporters(n,r):r}async checkpoint(e,t){let n=this.capture(e);if(n.status!==`accepted`||this.mode===`operational`)return n;let r=this.queue.find(e=>e.event.eventId===n.eventId)?.event;if(r===void 0)return g(n.eventId,`rejected`,`none`,`exporter-unavailable`);let i=new Set(this.queue.filter(e=>e.event.priority===`critical`&&e.event.correlation.runId===r.correlation.runId&&e.event.sequence<=r.sequence).map(e=>e.event.eventId));return(await this.scheduleFlush(i,this.options.flushTimeoutMs,t)).requiredComplete?g(n.eventId,`accepted`,v(this.registrations)):g(n.eventId,`rejected`,`none`,`exporter-unavailable`)}logger(e){return c({minimumLevel:this.options.minimumLogLevel,resource:this.resource,emit:e=>{this.capture(e)}},e)}health(){let t=this.closed?`closed`:this.counters.requiredFailure||this.counters.criticalRejected>0||this.counters.flushTimeouts>0?`failed`:this.counters.processorFailures>0||this.counters.exporterFailures>0||this.counters.droppedVerbose>0||this.counters.droppedNormal>0?`degraded`:`healthy`;return e({state:t,queuedEvents:this.queue.length,queuedBytes:this.queueBytes,accepted:this.counters.accepted,exported:this.counters.exported,droppedVerbose:this.counters.droppedVerbose,droppedNormal:this.counters.droppedNormal,criticalRejected:this.counters.criticalRejected,processorFailures:this.counters.processorFailures,exporterFailures:this.counters.exporterFailures,flushTimeouts:this.counters.flushTimeouts,...this.counters.lastExportAt===void 0?{}:{lastExportAt:this.counters.lastExportAt},...this.counters.lastFailure===void 0?{}:{lastFailure:this.counters.lastFailure}})}flush(e){if(this.closed||this.closing)throw TypeError(`observability is closed`);return this.scheduleFlush(new Set(this.queue.map(e=>e.event.eventId)),this.options.flushTimeoutMs,e).then(C)}shutdown(e){if(this.shutdownPromise!==void 0)return this.shutdownPromise;this.closing=!0;let t=new Set(this.queue.map(e=>e.event.eventId));return this.shutdownPromise=(async()=>{let n=b(this.options.shutdownTimeoutMs,e),r;try{r=C(await this.scheduleFlush(t,this.options.shutdownTimeoutMs,n.signal));for(let e of[...this.registrations].reverse()){let t=e.exporter.shutdown;if(t!==void 0)try{await x(Promise.resolve(t.call(e.exporter,n.signal)),n.signal)}catch(t){this.recordExporterFailure(e,t,!1),r=Object.freeze({...r,complete:!1})}}}finally{n.clear(),this.closed=!0,this.notifyHealth()}return r})(),this.shutdownPromise}prepareEvent(e,t){let n={content:this.options.content,redactors:this.options.redactors??[],includeErrorStacks:this.options.includeErrorStacks},r=o(e,n);if(t)return r;for(let e of this.processors){let t=e.transform(r);if(t===void 0)throw TypeError(`observation processor ${e.id} returned undefined`);let i=o(t,n);if(!w(r,i))throw TypeError(`observation processor ${e.id} changed the immutable event envelope`);r=i}return r}enqueue(e,t){let n=s(e);return n>this.options.maxBatchBytes||n>this.options.maxQueueBytes||!this.makeCapacity(n,t)?(!t&&e.priority===`critical`&&this.counters.criticalRejected++,t||(this.counters.lastFailure=h(RangeError(`capacity`),`observation queue capacity exhausted`),this.notifyHealth()),g(e.eventId,`rejected`,`none`,`capacity`)):(this.queue.push({event:e,bytes:n,protected:t,pending:new Set(this.registrations.map(e=>e.exporter.id))}),this.queueBytes+=n,this.counters.accepted++,this.notifyHealth(),g(e.eventId,`accepted`))}stageExporters(e,t){let n=this.queue.find(t=>t.event.eventId===e.eventId);if(n===void 0)return g(e.eventId,`rejected`,`none`,`exporter-unavailable`);let r=!1;for(let t of this.registrations){let i=t.exporter.stage;if(i!==void 0)try{let n=i.call(t.exporter,e);n!==void 0&&Promise.resolve(n).catch(()=>void 0)}catch(i){if(this.recordExporterFailure(t,i,!1),n.pending.delete(t.exporter.id),r=!0,t.requirement===`required`)return this.removeEntry(n,!1),e.priority===`critical`&&this.counters.criticalRejected++,this.notifyHealth(),g(e.eventId,`rejected`,`none`,`exporter-unavailable`)}}return r&&n.pending.size===0&&this.removeEntry(n,!1),t}makeCapacity(e,t){for(;this.queue.length+1>this.options.maxQueueEvents||this.queueBytes+e>this.options.maxQueueBytes;){let e=this.queue.findIndex(e=>e.event.priority===`verbose`);if(e===-1&&(e=this.queue.findIndex(e=>e.event.priority===`normal`)),e===-1)return!1;let[n]=this.queue.splice(e,1);if(n===void 0)return!1;this.queueBytes-=n.bytes,t||(n.event.priority===`verbose`?this.counters.droppedVerbose++:this.counters.droppedNormal++)}return!0}scheduleFlush(e,t,n){let r,i,a=new Promise((e,t)=>{r=e,i=t}),o=async()=>{try{r(await this.flushInternal(e,t,n))}catch(e){i(e)}};return this.flushChain=this.flushChain.then(o,o),a}async flushInternal(t,r,i){let a=this.counters.exported,o=b(r,i),s=!1,c=!1;try{if(this.registrations.length===0)for(let e of[...this.queue])t.has(e.event.eventId)&&this.removeEntry(e,!1);for(let r of this.registrations)for(;;){let i=this.queue.filter(e=>t.has(e.event.eventId)&&e.pending.has(r.exporter.id));if(i.length===0)break;let a=[],l=0;for(let e of i){if(a.length>=this.options.maxBatchEvents||l+e.bytes>this.options.maxBatchBytes)break;a.push(e),l+=e.bytes}if(a.length===0)break;let u=e({schemaVersion:1,batchId:n(),createdAt:new Date().toISOString(),events:a.map(e=>e.event)}),d;try{if(d=await x(Promise.resolve(r.exporter.export(u,o.signal)),o.signal),d.batchId!==u.batchId||d.accepted!==!0)throw TypeError(`observation exporter ${r.exporter.id} returned an invalid acknowledgment`)}catch(e){if(s=!0,c||=S(o.signal),this.recordExporterFailure(r,e,!0),r.requirement===`best-effort`)for(let e of a)e.pending.delete(r.exporter.id),e.pending.size===0&&this.removeEntry(e,!1);break}this.counters.lastExportAt=new Date().toISOString();for(let e of a)e.pending.delete(r.exporter.id),e.pending.size===0&&this.removeEntry(e,!0);this.notifyHealth()}}finally{S(o.signal)&&(c=!0,this.counters.flushTimeouts++,this.counters.lastFailure=h(o.signal.reason,`observation flush timed out`),this.notifyHealth()),o.clear()}let l=this.queue.filter(e=>t.has(e.event.eventId)),u=this.registrations.filter(e=>e.requirement===`required`).map(e=>e.exporter.id),d=l.every(e=>u.every(t=>!e.pending.has(t)));return Object.freeze({complete:!s&&!c&&l.length===0,requiredComplete:d,exportedEvents:this.counters.exported-a,pendingEvents:l.length,rejectedCritical:this.counters.criticalRejected,timedOut:c})}removeEntry(e,t){let n=this.queue.indexOf(e);n!==-1&&(this.queue.splice(n,1),this.queueBytes-=e.bytes,t&&this.counters.exported++)}recordExporterFailure(e,t,n){this.counters.exporterFailures++,e.requirement===`required`&&(this.counters.requiredFailure=!0),this.counters.lastFailure=h(t,`observation exporter failed`),this.notifyHealth(),n&&this.recordFailure(`exporter:${e.exporter.id}`,t,`observation exporter failed`,!0)}recordFailure(e,t,r,i){if(this.counters.lastFailure=h(t,r),this.notifyHealth(),!(!i||this.protectedFailures.has(e)||this.closing||this.closed)){this.protectedFailures.add(e);try{let t=this.prepareEvent({schemaVersion:1,eventId:n(),sequence:this.healthScope.nextSequence(),name:`sdk.observer.failure`,phase:`point`,occurredAt:new Date().toISOString(),monotonicMs:this.healthScope.monotonicMs(),priority:`critical`,resource:this.resource,correlation:this.healthCorrelation,data:{observerId:e,failureKind:`contained`,count:1,error:{...this.counters.lastFailure}}},!0);this.enqueue(t,!0)}catch{}}}notifyHealth(){let e=this.options.onHealthChange;if(e!==void 0)try{e(this.health())}catch{}}};function E(e={}){return new T(e)}export{E as createObservability};
1
+ import{deepFreeze as e}from"../primitives/freeze.js";import"../primitives/version.js";import{createObservationRunScope as t,createOperationId as n}from"../observation/context.js";import{safeErrorRecord as r}from"../observation/event.js";import{createCoreSpan as i,snapshotObservationSpan as a}from"../observation/port.js";import{sanitizeObservationEvent as o,serializedEventBytes as s}from"../observation/privacy.js";import{createBusLogger as c}from"./logger.js";const l={none:0,"local-durable":1,"remote-acknowledged":2},u=new Set([`ABORT_ERR`,`ECONNREFUSED`,`ECONNRESET`,`EHOSTUNREACH`,`ENETUNREACH`,`ETIMEDOUT`,`OBSERVABILITY_EXPORT_FAILED`,`OBSERVABILITY_FLUSH_TIMEOUT`,`OBSERVABILITY_PROCESSOR_FAILED`,`OTEL_PROVIDER_UNCONFIGURED`]),d=/^[A-Za-z0-9](?:[A-Za-z0-9._-]{0,63})$/,f=new Set([`none`,`metadata`,`redacted`,`full`]),p=new Set([`trace`,`debug`,`info`,`warn`,`error`,`fatal`]);function m(e,t){if(!Number.isSafeInteger(e)||e<1)throw RangeError(`${t} must be a positive safe integer`);return e}function h(t,n){let i=r(t);return e({type:[`AbortError`,`Error`,`RangeError`,`TypeError`].includes(i.type)?i.type:`Error`,message:n,...i.code!==void 0&&u.has(i.code)?{code:i.code}:{},...i.retryable===void 0?{}:{retryable:i.retryable},...i.status===void 0?{}:{status:i.status}})}function g(e,t,n=`none`,r){return Object.freeze({eventId:e,status:t,durable:t===`accepted`&&n!==`none`,boundary:n,...r===void 0?{}:{reason:r}})}function _(e){try{let t=Reflect.get(e,`eventId`);return typeof t==`string`&&t.length>0?t:n()}catch{return n()}}function v(e){let t=`none`;for(let n of e)n.requirement===`required`&&l[n.boundary]>l[t]&&(t=n.boundary);return t}function y(e,t){let n=new Set;for(let r of t){let t=r.exporter?.id;if(typeof t!=`string`||!d.test(t))throw TypeError(`observation exporter id must be a safe 1-64 character identifier`);if(n.has(t))throw TypeError(`duplicate observation exporter id: ${t}`);if(n.add(t),r.requirement!==`required`&&r.requirement!==`best-effort`)throw TypeError(`observation exporter ${t} has an invalid requirement`);if(!(r.boundary in l))throw TypeError(`observation exporter ${t} has an invalid boundary`);let i=r.exporter.supportedBoundaries??[`none`];if(typeof r.exporter.export!=`function`)throw TypeError(`observation exporter ${t} has no export function`);if(!i.includes(r.boundary))throw TypeError(`observation exporter ${t} does not support ${r.boundary}`);if(e===`operational`&&r.requirement===`required`)throw TypeError(`operational observation exporters must be best-effort`)}if(e!==`operational`&&!t.some(e=>e.requirement===`required`&&e.boundary!==`none`))throw TypeError(`${e} observability requires a durable required exporter`);return Object.freeze(t.map(e=>Object.freeze({...e})))}function b(e,t){let n=new AbortController,r=setTimeout(()=>n.abort(new DOMException(`observation deadline exceeded`,`TimeoutError`)),e),i=()=>n.abort(t?.reason??new DOMException(`observation aborted`,`AbortError`));return t?.aborted===!0?i():t?.addEventListener(`abort`,i,{once:!0}),{signal:n.signal,clear(){clearTimeout(r),t?.removeEventListener(`abort`,i)}}}function x(e,t){return t.aborted?Promise.reject(t.reason??Error(`observation aborted`)):new Promise((n,r)=>{let i=()=>{a(),r(t.reason??Error(`observation aborted`))},a=()=>t.removeEventListener(`abort`,i);t.addEventListener(`abort`,i,{once:!0}),e.then(e=>{a(),n(e)},e=>{a(),r(e)})})}function S(e){try{let t=e.reason;return typeof t==`object`&&!!t&&Reflect.get(t,`name`)===`TimeoutError`}catch{return!1}}function C(e){return Object.freeze({complete:e.complete,exportedEvents:e.exportedEvents,pendingEvents:e.pendingEvents,rejectedCritical:e.rejectedCritical,timedOut:e.timedOut})}function w(e,t){return e.eventId===t.eventId&&e.sequence===t.sequence&&e.name===t.name&&e.phase===t.phase&&e.occurredAt===t.occurredAt&&e.monotonicMs===t.monotonicMs&&e.priority===t.priority&&JSON.stringify(e.resource)===JSON.stringify(t.resource)&&JSON.stringify(e.correlation)===JSON.stringify(t.correlation)}var T=class{mode;resource;registrations;processors;options;queue=[];queueBytes=0;closing=!1;closed=!1;shutdownPromise;flushChain=Promise.resolve();protectedFailures=new Set;healthScope=t();healthRunId=n();healthCorrelation=i({name:`sdk.integration.request`,runId:this.healthRunId,startedAt:new Date().toISOString(),monotonicMs:this.healthScope.monotonicMs()}).correlation;counters={accepted:0,exported:0,droppedVerbose:0,droppedNormal:0,criticalRejected:0,processorFailures:0,exporterFailures:0,flushTimeouts:0,requiredFailure:!1};constructor(t){if(this.mode=t.mode??`operational`,![`operational`,`reliable`,`audit`].includes(this.mode))throw TypeError(`invalid observation mode`);this.resource=e({sdkName:`ai-agent-sdk`,sdkVersion:t.resource?.sdkVersion??`0.1.6`,...t.resource?.serviceName===void 0?{}:{serviceName:t.resource.serviceName},...t.resource?.serviceVersion===void 0?{}:{serviceVersion:t.resource.serviceVersion},runtime:t.resource?.runtime??`unknown`}),this.registrations=y(this.mode,t.exporters??[]);let n=new Set;for(let e of t.processors??[]){if(typeof e.id!=`string`||!d.test(e.id))throw TypeError(`processor id must be a safe 1-64 character identifier`);if(n.has(e.id))throw TypeError(`duplicate observation processor id: ${e.id}`);if(typeof e.transform!=`function`)throw TypeError(`observation processor ${e.id} is invalid`);n.add(e.id)}if(this.processors=Object.freeze([...t.processors??[]]),!f.has(t.content??`none`))throw TypeError(`invalid observation content policy`);if(!p.has(t.minimumLogLevel??`info`))throw TypeError(`invalid minimum log level`);let r=new Set;for(let e of t.redactors??[]){if(typeof e.id!=`string`||!d.test(e.id)||typeof e.redact!=`function`)throw TypeError(`invalid observation content redactor`);if(r.has(e.id))throw TypeError(`duplicate observation redactor id: ${e.id}`);r.add(e.id)}this.options={content:t.content??`none`,includeErrorStacks:t.includeErrorStacks??!1,minimumLogLevel:t.minimumLogLevel??`info`,maxQueueEvents:m(t.maxQueueEvents??1e4,`maxQueueEvents`),maxQueueBytes:m(t.maxQueueBytes??16777216,`maxQueueBytes`),maxBatchEvents:m(t.maxBatchEvents??256,`maxBatchEvents`),maxBatchBytes:m(t.maxBatchBytes??524288,`maxBatchBytes`),flushTimeoutMs:m(t.flushTimeoutMs??1e4,`flushTimeoutMs`),shutdownTimeoutMs:m(t.shutdownTimeoutMs??3e4,`shutdownTimeoutMs`),redactors:Object.freeze([...t.redactors??[]]),...t.onHealthChange===void 0?{}:{onHealthChange:t.onHealthChange},...t.openSpan===void 0?{}:{openSpan:t.openSpan}}}openSpan(e){let t=this.options.openSpan;if(t===void 0)return i(e);try{let n=a(t(e));if(n!==void 0)return n;this.counters.processorFailures++,this.recordFailure(`span:invalid`,TypeError(`invalid span`),`observation span backend returned an invalid span`,!1)}catch(e){this.counters.processorFailures++,this.recordFailure(`span:throw`,e,`observation span backend failed`,!1)}return i(e)}capture(e){let t=_(e);if(this.closing||this.closed)return g(t,`rejected`,`none`,`closed`);let n;try{n=this.prepareEvent(e,!1)}catch(e){return this.counters.processorFailures++,this.counters.lastFailure=h(e,`observation processor failed`),this.notifyHealth(),this.recordFailure(`processor:capture`,e,`observation processor failed`,!0),g(t,`rejected`,`none`,`processor-failed`)}let r=this.enqueue(n,!1);return r.status===`accepted`?this.stageExporters(n,r):r}async checkpoint(e,t){let n=this.capture(e);if(n.status!==`accepted`||this.mode===`operational`)return n;let r=this.queue.find(e=>e.event.eventId===n.eventId)?.event;if(r===void 0)return g(n.eventId,`rejected`,`none`,`exporter-unavailable`);let i=new Set(this.queue.filter(e=>e.event.priority===`critical`&&e.event.correlation.runId===r.correlation.runId&&e.event.sequence<=r.sequence).map(e=>e.event.eventId));return(await this.scheduleFlush(i,this.options.flushTimeoutMs,t)).requiredComplete?g(n.eventId,`accepted`,v(this.registrations)):g(n.eventId,`rejected`,`none`,`exporter-unavailable`)}logger(e){return c({minimumLevel:this.options.minimumLogLevel,resource:this.resource,emit:e=>{this.capture(e)}},e)}health(){let t=this.closed?`closed`:this.counters.requiredFailure||this.counters.criticalRejected>0||this.counters.flushTimeouts>0?`failed`:this.counters.processorFailures>0||this.counters.exporterFailures>0||this.counters.droppedVerbose>0||this.counters.droppedNormal>0?`degraded`:`healthy`;return e({state:t,queuedEvents:this.queue.length,queuedBytes:this.queueBytes,accepted:this.counters.accepted,exported:this.counters.exported,droppedVerbose:this.counters.droppedVerbose,droppedNormal:this.counters.droppedNormal,criticalRejected:this.counters.criticalRejected,processorFailures:this.counters.processorFailures,exporterFailures:this.counters.exporterFailures,flushTimeouts:this.counters.flushTimeouts,...this.counters.lastExportAt===void 0?{}:{lastExportAt:this.counters.lastExportAt},...this.counters.lastFailure===void 0?{}:{lastFailure:this.counters.lastFailure}})}flush(e){if(this.closed||this.closing)throw TypeError(`observability is closed`);return this.scheduleFlush(new Set(this.queue.map(e=>e.event.eventId)),this.options.flushTimeoutMs,e).then(C)}shutdown(e){if(this.shutdownPromise!==void 0)return this.shutdownPromise;this.closing=!0;let t=new Set(this.queue.map(e=>e.event.eventId));return this.shutdownPromise=(async()=>{let n=b(this.options.shutdownTimeoutMs,e),r;try{r=C(await this.scheduleFlush(t,this.options.shutdownTimeoutMs,n.signal));for(let e of[...this.registrations].reverse()){let t=e.exporter.shutdown;if(t!==void 0)try{await x(Promise.resolve(t.call(e.exporter,n.signal)),n.signal)}catch(t){this.recordExporterFailure(e,t,!1),r=Object.freeze({...r,complete:!1})}}}finally{n.clear(),this.closed=!0,this.notifyHealth()}return r})(),this.shutdownPromise}prepareEvent(e,t){let n={content:this.options.content,redactors:this.options.redactors??[],includeErrorStacks:this.options.includeErrorStacks},r=o(e,n);if(t)return r;for(let e of this.processors){let t=e.transform(r);if(t===void 0)throw TypeError(`observation processor ${e.id} returned undefined`);let i=o(t,n);if(!w(r,i))throw TypeError(`observation processor ${e.id} changed the immutable event envelope`);r=i}return r}enqueue(e,t){let n=s(e);return n>this.options.maxBatchBytes||n>this.options.maxQueueBytes||!this.makeCapacity(n,t)?(!t&&e.priority===`critical`&&this.counters.criticalRejected++,t||(this.counters.lastFailure=h(RangeError(`capacity`),`observation queue capacity exhausted`),this.notifyHealth()),g(e.eventId,`rejected`,`none`,`capacity`)):(this.queue.push({event:e,bytes:n,protected:t,pending:new Set(this.registrations.map(e=>e.exporter.id))}),this.queueBytes+=n,this.counters.accepted++,this.notifyHealth(),g(e.eventId,`accepted`))}stageExporters(e,t){let n=this.queue.find(t=>t.event.eventId===e.eventId);if(n===void 0)return g(e.eventId,`rejected`,`none`,`exporter-unavailable`);let r=!1;for(let t of this.registrations){let i=t.exporter.stage;if(i!==void 0)try{let n=i.call(t.exporter,e);n!==void 0&&Promise.resolve(n).catch(()=>void 0)}catch(i){if(this.recordExporterFailure(t,i,!1),n.pending.delete(t.exporter.id),r=!0,t.requirement===`required`)return this.removeEntry(n,!1),e.priority===`critical`&&this.counters.criticalRejected++,this.notifyHealth(),g(e.eventId,`rejected`,`none`,`exporter-unavailable`)}}return r&&n.pending.size===0&&this.removeEntry(n,!1),t}makeCapacity(e,t){for(;this.queue.length+1>this.options.maxQueueEvents||this.queueBytes+e>this.options.maxQueueBytes;){let e=this.queue.findIndex(e=>e.event.priority===`verbose`);if(e===-1&&(e=this.queue.findIndex(e=>e.event.priority===`normal`)),e===-1)return!1;let[n]=this.queue.splice(e,1);if(n===void 0)return!1;this.queueBytes-=n.bytes,t||(n.event.priority===`verbose`?this.counters.droppedVerbose++:this.counters.droppedNormal++)}return!0}scheduleFlush(e,t,n){let r,i,a=new Promise((e,t)=>{r=e,i=t}),o=async()=>{try{r(await this.flushInternal(e,t,n))}catch(e){i(e)}};return this.flushChain=this.flushChain.then(o,o),a}async flushInternal(t,r,i){let a=this.counters.exported,o=b(r,i),s=!1,c=!1;try{if(this.registrations.length===0)for(let e of[...this.queue])t.has(e.event.eventId)&&this.removeEntry(e,!1);for(let r of this.registrations)for(;;){let i=this.queue.filter(e=>t.has(e.event.eventId)&&e.pending.has(r.exporter.id));if(i.length===0)break;let a=[],l=0;for(let e of i){if(a.length>=this.options.maxBatchEvents||l+e.bytes>this.options.maxBatchBytes)break;a.push(e),l+=e.bytes}if(a.length===0)break;let u=e({schemaVersion:1,batchId:n(),createdAt:new Date().toISOString(),events:a.map(e=>e.event)}),d;try{if(d=await x(Promise.resolve(r.exporter.export(u,o.signal)),o.signal),d.batchId!==u.batchId||d.accepted!==!0)throw TypeError(`observation exporter ${r.exporter.id} returned an invalid acknowledgment`)}catch(e){if(s=!0,c||=S(o.signal),this.recordExporterFailure(r,e,!0),r.requirement===`best-effort`)for(let e of a)e.pending.delete(r.exporter.id),e.pending.size===0&&this.removeEntry(e,!1);break}this.counters.lastExportAt=new Date().toISOString();for(let e of a)e.pending.delete(r.exporter.id),e.pending.size===0&&this.removeEntry(e,!0);this.notifyHealth()}}finally{S(o.signal)&&(c=!0,this.counters.flushTimeouts++,this.counters.lastFailure=h(o.signal.reason,`observation flush timed out`),this.notifyHealth()),o.clear()}let l=this.queue.filter(e=>t.has(e.event.eventId)),u=this.registrations.filter(e=>e.requirement===`required`).map(e=>e.exporter.id),d=l.every(e=>u.every(t=>!e.pending.has(t)));return Object.freeze({complete:!s&&!c&&l.length===0,requiredComplete:d,exportedEvents:this.counters.exported-a,pendingEvents:l.length,rejectedCritical:this.counters.criticalRejected,timedOut:c})}removeEntry(e,t){let n=this.queue.indexOf(e);n!==-1&&(this.queue.splice(n,1),this.queueBytes-=e.bytes,t&&this.counters.exported++)}recordExporterFailure(e,t,n){this.counters.exporterFailures++,e.requirement===`required`&&(this.counters.requiredFailure=!0),this.counters.lastFailure=h(t,`observation exporter failed`),this.notifyHealth(),n&&this.recordFailure(`exporter:${e.exporter.id}`,t,`observation exporter failed`,!0)}recordFailure(e,t,r,i){if(this.counters.lastFailure=h(t,r),this.notifyHealth(),!(!i||this.protectedFailures.has(e)||this.closing||this.closed)){this.protectedFailures.add(e);try{let t=this.prepareEvent({schemaVersion:1,eventId:n(),sequence:this.healthScope.nextSequence(),name:`sdk.observer.failure`,phase:`point`,occurredAt:new Date().toISOString(),monotonicMs:this.healthScope.monotonicMs(),priority:`critical`,resource:this.resource,correlation:this.healthCorrelation,data:{observerId:e,failureKind:`contained`,count:1,error:{...this.counters.lastFailure}}},!0);this.enqueue(t,!0)}catch{}}}notifyHealth(){let e=this.options.onHealthChange;if(e!==void 0)try{e(this.health())}catch{}}};function E(e={}){return new T(e)}export{E as createObservability};
2
2
  //# sourceMappingURL=bus.js.map
@@ -1,6 +1,6 @@
1
1
  //#region src/primitives/version.d.ts
2
2
  /** Package version injected as a Web-standard literal; release tooling updates this file. */
3
- declare const SDK_VERSION = "0.1.4";
3
+ declare const SDK_VERSION = "0.1.6";
4
4
  //#endregion
5
5
  export { SDK_VERSION };
6
6
  //# sourceMappingURL=version.d.ts.map
@@ -1,2 +1,2 @@
1
- const e=`0.1.4`;export{e as SDK_VERSION};
1
+ const e=`0.1.6`;export{e as SDK_VERSION};
2
2
  //# sourceMappingURL=version.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"version.js","names":[],"sources":["../../src/primitives/version.ts"],"sourcesContent":["/** Package version injected as a Web-standard literal; release tooling updates this file. */\nexport const SDK_VERSION = '0.1.4'\n"],"mappings":"AACA,MAAa,EAAc"}
1
+ {"version":3,"file":"version.js","names":[],"sources":["../../src/primitives/version.ts"],"sourcesContent":["/** Package version injected as a Web-standard literal; release tooling updates this file. */\nexport const SDK_VERSION = '0.1.6'\n"],"mappings":"AACA,MAAa,EAAc"}
@@ -1,2 +1,2 @@
1
- import{deepFreeze as e}from"../primitives/freeze.js";import"../primitives/version.js";import{PLUGIN_ERROR_CODES as t,PluginError as n}from"../plugin/provider-plugin.js";import{ModelError as r,REGISTRY_ERROR_CODES as i}from"../errors/model-error.js";import{callConfigEquals as a}from"../contract/call-config.js";import{resolveRetryPolicy as o}from"../contract/retry-policy.js";import{createModelCallHandle as s}from"./model-call-handle.js";import{normalizeResolvedModelInfo as c,resolveCallWithModelInfo as l,validateCatalogModels as u,validateModelCatalogSnapshot as d}from"./model-metadata.js";import{streamAdapter as f}from"./model-stream.js";function p(e){if((typeof e!=`object`||!e)&&typeof e!=`function`)return!1;let t;try{t=Reflect.get(e,`then`)}catch{return!0}if(typeof t!=`function`)return!1;try{Promise.resolve(e).catch(()=>{})}catch{}return!0}function m(e){try{return p(e())?TypeError(`plugin cleanup must be synchronous`):void 0}catch(e){return e}}var h=class{adapters=new Map;middleware=[];listeners=new Set;plugins=new Map;maxCatalogModels;maxCatalogBytes;observation;observationResource;defaults;constructor(t={}){this.maxCatalogModels=g(t.maxCatalogModels??2048,`maxCatalogModels`),this.maxCatalogBytes=g(t.maxCatalogBytes??4194304,`maxCatalogBytes`),this.observation=t.observation,this.defaults=_(t.defaults??{}),this.observationResource=e(t.observationResource??{sdkName:`ai-agent-sdk`,sdkVersion:`0.1.4`,runtime:`unknown`})}install(e){let a=typeof e?.id==`string`?e.id:``,o=(e,r,i=[])=>{let o=[...r===void 0?[]:[r],...i],s=o.length<=1?o[0]:AggregateError(o,`plugin ${a} install cleanup failed`);throw new n(e,t.INSTALL_FAILED,a,s===void 0?void 0:{cause:s})};(a.trim().length===0||a!==a.trim())&&o(`plugin id must be a non-empty trimmed string`),this.plugins.has(a)&&o(`plugin "${a}" is already installed`),(typeof e.displayName!=`string`||e.displayName.trim().length===0)&&o(`plugin "${a}" displayName must be non-empty`),typeof e.setup!=`function`&&o(`plugin "${a}" setup must be a function`);let s=e.family??a;(typeof s!=`string`||s.trim().length===0||s!==s.trim())&&o(`plugin "${a}" family must be a non-empty trimmed string`);let c=Object.freeze({pluginId:a,family:s}),l=[],u=[],d=!0,f={registerAdapter:(e,t)=>{if(d||o(`plugin "${a}" staging registrar is closed`),e.length===0)throw new r(`an adapter must register at least one provider route`,i.INVALID_ADAPTER);let n={active:!0,routes:[...e],adapter:t},s=new Set(l.filter(e=>e.active).flatMap(e=>e.routes));for(let t of e)if(s.has(t))throw new r(`an adapter for provider route "${t}" is already staged`,i.DUPLICATE_ADAPTER);this.prepareRoutes(e,t,new Set,c),l.push(n);let u=(()=>{d&&(n.active=!1)});return u.replace=e=>{if(!d||!n.active)throw new r(`a disposed staged registration cannot replace routes`,i.REGISTRATION_DISPOSED);let a=new Set(l.filter(e=>e.active&&e!==n).flatMap(e=>e.routes));for(let t of e)if(a.has(t))throw new r(`an adapter for provider route "${t}" is already staged`,i.DUPLICATE_ADAPTER);this.prepareRoutes(e,t,new Set,c),n.routes=[...e]},u},use:e=>{if(d||o(`plugin "${a}" staging registrar is closed`),typeof e!=`function`)throw TypeError(`plugin middleware must be a function`);let t={active:!0,middleware:e};return u.push(t),()=>{d&&(t.active=!1)}}},h;try{let t=e.setup(f);p(t)&&o(`plugin "${a}" setup must be synchronous`),t!==void 0&&typeof t!=`function`&&o(`plugin "${a}" setup must be synchronous and return void or cleanup`),h=typeof t==`function`?t:void 0}catch(e){if(e instanceof n&&e.code===t.INSTALL_FAILED)throw e;o(`plugin "${a}" setup failed`,e)}finally{d=!1}let g=[],_=new Set;try{for(let e of l)if(e.active){for(let t of e.routes){if(_.has(t))throw new r(`an adapter for provider route "${t}" is already staged`,i.DUPLICATE_ADAPTER);_.add(t)}g.push(...this.prepareRoutes(e.routes,e.adapter,new Set,c))}}catch(e){let t=[];if(h){let e=m(h);e!==void 0&&t.push(e)}o(`plugin "${a}" commit validation failed`,e,t)}let v=u.filter(e=>e.active).map(e=>e.middleware);for(let e of g)this.adapters.set(e.provider.id,e);this.middleware.push(...v);let y={routes:_,registrations:g,middleware:v,...h===void 0?{}:{cleanup:h}};this.plugins.set(a,y),this.emitAdaptersUpdated();let b=!1,x=(()=>{if(b)return;b=!0,this.plugins.delete(a);for(let e of y.registrations)this.adapters.get(e.provider.id)===e&&this.adapters.delete(e.provider.id);for(let e=y.middleware.length-1;e>=0;e--){let t=y.middleware[e],n=t===void 0?-1:this.middleware.lastIndexOf(t);n>=0&&this.middleware.splice(n,1)}this.emitAdaptersUpdated();let e=[];if(y.cleanup){let t=m(y.cleanup);t!==void 0&&e.push(t)}if(e.length>0)throw new n(`plugin "${a}" cleanup failed`,t.CLEANUP_FAILED,a,{cause:AggregateError(e,`plugin "${a}" cleanup failed`)})});return Object.defineProperty(x,"pluginId",{value:a,enumerable:!0}),x}registerAdapter(e,t){if(e.length===0)throw new r(`an adapter must register at least one provider route`,i.INVALID_ADAPTER);let n=new Set,a=!1;this.commitRoutes(n,this.prepareRoutes(e,t,n));let o=(()=>{if(!a){a=!0;for(let e of n)this.adapters.delete(e);n.clear(),this.emitAdaptersUpdated()}});return o.replace=e=>{if(a)throw new r(`a disposed adapter registration cannot replace its routes`,i.REGISTRATION_DISPOSED);this.commitRoutes(n,this.prepareRoutes(e,t,n))},o}prepareRoutes(e,t,n,a){let s=new Set,c=[];for(let l of e){if(typeof l!=`string`||l.length===0)throw new r(`adapter provider route names must be non-empty strings`,i.INVALID_ADAPTER);if(s.has(l)||this.adapters.has(l)&&!n.has(l))throw new r(`an adapter for provider route "${l}" is already registered`,i.DUPLICATE_ADAPTER);let e=t.providerInfo(l);if(typeof e.id!=`string`||e.id!==l||typeof e.name!=`string`||e.name.length===0)throw new r(`adapter metadata for route "${l}" must preserve its id and carry a non-empty name`,i.INVALID_ADAPTER);s.add(l),c.push({adapter:t,provider:{id:e.id,name:e.name},...a===void 0?{}:a,retryPolicy:t.providerRetryPolicy(l)??o(void 0,`provider "${l}" retryPolicy`)})}return c}commitRoutes(e,t){for(let t of e)this.adapters.delete(t);e.clear();for(let n of t)this.adapters.set(n.provider.id,n),e.add(n.provider.id);this.emitAdaptersUpdated()}use(e){return this.middleware.push(e),()=>{let t=this.middleware.indexOf(e);t>=0&&this.middleware.splice(t,1)}}onAdaptersUpdated(e){return this.listeners.add(e),()=>void this.listeners.delete(e)}emitAdaptersUpdated(){for(let e of[...this.listeners])try{e()}catch{}}listProviders(){return[...this.adapters.values()].map(({provider:e})=>({...e}))}async listModels(e,t){let n=await this.registration(e).adapter.listModels(e,t);return u(e,n,this.maxCatalogModels,this.maxCatalogBytes)}async modelCatalog(e,t={}){let n=await this.registration(e).adapter.modelCatalog(e,t);return d(e,n,this.maxCatalogModels,this.maxCatalogBytes)}async resolveModelInfo(e,t,n){let r=this.registration(e),i=await r.adapter.resolveModel(e,t,n);return c(r.provider.id,t,i,this.maxCatalogBytes,this.defaults)}retryPolicy(e){return this.registration(e).retryPolicy}async prepareCall(t,n,o){let s=this.registration(t.provider),u=await s.adapter.prepareCall(t.provider,t.model,n,o),d=c(s.provider.id,t.model,u.model,this.maxCatalogBytes,this.defaults),f=l(t,d,this.defaults),p=e(structuredClone(f.config)),m=f.context===void 0?void 0:e(structuredClone(f.context)),h=e({...t.maxTokens===void 0&&p.maxTokens!==void 0?{maxTokens:!0}:{}}),g=!1,_=e(structuredClone(d));return Object.freeze({config:p,model:_,retryPolicy:s.retryPolicy,adapterDefaults:h,...m===void 0?{}:{context:m},...f.inputModalities===void 0?{}:{inputModalities:Object.freeze([...f.inputModalities])},stream:(e,t=o)=>{if(g)throw new r(`a prepared call can only be dispatched once`,i.INVALID_PREPARED_CALL);if(!a(e,p))throw new r(`prepared call config changed before adapter dispatch`,i.INVALID_PREPARED_CALL);return g=!0,this.dispatch(e,t,{registration:s,config:p,modelInfo:d,dispatch:(e,t)=>u.stream(e,t)})}})}stream(e,t){return this.dispatch(e,t)}dispatch(e,t,n){let r=`not-sent`,i=n?.registration??this.adapters.get(e.provider);return s({options:e,...i?.family===void 0?{}:{providerFamily:i.family},...i?.pluginId===void 0?{}:{providerPluginId:i.pluginId},...i===void 0?{}:{isRetryable:e=>i.retryPolicy.mode===`always`||i.retryPolicy.retryableCodes.includes(e)},...t===void 0?{}:{context:t},...this.observation===void 0?{}:{defaultObservation:this.observation},resource:this.observationResource,routePresent:n!==void 0||this.adapters.has(e.provider),dispatchState:()=>r,stream:t=>this.dispatchRaw(e,t,()=>{r=`unknown`},n)})}dispatchRaw(e,t,n,r){let i=[...this.middleware],a=()=>{let a=()=>f({options:e,context:t,onDispatch:n,maxCatalogBytes:this.maxCatalogBytes,defaults:this.defaults,registration:e=>this.registration(e),registeredAdapter:e=>this.adapters.get(e)?.adapter,...r===void 0?{}:{prepared:r}});for(let n=i.length-1;n>=0;n--){let r=i[n];if(r===void 0)continue;let o=a;a=()=>r(e,o,t)}return a()};return{async*[Symbol.asyncIterator](){yield*a()}}}registration(e){let t=this.adapters.get(e);if(t===void 0)throw new r(`no adapter registered for provider route "${e}"`,i.NO_ADAPTER);return t}};function g(e,t){if(!Number.isSafeInteger(e)||e<1)throw RangeError(`ModelRegistry ${t} must be a positive safe integer`);return e}function _(t){if(t.contextWindow!==void 0&&g(t.contextWindow,`defaults.contextWindow`),t.maxTokens!==void 0&&g(t.maxTokens,`defaults.maxTokens`),t.inputModalities!==void 0&&(t.inputModalities.length===0||new Set(t.inputModalities).size!==t.inputModalities.length))throw RangeError(`ModelRegistry defaults.inputModalities must be non-empty and unique`);return e({...t.contextWindow===void 0?{}:{contextWindow:t.contextWindow},...t.maxTokens===void 0?{}:{maxTokens:t.maxTokens},...t.inputModalities===void 0?{}:{inputModalities:[...t.inputModalities]}})}export{h as ModelRegistry};
1
+ import{deepFreeze as e}from"../primitives/freeze.js";import"../primitives/version.js";import{PLUGIN_ERROR_CODES as t,PluginError as n}from"../plugin/provider-plugin.js";import{ModelError as r,REGISTRY_ERROR_CODES as i}from"../errors/model-error.js";import{callConfigEquals as a}from"../contract/call-config.js";import{resolveRetryPolicy as o}from"../contract/retry-policy.js";import{createModelCallHandle as s}from"./model-call-handle.js";import{normalizeResolvedModelInfo as c,resolveCallWithModelInfo as l,validateCatalogModels as u,validateModelCatalogSnapshot as d}from"./model-metadata.js";import{streamAdapter as f}from"./model-stream.js";function p(e){if((typeof e!=`object`||!e)&&typeof e!=`function`)return!1;let t;try{t=Reflect.get(e,`then`)}catch{return!0}if(typeof t!=`function`)return!1;try{Promise.resolve(e).catch(()=>{})}catch{}return!0}function m(e){try{return p(e())?TypeError(`plugin cleanup must be synchronous`):void 0}catch(e){return e}}var h=class{adapters=new Map;middleware=[];listeners=new Set;plugins=new Map;maxCatalogModels;maxCatalogBytes;observation;observationResource;defaults;constructor(t={}){this.maxCatalogModels=g(t.maxCatalogModels??2048,`maxCatalogModels`),this.maxCatalogBytes=g(t.maxCatalogBytes??4194304,`maxCatalogBytes`),this.observation=t.observation,this.defaults=_(t.defaults??{}),this.observationResource=e(t.observationResource??{sdkName:`ai-agent-sdk`,sdkVersion:`0.1.6`,runtime:`unknown`})}install(e){let a=typeof e?.id==`string`?e.id:``,o=(e,r,i=[])=>{let o=[...r===void 0?[]:[r],...i],s=o.length<=1?o[0]:AggregateError(o,`plugin ${a} install cleanup failed`);throw new n(e,t.INSTALL_FAILED,a,s===void 0?void 0:{cause:s})};(a.trim().length===0||a!==a.trim())&&o(`plugin id must be a non-empty trimmed string`),this.plugins.has(a)&&o(`plugin "${a}" is already installed`),(typeof e.displayName!=`string`||e.displayName.trim().length===0)&&o(`plugin "${a}" displayName must be non-empty`),typeof e.setup!=`function`&&o(`plugin "${a}" setup must be a function`);let s=e.family??a;(typeof s!=`string`||s.trim().length===0||s!==s.trim())&&o(`plugin "${a}" family must be a non-empty trimmed string`);let c=Object.freeze({pluginId:a,family:s}),l=[],u=[],d=!0,f={registerAdapter:(e,t)=>{if(d||o(`plugin "${a}" staging registrar is closed`),e.length===0)throw new r(`an adapter must register at least one provider route`,i.INVALID_ADAPTER);let n={active:!0,routes:[...e],adapter:t},s=new Set(l.filter(e=>e.active).flatMap(e=>e.routes));for(let t of e)if(s.has(t))throw new r(`an adapter for provider route "${t}" is already staged`,i.DUPLICATE_ADAPTER);this.prepareRoutes(e,t,new Set,c),l.push(n);let u=(()=>{d&&(n.active=!1)});return u.replace=e=>{if(!d||!n.active)throw new r(`a disposed staged registration cannot replace routes`,i.REGISTRATION_DISPOSED);let a=new Set(l.filter(e=>e.active&&e!==n).flatMap(e=>e.routes));for(let t of e)if(a.has(t))throw new r(`an adapter for provider route "${t}" is already staged`,i.DUPLICATE_ADAPTER);this.prepareRoutes(e,t,new Set,c),n.routes=[...e]},u},use:e=>{if(d||o(`plugin "${a}" staging registrar is closed`),typeof e!=`function`)throw TypeError(`plugin middleware must be a function`);let t={active:!0,middleware:e};return u.push(t),()=>{d&&(t.active=!1)}}},h;try{let t=e.setup(f);p(t)&&o(`plugin "${a}" setup must be synchronous`),t!==void 0&&typeof t!=`function`&&o(`plugin "${a}" setup must be synchronous and return void or cleanup`),h=typeof t==`function`?t:void 0}catch(e){if(e instanceof n&&e.code===t.INSTALL_FAILED)throw e;o(`plugin "${a}" setup failed`,e)}finally{d=!1}let g=[],_=new Set;try{for(let e of l)if(e.active){for(let t of e.routes){if(_.has(t))throw new r(`an adapter for provider route "${t}" is already staged`,i.DUPLICATE_ADAPTER);_.add(t)}g.push(...this.prepareRoutes(e.routes,e.adapter,new Set,c))}}catch(e){let t=[];if(h){let e=m(h);e!==void 0&&t.push(e)}o(`plugin "${a}" commit validation failed`,e,t)}let v=u.filter(e=>e.active).map(e=>e.middleware);for(let e of g)this.adapters.set(e.provider.id,e);this.middleware.push(...v);let y={routes:_,registrations:g,middleware:v,...h===void 0?{}:{cleanup:h}};this.plugins.set(a,y),this.emitAdaptersUpdated();let b=!1,x=(()=>{if(b)return;b=!0,this.plugins.delete(a);for(let e of y.registrations)this.adapters.get(e.provider.id)===e&&this.adapters.delete(e.provider.id);for(let e=y.middleware.length-1;e>=0;e--){let t=y.middleware[e],n=t===void 0?-1:this.middleware.lastIndexOf(t);n>=0&&this.middleware.splice(n,1)}this.emitAdaptersUpdated();let e=[];if(y.cleanup){let t=m(y.cleanup);t!==void 0&&e.push(t)}if(e.length>0)throw new n(`plugin "${a}" cleanup failed`,t.CLEANUP_FAILED,a,{cause:AggregateError(e,`plugin "${a}" cleanup failed`)})});return Object.defineProperty(x,"pluginId",{value:a,enumerable:!0}),x}registerAdapter(e,t){if(e.length===0)throw new r(`an adapter must register at least one provider route`,i.INVALID_ADAPTER);let n=new Set,a=!1;this.commitRoutes(n,this.prepareRoutes(e,t,n));let o=(()=>{if(!a){a=!0;for(let e of n)this.adapters.delete(e);n.clear(),this.emitAdaptersUpdated()}});return o.replace=e=>{if(a)throw new r(`a disposed adapter registration cannot replace its routes`,i.REGISTRATION_DISPOSED);this.commitRoutes(n,this.prepareRoutes(e,t,n))},o}prepareRoutes(e,t,n,a){let s=new Set,c=[];for(let l of e){if(typeof l!=`string`||l.length===0)throw new r(`adapter provider route names must be non-empty strings`,i.INVALID_ADAPTER);if(s.has(l)||this.adapters.has(l)&&!n.has(l))throw new r(`an adapter for provider route "${l}" is already registered`,i.DUPLICATE_ADAPTER);let e=t.providerInfo(l);if(typeof e.id!=`string`||e.id!==l||typeof e.name!=`string`||e.name.length===0)throw new r(`adapter metadata for route "${l}" must preserve its id and carry a non-empty name`,i.INVALID_ADAPTER);s.add(l),c.push({adapter:t,provider:{id:e.id,name:e.name},...a===void 0?{}:a,retryPolicy:t.providerRetryPolicy(l)??o(void 0,`provider "${l}" retryPolicy`)})}return c}commitRoutes(e,t){for(let t of e)this.adapters.delete(t);e.clear();for(let n of t)this.adapters.set(n.provider.id,n),e.add(n.provider.id);this.emitAdaptersUpdated()}use(e){return this.middleware.push(e),()=>{let t=this.middleware.indexOf(e);t>=0&&this.middleware.splice(t,1)}}onAdaptersUpdated(e){return this.listeners.add(e),()=>void this.listeners.delete(e)}emitAdaptersUpdated(){for(let e of[...this.listeners])try{e()}catch{}}listProviders(){return[...this.adapters.values()].map(({provider:e})=>({...e}))}async listModels(e,t){let n=await this.registration(e).adapter.listModels(e,t);return u(e,n,this.maxCatalogModels,this.maxCatalogBytes)}async modelCatalog(e,t={}){let n=await this.registration(e).adapter.modelCatalog(e,t);return d(e,n,this.maxCatalogModels,this.maxCatalogBytes)}async resolveModelInfo(e,t,n){let r=this.registration(e),i=await r.adapter.resolveModel(e,t,n);return c(r.provider.id,t,i,this.maxCatalogBytes,this.defaults)}retryPolicy(e){return this.registration(e).retryPolicy}async prepareCall(t,n,o){let s=this.registration(t.provider),u=await s.adapter.prepareCall(t.provider,t.model,n,o),d=c(s.provider.id,t.model,u.model,this.maxCatalogBytes,this.defaults),f=l(t,d,this.defaults),p=e(structuredClone(f.config)),m=f.context===void 0?void 0:e(structuredClone(f.context)),h=e({...t.maxTokens===void 0&&p.maxTokens!==void 0?{maxTokens:!0}:{}}),g=!1,_=e(structuredClone(d));return Object.freeze({config:p,model:_,retryPolicy:s.retryPolicy,adapterDefaults:h,...m===void 0?{}:{context:m},...f.inputModalities===void 0?{}:{inputModalities:Object.freeze([...f.inputModalities])},stream:(e,t=o)=>{if(g)throw new r(`a prepared call can only be dispatched once`,i.INVALID_PREPARED_CALL);if(!a(e,p))throw new r(`prepared call config changed before adapter dispatch`,i.INVALID_PREPARED_CALL);return g=!0,this.dispatch(e,t,{registration:s,config:p,modelInfo:d,dispatch:(e,t)=>u.stream(e,t)})}})}stream(e,t){return this.dispatch(e,t)}dispatch(e,t,n){let r=`not-sent`,i=n?.registration??this.adapters.get(e.provider);return s({options:e,...i?.family===void 0?{}:{providerFamily:i.family},...i?.pluginId===void 0?{}:{providerPluginId:i.pluginId},...i===void 0?{}:{isRetryable:e=>i.retryPolicy.mode===`always`||i.retryPolicy.retryableCodes.includes(e)},...t===void 0?{}:{context:t},...this.observation===void 0?{}:{defaultObservation:this.observation},resource:this.observationResource,routePresent:n!==void 0||this.adapters.has(e.provider),dispatchState:()=>r,stream:t=>this.dispatchRaw(e,t,()=>{r=`unknown`},n)})}dispatchRaw(e,t,n,r){let i=[...this.middleware],a=()=>{let a=()=>f({options:e,context:t,onDispatch:n,maxCatalogBytes:this.maxCatalogBytes,defaults:this.defaults,registration:e=>this.registration(e),registeredAdapter:e=>this.adapters.get(e)?.adapter,...r===void 0?{}:{prepared:r}});for(let n=i.length-1;n>=0;n--){let r=i[n];if(r===void 0)continue;let o=a;a=()=>r(e,o,t)}return a()};return{async*[Symbol.asyncIterator](){yield*a()}}}registration(e){let t=this.adapters.get(e);if(t===void 0)throw new r(`no adapter registered for provider route "${e}"`,i.NO_ADAPTER);return t}};function g(e,t){if(!Number.isSafeInteger(e)||e<1)throw RangeError(`ModelRegistry ${t} must be a positive safe integer`);return e}function _(t){if(t.contextWindow!==void 0&&g(t.contextWindow,`defaults.contextWindow`),t.maxTokens!==void 0&&g(t.maxTokens,`defaults.maxTokens`),t.inputModalities!==void 0&&(t.inputModalities.length===0||new Set(t.inputModalities).size!==t.inputModalities.length))throw RangeError(`ModelRegistry defaults.inputModalities must be non-empty and unique`);return e({...t.contextWindow===void 0?{}:{contextWindow:t.contextWindow},...t.maxTokens===void 0?{}:{maxTokens:t.maxTokens},...t.inputModalities===void 0?{}:{inputModalities:[...t.inputModalities]}})}export{h as ModelRegistry};
2
2
  //# sourceMappingURL=registry.js.map
package/dist/tools.d.ts CHANGED
@@ -6,10 +6,13 @@ import { MemorySpillStoreLimits, SPILL_TOOL_NAME, SpillRecord, SpillSlice, Spill
6
6
  import { ApprovalBroker, ApprovalDecision, ApprovalRequest, ApprovalStateStore, InteractiveApprovalBroker, InteractiveApprovalBrokerOptions, createApprovalBroker, createApprovalRequest, fixedApprovalBroker, withApprovalPersistence } from "./agent/tool/approval.js";
7
7
  import { REGISTRY_ERROR_CODES, ToolCatalog, ToolFilter, ToolRegistry } from "./agent/tool/registry.js";
8
8
  import { AuthorizationOutcome, AuthorizedToolCall, DispatchToolCallOptions, PostToolDecision, PreToolDecision, PreparedToolCall, ToolCallContext, ToolCallRequest, ToolInterceptor, authorizeToolCall, dispatchAuthorizedToolCall, dispatchToolCall, finalizeToolCall, prepareToolCall, toolFailure } from "./agent/tool/pipeline.js";
9
+ import { ExperimentalProgramGrant, NESTED_TOOL_ERROR_CODES, NestedCallOptions, NestedLoadResult, NestedToolDescriptor, NestedToolPort, NestedToolResult, nestedToolPort } from "./agent/tool/nested.js";
9
10
  import { ToolCatalogSnapshot, ToolSource, ToolSourceDefinition, ToolSourceRunReference, ToolSourceSnapshotOptions } from "./agent/tool/source-types.js";
11
+ import { EvidenceLine, EvidenceReducer, EvidenceReductionInput, EvidenceReductionResult, createModelEvidenceReducer, diagnosticLineNumbers, reduceEvidence } from "./agent/tool/evidence-reducer.js";
10
12
  import { TOOL_ERROR_CODES, ToolError, ToolErrorDisposition, toolErrorDisposition } from "./agent/tool/errors.js";
11
13
  import { RuntimeSchema, defineToolFromSchema } from "./agent/tool/schema.js";
12
14
  import { ToolExecutionBackend, ToolExecutionCapabilities, ToolExecutionRequest, ToolExecutionStore, ToolOperation, ToolOperationClaim, createToolExecutionInterceptor, localToolExecutionBackend } from "./agent/tool/execution.js";
15
+ import { ActionFusionStep, defineActionFusion } from "./agent/tool/action-fusion.js";
13
16
  import { TOOL_SOURCE_API_VERSION } from "./composition/tool-source/config.js";
14
17
  import { defineToolSource } from "./composition/tool-source/definition.js";
15
- export { type ApprovalBroker, type ApprovalDecision, type ApprovalRequest, type ApprovalStateStore, type AuthorizationOutcome, type AuthorizedToolCall, type DispatchToolCallOptions, type InteractiveApprovalBroker, type InteractiveApprovalBrokerOptions, type JsonObject, type JsonValue, type MemorySpillStoreLimits, type PostToolDecision, type PreToolDecision, type PreparedToolCall, type RuntimeSchema, SPILL_TOOL_NAME, type SdkLogger, type SpillRecord, type SpillSlice, type SpillStore, TOOL_ERROR_CODES, REGISTRY_ERROR_CODES as TOOL_REGISTRY_ERROR_CODES, TOOL_SOURCE_API_VERSION, type ToolCallContext, type ToolCallPosition, type ToolCallRequest, type ToolCatalog, type ToolCatalogSnapshot, type ToolDefinition, ToolError, type ToolErrorDisposition, type ToolExecutionBackend, type ToolExecutionCapabilities, type ToolExecutionMode, type ToolExecutionRequest, type ToolExecutionResult, type ToolExecutionStore, type ToolFailure, type ToolFilter, type ToolInterceptor, type ToolOperation, type ToolOperationClaim, type ToolOutputOverflowPolicy, ToolRegistry, type ToolRunContext, type ToolSchema, type ToolSource, type ToolSourceDefinition, type ToolSourceRunReference, type ToolSourceSnapshotOptions, type ToolSuccess, type TruncatedText, authorizeToolCall, createApprovalBroker, createApprovalRequest, createMemorySpillStore, createToolExecutionInterceptor, defineTool, defineToolFromSchema, defineToolSource, dispatchAuthorizedToolCall, dispatchToolCall, estimateTextBlockTokens, estimateTextTokens, executionModeOf, finalizeToolCall, fixedApprovalBroker, localToolExecutionBackend, prepareToolCall, previewForSpill, readSpillTool, renderJsonValue, toolErrorDisposition, toolFailure, truncateMiddleToTokens, withApprovalPersistence };
18
+ export { type ActionFusionStep, type ApprovalBroker, type ApprovalDecision, type ApprovalRequest, type ApprovalStateStore, type AuthorizationOutcome, type AuthorizedToolCall, type DispatchToolCallOptions, NESTED_TOOL_ERROR_CODES as EXPERIMENTAL_NESTED_TOOL_ERROR_CODES, type EvidenceLine, type EvidenceReducer, type EvidenceReductionInput, type EvidenceReductionResult, type NestedCallOptions as ExperimentalNestedCallOptions, type NestedLoadResult as ExperimentalNestedLoadResult, type NestedToolDescriptor as ExperimentalNestedToolDescriptor, type NestedToolPort as ExperimentalNestedToolPort, type NestedToolResult as ExperimentalNestedToolResult, type ExperimentalProgramGrant, type InteractiveApprovalBroker, type InteractiveApprovalBrokerOptions, type JsonObject, type JsonValue, type MemorySpillStoreLimits, type PostToolDecision, type PreToolDecision, type PreparedToolCall, type RuntimeSchema, SPILL_TOOL_NAME, type SdkLogger, type SpillRecord, type SpillSlice, type SpillStore, TOOL_ERROR_CODES, REGISTRY_ERROR_CODES as TOOL_REGISTRY_ERROR_CODES, TOOL_SOURCE_API_VERSION, type ToolCallContext, type ToolCallPosition, type ToolCallRequest, type ToolCatalog, type ToolCatalogSnapshot, type ToolDefinition, ToolError, type ToolErrorDisposition, type ToolExecutionBackend, type ToolExecutionCapabilities, type ToolExecutionMode, type ToolExecutionRequest, type ToolExecutionResult, type ToolExecutionStore, type ToolFailure, type ToolFilter, type ToolInterceptor, type ToolOperation, type ToolOperationClaim, type ToolOutputOverflowPolicy, ToolRegistry, type ToolRunContext, type ToolSchema, type ToolSource, type ToolSourceDefinition, type ToolSourceRunReference, type ToolSourceSnapshotOptions, type ToolSuccess, type TruncatedText, authorizeToolCall, createApprovalBroker, createApprovalRequest, createMemorySpillStore, createModelEvidenceReducer, createToolExecutionInterceptor, defineActionFusion, defineTool, defineToolFromSchema, defineToolSource, diagnosticLineNumbers, dispatchAuthorizedToolCall, dispatchToolCall, estimateTextBlockTokens, estimateTextTokens, executionModeOf, nestedToolPort as experimentalNestedToolPort, finalizeToolCall, fixedApprovalBroker, localToolExecutionBackend, prepareToolCall, previewForSpill, readSpillTool, reduceEvidence, renderJsonValue, toolErrorDisposition, toolFailure, truncateMiddleToTokens, withApprovalPersistence };
package/dist/tools.js CHANGED
@@ -1 +1 @@
1
- import{defineTool as e,executionModeOf as t,renderJsonValue as n}from"./agent/tool/definition.js";import{REGISTRY_ERROR_CODES as r,ToolRegistry as i}from"./agent/tool/registry.js";import{SPILL_TOOL_NAME as a,createMemorySpillStore as o,estimateTextBlockTokens as s,estimateTextTokens as c,previewForSpill as l,readSpillTool as u,truncateMiddleToTokens as d}from"./agent/tool/output-budget.js";import{TOOL_ERROR_CODES as f,ToolError as p,toolErrorDisposition as m}from"./agent/tool/errors.js";import{createApprovalBroker as h,createApprovalRequest as g,fixedApprovalBroker as _,withApprovalPersistence as v}from"./agent/tool/approval.js";import{authorizeToolCall as y,dispatchAuthorizedToolCall as b,dispatchToolCall as x,finalizeToolCall as S,prepareToolCall as C,toolFailure as w}from"./agent/tool/pipeline.js";import{TOOL_SOURCE_API_VERSION as T}from"./composition/tool-source/config.js";import{defineToolSource as E}from"./composition/tool-source/definition.js";import{defineToolFromSchema as D}from"./agent/tool/schema.js";import{createToolExecutionInterceptor as O,localToolExecutionBackend as k}from"./agent/tool/execution.js";export{a as SPILL_TOOL_NAME,f as TOOL_ERROR_CODES,r as TOOL_REGISTRY_ERROR_CODES,T as TOOL_SOURCE_API_VERSION,p as ToolError,i as ToolRegistry,y as authorizeToolCall,h as createApprovalBroker,g as createApprovalRequest,o as createMemorySpillStore,O as createToolExecutionInterceptor,e as defineTool,D as defineToolFromSchema,E as defineToolSource,b as dispatchAuthorizedToolCall,x as dispatchToolCall,s as estimateTextBlockTokens,c as estimateTextTokens,t as executionModeOf,S as finalizeToolCall,_ as fixedApprovalBroker,k as localToolExecutionBackend,C as prepareToolCall,l as previewForSpill,u as readSpillTool,n as renderJsonValue,m as toolErrorDisposition,w as toolFailure,d as truncateMiddleToTokens,v as withApprovalPersistence};
1
+ import{defineTool as e,executionModeOf as t,renderJsonValue as n}from"./agent/tool/definition.js";import{SPILL_TOOL_NAME as r,createMemorySpillStore as i,estimateTextBlockTokens as a,estimateTextTokens as o,previewForSpill as s,readSpillTool as c,truncateMiddleToTokens as l}from"./agent/tool/output-budget.js";import{createModelEvidenceReducer as u,diagnosticLineNumbers as d,reduceEvidence as f}from"./agent/tool/evidence-reducer.js";import{REGISTRY_ERROR_CODES as p,ToolRegistry as m}from"./agent/tool/registry.js";import{TOOL_ERROR_CODES as h,ToolError as g,toolErrorDisposition as _}from"./agent/tool/errors.js";import{createApprovalBroker as v,createApprovalRequest as y,fixedApprovalBroker as b,withApprovalPersistence as x}from"./agent/tool/approval.js";import{NESTED_TOOL_ERROR_CODES as S,nestedToolPort as C}from"./agent/tool/nested.js";import{authorizeToolCall as w,dispatchAuthorizedToolCall as T,dispatchToolCall as E,finalizeToolCall as D,prepareToolCall as O,toolFailure as k}from"./agent/tool/pipeline.js";import{TOOL_SOURCE_API_VERSION as A}from"./composition/tool-source/config.js";import{defineToolSource as j}from"./composition/tool-source/definition.js";import{defineToolFromSchema as M}from"./agent/tool/schema.js";import{createToolExecutionInterceptor as N,localToolExecutionBackend as P}from"./agent/tool/execution.js";import{defineActionFusion as F}from"./agent/tool/action-fusion.js";export{S as EXPERIMENTAL_NESTED_TOOL_ERROR_CODES,r as SPILL_TOOL_NAME,h as TOOL_ERROR_CODES,p as TOOL_REGISTRY_ERROR_CODES,A as TOOL_SOURCE_API_VERSION,g as ToolError,m as ToolRegistry,w as authorizeToolCall,v as createApprovalBroker,y as createApprovalRequest,i as createMemorySpillStore,u as createModelEvidenceReducer,N as createToolExecutionInterceptor,F as defineActionFusion,e as defineTool,M as defineToolFromSchema,j as defineToolSource,d as diagnosticLineNumbers,T as dispatchAuthorizedToolCall,E as dispatchToolCall,a as estimateTextBlockTokens,o as estimateTextTokens,t as executionModeOf,C as experimentalNestedToolPort,D as finalizeToolCall,b as fixedApprovalBroker,P as localToolExecutionBackend,O as prepareToolCall,s as previewForSpill,c as readSpillTool,f as reduceEvidence,n as renderJsonValue,_ as toolErrorDisposition,k as toolFailure,l as truncateMiddleToTokens,x as withApprovalPersistence};
package/package.json CHANGED
@@ -4,7 +4,7 @@
4
4
  "name": "alvin0 - chaulamdinhai",
5
5
  "email": "chaulamdinhai@gmail.com"
6
6
  },
7
- "version": "0.1.4",
7
+ "version": "0.1.6",
8
8
  "description": "Universal contracts and runtime primitives for ai-agent-sdk",
9
9
  "license": "MIT",
10
10
  "repository": {