@alvin0/ai-agent-sdk-core 0.1.0 → 0.1.1

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 (178) hide show
  1. package/dist/agent/define/session/model-config.js +1 -1
  2. package/dist/agent/define/session/model-config.js.map +1 -1
  3. package/dist/agent/define/session/types.d.ts +21 -0
  4. package/dist/agent/define/session/types.d.ts.map +1 -1
  5. package/dist/agent/define/session.d.ts +2 -0
  6. package/dist/agent/define/session.d.ts.map +1 -1
  7. package/dist/agent/define/session.js +1 -1
  8. package/dist/agent/define/session.js.map +1 -1
  9. package/dist/agent/history/validation.js +1 -1
  10. package/dist/agent/history/validation.js.map +1 -1
  11. package/dist/agent/loop/events.d.ts +5 -0
  12. package/dist/agent/loop/events.d.ts.map +1 -1
  13. package/dist/agent/loop/schedule.js +1 -1
  14. package/dist/agent/loop/schedule.js.map +1 -1
  15. package/dist/agent/loop/turn/model-round.js +1 -1
  16. package/dist/agent/loop/turn/model-round.js.map +1 -1
  17. package/dist/agent/loop/turn/types.d.ts +2 -0
  18. package/dist/agent/loop/turn/types.d.ts.map +1 -1
  19. package/dist/agent/loop/turn/validation.js +1 -1
  20. package/dist/agent/loop/turn/validation.js.map +1 -1
  21. package/dist/agent/memory/compaction.d.ts +10 -1
  22. package/dist/agent/memory/compaction.d.ts.map +1 -1
  23. package/dist/agent/memory/compaction.js +2 -2
  24. package/dist/agent/memory/compaction.js.map +1 -1
  25. package/dist/agent/memory/token-estimator.js +1 -1
  26. package/dist/agent/memory/token-estimator.js.map +1 -1
  27. package/dist/agent/mode/run-agent.js +1 -1
  28. package/dist/agent/mode/run-agent.js.map +1 -1
  29. package/dist/composition/agent/options.js +1 -1
  30. package/dist/composition/agent/options.js.map +1 -1
  31. package/dist/composition/agent/session.js +1 -1
  32. package/dist/composition/agent/session.js.map +1 -1
  33. package/dist/composition/agent/types.d.ts +43 -1
  34. package/dist/composition/agent/types.d.ts.map +1 -1
  35. package/dist/composition/common/errors.d.ts.map +1 -1
  36. package/dist/composition/common/errors.js +1 -1
  37. package/dist/composition/common/errors.js.map +1 -1
  38. package/dist/composition/embedding/activation.js +2 -0
  39. package/dist/composition/embedding/activation.js.map +1 -0
  40. package/dist/composition/embedding/cache.js +2 -0
  41. package/dist/composition/embedding/cache.js.map +1 -0
  42. package/dist/composition/embedding/definition.d.ts +7 -0
  43. package/dist/composition/embedding/definition.d.ts.map +1 -0
  44. package/dist/composition/embedding/definition.js +2 -0
  45. package/dist/composition/embedding/definition.js.map +1 -0
  46. package/dist/composition/embedding/handle.js +2 -0
  47. package/dist/composition/embedding/handle.js.map +1 -0
  48. package/dist/composition/embedding/limiter.js +2 -0
  49. package/dist/composition/embedding/limiter.js.map +1 -0
  50. package/dist/composition/embedding/manager.js +2 -0
  51. package/dist/composition/embedding/manager.js.map +1 -0
  52. package/dist/composition/embedding/observation.js +2 -0
  53. package/dist/composition/embedding/observation.js.map +1 -0
  54. package/dist/composition/embedding/planner.js +2 -0
  55. package/dist/composition/embedding/planner.js.map +1 -0
  56. package/dist/composition/embedding/plugin-types.d.ts +48 -0
  57. package/dist/composition/embedding/plugin-types.d.ts.map +1 -0
  58. package/dist/composition/embedding/plugin-types.js +2 -0
  59. package/dist/composition/embedding/plugin-types.js.map +1 -0
  60. package/dist/composition/embedding/preflight.js +2 -0
  61. package/dist/composition/embedding/preflight.js.map +1 -0
  62. package/dist/composition/embedding/registry.js +2 -0
  63. package/dist/composition/embedding/registry.js.map +1 -0
  64. package/dist/composition/embedding/retry.js +2 -0
  65. package/dist/composition/embedding/retry.js.map +1 -0
  66. package/dist/composition/embedding/usage.js +2 -0
  67. package/dist/composition/embedding/usage.js.map +1 -0
  68. package/dist/composition/lifecycle/types.d.ts +5 -1
  69. package/dist/composition/lifecycle/types.d.ts.map +1 -1
  70. package/dist/composition/lifecycle/types.js +1 -1
  71. package/dist/composition/lifecycle/types.js.map +1 -1
  72. package/dist/composition/preflight.js +1 -1
  73. package/dist/composition/preflight.js.map +1 -1
  74. package/dist/composition/provider/activation.js +1 -1
  75. package/dist/composition/provider/activation.js.map +1 -1
  76. package/dist/composition/provider/model-selection.js +1 -1
  77. package/dist/composition/provider/model-selection.js.map +1 -1
  78. package/dist/composition/provider/preflight.js +1 -1
  79. package/dist/composition/provider/preflight.js.map +1 -1
  80. package/dist/composition/runtime/owner.js +1 -1
  81. package/dist/composition/runtime/owner.js.map +1 -1
  82. package/dist/composition/runtime/public.js +1 -1
  83. package/dist/composition/runtime/public.js.map +1 -1
  84. package/dist/composition/runtime/types.d.ts +25 -2
  85. package/dist/composition/runtime/types.d.ts.map +1 -1
  86. package/dist/composition/startup.js +1 -1
  87. package/dist/composition/startup.js.map +1 -1
  88. package/dist/composition/team/options.js +1 -1
  89. package/dist/composition/team/options.js.map +1 -1
  90. package/dist/composition/team/runtime.js +1 -1
  91. package/dist/composition/team/runtime.js.map +1 -1
  92. package/dist/composition/team/types.d.ts +3 -0
  93. package/dist/composition/team/types.d.ts.map +1 -1
  94. package/dist/contract/generate-options.d.ts +2 -0
  95. package/dist/contract/generate-options.d.ts.map +1 -1
  96. package/dist/contract/model-info.d.ts +12 -2
  97. package/dist/contract/model-info.d.ts.map +1 -1
  98. package/dist/embedding/adapter.d.ts +104 -0
  99. package/dist/embedding/adapter.d.ts.map +1 -0
  100. package/dist/embedding/adapter.js +2 -0
  101. package/dist/embedding/adapter.js.map +1 -0
  102. package/dist/embedding/catalog.d.ts +82 -0
  103. package/dist/embedding/catalog.d.ts.map +1 -0
  104. package/dist/embedding/catalog.js +2 -0
  105. package/dist/embedding/catalog.js.map +1 -0
  106. package/dist/embedding/errors.d.ts +98 -0
  107. package/dist/embedding/errors.d.ts.map +1 -0
  108. package/dist/embedding/errors.js +2 -0
  109. package/dist/embedding/errors.js.map +1 -0
  110. package/dist/embedding/handle.d.ts +76 -0
  111. package/dist/embedding/handle.d.ts.map +1 -0
  112. package/dist/embedding/limits.d.ts +47 -0
  113. package/dist/embedding/limits.d.ts.map +1 -0
  114. package/dist/embedding/limits.js +2 -0
  115. package/dist/embedding/limits.js.map +1 -0
  116. package/dist/embedding/profile.d.ts +89 -0
  117. package/dist/embedding/profile.d.ts.map +1 -0
  118. package/dist/embedding/profile.js +2 -0
  119. package/dist/embedding/profile.js.map +1 -0
  120. package/dist/embedding/purpose.d.ts +37 -0
  121. package/dist/embedding/purpose.d.ts.map +1 -0
  122. package/dist/embedding/request.d.ts +54 -0
  123. package/dist/embedding/request.d.ts.map +1 -0
  124. package/dist/embedding/request.js +2 -0
  125. package/dist/embedding/request.js.map +1 -0
  126. package/dist/embedding/result.d.ts +50 -0
  127. package/dist/embedding/result.d.ts.map +1 -0
  128. package/dist/embedding/usage.d.ts +64 -0
  129. package/dist/embedding/usage.d.ts.map +1 -0
  130. package/dist/embedding/usage.js +2 -0
  131. package/dist/embedding/usage.js.map +1 -0
  132. package/dist/embedding/validation.d.ts +68 -0
  133. package/dist/embedding/validation.d.ts.map +1 -0
  134. package/dist/embedding/validation.js +2 -0
  135. package/dist/embedding/validation.js.map +1 -0
  136. package/dist/embedding.d.ts +12 -0
  137. package/dist/embedding.js +1 -0
  138. package/dist/index.d.ts +6 -3
  139. package/dist/index.js +1 -1
  140. package/dist/message/content.d.ts +71 -1
  141. package/dist/message/content.d.ts.map +1 -1
  142. package/dist/message/projection.d.ts +28 -2
  143. package/dist/message/projection.d.ts.map +1 -1
  144. package/dist/message/projection.js +1 -1
  145. package/dist/message/projection.js.map +1 -1
  146. package/dist/observability/bus.js +1 -1
  147. package/dist/observation/event.d.ts +1 -1
  148. package/dist/observation/event.d.ts.map +1 -1
  149. package/dist/observation/event.js.map +1 -1
  150. package/dist/observation/port.d.ts +1 -1
  151. package/dist/observation/port.d.ts.map +1 -1
  152. package/dist/observation/port.js.map +1 -1
  153. package/dist/observation/privacy.js +1 -1
  154. package/dist/observation/privacy.js.map +1 -1
  155. package/dist/observation/report.d.ts +2 -0
  156. package/dist/observation/report.d.ts.map +1 -1
  157. package/dist/observation/report.js.map +1 -1
  158. package/dist/primitives/version.d.ts +1 -1
  159. package/dist/primitives/version.js +1 -1
  160. package/dist/primitives/version.js.map +1 -1
  161. package/dist/provider.d.ts +3 -1
  162. package/dist/provider.js +1 -1
  163. package/dist/runtime/model-call-handle.js +1 -1
  164. package/dist/runtime/model-call-handle.js.map +1 -1
  165. package/dist/runtime/model-metadata.js +1 -1
  166. package/dist/runtime/model-metadata.js.map +1 -1
  167. package/dist/runtime/model-stream.js +1 -1
  168. package/dist/runtime/model-stream.js.map +1 -1
  169. package/dist/runtime/registry.js +1 -1
  170. package/dist/runtime/with-retry.d.ts.map +1 -1
  171. package/dist/runtime/with-retry.js +1 -1
  172. package/dist/runtime/with-retry.js.map +1 -1
  173. package/dist/stream/assembler.d.ts.map +1 -1
  174. package/dist/stream/assembler.js +1 -1
  175. package/dist/stream/assembler.js.map +1 -1
  176. package/dist/stream/chunk.d.ts +6 -0
  177. package/dist/stream/chunk.d.ts.map +1 -1
  178. package/package.json +6 -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 { 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 } 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 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)\n const started = this.start(input, options)\n return runtimeHandle(started.legacy, started.report, started.result, this.nativeProvider)\n }\n\n private start(input: AgentInput | undefined, options: RuntimeAgentInvocationOptions): 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 })\n : streamRuntimeSession(this.session, input, { signal: lease.signal, ...(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 }) }, 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)\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)\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 })\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\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): 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)\n } })\n}\n\nasync function* projectEvents(\n source: LegacyRunHandle & { readonly traceId: string; abort(reason?: unknown): void },\n report: Promise<RuntimeRunReport>,\n nativeProvider: string,\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)\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): ProjectedEvent | undefined {\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":"0zCAsDA,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,cAA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,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 type { ReasoningEffortId } from '../../primitives/brand.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 reasoningEffort?: ReturnType<typeof ReasoningEffortId>\n readonly maxTokens?: number\n} {\n return {\n ...(options.model === undefined ? {} : { model: { provider: options.model.provider, model: options.model.id } }),\n ...(options.effort === undefined ? {} : { reasoningEffort: options.effort }),\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":"0zCA+DA,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,cAAc,EAAsC,CAAE,OAAO,EAAqB,EAAM,EAAY,CAAO,CAAE,EAC7G,cAAc,EAAuC,EAAsC,CACzF,OAAO,EAAqB,EAAM,EAAY,EAAS,CAAQ,CACjE,CACF,CAAC,EAED,OADA,EAAqB,IAAI,EAAO,OAAO,OAAO,CAAE,OAAM,YAAW,CAAC,CAAC,EAC5D,CACT,CAEA,SAAgB,EACd,EACA,EACA,EACA,EACA,EACwE,CACxE,IAAM,EAAU,EAAqB,IAAI,CAAK,EAC9C,GAAI,GAAS,OAAS,EAAM,MAAM,IAAI,EACpC,4DAA6D,8BAC/D,EACA,IAAM,EAAO,EAAqB,EAAM,EAAQ,WAAY,EAAS,IAAA,GAAW,EAAM,CAAW,EACjG,OAAO,OAAO,OAAO,CAAE,OAAM,KAAM,EAAK,QAAS,CAAC,CACpD,CAEA,SAAgB,EACd,EACA,EACA,EACA,EACM,CACN,IAAM,EAAU,EAAqB,IAAI,CAAK,EAC9C,GAAI,GAAS,OAAS,EAAM,MAAM,IAAI,EACpC,4DAA6D,8BAC/D,EACA,EAA4B,CAC1B,MAAO,CAAC,GAAG,EAAQ,WAAW,OAAO,MAAO,GAAG,EAAQ,OAAS,CAAC,CAAC,EAClE,YAAa,EAAQ,WAAW,OAAO,YACvC,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G,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,4 +1,5 @@
1
1
  import { JsonValue } from "../../primitives/json.js";
2
+ import { UsageCounters } from "../../observation/usage.js";
2
3
  import { Message } from "../../message/message.js";
3
4
  import { NativeToolSchema, ToolChoice } from "../../contract/tool.js";
4
5
  import { ModelOutputFormat } from "../../contract/output-format.js";
@@ -100,6 +101,36 @@ interface RuntimeAgentSessionOptions {
100
101
  readonly compaction?: AgentCompactionOptions | false;
101
102
  }
102
103
  interface RuntimeAgentInvocationOptions {
104
+ /**
105
+ * Model for THIS invocation only.
106
+ *
107
+ * The agent's bound target is unchanged — `agent.model` still reports it, and
108
+ * the next call without an override uses it again — so one session can put
109
+ * successive turns on different models without becoming a different agent.
110
+ * Resolved against the same configured routes as the binding, with the same
111
+ * failures (`MODEL_ROUTE_UNKNOWN`, `MODEL_DEFAULT_MISSING`), and resolved
112
+ * before the run acquires anything, so a bad target costs no I/O. Route-only
113
+ * (`{ provider }`) takes that route's configured default model.
114
+ *
115
+ * The target is frozen for the run it starts: every step of that turn reaches
116
+ * the same model. There is deliberately no fallback to another model when the
117
+ * chosen one fails — the failure is raised to the caller.
118
+ */
119
+ readonly model?: {
120
+ readonly provider: string;
121
+ readonly id?: string;
122
+ };
123
+ /**
124
+ * Reasoning effort for this invocation only.
125
+ *
126
+ * Alone it re-runs the agent's own model at a different effort. With `model`
127
+ * it applies to that model. Omitted alongside a `model` that differs from the
128
+ * binding, the agent's effort is NOT carried over: an effort belongs to the
129
+ * ladder of the model that offers it, and the route decides the default.
130
+ */
131
+ readonly effort?: string;
132
+ /** Output ceiling for this invocation only; dropped like `effort` on a model switch. */
133
+ readonly maxTokens?: number;
103
134
  /** One schema adapter supplies the provider schema and a synchronous runtime validator. */
104
135
  readonly structuredOutput?: {
105
136
  readonly name: string;
@@ -107,8 +138,12 @@ interface RuntimeAgentInvocationOptions {
107
138
  };
108
139
  /** strict rejects known text-only models when request history contains images; project permits lossy conversion. */
109
140
  readonly imagePolicy?: 'strict' | 'project';
141
+ /** strict rejects models that decline document input when history contains documents; project permits lossy conversion. */
142
+ readonly documentPolicy?: 'strict' | 'project';
110
143
  readonly signal?: AbortSignal;
111
144
  readonly additionalInstructions?: string;
145
+ /** Include raw span lifecycle events in the public stream for host tracing. */
146
+ readonly includeTraceEvents?: boolean;
112
147
  readonly onEvent?: (event: RuntimeAgentRunEvent) => void | Promise<void>;
113
148
  }
114
149
  interface RuntimeAgentRunEventContext {
@@ -122,7 +157,10 @@ type PublicContentEvent = AgentRunEvent extends (infer E) ? E extends {
122
157
  } ? Omit<E, 'trace'> & {
123
158
  readonly blockId?: string;
124
159
  } : never : never;
125
- type RuntimeAgentRunEvent = RuntimeAgentRunEventContext & (PublicContentEvent | {
160
+ type PublicTraceEvent = Extract<AgentRunEvent, {
161
+ type: 'span-start' | 'span-end';
162
+ }>;
163
+ type RuntimeAgentRunEvent = RuntimeAgentRunEventContext & (PublicContentEvent | PublicTraceEvent | {
126
164
  readonly type: 'commentary-delta';
127
165
  readonly text: string;
128
166
  readonly index: number;
@@ -167,6 +205,10 @@ type RuntimeAgentRunEvent = RuntimeAgentRunEventContext & (PublicContentEvent |
167
205
  readonly type: 'usage';
168
206
  readonly usage: RuntimeRunReport['usage'];
169
207
  readonly report: RuntimeRunReport;
208
+ } | {
209
+ readonly type: 'usage-progress';
210
+ readonly usage: UsageCounters;
211
+ readonly attemptId?: string;
170
212
  } | {
171
213
  readonly type: 'error';
172
214
  readonly error: RuntimeRunReport['errors'][number];
@@ -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;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;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
+ {"version":3,"file":"types.d.ts","names":[],"sources":["../../../src/composition/agent/types.ts"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;UAyBiB;WACN;WACA;WACA;WACA,OAAO;WACP;WACA;WACA;WACA;WACA,iBAAiB;WACjB,uBAAuB;WACvB,aAAa;WACb,eAAe;WACf,uBAAuB;WACvB,kBAAkB;WAClB;WACA,SAAS;;;;;;;;WAQT,2BAA2B;WAC3B,aAAa;;WAEb;WACA;WACA;;UAGM,+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;;;;;;;;;;WAS9C;;WAEA;;WAEA;aACE;aACA,QAA2D,cAAA;;;WAG7D;;WAEA;WACA,SAAS;WACT;;WAEA;WACA,WAAW,OAAO,gCAAgC;;UAG5C;WACN;WACA;WACA;WACA;;KAGN,qBAAqB,6BAA4B,KAClD;EAAY;IACV,KAAK;WAAyB;;KAG/B,mBAAmB,QAAQ;EAAiB;;KAErC,uBAAuB,+BAC/B,qBACA;WACW;WAAmC;WAAuB;WAAwB;WAA0B,OADvH;;WAEW;WAAkC;WAAuB;WAAwB;WAA0B,OAD6C;;WAExJ;WAA4B;WAAyB;WAAuB;;WAC5E;WAA8B;WAAyB;WACvD;WACA;;WACA;WAAwC;WAAyB;WACjE;WAAuB;WACvB,QAAQ;WAAoB,SAAS;;WACrC;WAAmC,SAAS;;WAC5C;WAAqC,SAAS;;WAC9C;WAAsC;WAA4B,UAAU;;WAC5E;WAAwB,OAAO;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 +1 @@
1
- {"version":3,"file":"errors.d.ts","names":[],"sources":["../../../src/composition/common/errors.ts"],"mappings":";;UAoBiB;WACN;WACA;WACA;WACA;aAAmB;aAAuB;aAAwB"}
1
+ {"version":3,"file":"errors.d.ts","names":[],"sources":["../../../src/composition/common/errors.ts"],"mappings":";;UAsBiB;WACN;WACA;WACA;WACA;aAAmB;aAAuB;aAAwB"}
@@ -1,2 +1,2 @@
1
- var e=class extends Error{code=`RUNTIME_CONSTRUCTION_FAILED`;failureCode;stage;reason;component;conflict;cleanup;constructor(e){super(`Agent runtime construction did not complete`),this.name=`AgentRuntimeConstructionError`,this.failureCode=e.failureCode,this.stage=e.stage,this.reason=e.reason,e.component!==void 0&&(this.component=Object.freeze({...e.component})),e.conflict!==void 0&&(this.conflict=Object.freeze({...e.conflict})),this.cleanup=Object.freeze((e.cleanup??[]).map(e=>Object.freeze({...e,...e.error===void 0?{}:{error:Object.freeze({...e.error})}})))}};function t(t=`CAPABILITY_STARTUP_FAILED`,n){return new e({failureCode:t,stage:`preflight`,reason:`invalid`,...n===void 0?{}:{conflict:n}})}function n(t){if(t?.aborted)throw new e({failureCode:`CAPABILITY_STARTUP_ABORTED`,stage:`preflight`,reason:`aborted`})}export{e as AgentRuntimeConstructionError,n as checkPreflightAbort,t as invalidPreflight};
1
+ var e=class extends Error{code=`RUNTIME_CONSTRUCTION_FAILED`;failureCode;stage;reason;component;conflict;cleanup;aggregate;constructor(e){super(`Agent runtime construction did not complete`),this.name=`AgentRuntimeConstructionError`,this.failureCode=e.failureCode,this.stage=e.stage,this.reason=e.reason,e.component!==void 0&&(this.component=Object.freeze({...e.component})),e.conflict!==void 0&&(this.conflict=Object.freeze({...e.conflict})),this.cleanup=Object.freeze((e.cleanup??[]).map(e=>Object.freeze({...e,...e.error===void 0?{}:{error:Object.freeze({...e.error})}}))),this.aggregate=Object.freeze((e.aggregate??[]).map(e=>Object.freeze({...e})))}};function t(t=`CAPABILITY_STARTUP_FAILED`,n){return new e({failureCode:t,stage:`preflight`,reason:`invalid`,...n===void 0?{}:{conflict:n}})}function n(t){if(t?.aborted)throw new e({failureCode:`CAPABILITY_STARTUP_ABORTED`,stage:`preflight`,reason:`aborted`})}export{e as AgentRuntimeConstructionError,n as checkPreflightAbort,t as invalidPreflight};
2
2
  //# sourceMappingURL=errors.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"errors.js","names":[],"sources":["../../../src/composition/common/errors.ts"],"sourcesContent":["export type RuntimeConstructionFailureReason = 'invalid' | 'failed' | 'timed-out' | 'aborted'\n\nexport type RuntimeConstructionFailureCode =\n | 'CAPABILITY_KIND_MISMATCH'\n | 'CAPABILITY_API_UNSUPPORTED'\n | 'CAPABILITY_ID_CONFLICT'\n | 'PROVIDER_ROUTE_CONFLICT'\n | 'PROVIDER_SETUP_ASYNC_UNSUPPORTED'\n | 'OBSERVATION_BOUNDARY_UNSUPPORTED'\n | 'CAPABILITY_STARTUP_FAILED'\n | 'CAPABILITY_STARTUP_TIMEOUT'\n | 'CAPABILITY_STARTUP_ABORTED'\n\nimport type { CapabilityIdentityConflict } from '../../errors/capability-identity.ts'\nexport type { CapabilityIdentityConflict } from '../../errors/capability-identity.ts'\n\nexport type RuntimeConstructionComponent =\n | { readonly kind: 'provider-plugin'; readonly id: string }\n | { readonly kind: 'observation-exporter'; readonly id: string }\n\nexport interface RuntimeComponentCloseReport {\n readonly kind: 'provider-registration' | 'observation-exporter' | 'agent-team'\n readonly id: string\n readonly status: 'closed' | 'failed' | 'timed-out'\n readonly error?: { readonly code: string; readonly stage: string; readonly message: string }\n}\n\nexport interface ConstructionFailure {\n readonly failureCode: RuntimeConstructionFailureCode\n readonly stage: 'preflight' | 'provider-setup' | 'exporter-ready' | 'activation'\n readonly reason: RuntimeConstructionFailureReason\n readonly component?: RuntimeConstructionComponent\n readonly conflict?: CapabilityIdentityConflict\n readonly cleanup?: readonly RuntimeComponentCloseReport[]\n}\n\n/** Support-safe envelope: deliberately carries no raw input, exception or cause. */\nexport class AgentRuntimeConstructionError extends Error {\n readonly code = 'RUNTIME_CONSTRUCTION_FAILED' as const\n readonly failureCode: RuntimeConstructionFailureCode\n readonly stage: ConstructionFailure['stage']\n readonly reason: RuntimeConstructionFailureReason\n readonly component?: RuntimeConstructionComponent\n readonly conflict?: CapabilityIdentityConflict\n readonly cleanup: readonly RuntimeComponentCloseReport[]\n\n constructor(failure: ConstructionFailure) {\n super('Agent runtime construction did not complete')\n this.name = 'AgentRuntimeConstructionError'\n this.failureCode = failure.failureCode\n this.stage = failure.stage\n this.reason = failure.reason\n if (failure.component !== undefined) this.component = Object.freeze({ ...failure.component })\n if (failure.conflict !== undefined) this.conflict = Object.freeze({ ...failure.conflict })\n this.cleanup = Object.freeze((failure.cleanup ?? []).map(row => Object.freeze({\n ...row,\n ...(row.error === undefined ? {} : { error: Object.freeze({ ...row.error }) }),\n })))\n }\n}\n\nexport function invalidPreflight(\n failureCode: RuntimeConstructionFailureCode = 'CAPABILITY_STARTUP_FAILED',\n conflict?: CapabilityIdentityConflict,\n): AgentRuntimeConstructionError {\n return new AgentRuntimeConstructionError({\n failureCode, stage: 'preflight', reason: 'invalid',\n ...(conflict === undefined ? {} : { conflict }),\n })\n}\n\nexport function checkPreflightAbort(signal?: AbortSignal): void {\n if (signal?.aborted) throw new AgentRuntimeConstructionError({\n failureCode: 'CAPABILITY_STARTUP_ABORTED', stage: 'preflight', reason: 'aborted',\n })\n}\n"],"mappings":"AAqCA,IAAa,EAAb,cAAmD,KAAM,CACvD,KAAgB,8BAChB,YACA,MACA,OACA,UACA,SACA,QAEA,YAAY,EAA8B,CACxC,MAAM,6CAA6C,EACnD,KAAK,KAAO,gCACZ,KAAK,YAAc,EAAQ,YAC3B,KAAK,MAAQ,EAAQ,MACrB,KAAK,OAAS,EAAQ,OAClB,EAAQ,YAAc,IAAA,KAAW,KAAK,UAAY,OAAO,OAAO,CAAE,GAAG,EAAQ,SAAU,CAAC,GACxF,EAAQ,WAAa,IAAA,KAAW,KAAK,SAAW,OAAO,OAAO,CAAE,GAAG,EAAQ,QAAS,CAAC,GACzF,KAAK,QAAU,OAAO,QAAQ,EAAQ,SAAW,CAAC,EAAA,CAAG,IAAI,GAAO,OAAO,OAAO,CAC5E,GAAG,EACH,GAAI,EAAI,QAAU,IAAA,GAAY,CAAC,EAAI,CAAE,MAAO,OAAO,OAAO,CAAE,GAAG,EAAI,KAAM,CAAC,CAAE,CAC9E,CAAC,CAAC,CAAC,CACL,CACF,EAEA,SAAgB,EACd,EAA8C,4BAC9C,EAC+B,CAC/B,OAAO,IAAI,EAA8B,CACvC,cAAa,MAAO,YAAa,OAAQ,UACzC,GAAI,IAAa,IAAA,GAAY,CAAC,EAAI,CAAE,UAAS,CAC/C,CAAC,CACH,CAEA,SAAgB,EAAoB,EAA4B,CAC9D,GAAI,GAAQ,QAAS,MAAM,IAAI,EAA8B,CAC3D,YAAa,6BAA8B,MAAO,YAAa,OAAQ,SACzE,CAAC,CACH"}
1
+ {"version":3,"file":"errors.js","names":[],"sources":["../../../src/composition/common/errors.ts"],"sourcesContent":["export type RuntimeConstructionFailureReason = 'invalid' | 'failed' | 'timed-out' | 'aborted'\n\nexport type RuntimeConstructionFailureCode =\n | 'CAPABILITY_KIND_MISMATCH'\n | 'CAPABILITY_API_UNSUPPORTED'\n | 'CAPABILITY_ID_CONFLICT'\n | 'PROVIDER_ROUTE_CONFLICT'\n /** Two plugins of the SAME operation claim one route (Requirement 11.6). */\n | 'PROVIDER_OPERATION_CONFLICT'\n | 'PROVIDER_SETUP_ASYNC_UNSUPPORTED'\n | 'OBSERVATION_BOUNDARY_UNSUPPORTED'\n | 'CAPABILITY_STARTUP_FAILED'\n | 'CAPABILITY_STARTUP_TIMEOUT'\n | 'CAPABILITY_STARTUP_ABORTED'\n\nimport type { CapabilityIdentityConflict } from '../../errors/capability-identity.ts'\nexport type { CapabilityIdentityConflict } from '../../errors/capability-identity.ts'\n\nexport type RuntimeConstructionComponent =\n | { readonly kind: 'provider-plugin'; readonly id: string }\n | { readonly kind: 'observation-exporter'; readonly id: string }\n\nexport interface RuntimeComponentCloseReport {\n readonly kind: 'provider-registration' | 'observation-exporter' | 'agent-team'\n readonly id: string\n readonly status: 'closed' | 'failed' | 'timed-out'\n readonly error?: { readonly code: string; readonly stage: string; readonly message: string }\n}\n\n/**\n * One entry of a whole-input failure sweep.\n *\n * Declared here rather than beside the preflight that produces it so\n * {@link ConstructionFailure} can carry it without importing a composition\n * phase. `ProviderPreflightFailure` narrows `code` to the subset a provider\n * sweep can produce.\n */\nexport interface RuntimeConstructionAggregateEntry {\n /** Position in the caller's input list. */\n readonly index: number\n readonly code: RuntimeConstructionFailureCode\n /** Present only when the id was readable as inert, bounded data. */\n readonly pluginId?: string\n /** The earlier index this entry collides with, for conflict codes. */\n readonly conflictsWithIndex?: number\n}\n\nexport interface ConstructionFailure {\n readonly failureCode: RuntimeConstructionFailureCode\n readonly stage: 'preflight' | 'provider-setup' | 'exporter-ready' | 'activation'\n readonly reason: RuntimeConstructionFailureReason\n readonly component?: RuntimeConstructionComponent\n readonly conflict?: CapabilityIdentityConflict\n readonly cleanup?: readonly RuntimeComponentCloseReport[]\n /**\n * Every failure the sweep found, not just the reported one.\n *\n * `failureCode` stays the FIRST failure's code so existing assertions keep\n * their meaning; this list is purely additive (DD-3).\n */\n readonly aggregate?: readonly RuntimeConstructionAggregateEntry[]\n}\n\n/** Support-safe envelope: deliberately carries no raw input, exception or cause. */\nexport class AgentRuntimeConstructionError extends Error {\n readonly code = 'RUNTIME_CONSTRUCTION_FAILED' as const\n readonly failureCode: RuntimeConstructionFailureCode\n readonly stage: ConstructionFailure['stage']\n readonly reason: RuntimeConstructionFailureReason\n readonly component?: RuntimeConstructionComponent\n readonly conflict?: CapabilityIdentityConflict\n readonly cleanup: readonly RuntimeComponentCloseReport[]\n /** Empty unless the failure came from a whole-input sweep. */\n readonly aggregate: readonly RuntimeConstructionAggregateEntry[]\n\n constructor(failure: ConstructionFailure) {\n super('Agent runtime construction did not complete')\n this.name = 'AgentRuntimeConstructionError'\n this.failureCode = failure.failureCode\n this.stage = failure.stage\n this.reason = failure.reason\n if (failure.component !== undefined) this.component = Object.freeze({ ...failure.component })\n if (failure.conflict !== undefined) this.conflict = Object.freeze({ ...failure.conflict })\n this.cleanup = Object.freeze((failure.cleanup ?? []).map(row => Object.freeze({\n ...row,\n ...(row.error === undefined ? {} : { error: Object.freeze({ ...row.error }) }),\n })))\n this.aggregate = Object.freeze((failure.aggregate ?? []).map(entry => Object.freeze({ ...entry })))\n }\n}\n\nexport function invalidPreflight(\n failureCode: RuntimeConstructionFailureCode = 'CAPABILITY_STARTUP_FAILED',\n conflict?: CapabilityIdentityConflict,\n): AgentRuntimeConstructionError {\n return new AgentRuntimeConstructionError({\n failureCode, stage: 'preflight', reason: 'invalid',\n ...(conflict === undefined ? {} : { conflict }),\n })\n}\n\nexport function checkPreflightAbort(signal?: AbortSignal): void {\n if (signal?.aborted) throw new AgentRuntimeConstructionError({\n failureCode: 'CAPABILITY_STARTUP_ABORTED', stage: 'preflight', reason: 'aborted',\n })\n}\n"],"mappings":"AAgEA,IAAa,EAAb,cAAmD,KAAM,CACvD,KAAgB,8BAChB,YACA,MACA,OACA,UACA,SACA,QAEA,UAEA,YAAY,EAA8B,CACxC,MAAM,6CAA6C,EACnD,KAAK,KAAO,gCACZ,KAAK,YAAc,EAAQ,YAC3B,KAAK,MAAQ,EAAQ,MACrB,KAAK,OAAS,EAAQ,OAClB,EAAQ,YAAc,IAAA,KAAW,KAAK,UAAY,OAAO,OAAO,CAAE,GAAG,EAAQ,SAAU,CAAC,GACxF,EAAQ,WAAa,IAAA,KAAW,KAAK,SAAW,OAAO,OAAO,CAAE,GAAG,EAAQ,QAAS,CAAC,GACzF,KAAK,QAAU,OAAO,QAAQ,EAAQ,SAAW,CAAC,EAAA,CAAG,IAAI,GAAO,OAAO,OAAO,CAC5E,GAAG,EACH,GAAI,EAAI,QAAU,IAAA,GAAY,CAAC,EAAI,CAAE,MAAO,OAAO,OAAO,CAAE,GAAG,EAAI,KAAM,CAAC,CAAE,CAC9E,CAAC,CAAC,CAAC,EACH,KAAK,UAAY,OAAO,QAAQ,EAAQ,WAAa,CAAC,EAAA,CAAG,IAAI,GAAS,OAAO,OAAO,CAAE,GAAG,CAAM,CAAC,CAAC,CAAC,CACpG,CACF,EAEA,SAAgB,EACd,EAA8C,4BAC9C,EAC+B,CAC/B,OAAO,IAAI,EAA8B,CACvC,cAAa,MAAO,YAAa,OAAQ,UACzC,GAAI,IAAa,IAAA,GAAY,CAAC,EAAI,CAAE,UAAS,CAC/C,CAAC,CACH,CAEA,SAAgB,EAAoB,EAA4B,CAC9D,GAAI,GAAQ,QAAS,MAAM,IAAI,EAA8B,CAC3D,YAAa,6BAA8B,MAAO,YAAa,OAAQ,SACzE,CAAC,CACH"}
@@ -0,0 +1,2 @@
1
+ import{arrayData as e,boundedText as t}from"../../capability/common/data.js";import{beginCoreCapabilityOperation as n}from"../../platform/capability-operation.js";import{COMPOSITION_LIMITS as r}from"../../capability/common/config.js";import{AgentRuntimeConstructionError as i,checkPreflightAbort as a}from"../common/errors.js";import{activateProviders as o,asynchronous as s,closeRow as c,providerClaimError as l,providerLifecycleError as u}from"../provider/activation.js";function d(o,d,f,p,m,h){a(p);let g=h?.installed??[],_=g.length;for(let[h,v]of d.entries()){let d=n(f.child({providerIndex:_+h}),`core-provider`,`setup`),y=`setup`,b=`CAPABILITY_STARTUP_FAILED`,x,S,C=!1,w=!1,T,E,D=[],O=`provider-${_+h}`,k=()=>{for(let e of[...D].reverse())if(e.active){e.active=!1;try{e.handle()}catch{}}},A=()=>{if(C)return x??c(O);w||(E??=p?.aborted===!0),C=!0,y=`cleanup`;let e;try{w||(T??=m?.rollback());let t=T!==void 0&&T.now()>=T.at;t&&(e=`CAPABILITY_CLEANUP_TIMEOUT`),k(),S!==void 0&&!t&&s(S())&&(e=`PROVIDER_CLEANUP_ASYNC_UNSUPPORTED`)}catch{e=`CAPABILITY_CLEANUP_FAILED`}finally{y=`closed`}let t=c(O,e);return x=t,t};try{if(a(p),m!==void 0&&m.startup.now()>=m.startup.at)throw b=`CAPABILITY_STARTUP_TIMEOUT`,Error(`Provider startup deadline exhausted`);let n=()=>{if(y!==`setup`)throw u();a(p)},i=()=>{if(y!==`setup`&&y!==`cleanup`&&y!==`closed`)throw u()},c=i=>{n();let a=e(i,r.routesPerProvider).map(e=>t(e,r.identityBytes));if(a.length===0||new Set(a).size!==a.length)throw l();for(let e of a)if(!v.routes.includes(e))throw l();return Object.freeze(a)},h=Object.freeze({logger:f,registerEmbeddingAdapter(e,t,n){let r=c(e),a=o.registerEmbeddingAdapter(r,t,n),s={active:!0,routes:r,handle:a};D.push(s);let l=(()=>{i(),s.active&&=(a(),!1)});return l.replace=e=>{if(!s.active)throw u();let t=c(e);a.replace(t),s.routes=t},Object.freeze(l)}});try{let e=v.setup(h);if(y=`sealed`,S=typeof e==`function`?e:void 0,s(e))throw b=`PROVIDER_SETUP_ASYNC_UNSUPPORTED`,Error(`Asynchronous provider setup is unsupported`);if(e!==void 0&&typeof e!=`function`)throw Error(`Invalid provider setup result`);a(p);let t=new Set(D.filter(e=>e.active).flatMap(e=>e.routes));if(v.routes.some(e=>!t.has(e)))throw l()}catch(e){throw p?.aborted===!0?d.abort():d.fail(e),E=p?.aborted===!0,y=`sealed`,(S!==void 0||D.some(e=>e.active))&&(x=A()),e}finally{y===`setup`&&(y=`sealed`)}d.success(),w=!0;let _;g.push(Object.freeze({id:v.id,close(e){return _===void 0?(T=e,_=A(),_):_}})),a(p)}catch(e){let t=E??p?.aborted===!0;t?d.abort():d.fail(e);let n=[];x!==void 0&&n.push(x);let r=m?.rollback();for(let e of[...g].reverse())n.push(e.close(r));throw new i({failureCode:t?`CAPABILITY_STARTUP_ABORTED`:b,stage:`provider-setup`,reason:t?`aborted`:b===`CAPABILITY_STARTUP_TIMEOUT`?`timed-out`:`failed`,component:{kind:`provider-plugin`,id:O},cleanup:n})}}return Object.freeze([...g])}function f(e){let t={installed:[]};return o(e.registry,e.providers,e.logger,e.signal,e.deadlines,t),d(e.embeddingRegistry,e.embeddingProviders,e.logger,e.signal,e.deadlines,t)}export{d as activateEmbeddingProviders,f as activateRuntimeProviders};
2
+ //# sourceMappingURL=activation.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"activation.js","names":[],"sources":["../../../src/composition/embedding/activation.ts"],"sourcesContent":["/**\n * Activation for the embedding plugin kind, sharing ONE rollback list with generation.\n *\n * The shape mirrors `activateProviders` on purpose — same phase machine, same\n * cleanup accounting, same `provider-N` report ids — because the two kinds must be\n * indistinguishable from the outside once startup either succeeded or unwound\n * (Requirement 11.7). What differs is only where a registration lands:\n * `EmbeddingRegistry` is itself the registrar, so there is no `install()`\n * transaction to borrow and this module releases the route handles it took.\n *\n * Rollback is not atomic per route — two kinds are two plugin objects and two\n * `setup()` calls. Two other layers make that safe: the whole-input preflight\n * rejects every route–operation conflict BEFORE any plugin is committed, and the\n * `installed[]` list swept here spans both kinds, so a failing embedding plugin\n * releases the generation registrations that went in before it.\n *\n * Both edge configurations are first-class, not special cases: a `providers` list\n * of only generation plugins never constructs an embedding registration\n * (Requirement 11.8), and a list of only embedding plugins activates, serves and\n * closes with an empty generation registry (Requirement 11.9).\n *\n * @module ai-agent-sdk/core/composition/embedding/activation\n */\n\nimport type { SdkLogger } from '../../logging/types.ts'\nimport type { AdapterRegistrationHandle } from '../../plugin/provider-plugin.ts'\nimport type { ModelRegistry } from '../../runtime/registry.ts'\nimport type { EmbeddingAdapter } from '../../embedding/adapter.ts'\nimport { COMPOSITION_LIMITS } from '../common/config.ts'\nimport { arrayData, boundedText } from '../common/data.ts'\nimport { AgentRuntimeConstructionError, checkPreflightAbort } from '../common/errors.ts'\nimport type { RuntimeComponentCloseReport, RuntimeConstructionFailureCode } from '../common/errors.ts'\nimport { beginCoreCapabilityOperation } from '../logging/capability.ts'\nimport {\n activateProviders, asynchronous, closeRow, providerClaimError, providerLifecycleError,\n type CleanupCode, type ProviderActivationDeadlines, type ProviderCleanupDeadline,\n type ProviderRegistration, type SharedProviderActivation,\n} from '../provider/activation.ts'\nimport type { CapturedProvider } from '../provider/types.ts'\nimport type { CapturedEmbeddingProvider } from './preflight.ts'\nimport type { EmbeddingProviderRegistrar } from './plugin-types.ts'\nimport { EmbeddingRegistry } from './registry.ts'\n\n/** What an embedding plugin's `setup()` receives, logger included. */\nexport interface RuntimeEmbeddingProviderRegistrar extends EmbeddingProviderRegistrar {\n readonly logger: SdkLogger\n}\n\ninterface RouteRegistration {\n active: boolean\n routes: readonly string[]\n readonly handle: AdapterRegistrationHandle\n}\n\n/**\n * Activate already-captured embedding plugins against one runtime registry.\n *\n * @param registry - the runtime's embedding registry, never the `ModelRegistry`.\n * @param providers - plugins whose `setup` was captured by the preflight.\n * @param shared - the cross-kind rollback list; omit for a private one.\n * @returns every registration in the shared list, this activation's included.\n * @throws AgentRuntimeConstructionError after rolling back the WHOLE shared list.\n */\nexport function activateEmbeddingProviders(\n registry: EmbeddingRegistry,\n providers: readonly CapturedEmbeddingProvider[],\n logger: SdkLogger,\n signal?: AbortSignal,\n deadlines?: ProviderActivationDeadlines,\n shared?: SharedProviderActivation,\n): readonly ProviderRegistration[] {\n checkPreflightAbort(signal)\n const installed: ProviderRegistration[] = shared?.installed ?? []\n const idOffset = installed.length\n for (const [index, provider] of providers.entries()) {\n const setupOperation = beginCoreCapabilityOperation(\n logger.child({ providerIndex: idOffset + index }), 'core-provider', 'setup',\n )\n let phase: 'setup' | 'sealed' | 'cleanup' | 'closed' = 'setup'\n let failureCode: RuntimeConstructionFailureCode = 'CAPABILITY_STARTUP_FAILED'\n let failureCleanup: RuntimeComponentCloseReport | undefined\n let cleanup: (() => void) | undefined\n let cleaned = false\n let committed = false\n let cleanupDeadline: ProviderCleanupDeadline | undefined\n let failureWasAbort: boolean | undefined\n const registrations: RouteRegistration[] = []\n // Support reports do not echo an arbitrary user-supplied identity.\n const reportId = `provider-${idOffset + index}`\n /** Topology leaves the registry BEFORE user cleanup runs, as it does for generation. */\n const release = (): void => {\n for (const row of [...registrations].reverse()) {\n if (!row.active) continue\n row.active = false\n try { row.handle() } catch { /* a broken disposer must not strand the others */ }\n }\n }\n const finishCleanup = (): RuntimeComponentCloseReport => {\n if (cleaned) return failureCleanup ?? closeRow(reportId)\n if (!committed) failureWasAbort ??= signal?.aborted === true\n cleaned = true\n phase = 'cleanup'\n let code: CleanupCode | undefined\n try {\n if (!committed) cleanupDeadline ??= deadlines?.rollback()\n const expired = cleanupDeadline !== undefined && cleanupDeadline.now() >= cleanupDeadline.at\n // An expired budget still removes topology; only the plugin's own\n // disposer is skipped, matching the generation contract exactly.\n if (expired) code = 'CAPABILITY_CLEANUP_TIMEOUT'\n release()\n if (cleanup !== undefined && !expired && asynchronous(cleanup())) {\n code = 'PROVIDER_CLEANUP_ASYNC_UNSUPPORTED'\n }\n } catch { code = 'CAPABILITY_CLEANUP_FAILED' }\n finally { phase = 'closed' }\n const row = closeRow(reportId, code)\n failureCleanup = row\n return row\n }\n try {\n checkPreflightAbort(signal)\n if (deadlines !== undefined && deadlines.startup.now() >= deadlines.startup.at) {\n failureCode = 'CAPABILITY_STARTUP_TIMEOUT'\n throw new Error('Provider startup deadline exhausted')\n }\n const setupOnly = (): void => {\n if (phase !== 'setup') throw providerLifecycleError()\n checkPreflightAbort(signal)\n }\n const disposeOnly = (): void => {\n if (phase !== 'setup' && phase !== 'cleanup' && phase !== 'closed') throw providerLifecycleError()\n }\n /**\n * Route claims are checked here, not in the registry: the registry owns\n * cross-plugin vacancy, this owns \"inside what this plugin predeclared\".\n */\n const routesFor = (input: unknown): readonly string[] => {\n setupOnly()\n const routes = arrayData(input, COMPOSITION_LIMITS.routesPerProvider)\n .map(route => boundedText(route, COMPOSITION_LIMITS.identityBytes))\n if (routes.length === 0 || new Set(routes).size !== routes.length) throw providerClaimError()\n for (const route of routes) if (!provider.routes.includes(route)) throw providerClaimError()\n return Object.freeze(routes)\n }\n const registrar: RuntimeEmbeddingProviderRegistrar = Object.freeze({\n logger,\n registerEmbeddingAdapter(\n input: readonly string[], adapter: EmbeddingAdapter, models?: readonly string[],\n ) {\n const routes = routesFor(input)\n // Model-scoped and route-wide claims coexist by design, so same-route\n // duplication is the registry's call, not this layer's.\n const handle = registry.registerEmbeddingAdapter(routes, adapter, models)\n const row: RouteRegistration = { active: true, routes, handle }\n registrations.push(row)\n const dispose = (() => {\n disposeOnly()\n if (!row.active) return\n handle()\n row.active = false\n }) as AdapterRegistrationHandle\n dispose.replace = next => {\n if (!row.active) throw providerLifecycleError()\n const replacement = routesFor(next)\n handle.replace(replacement)\n row.routes = replacement\n }\n return Object.freeze(dispose)\n },\n })\n try {\n const result = provider.setup(registrar)\n phase = 'sealed'\n cleanup = typeof result === 'function' ? result : undefined\n if (asynchronous(result)) {\n failureCode = 'PROVIDER_SETUP_ASYNC_UNSUPPORTED'\n throw new Error('Asynchronous provider setup is unsupported')\n }\n if (result !== undefined && typeof result !== 'function') throw new Error('Invalid provider setup result')\n checkPreflightAbort(signal)\n const claimed = new Set(registrations.filter(row => row.active).flatMap(row => row.routes))\n if (provider.routes.some(route => !claimed.has(route))) throw providerClaimError()\n } catch (error) {\n if (signal?.aborted === true) setupOperation.abort(); else setupOperation.fail(error)\n failureWasAbort = signal?.aborted === true\n phase = 'sealed'\n // Nothing else will release what this setup already put into the\n // registry: it never became a registration in `installed`.\n if (cleanup !== undefined || registrations.some(row => row.active)) failureCleanup = finishCleanup()\n throw error\n } finally {\n if (phase === 'setup') phase = 'sealed'\n }\n setupOperation.success()\n committed = true\n let report: RuntimeComponentCloseReport | undefined\n installed.push(Object.freeze({\n id: provider.id,\n close(deadline?: ProviderCleanupDeadline) {\n if (report !== undefined) return report\n cleanupDeadline = deadline\n report = finishCleanup()\n return report\n },\n }))\n checkPreflightAbort(signal)\n } catch (error: unknown) {\n const aborted = failureWasAbort ?? signal?.aborted === true\n if (aborted) setupOperation.abort(); else setupOperation.fail(error)\n const cleanupRows: RuntimeComponentCloseReport[] = []\n if (failureCleanup !== undefined) cleanupRows.push(failureCleanup)\n const deadline = deadlines?.rollback()\n for (const registration of [...installed].reverse()) cleanupRows.push(registration.close(deadline))\n throw new AgentRuntimeConstructionError({\n failureCode: aborted ? 'CAPABILITY_STARTUP_ABORTED' : failureCode,\n stage: 'provider-setup',\n reason: aborted ? 'aborted' : failureCode === 'CAPABILITY_STARTUP_TIMEOUT' ? 'timed-out' : 'failed',\n component: { kind: 'provider-plugin', id: reportId }, cleanup: cleanupRows,\n })\n }\n }\n return Object.freeze([...installed])\n}\n\n/** Both halves of one validated `providers` list, ready to activate. */\nexport interface RuntimeProviderActivationInput {\n readonly registry: ModelRegistry\n readonly embeddingRegistry: EmbeddingRegistry\n readonly providers: readonly CapturedProvider[]\n readonly embeddingProviders: readonly CapturedEmbeddingProvider[]\n readonly logger: SdkLogger\n readonly signal?: AbortSignal\n readonly deadlines?: ProviderActivationDeadlines\n}\n\n/**\n * Activate generation first, then embedding, over ONE rollback list.\n *\n * Order matters only for reporting: whichever step fails, the failure unwinds the\n * complete list, so the runtime either owns every registration or none.\n *\n * @returns the combined registration list, in installation order.\n */\nexport function activateRuntimeProviders(\n input: RuntimeProviderActivationInput,\n): readonly ProviderRegistration[] {\n const shared: SharedProviderActivation = { installed: [] }\n activateProviders(input.registry, input.providers, input.logger, input.signal, input.deadlines, shared)\n return activateEmbeddingProviders(input.embeddingRegistry, input.embeddingProviders,\n input.logger, input.signal, input.deadlines, shared)\n}\n"],"mappings":"ydA+DA,SAAgB,EACd,EACA,EACA,EACA,EACA,EACA,EACiC,CACjC,EAAoB,CAAM,EAC1B,IAAM,EAAoC,GAAQ,WAAa,CAAC,EAC1D,EAAW,EAAU,OAC3B,IAAK,GAAM,CAAC,EAAO,KAAa,EAAU,QAAQ,EAAG,CACnD,IAAM,EAAiB,EACrB,EAAO,MAAM,CAAE,cAAe,EAAW,CAAM,CAAC,EAAG,gBAAiB,OACtE,EACI,EAAmD,QACnD,EAA8C,4BAC9C,EACA,EACA,EAAU,GACV,EAAY,GACZ,EACA,EACE,EAAqC,CAAC,EAEtC,EAAW,YAAY,EAAW,IAElC,MAAsB,CAC1B,IAAK,IAAM,IAAO,CAAC,GAAG,CAAa,CAAC,CAAC,QAAQ,EACtC,KAAI,OACT,GAAI,OAAS,GACb,GAAI,CAAE,EAAI,OAAO,CAAE,MAAQ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,EAAc,EAChB,GAH0B,CAInC,CACF,CAAC,CAAC,EACF,EAAoB,CAAM,CAC5B,OAAS,EAAgB,CACvB,IAAM,EAAU,GAAmB,GAAQ,UAAY,GACnD,EAAS,EAAe,MAAM,EAAQ,EAAe,KAAK,CAAK,EACnE,IAAM,EAA6C,CAAC,EAChD,IAAmB,IAAA,IAAW,EAAY,KAAK,CAAc,EACjE,IAAM,EAAW,GAAW,SAAS,EACrC,IAAK,IAAM,IAAgB,CAAC,GAAG,CAAS,CAAC,CAAC,QAAQ,EAAG,EAAY,KAAK,EAAa,MAAM,CAAQ,CAAC,EAClG,MAAM,IAAI,EAA8B,CACtC,YAAa,EAAU,6BAA+B,EACtD,MAAO,iBACP,OAAQ,EAAU,UAAY,IAAgB,6BAA+B,YAAc,SAC3F,UAAW,CAAE,KAAM,kBAAmB,GAAI,CAAS,EAAG,QAAS,CACjE,CAAC,CACH,CACF,CACA,OAAO,OAAO,OAAO,CAAC,GAAG,CAAS,CAAC,CACrC,CAqBA,SAAgB,EACd,EACiC,CACjC,IAAM,EAAmC,CAAE,UAAW,CAAC,CAAE,EAEzD,OADA,EAAkB,EAAM,SAAU,EAAM,UAAW,EAAM,OAAQ,EAAM,OAAQ,EAAM,UAAW,CAAM,EAC/F,EAA2B,EAAM,kBAAmB,EAAM,mBAC/D,EAAM,OAAQ,EAAM,OAAQ,EAAM,UAAW,CAAM,CACvD"}
@@ -0,0 +1,2 @@
1
+ import{EMBEDDING_ERROR_CODES as e,EmbeddingError as t}from"../../embedding/errors.js";function n(e){return e.replace(/\\/g,`\\\\`).replace(/\|/g,`\\|`)}async function r(e){let t=await crypto.subtle.digest(`SHA-256`,new TextEncoder().encode(e)),n=``;for(let e of new Uint8Array(t))n+=e.toString(16).padStart(2,`0`);return n}function i(n){if(n!==void 0){if(typeof n.scope!=`string`||n.scope.length===0)throw new t("Embedding cache requires a non-empty `scope`; there is no default security scope",e.CONFIGURATION_INVALID);if(n.store===null||typeof n.store!=`object`||typeof n.store.get!=`function`||typeof n.store.set!=`function`)throw new t("Embedding cache requires a `store` exposing `get` and `set`",e.CONFIGURATION_INVALID);return n}}async function a(e){let{profile:t}=e,i=e.purpose===`retrieval-query`?t.queryRecipeRevision:t.documentRecipeRevision,a=t.postProcessing===void 0?`none`:`${t.postProcessing.kind}:${t.postProcessing.revision}`,o=await r(e.contentParts.map(e=>`${e.type}:${n(e.text)}`).join(`|`));return r([`embcache:1`,e.scope,`${t.modelIdentity}#${t.modelRevision??`none`}#${t.profileRevision}`,`${e.purpose}#${i}`,`${String(t.dimensions)}#${a}`,o].map(n).join(`|`))}async function o(e,t,n,r){try{let i=await e.store.get(t);if(typeof i!=`object`||!i||i.space!==n)return;let a=i.values;if(!Array.isArray(a)||a.length===0||r!==void 0&&r>0&&a.length!==r)return;let o=[];for(let e of a){if(typeof e!=`number`||!Number.isFinite(e))return;o.push(e)}return Object.freeze({space:n,values:Object.freeze(o)})}catch{return}}async function s(e,t,n){try{await e.store.set(t,Object.freeze({space:n.space,values:Object.freeze([...n.values])}))}catch{}}export{a as embeddingCacheKey,o as readEmbeddingCacheEntry,i as resolveEmbeddingCache,s as writeEmbeddingCacheEntry};
2
+ //# sourceMappingURL=cache.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"cache.js","names":[],"sources":["../../../src/composition/embedding/cache.ts"],"sourcesContent":["/**\n * The optional `Embedding_Cache`: key derivation plus the two gates a read must\n * pass before its vector is reused.\n *\n * DISABLED BY DEFAULT (Requirement 5.1). Nothing here runs unless the caller\n * supplies `EmbeddingModelOptions.cache`, which is what keeps `crypto.subtle`\n * off every mandatory code path of `packages/core` (DD-11).\n *\n * `EmbeddingCacheOptions`, `EmbeddingCacheStore` and `EmbeddingCacheEntry` are\n * declared in `embedding/handle.ts` because `EmbeddingModelOptions.cache` needs\n * them and `embedding/` may not import `composition/` (DD-8). This module\n * CONSUMES those types and redeclares none of them; the only new type here is\n * {@link EmbeddingCacheKeyInput}, which is an input of this module alone.\n *\n * @module ai-agent-sdk/core/composition/embedding/cache\n */\n\nimport { EMBEDDING_ERROR_CODES, EmbeddingError } from '../../embedding/errors.ts'\nimport type {\n EmbeddingCacheEntry,\n EmbeddingCacheOptions,\n} from '../../embedding/handle.ts'\nimport type { EmbeddingProfile, EmbeddingSpaceId } from '../../embedding/profile.ts'\nimport type { EmbeddingPurpose } from '../../embedding/purpose.ts'\nimport type { EmbeddingContentPart } from '../../embedding/request.ts'\n\n/** Version prefix of the canonical pre-image, so key format changes never collide. */\nconst CACHE_KEY_VERSION = 'embcache:1'\n\n/** Everything a cache key depends on, for exactly one item of one call. */\nexport interface EmbeddingCacheKeyInput {\n /** REQUIRED security scope from {@link EmbeddingCacheOptions.scope}. */\n readonly scope: string\n /** Resolved profile of the `Prepared_Embedding_Call`. */\n readonly profile: EmbeddingProfile\n /** Purpose of this call; it selects which recipe revision enters the key. */\n readonly purpose: EmbeddingPurpose\n /**\n * The EFFECTIVE input, i.e. the content parts as the adapter normalized them.\n * Hashing anything earlier would key on text the provider never saw.\n */\n readonly contentParts: readonly EmbeddingContentPart[]\n}\n\n/** Escapes `|` and `\\` so two distinct component tuples cannot join to one string. */\nfunction escapeComponent(value: string): string {\n return value.replace(/\\\\/g, '\\\\\\\\').replace(/\\|/g, '\\\\|')\n}\n\n/** Lowercase hex of a SHA-256 digest over the UTF-8 bytes of `value`. */\nasync function sha256Hex(value: string): Promise<string> {\n const digest = await crypto.subtle.digest('SHA-256', new TextEncoder().encode(value))\n let hex = ''\n for (const byte of new Uint8Array(digest)) {\n hex += byte.toString(16).padStart(2, '0')\n }\n return hex\n}\n\n/**\n * Validates the cache configuration and reports whether the cache is on.\n *\n * `scope` is REQUIRED with no default: there is no safe default answer to \"may\n * two tenants share a cache entry\", so a missing or empty scope is\n * `EMBEDDING_CONFIGURATION_INVALID` rather than something the runtime fills in\n * (DD-8, Requirement 5.2). Absent options mean the cache is simply off, which is\n * not an error (Requirement 5.1).\n *\n * @throws {EmbeddingError} `EMBEDDING_CONFIGURATION_INVALID` when a cache is\n * supplied without a usable `store` or without a non-empty `scope`.\n */\nexport function resolveEmbeddingCache(\n options: EmbeddingCacheOptions | undefined,\n): EmbeddingCacheOptions | undefined {\n if (options === undefined) return undefined\n\n if (typeof options.scope !== 'string' || options.scope.length === 0) {\n throw new EmbeddingError(\n 'Embedding cache requires a non-empty `scope`; there is no default security scope',\n EMBEDDING_ERROR_CODES.CONFIGURATION_INVALID,\n )\n }\n if (\n options.store === null\n || typeof options.store !== 'object'\n || typeof options.store.get !== 'function'\n || typeof options.store.set !== 'function'\n ) {\n throw new EmbeddingError(\n 'Embedding cache requires a `store` exposing `get` and `set`',\n EMBEDDING_ERROR_CODES.CONFIGURATION_INVALID,\n )\n }\n return options\n}\n\n/**\n * Derives the cache key of one input from the five components of Requirement 5.2:\n *\n * 1. security scope,\n * 2. model identity + model revision + profile revision,\n * 3. purpose + the recipe revision that purpose selects,\n * 4. dimensions + post-processing (kind and revision),\n * 5. the digest of the effective input content.\n *\n * ASYNC on purpose, and the ONLY digest in this design. A cache key must\n * compress an unbounded amount of input content into a fixed-length string, so a\n * hash is required. `deriveSpaceId` is the opposite case: it joins a finite set\n * of short metadata fields, so it stays synchronous and unhashed (DD-11).\n *\n * Changing any one of the five components yields a different key; keeping all\n * five yields an equal key.\n */\nexport async function embeddingCacheKey(input: EmbeddingCacheKeyInput): Promise<string> {\n const { profile } = input\n const recipeRevision =\n input.purpose === 'retrieval-query'\n ? profile.queryRecipeRevision\n : profile.documentRecipeRevision\n const postProcessing =\n profile.postProcessing === undefined\n ? 'none'\n : `${profile.postProcessing.kind}:${profile.postProcessing.revision}`\n\n // The effective input is hashed FIRST and separately: it is the only unbounded\n // component, and pre-hashing it keeps the outer pre-image a fixed size.\n const contentDigest = await sha256Hex(\n input.contentParts.map(part => `${part.type}:${escapeComponent(part.text)}`).join('|'),\n )\n\n const components = [\n CACHE_KEY_VERSION,\n input.scope,\n `${profile.modelIdentity}#${profile.modelRevision ?? 'none'}#${profile.profileRevision}`,\n `${input.purpose}#${recipeRevision}`,\n `${String(profile.dimensions)}#${postProcessing}`,\n contentDigest,\n ]\n\n return sha256Hex(components.map(escapeComponent).join('|'))\n}\n\n/**\n * Reads one entry and applies the SECOND gate: an entry whose `Space_Id` differs\n * from the prepared call's `Space_Id` is ignored, so the item falls through to a\n * new `Physical_Batch` (Requirement 5.3).\n *\n * This defends against a key collision caused by a configuration change that was\n * never reflected in `profileRevision`. A store fault is also treated as a miss:\n * a cache is an optimisation and must not be able to fail a call.\n */\nexport async function readEmbeddingCacheEntry(\n cache: EmbeddingCacheOptions,\n key: string,\n space: EmbeddingSpaceId,\n dimensions?: number,\n): Promise<EmbeddingCacheEntry | undefined> {\n try {\n const entry = await cache.store.get(key)\n if (entry === null || typeof entry !== 'object' || entry.space !== space) return undefined\n const values = entry.values\n if (!Array.isArray(values) || values.length === 0\n || (dimensions !== undefined && dimensions > 0 && values.length !== dimensions)) return undefined\n const snapshot: number[] = []\n for (const value of values) {\n if (typeof value !== 'number' || !Number.isFinite(value)) return undefined\n snapshot.push(value)\n }\n return Object.freeze({ space, values: Object.freeze(snapshot) })\n } catch {\n return undefined\n }\n}\n\n/**\n * Writes one vector together with the space it was produced in, so the second\n * gate has something to check on the way back out.\n *\n * A store fault is swallowed for the same reason as on read: a cache write must\n * not turn a successful embedding call into a failure.\n */\nexport async function writeEmbeddingCacheEntry(\n cache: EmbeddingCacheOptions,\n key: string,\n entry: EmbeddingCacheEntry,\n): Promise<void> {\n try {\n await cache.store.set(key, Object.freeze({ space: entry.space, values: Object.freeze([...entry.values]) }))\n } catch {\n // Intentionally ignored: the vector is already computed and returned.\n }\n}\n"],"mappings":"sFA6CA,SAAS,EAAgB,EAAuB,CAC9C,OAAO,EAAM,QAAQ,MAAO,MAAM,CAAC,CAAC,QAAQ,MAAO,KAAK,CAC1D,CAGA,eAAe,EAAU,EAAgC,CACvD,IAAM,EAAS,MAAM,OAAO,OAAO,OAAO,UAAW,IAAI,YAAY,CAAC,CAAC,OA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,OACrB,GAAI,CAAC,MAAM,QAAQ,CAAM,GAAK,EAAO,SAAW,GAC1C,IAAe,IAAA,IAAa,EAAa,GAAK,EAAO,SAAW,EAAa,OACnF,IAAM,EAAqB,CAAC,EAC5B,IAAK,IAAM,KAAS,EAAQ,CAC1B,GAAI,OAAO,GAAU,UAAY,CAAC,OAAO,SAAS,CAAK,EAAG,OAC1D,EAAS,KAAK,CAAK,CACrB,CACA,OAAO,OAAO,OAAO,CAAE,QAAO,OAAQ,OAAO,OAAO,CAAQ,CAAE,CAAC,CACjE,MAAQ,CACN,MACF,CACF,CASA,eAAsB,EACpB,EACA,EACA,EACe,CACf,GAAI,CACF,MAAM,EAAM,MAAM,IAAI,EAAK,OAAO,OAAO,CAAE,MAAO,EAAM,MAAO,OAAQ,OAAO,OAAO,CAAC,GAAG,EAAM,MAAM,CAAC,CAAE,CAAC,CAAC,CAC5G,MAAQ,CAER,CACF"}
@@ -0,0 +1,7 @@
1
+ import { ComposableEmbeddingProviderPlugin, EmbeddingProviderPluginDefinition } from "./plugin-types.js";
2
+ //#region src/composition/embedding/definition.d.ts
3
+ /** Create an inert embedding plugin wrapper; setup and cleanup stay deferred to activation. */
4
+ declare function defineEmbeddingProviderPlugin(definition: EmbeddingProviderPluginDefinition): ComposableEmbeddingProviderPlugin;
5
+ //#endregion
6
+ export { defineEmbeddingProviderPlugin };
7
+ //# sourceMappingURL=definition.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"definition.d.ts","names":[],"sources":["../../../src/composition/embedding/definition.ts"],"mappings":";;;iBAYgB,8BACd,YAAY,oCACX"}
@@ -0,0 +1,2 @@
1
+ import{arrayData as e,boundedText as t,capturedMethod as n,objectValue as r,ownData as i}from"../../capability/common/data.js";import{COMPOSITION_LIMITS as a}from"../../capability/common/config.js";import{captureModelTarget as o}from"../provider/model-selection.js";import"./plugin-types.js";function s(s){let d=r(s),f=t(i(d,`id`),a.identityBytes),p=t(i(d,`displayName`),a.displayNameBytes),m=i(d,`family`,!1),h=m===void 0?void 0:t(m,a.identityBytes),g=e(i(d,`routes`),a.routesPerProvider).map(e=>t(e,a.identityBytes));if(g.length===0||new Set(g).size!==g.length)throw TypeError(`Provider route claims must be non-empty and unique`);let _=i(d,`defaultModel`,!1),v=_===void 0?void 0:o(_,!1);if(v!==void 0&&!g.includes(v.provider))throw TypeError(`Provider default model route is not claimed`);let y=n(d,`setup`),b=Object.freeze(g),x=e=>{let t=u(e),n=Object.freeze({logger:t,registerEmbeddingAdapter(t,n){let r=n?.routes===void 0?b:c(n.routes,b),i=n?.models===void 0?void 0:l(n.models);return e.registerEmbeddingAdapter(r,t,i)}}),r=y(n);if(r!==void 0)return typeof r==`function`?()=>{r()}:r};return Object.freeze({kind:`embedding-provider-plugin`,apiVersion:1,id:f,displayName:p,routes:b,...h===void 0?{}:{family:h},...v===void 0?{}:{defaultModel:v},setup:x})}function c(n,r){let i=e(n,a.routesPerProvider).map(e=>t(e,a.identityBytes));if(i.length===0||new Set(i).size!==i.length)throw TypeError(`Embedding adapter route selection must be non-empty and unique`);for(let e of i)if(!r.includes(e))throw TypeError(`Embedding adapter route is not claimed by this plugin`);return Object.freeze(i)}function l(n){let r=e(n,a.routesPerProvider).map(e=>t(e,a.modelIdBytes));if(r.length===0||new Set(r).size!==r.length)throw TypeError(`Embedding adapter model selection must be non-empty and unique`);return Object.freeze(r)}function u(e){let t=Reflect.get(e,`logger`);if(t===void 0||typeof t.child!=`function`||typeof t.info!=`function`||typeof t.error!=`function`)throw TypeError(`Composable embedding provider setup requires a runtime-bound logger`);return t}export{s as defineEmbeddingProviderPlugin};
2
+ //# sourceMappingURL=definition.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"definition.js","names":[],"sources":["../../../src/composition/embedding/definition.ts"],"sourcesContent":["import type { EmbeddingAdapter } from '../../embedding/adapter.ts'\nimport type { SdkLogger } from '../../logging/types.ts'\nimport { COMPOSITION_LIMITS } from '../common/config.ts'\nimport { arrayData, boundedText, capturedMethod, objectValue, ownData } from '../common/data.ts'\nimport { captureModelTarget } from '../provider/model-selection.ts'\nimport {\n EMBEDDING_PROVIDER_PLUGIN_API_VERSION, type ComposableEmbeddingProviderPlugin,\n type ComposableEmbeddingProviderRegistrar, type EmbeddingProviderPluginCleanupDefinition,\n type EmbeddingProviderPluginDefinition, type EmbeddingProviderRegistrar,\n} from './plugin-types.ts'\n\n/** Create an inert embedding plugin wrapper; setup and cleanup stay deferred to activation. */\nexport function defineEmbeddingProviderPlugin(\n definition: EmbeddingProviderPluginDefinition,\n): ComposableEmbeddingProviderPlugin {\n const source = objectValue(definition)\n const id = boundedText(ownData(source, 'id'), COMPOSITION_LIMITS.identityBytes)\n const displayName = boundedText(ownData(source, 'displayName'), COMPOSITION_LIMITS.displayNameBytes)\n const familyValue = ownData(source, 'family', false)\n const family = familyValue === undefined ? undefined\n : boundedText(familyValue, COMPOSITION_LIMITS.identityBytes)\n const routes = arrayData(ownData(source, 'routes'), COMPOSITION_LIMITS.routesPerProvider)\n .map(route => boundedText(route, COMPOSITION_LIMITS.identityBytes))\n if (routes.length === 0 || new Set(routes).size !== routes.length) {\n throw new TypeError('Provider route claims must be non-empty and unique')\n }\n const defaultValue = ownData(source, 'defaultModel', false)\n const defaultModel = defaultValue === undefined ? undefined : captureModelTarget(defaultValue, false)\n if (defaultModel !== undefined && !routes.includes(defaultModel.provider)) {\n throw new TypeError('Provider default model route is not claimed')\n }\n const authorSetup = capturedMethod<\n [ComposableEmbeddingProviderRegistrar], undefined | EmbeddingProviderPluginCleanupDefinition\n >(source, 'setup')\n const claims = Object.freeze(routes)\n const setup = (registrar: EmbeddingProviderRegistrar): void | (() => void) => {\n const logger = boundLogger(registrar)\n const scoped: ComposableEmbeddingProviderRegistrar = Object.freeze({\n logger,\n registerEmbeddingAdapter(\n adapter: EmbeddingAdapter,\n options?: { readonly routes?: readonly string[]; readonly models?: readonly string[] },\n ) {\n const selected = options?.routes === undefined ? claims : capturedRoutes(options.routes, claims)\n const models = options?.models === undefined ? undefined : capturedModels(options.models)\n return registrar.registerEmbeddingAdapter(selected, adapter, models)\n },\n })\n const cleanup = authorSetup(scoped)\n if (cleanup === undefined) return\n if (typeof cleanup !== 'function') return cleanup as never\n return () => { cleanup() }\n }\n return Object.freeze({\n kind: 'embedding-provider-plugin', apiVersion: EMBEDDING_PROVIDER_PLUGIN_API_VERSION,\n id, displayName, routes: claims, ...(family === undefined ? {} : { family }),\n ...(defaultModel === undefined ? {} : { defaultModel }), setup,\n })\n}\n\n/** Registration cannot reach outside the predeclared claims (Requirement 11.5). */\nfunction capturedRoutes(\n value: readonly string[],\n claims: readonly string[],\n): readonly string[] {\n const selected = arrayData(value, COMPOSITION_LIMITS.routesPerProvider)\n .map(route => boundedText(route, COMPOSITION_LIMITS.identityBytes))\n if (selected.length === 0 || new Set(selected).size !== selected.length) {\n throw new TypeError('Embedding adapter route selection must be non-empty and unique')\n }\n for (const route of selected) {\n if (!claims.includes(route)) {\n throw new TypeError('Embedding adapter route is not claimed by this plugin')\n }\n }\n return Object.freeze(selected)\n}\n\nfunction capturedModels(value: readonly string[]): readonly string[] {\n const models = arrayData(value, COMPOSITION_LIMITS.routesPerProvider)\n .map(model => boundedText(model, COMPOSITION_LIMITS.modelIdBytes))\n if (models.length === 0 || new Set(models).size !== models.length) {\n throw new TypeError('Embedding adapter model selection must be non-empty and unique')\n }\n return Object.freeze(models)\n}\n\nfunction boundLogger(registrar: EmbeddingProviderRegistrar): SdkLogger {\n const logger = Reflect.get(registrar, 'logger') as Partial<SdkLogger> | undefined\n if (logger === undefined || typeof logger.child !== 'function'\n || typeof logger.info !== 'function' || typeof logger.error !== 'function') {\n throw new TypeError('Composable embedding provider setup requires a runtime-bound logger')\n }\n return logger as SdkLogger\n}\n"],"mappings":"oSAYA,SAAgB,EACd,EACmC,CACnC,IAAM,EAAS,EAAY,CAAU,EAC/B,EAAK,EAAY,EAAQ,EAAQ,IAAI,EAAG,EAAmB,aAAa,EACxE,EAAc,EAAY,EAAQ,EAAQ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AAC,CACH,CAGA,SAAS,EACP,EACA,EACmB,CACnB,IAAM,EAAW,EAAU,EAAO,EAAmB,iBAAiB,CAAC,CACpE,IAAI,GAAS,EAAY,EAAO,EAAmB,aAAa,CAAC,EACpE,GAAI,EAAS,SAAW,GAAK,IAAI,IAAI,CAAQ,CAAC,CAAC,OAAS,EAAS,OAC/D,MAAU,UAAU,gEAAgE,EAEtF,IAAK,IAAM,KAAS,EAClB,GAAI,CAAC,EAAO,SAAS,CAAK,EACxB,MAAU,UAAU,uDAAuD,EAG/E,OAAO,OAAO,OAAO,CAAQ,CAC/B,CAEA,SAAS,EAAe,EAA6C,CACnE,IAAM,EAAS,EAAU,EAAO,EAAmB,iBAAiB,CAAC,CAClE,IAAI,GAAS,EAAY,EAAO,EAAmB,YAAY,CAAC,EACnE,GAAI,EAAO,SAAW,GAAK,IAAI,IAAI,CAAM,CAAC,CAAC,OAAS,EAAO,OACzD,MAAU,UAAU,gEAAgE,EAEtF,OAAO,OAAO,OAAO,CAAM,CAC7B,CAEA,SAAS,EAAY,EAAkD,CACrE,IAAM,EAAS,QAAQ,IAAI,EAAW,QAAQ,EAC9C,GAAI,IAAW,IAAA,IAAa,OAAO,EAAO,OAAU,YAC/C,OAAO,EAAO,MAAS,YAAc,OAAO,EAAO,OAAU,WAChE,MAAU,UAAU,qEAAqE,EAE3F,OAAO,CACT"}
@@ -0,0 +1,2 @@
1
+ import{MODEL_ERROR_CODES as e}from"../../errors/model-error.js";import{normalizeModelFailure as t}from"../../errors/failure.js";import{EMBEDDING_ERROR_CODES as n,EmbeddingError as r}from"../../embedding/errors.js";import"../../embedding/request.js";import{validateBatchResult as i,validatePreDispatch as a}from"../../embedding/validation.js";import{beginEmbeddingCallObservation as o}from"./observation.js";import{embeddingCacheKey as s,readEmbeddingCacheEntry as c,resolveEmbeddingCache as l,writeEmbeddingCacheEntry as u}from"./cache.js";import{resolveEmbeddingConcurrency as d,runBatchesWithConcurrency as f}from"./limiter.js";import{planEmbeddingBatches as p}from"./planner.js";import{createEmbeddingRetryLedger as m}from"./retry.js";import{aggregateEmbeddingUsage as h}from"./usage.js";function g(e){return new r(e,n.CONFIGURATION_INVALID)}const _=new Set([n.ABORTED,e.ABORTED,`RUNTIME_OPERATION_ABORTED`,`RUNTIME_CLOSING`,`RUNTIME_CLOSED`]);function v(e){return _.has(t(e).code)?`aborted`:`error`}function y(e,t){if(typeof e!=`string`||e.length===0)throw g(`embedding handle requires a non-empty \`${t}\``);return e}function b(e){let t=e.compatibilityIdentity===void 0?void 0:y(e.compatibilityIdentity,`compatibilityIdentity`),n=e.fallback;if(n===void 0)return t;if(!Array.isArray(n)||n.length===0)throw g(`embedding fallback declaration must be a non-empty array`);let r=t;for(let e of n){if(typeof e!=`object`||!e)throw g(`each embedding fallback entry must declare a model and an identity`);y(e.model,`fallback.model`);let t=y(e.compatibilityIdentity,`fallback.compatibilityIdentity`);if(r===void 0)r=t;else if(r!==t)throw g(`embedding fallback models must all declare the same compatibilityIdentity`)}return r}function x(e,t){if(typeof e==`string`)return[{type:`text`,text:e}];if(Array.isArray(e)){let i=[];for(let a of e){if(typeof a!=`object`||!a||a.type!==`text`||typeof a.text!=`string`)throw new r(`embedding content parts must have type "text" and a string text value`,n.REQUEST_INVALID,{itemIndexes:[t]});i.push(Object.freeze({type:`text`,text:a.text}))}return Object.freeze(i)}throw new r(`embedding input must be a string or an array of content parts`,n.REQUEST_INVALID,{itemIndexes:[t]})}function S(e){if(!Array.isArray(e))throw new r(`embedding input values must be an array`,n.REQUEST_INVALID);return Array.from(e,(e,t)=>({index:t,contentParts:x(e,t)}))}function C(e,t){return e!==`allow`||t.length===0?[]:[Object.freeze({code:`input-truncated`,itemIndexes:Object.freeze([...t]),message:`provider reported that it truncated the input before embedding it`})]}function w(e){let{adapter:t,context:_,operations:x,options:w,retryPolicy:T}=e,E=y(w.provider,`provider`),D=y(w.model,`model`),O=w.truncation??`reject`,k=d(w.concurrency),A=l(w.cache),j=b(w),M=e=>{if(j!==void 0&&e.profile.compatibilityIdentity!==j)throw g(`embedding fallback group declares compatibility identity "${j}" but route "${E}" resolved "${e.profile.compatibilityIdentity}"`)},N=async(e,t,n,r,i,a)=>{let o=[];for(let l of t){let t=await s({scope:e.scope,profile:n.profile,purpose:r,contentParts:l.contentParts}),u=await c(e,t,n.spaceId,n.profile.dimensions);if(u===void 0){a.set(l.index,t),o.push(l);continue}i[l.index]=u.values}return o},P=async(t,n,r,i)=>{let a=S(n),s=o({route:E,model:D,purpose:t,itemCount:a.length},{..._===void 0?{}:{context:_},...e.observation===void 0?{}:{observation:e.observation},...e.resource===void 0?{}:{resource:e.resource}}),c=0,l=0,u;try{let e=await F(s,t,a,r,i,e=>{c=e.cacheHits??c,l=e.providerAttempts??l,u=e.space??u});return s.end({status:`success`,spaceId:e.space,cacheHits:c,providerAttempts:e.usage.providerAttempts}),e}catch(e){throw s.end({status:v(e),...u===void 0?{}:{spaceId:u},cacheHits:c,providerAttempts:l,error:e}),e}},F=async(e,o,s,c,l,d)=>x.execute(`embedding-call`,c===void 0?{}:{signal:c},async c=>{let g=await t.prepareEmbeddingCall(E,D,{...w.dimensions===void 0?{}:{dimensions:w.dimensions},...w.batchLimits===void 0?{}:{limits:w.batchLimits}},c.signal,e.context);M(g),d({space:g.spaceId}),a({purpose:o,items:s,...w.dimensions===void 0?{}:{dimensions:w.dimensions},truncation:O,...l===void 0?{}:{expectedSpace:l}},g);let _=Array(s.length),y=new Map,b=A===void 0?s:await N(A,s,g,o,_,y);d({cacheHits:s.length-b.length});let x=m(g,{...T===void 0?{}:{policy:T},signal:c.signal,...e.context===void 0?{}:{context:e.context}}),S=0,j=new Map;if((await f(p(b,g.limits),async t=>{let a={provider:E,model:D,purpose:o,items:t.items,...w.dimensions===void 0?{}:{dimensions:w.dimensions},truncation:O,signal:c.signal},s=e.beginBatch({batchIndex:t.batchIndex,itemCount:t.items.length,byteCount:t.bytes,estimatedTokens:t.estimatedTokens,...w.dimensions===void 0?{}:{dimensions:w.dimensions}});try{let e=await x.dispatch(t.batchIndex,a,s.context);S+=e.attempts,d({providerAttempts:S});let o=e.state;if(o.phase===`failed`)throw o.error;if(o.phase!==`succeeded`)throw new r(`embedding batch ${t.batchIndex} settled in a non-terminal state`,n.RESPONSE_MALFORMED,{provider:E,model:D,itemIndexes:[...e.itemIndexes]});let c=o.vectors;i(a,{vectors:c});let l=[];for(let e of c)_[e.index]=e.values,e.truncated===!0&&l.push(e.index);if(j.set(t.batchIndex,{evidence:{itemIndexes:e.itemIndexes,attempts:e.attempts,...e.usage===void 0?{}:{usage:e.usage}},warnings:[...e.warnings,...C(O,l)]}),A!==void 0)for(let e of c){let t=y.get(e.index);t!==void 0&&await u(A,t,{values:e.values,space:g.spaceId})}s.end(`success`)}catch(e){throw s.end(v(e),e),e}},{concurrency:k,signal:c.signal})).aborted)throw new r(`embedding call aborted before every batch was dispatched`,n.ABORTED,{provider:E,model:D,space:g.spaceId});let P=[...j.keys()].sort((e,t)=>e-t),F=h({inputCount:s.length,batches:P.map(e=>j.get(e).evidence)}),I=[...P.flatMap(e=>j.get(e).warnings),...F.warnings];return{vectors:_.map((e,t)=>{if(e!==void 0)return e;throw new r(`embedding call produced no vector for an input`,n.RESPONSE_MALFORMED,{provider:E,model:D,itemIndexes:[t]})}),space:g.spaceId,prepared:g,usage:F.report,warnings:Object.freeze(I)}});return Object.freeze({async embed(e){let t=await P(e.purpose,[e.value],e.signal,e.expectedSpace??w.expectedSpace);return Object.freeze({embedding:t.vectors[0],space:t.space,profile:t.prepared.profile,usage:t.usage,warnings:t.warnings})},async embedMany(e){let t=await P(e.purpose,e.values,e.signal,e.expectedSpace??w.expectedSpace);return Object.freeze({embeddings:Object.freeze(t.vectors),space:t.space,profile:t.prepared.profile,usage:t.usage,warnings:t.warnings})}})}export{w as createEmbeddingModelHandle};
2
+ //# sourceMappingURL=handle.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"handle.js","names":[],"sources":["../../../src/composition/embedding/handle.ts"],"sourcesContent":["/**\n * `embed()` and `embedMany()`: the composition root of one `Logical_Call`.\n *\n * This module owns nothing new. Every mechanism it needs already exists and has\n * exactly one owner — `prepareEmbeddingCall()` for the configuration snapshot,\n * `validatePreDispatch()` for pre-dispatch rejection, `embeddingCacheKey()` for\n * the optional cache, `planEmbeddingBatches()` for splitting,\n * `runBatchesWithConcurrency()` for the in-flight bound,\n * `createEmbeddingRetryLedger()` for retry, `aggregateEmbeddingUsage()` for\n * honest usage. What is left here is the ORDER those pieces run in, and the four\n * decisions that only a `Logical_Call` is in a position to make:\n *\n * 1. **One snapshot per logical call.** `prepareEmbeddingCall()` is called ONCE,\n * and every `Physical_Batch` — first attempt or fifth retry — dispatches\n * through that same generation. Validation reads its metadata and the result\n * reports its `Space_Id`, so a provider reconfiguration mid-call cannot make\n * the call report a space it did not produce vectors in (Requirements 2.2,\n * 2.3, 2.4).\n * 2. **Order comes from `item.index`, never from settlement time.** Vectors are\n * written into a pre-allocated array at `results[item.index]`. Batches may\n * settle in any order, retries may reorder them further, and a provider may\n * return the vectors of one batch permuted; none of that is observable in the\n * output (Requirement 4.6).\n * 3. **`expectedSpace` is a rejection, not a warning.** An incompatible expected\n * space fails with `EMBEDDING_SPACE_INCOMPATIBLE` before the first attempt,\n * which `validatePreDispatch()` performs against the prepared call\n * (Requirements 6.2, 6.5).\n * 4. **A fallback group is checked when it is configured, not after a failure.**\n * A declared fallback outside the group sharing one `compatibilityIdentity`\n * is `EMBEDDING_CONFIGURATION_INVALID`. There is no fallback DISPATCH here at\n * all: a failure of the primary model propagates (Requirements 6.6, 6.7).\n *\n * Memory: nothing per-batch survives the batch. The run callback writes vectors,\n * records a few numbers of evidence, and drops the request — so peak payload\n * memory stays `concurrency × maxBytes` rather than scaling with the corpus.\n *\n * Observation is opened here because this is the only scope that knows all three\n * levels at once: `observation.ts` owns the record shapes, and this file owns\n * WHEN each level opens and closes. One `sdk.embedding.call` per logical call,\n * one `sdk.embedding.batch` per `Physical_Batch`, and provider attempts through\n * the existing `context.startProviderAttempt` / `attempt.end` pair, so embedding\n * retries land in the same ledger as generation retries (Requirements 16.1,\n * 16.4, 16.5).\n *\n * @module ai-agent-sdk/core/composition/embedding/handle\n */\n\nimport type { ResolvedRetryPolicy } from '../../contract/retry-policy.ts'\nimport type { EmbeddingAdapter, PreparedEmbeddingCall } from '../../embedding/adapter.ts'\nimport { EMBEDDING_ERROR_CODES, EmbeddingError } from '../../embedding/errors.ts'\nimport type {\n EmbedManyInput,\n EmbedOneInput,\n EmbeddingCacheOptions,\n EmbeddingModelHandle,\n EmbeddingModelOptions,\n} from '../../embedding/handle.ts'\nimport type { EmbeddingSpaceId } from '../../embedding/profile.ts'\nimport type { EmbeddingPurpose } from '../../embedding/purpose.ts'\nimport type {\n EmbeddingBatchRequest,\n EmbeddingContentPart,\n EmbeddingItem,\n EmbeddingTruncation,\n} from '../../embedding/request.ts'\nimport { DEFAULT_EMBEDDING_TRUNCATION } from '../../embedding/request.ts'\nimport type {\n EmbeddingManyResult,\n EmbeddingResult,\n EmbeddingWarning,\n} from '../../embedding/result.ts'\nimport type { EmbeddingUsageReport } from '../../embedding/usage.ts'\nimport { validateBatchResult, validatePreDispatch } from '../../embedding/validation.ts'\nimport { normalizeModelFailure } from '../../errors/failure.ts'\nimport { MODEL_ERROR_CODES } from '../../errors/model-error.ts'\nimport type { ObservationResource, OperationStatus } from '../../observation/event.ts'\nimport type { ObservationPort } from '../../observation/port.ts'\nimport type { ModelInvocationContext } from '../../observation/report.ts'\nimport type { OperationLease, OperationOptions } from '../lifecycle/types.ts'\nimport {\n beginEmbeddingCallObservation,\n type EmbeddingCallObservation,\n} from './observation.ts'\nimport {\n embeddingCacheKey,\n readEmbeddingCacheEntry,\n resolveEmbeddingCache,\n writeEmbeddingCacheEntry,\n} from './cache.ts'\nimport { resolveEmbeddingConcurrency, runBatchesWithConcurrency } from './limiter.ts'\nimport { planEmbeddingBatches } from './planner.ts'\nimport { createEmbeddingRetryLedger } from './retry.ts'\nimport {\n aggregateEmbeddingUsage,\n type EmbeddingBatchUsageEvidence,\n} from './usage.ts'\n\n/**\n * The admission surface this handle needs from `RuntimeOperations`.\n *\n * Structural on purpose: the handle needs a lease whose signal already fuses the\n * runtime root controller with the caller's signal, and nothing else. Declaring\n * the dependency this narrowly is what lets a test drive one `Logical_Call`\n * without standing up a whole runtime.\n */\nexport interface EmbeddingOperationScheduler {\n execute<T>(\n kind: 'embedding-call',\n options: OperationOptions,\n work: (lease: OperationLease) => Promise<T>,\n ): Promise<T>\n}\n\n/**\n * One member of a declared fallback group.\n *\n * `compatibilityIdentity` is REQUIRED, and that is the whole point: a fallback is\n * only legitimate when the provider has declared that the two models share an\n * embedding space. Naming a model id alone would ask the runtime to infer\n * compatibility from a name, which is exactly what Requirement 6.3 forbids.\n */\nexport interface EmbeddingFallbackDeclaration {\n readonly model: string\n /** The provider's declaration that this model shares the primary's space. */\n readonly compatibilityIdentity: string\n}\n\n/**\n * Handle configuration: the public {@link EmbeddingModelOptions} plus the two\n * fields that only exist to make a fallback group checkable.\n *\n * These live here rather than on `EmbeddingModelOptions` because they are\n * runtime configuration of one handle, not part of the type-only public surface\n * that `embedding/handle.ts` owns.\n */\nexport interface EmbeddingHandleOptions extends EmbeddingModelOptions {\n /**\n * The `compatibilityIdentity` the caller believes this route resolves to.\n *\n * When present it is enforced against the prepared call, so a route whose\n * declared identity has changed fails loudly instead of quietly producing\n * vectors in another space.\n */\n readonly compatibilityIdentity?: string\n /** Models declared to share this call's embedding space. */\n readonly fallback?: readonly EmbeddingFallbackDeclaration[]\n}\n\n/** Everything {@link createEmbeddingModelHandle} needs, resolved by the manager. */\nexport interface EmbeddingHandleDependencies {\n /** Runtime admission; supplies the lease whose signal covers `close()`. */\n readonly operations: EmbeddingOperationScheduler\n /** The adapter the registry resolved for this route + model. */\n readonly adapter: Pick<EmbeddingAdapter, 'prepareEmbeddingCall'>\n readonly options: EmbeddingHandleOptions\n /** Route policy captured at registration; omission takes the SDK defaults. */\n readonly retryPolicy?: ResolvedRetryPolicy\n /**\n * Caller invocation context.\n *\n * Its port, resource, correlation and scope are adopted so an embedding call\n * nested in a larger trace joins that trace. When it already performs attempt\n * accounting, that accounting is kept and this handle adds none of its own.\n */\n readonly context?: ModelInvocationContext\n /** Runtime default observation port, used when the context carries none. */\n readonly observation?: ObservationPort\n /** Runtime resource identity, used when the context carries none. */\n readonly resource?: ObservationResource\n}\n\n/** One settled batch's small, order-independent residue. */\ninterface BatchResidue {\n readonly evidence: EmbeddingBatchUsageEvidence\n readonly warnings: readonly EmbeddingWarning[]\n}\n\n/**\n * Facts a `Logical_Call` learns as it progresses, reported outward so the\n * terminal observation record is accurate even when the call fails.\n *\n * Every field is optional because each becomes known at a different point, and a\n * field that is not yet known must stay absent rather than be reported as zero.\n */\ninterface LogicalCallEvidence {\n readonly space?: EmbeddingSpaceId\n readonly cacheHits?: number\n readonly providerAttempts?: number\n}\n\n/** What one `Logical_Call` produces, before it is shaped into one of two results. */\ninterface LogicalCallOutcome {\n readonly vectors: readonly (readonly number[])[]\n readonly space: EmbeddingSpaceId\n readonly prepared: PreparedEmbeddingCall\n readonly usage: EmbeddingUsageReport\n readonly warnings: readonly EmbeddingWarning[]\n}\n\nfunction configurationError(message: string): EmbeddingError {\n return new EmbeddingError(message, EMBEDDING_ERROR_CODES.CONFIGURATION_INVALID)\n}\n\n/** Codes that mean the caller or the runtime stopped this, not that it broke. */\nconst ABORT_CODES: ReadonlySet<string> = new Set([\n EMBEDDING_ERROR_CODES.ABORTED,\n MODEL_ERROR_CODES.ABORTED,\n 'RUNTIME_OPERATION_ABORTED',\n 'RUNTIME_CLOSING',\n 'RUNTIME_CLOSED',\n])\n\n/**\n * Terminal status of one failed span.\n *\n * A cancellation is reported as `aborted` rather than `error` so an operator\n * reading a trace can tell a broken provider from a caller that changed its mind\n * — the two have very different follow-ups.\n */\nfunction terminalStatus(error: unknown): OperationStatus {\n return ABORT_CODES.has(normalizeModelFailure(error).code) ? 'aborted' : 'error'\n}\n\n/** A non-empty string, or a configuration failure naming the field. */\nfunction requireIdentifier(value: unknown, field: string): string {\n if (typeof value !== 'string' || value.length === 0) {\n throw configurationError(`embedding handle requires a non-empty \\`${field}\\``)\n }\n return value\n}\n\n/**\n * Validates a declared fallback group and reduces it to the ONE identity every\n * member must share.\n *\n * Rejecting at construction rather than at failure time is deliberate: a group\n * that spans two embedding spaces is misconfigured whether or not the primary\n * model ever fails, and discovering it only during an incident is the worst\n * possible moment (Requirement 6.7).\n */\nfunction resolveFallbackIdentity(options: EmbeddingHandleOptions): string | undefined {\n const declared = options.compatibilityIdentity === undefined\n ? undefined\n : requireIdentifier(options.compatibilityIdentity, 'compatibilityIdentity')\n const fallback = options.fallback\n if (fallback === undefined) return declared\n if (!Array.isArray(fallback) || fallback.length === 0) {\n throw configurationError('embedding fallback declaration must be a non-empty array')\n }\n\n let identity = declared\n for (const entry of fallback) {\n if (entry === null || typeof entry !== 'object') {\n throw configurationError('each embedding fallback entry must declare a model and an identity')\n }\n requireIdentifier(entry.model, 'fallback.model')\n const entryIdentity = requireIdentifier(entry.compatibilityIdentity, 'fallback.compatibilityIdentity')\n if (identity === undefined) identity = entryIdentity\n else if (identity !== entryIdentity) {\n // Two identities in one group means at least one member produces vectors\n // in a different space, so the group is not a fallback group at all.\n throw configurationError(\n 'embedding fallback models must all declare the same compatibilityIdentity',\n )\n }\n }\n return identity\n}\n\n/** Normalises one caller value into the content parts of a single item. */\nfunction toContentParts(\n value: string | readonly EmbeddingContentPart[],\n index: number,\n): readonly EmbeddingContentPart[] {\n if (typeof value === 'string') return [{ type: 'text', text: value }]\n if (Array.isArray(value)) {\n const parts: EmbeddingContentPart[] = []\n for (const part of value) {\n if (part === null || typeof part !== 'object' || part.type !== 'text' || typeof part.text !== 'string') {\n throw new EmbeddingError(\n 'embedding content parts must have type \"text\" and a string text value',\n EMBEDDING_ERROR_CODES.REQUEST_INVALID,\n { itemIndexes: [index] },\n )\n }\n parts.push(Object.freeze({ type: 'text', text: part.text }))\n }\n return Object.freeze(parts)\n }\n throw new EmbeddingError(\n 'embedding input must be a string or an array of content parts',\n EMBEDDING_ERROR_CODES.REQUEST_INVALID,\n { itemIndexes: [index] },\n )\n}\n\n/**\n * Builds the items of one `Logical_Call`.\n *\n * `index` is the caller's position and is the ONLY coordinate that matters\n * downstream: batching, retry and out-of-order settlement all preserve it, and\n * output order is restored from it.\n */\nfunction toItems(\n values: readonly (string | readonly EmbeddingContentPart[])[],\n): readonly EmbeddingItem[] {\n if (!Array.isArray(values)) {\n throw new EmbeddingError(\n 'embedding input values must be an array',\n EMBEDDING_ERROR_CODES.REQUEST_INVALID,\n )\n }\n return Array.from(values, (value, index) => ({ index, contentParts: toContentParts(value, index) }))\n}\n\n/** The truncation warning of one batch, when the caller allowed truncation. */\nfunction truncationWarnings(\n truncation: EmbeddingTruncation,\n indexes: readonly number[],\n): readonly EmbeddingWarning[] {\n if (truncation !== 'allow' || indexes.length === 0) return []\n return [Object.freeze<EmbeddingWarning>({\n code: 'input-truncated',\n itemIndexes: Object.freeze([...indexes]),\n message: 'provider reported that it truncated the input before embedding it',\n })]\n}\n\n/**\n * Creates one `EmbeddingModelHandle`.\n *\n * Everything that can be decided without the provider IS decided here, at\n * construction: route identity, the concurrency bound, the cache configuration,\n * and the fallback group. `embeddingModel()` is synchronous, so a caller learns\n * about a misconfiguration at the call that made it rather than at the first\n * `embed()`.\n *\n * @throws {EmbeddingError} `EMBEDDING_CONFIGURATION_INVALID` for an unusable\n * route, concurrency, cache, or fallback declaration.\n */\nexport function createEmbeddingModelHandle(\n dependencies: EmbeddingHandleDependencies,\n): EmbeddingModelHandle {\n const { adapter, context, operations, options, retryPolicy } = dependencies\n const provider = requireIdentifier(options.provider, 'provider')\n const model = requireIdentifier(options.model, 'model')\n const truncation = options.truncation ?? DEFAULT_EMBEDDING_TRUNCATION\n // Both throw EMBEDDING_CONFIGURATION_INVALID; both belong at construction.\n const concurrency = resolveEmbeddingConcurrency(options.concurrency)\n const cache = resolveEmbeddingCache(options.cache)\n const groupIdentity = resolveFallbackIdentity(options)\n\n /**\n * Enforces the declared group against what the route actually resolved to.\n *\n * The declaration is checked at construction; this is the second half of the\n * same check, and it is the earliest point at which the route's real identity\n * is known.\n */\n const assertDeclaredIdentity = (prepared: PreparedEmbeddingCall): void => {\n if (groupIdentity === undefined) return\n if (prepared.profile.compatibilityIdentity === groupIdentity) return\n throw configurationError(\n `embedding fallback group declares compatibility identity \"${groupIdentity}\" `\n + `but route \"${provider}\" resolved \"${prepared.profile.compatibilityIdentity}\"`,\n )\n }\n\n /**\n * Reads the cache for every item, returning the misses in input order.\n *\n * A hit is written straight into `results`, so a fully cached call plans zero\n * batches and spends zero `Provider_Attempt`s. Two gates apply: the key covers\n * the five components of Requirement 5.2, and `readEmbeddingCacheEntry`\n * discards an entry from another `Space_Id` (Requirement 5.3).\n */\n const partitionByCache = async (\n active: EmbeddingCacheOptions,\n items: readonly EmbeddingItem[],\n prepared: PreparedEmbeddingCall,\n purpose: EmbeddingPurpose,\n results: (readonly number[] | undefined)[],\n keys: Map<number, string>,\n ): Promise<readonly EmbeddingItem[]> => {\n const misses: EmbeddingItem[] = []\n for (const item of items) {\n const key = await embeddingCacheKey({\n scope: active.scope,\n profile: prepared.profile,\n purpose,\n contentParts: item.contentParts,\n })\n const entry = await readEmbeddingCacheEntry(active, key, prepared.spaceId, prepared.profile.dimensions)\n if (entry === undefined) {\n keys.set(item.index, key)\n misses.push(item)\n continue\n }\n results[item.index] = entry.values\n }\n return misses\n }\n\n /** One `Logical_Call`, from admission to a fully ordered vector array. */\n const runLogicalCall = async (\n purpose: EmbeddingPurpose,\n values: readonly (string | readonly EmbeddingContentPart[])[],\n signal: AbortSignal | undefined,\n expectedSpace: EmbeddingSpaceId | undefined,\n ): Promise<LogicalCallOutcome> => {\n const items = toItems(values)\n\n // Opened before admission, so even a call rejected by a closing runtime or by\n // pre-dispatch validation leaves one record showing zero provider attempts.\n const observation = beginEmbeddingCallObservation({\n route: provider,\n model,\n purpose,\n itemCount: items.length,\n }, {\n ...(context === undefined ? {} : { context }),\n ...(dependencies.observation === undefined ? {} : { observation: dependencies.observation }),\n ...(dependencies.resource === undefined ? {} : { resource: dependencies.resource }),\n })\n // Filled in as the call learns them; whatever is known when the call ends is\n // what the terminal record carries, and nothing is defaulted to a lie.\n let cacheHits = 0\n let providerAttempts = 0\n let space: EmbeddingSpaceId | undefined\n\n try {\n const outcome = await runAdmitted(\n observation,\n purpose,\n items,\n signal,\n expectedSpace,\n (evidence) => {\n cacheHits = evidence.cacheHits ?? cacheHits\n providerAttempts = evidence.providerAttempts ?? providerAttempts\n space = evidence.space ?? space\n },\n )\n observation.end({\n status: 'success',\n spaceId: outcome.space,\n cacheHits,\n providerAttempts: outcome.usage.providerAttempts,\n })\n return outcome\n } catch (error: unknown) {\n observation.end({\n status: terminalStatus(error),\n ...(space === undefined ? {} : { spaceId: space }),\n cacheHits,\n providerAttempts,\n error,\n })\n throw error\n }\n }\n\n /** The admitted body of one `Logical_Call`; see {@link runLogicalCall}. */\n const runAdmitted = async (\n observation: EmbeddingCallObservation,\n purpose: EmbeddingPurpose,\n items: readonly EmbeddingItem[],\n signal: AbortSignal | undefined,\n expectedSpace: EmbeddingSpaceId | undefined,\n report: (evidence: LogicalCallEvidence) => void,\n ): Promise<LogicalCallOutcome> => {\n return operations.execute(\n 'embedding-call',\n signal === undefined ? {} : { signal },\n async (lease): Promise<LogicalCallOutcome> => {\n // ONE snapshot for the whole logical call: validation below and every\n // dispatch further down read this same generation (Requirements 2.2-2.4).\n const prepared = await adapter.prepareEmbeddingCall(\n provider,\n model,\n {\n ...(options.dimensions === undefined ? {} : { dimensions: options.dimensions }),\n ...(options.batchLimits === undefined ? {} : { limits: options.batchLimits }),\n },\n lease.signal,\n observation.context,\n )\n assertDeclaredIdentity(prepared)\n // Known from here on, so a later failure still reports the space the call\n // would have produced vectors in.\n report({ space: prepared.spaceId })\n\n // Rejects purpose, empty inputs, dimensions, truncation, expectedSpace and\n // over-long inputs with 0 `Provider_Attempt` spent.\n validatePreDispatch({\n purpose,\n items,\n ...(options.dimensions === undefined ? {} : { dimensions: options.dimensions }),\n truncation,\n ...(expectedSpace === undefined ? {} : { expectedSpace }),\n }, prepared)\n\n // Pre-allocated to the INPUT length: the one mechanism behind order\n // restoration, independent of batch settlement order (Requirement 4.6).\n const results: (readonly number[] | undefined)[] = new Array<readonly number[] | undefined>(items.length)\n const cacheKeys = new Map<number, string>()\n const pending = cache === undefined\n ? items\n : await partitionByCache(cache, items, prepared, purpose, results, cacheKeys)\n report({ cacheHits: items.length - pending.length })\n\n const ledger = createEmbeddingRetryLedger(prepared, {\n ...(retryPolicy === undefined ? {} : { policy: retryPolicy }),\n signal: lease.signal,\n ...(observation.context === undefined ? {} : { context: observation.context }),\n })\n // Running total, so a call that fails mid-flight still reports the cost of\n // the attempts it already spent (Requirement 16.6).\n let attemptsSpent = 0\n // Keyed by `batchIndex` so warnings and usage evidence are reported in\n // plan order no matter which batch settled first.\n const residues = new Map<number, BatchResidue>()\n\n const outcome = await runBatchesWithConcurrency(\n planEmbeddingBatches(pending, prepared.limits),\n async (plan): Promise<void> => {\n const request: EmbeddingBatchRequest = {\n provider,\n model,\n purpose,\n items: plan.items,\n ...(options.dimensions === undefined ? {} : { dimensions: options.dimensions }),\n truncation,\n signal: lease.signal,\n }\n // Size only: the planner already measured this batch, so describing it\n // costs nothing and reveals nothing (Requirement 16.4).\n const batchObservation = observation.beginBatch({\n batchIndex: plan.batchIndex,\n itemCount: plan.items.length,\n byteCount: plan.bytes,\n estimatedTokens: plan.estimatedTokens,\n ...(options.dimensions === undefined ? {} : { dimensions: options.dimensions }),\n })\n try {\n // The batch context is what parents each `Provider_Attempt` under\n // the batch that provoked it; retry accounting is unchanged.\n const settled = await ledger.dispatch(\n plan.batchIndex,\n request,\n batchObservation.context,\n )\n attemptsSpent += settled.attempts\n report({ providerAttempts: attemptsSpent })\n const state = settled.state\n if (state.phase === 'failed') {\n // No fallback model: the primary's failure IS the call's failure\n // (Requirement 6.6).\n throw state.error\n }\n if (state.phase !== 'succeeded') {\n // The ledger only ever returns a terminal state. A non-terminal one\n // means the ledger contract was violated, and guessing which half of\n // the batch exists would be worse than saying so.\n throw new EmbeddingError(\n `embedding batch ${plan.batchIndex} settled in a non-terminal state`,\n EMBEDDING_ERROR_CODES.RESPONSE_MALFORMED,\n { provider, model, itemIndexes: [...settled.itemIndexes] },\n )\n }\n\n const vectors = state.vectors\n // Guards the write below. A permuted order is fine — indexes carry\n // the mapping — but a duplicate or foreign index is a protocol fault,\n // never something to reconcile by position.\n validateBatchResult(request, { vectors })\n\n const truncated: number[] = []\n for (const vector of vectors) {\n results[vector.index] = vector.values\n if (vector.truncated === true) truncated.push(vector.index)\n }\n\n residues.set(plan.batchIndex, {\n evidence: {\n itemIndexes: settled.itemIndexes,\n attempts: settled.attempts,\n ...(settled.usage === undefined ? {} : { usage: settled.usage }),\n },\n warnings: [...settled.warnings, ...truncationWarnings(truncation, truncated)],\n })\n\n if (cache !== undefined) {\n for (const vector of vectors) {\n const key = cacheKeys.get(vector.index)\n if (key === undefined) continue\n await writeEmbeddingCacheEntry(cache, key, {\n values: vector.values,\n space: prepared.spaceId,\n })\n }\n }\n batchObservation.end('success')\n } catch (error: unknown) {\n batchObservation.end(terminalStatus(error), error)\n throw error\n }\n },\n { concurrency, signal: lease.signal },\n )\n\n if (outcome.aborted) {\n throw new EmbeddingError(\n 'embedding call aborted before every batch was dispatched',\n EMBEDDING_ERROR_CODES.ABORTED,\n { provider, model, space: prepared.spaceId },\n )\n }\n\n const ordered = [...residues.keys()].sort((left, right) => left - right)\n const usage = aggregateEmbeddingUsage({\n inputCount: items.length,\n batches: ordered.map(index => residues.get(index)!.evidence),\n })\n const warnings = [\n ...ordered.flatMap(index => residues.get(index)!.warnings),\n ...usage.warnings,\n ]\n\n const vectors = results.map((values, index) => {\n if (values !== undefined) return values\n // Unreachable through the paths above: a settled plan covers every\n // pending item and the cache covers the rest. Kept as a hard failure\n // rather than a hole in the output, because a silently missing vector\n // would be indistinguishable from a zero vector downstream.\n throw new EmbeddingError(\n 'embedding call produced no vector for an input',\n EMBEDDING_ERROR_CODES.RESPONSE_MALFORMED,\n { provider, model, itemIndexes: [index] },\n )\n })\n\n return {\n vectors,\n space: prepared.spaceId,\n prepared,\n usage: usage.report,\n warnings: Object.freeze(warnings),\n }\n },\n )\n }\n\n return Object.freeze<EmbeddingModelHandle>({\n async embed(input: EmbedOneInput): Promise<EmbeddingResult> {\n // One item is a `Logical_Call` like any other; nothing about batching,\n // cache or usage aggregation is special-cased for it.\n const outcome = await runLogicalCall(\n input.purpose,\n [input.value],\n input.signal,\n input.expectedSpace ?? options.expectedSpace,\n )\n return Object.freeze<EmbeddingResult>({\n embedding: outcome.vectors[0]!,\n space: outcome.space,\n profile: outcome.prepared.profile,\n usage: outcome.usage,\n warnings: outcome.warnings,\n })\n },\n\n async embedMany(input: EmbedManyInput): Promise<EmbeddingManyResult> {\n const outcome = await runLogicalCall(\n input.purpose,\n input.values,\n input.signal,\n input.expectedSpace ?? options.expectedSpace,\n )\n return Object.freeze<EmbeddingManyResult>({\n embeddings: Object.freeze(outcome.vectors),\n space: outcome.space,\n profile: outcome.prepared.profile,\n usage: outcome.usage,\n warnings: outcome.warnings,\n })\n },\n })\n}\n"],"mappings":"uxBAuMA,SAAS,EAAmB,EAAiC,CAC3D,OAAO,IAAI,EAAe,EAAS,EAAsB,qBAAqB,CAChF,CAGA,MAAM,EAAmC,IAAI,IAAI,CAC/C,EAAsB,QACtB,EAAkB,QAClB,4BACA,kBACA,gBACF,CAAC,EASD,SAAS,EAAe,EAAiC,CACvD,OAAO,EAAY,IAAI,EAAsB,CAAK,CAAC,CAAC,IAAI,EAAI,UAAY,OAC1E,CAGA,SAAS,EAAkB,EAAgB,EAAuB,CAChE,GAAI,OAAO,GAAU,UAAY,EAAM,SAAW,EAChD,MAAM,EAAmB,2CAA2C,EAAM,GAAG,EAE/E,OAAO,CACT,CAWA,SAAS,EAAwB,EAAqD,CACpF,IA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ACzD,GAAG,EAAM,QACX,EAeA,MAAO,CACL,QAdc,EAAQ,KAAK,EAAQ,IAAU,CAC7C,GAAI,IAAW,IAAA,GAAW,OAAO,EAKjC,MAAM,IAAI,EACR,iDACA,EAAsB,mBACtB,CAAE,WAAU,QAAO,YAAa,CAAC,CAAK,CAAE,CAC1C,CACF,CAGQ,EACN,MAAO,EAAS,QAChB,WACA,MAAO,EAAM,OACb,SAAU,OAAO,OAAO,CAAQ,CAClC,CACF,CACF,EAGF,OAAO,OAAO,OAA6B,CACzC,MAAM,MAAM,EAAgD,CAG1D,IAAM,EAAU,MAAM,EACpB,EAAM,QACN,CAAC,EAAM,KAAK,EACZ,EAAM,OACN,EAAM,eAAiB,EAAQ,aACjC,EACA,OAAO,OAAO,OAAwB,CACpC,UAAW,EAAQ,QAAQ,GAC3B,MAAO,EAAQ,MACf,QAAS,EAAQ,SAAS,QAC1B,MAAO,EAAQ,MACf,SAAU,EAAQ,QACpB,CAAC,CACH,EAEA,MAAM,UAAU,EAAqD,CACnE,IAAM,EAAU,MAAM,EACpB,EAAM,QACN,EAAM,OACN,EAAM,OACN,EAAM,eAAiB,EAAQ,aACjC,EACA,OAAO,OAAO,OAA4B,CACxC,WAAY,OAAO,OAAO,EAAQ,OAAO,EACzC,MAAO,EAAQ,MACf,QAAS,EAAQ,SAAS,QAC1B,MAAO,EAAQ,MACf,SAAU,EAAQ,QACpB,CAAC,CACH,CACF,CAAC,CACH"}
@@ -0,0 +1,2 @@
1
+ import{EMBEDDING_ERROR_CODES as e,EmbeddingError as t}from"../../embedding/errors.js";function n(n){if(n===void 0)return 4;if(!Number.isInteger(n)||n<=0)throw new t(`embedding concurrency must be a positive integer`,e.CONFIGURATION_INVALID);return n}async function r(e,t,r){let o=n(r?.concurrency),s=r?.signal,c=()=>s?.aborted===!0,l=i(e),u=0,d=!1,f=!1,p,m=Promise.resolve(),h=async()=>{for(;;){if(p!==void 0||f)return;if(c()){d=!0;return}let e=m.then(async()=>{if(p!==void 0||f||c())return;let e=await l.next();if(c()){d=!0;return}if(p===void 0){if(e.done===!0){f=!0;return}return{batch:e.value}}});m=e.then(()=>void 0,()=>void 0);let n;try{n=await e}catch(e){p??={error:e};return}if(n!==void 0){if(p!==void 0)return;if(c()){d=!0;return}try{await t(n.batch,u++)}catch(e){p??={error:e};return}}}},g=[];for(let e=0;e<o;e+=1)g.push(h());if(await Promise.all(g),p!==void 0)throw await a(l),p.error;return d||!f?(await a(l),{started:u,aborted:d||!f}):{started:u,aborted:!1}}function i(n){let r=n[Symbol.asyncIterator];if(typeof r==`function`)return r.call(n);let i=n[Symbol.iterator];if(typeof i==`function`)return i.call(n);throw new t(`embedding batch source must be iterable`,e.CONFIGURATION_INVALID)}async function a(e){try{await e.return?.(void 0)}catch{}}export{n as resolveEmbeddingConcurrency,r as runBatchesWithConcurrency};
2
+ //# sourceMappingURL=limiter.js.map