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

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 (52) hide show
  1. package/README.md +12 -1
  2. package/dist/agent/define/session.d.ts +5 -2
  3. package/dist/agent/define/session.d.ts.map +1 -1
  4. package/dist/agent/define/session.js +1 -1
  5. package/dist/agent/define/session.js.map +1 -1
  6. package/dist/agent/history/input-work.js +2 -0
  7. package/dist/agent/history/input-work.js.map +1 -0
  8. package/dist/agent/loop/control-text.d.ts +6 -0
  9. package/dist/agent/loop/control-text.d.ts.map +1 -0
  10. package/dist/agent/loop/control-text.js +2 -0
  11. package/dist/agent/loop/control-text.js.map +1 -0
  12. package/dist/agent/loop/run-turn.d.ts.map +1 -1
  13. package/dist/agent/loop/run-turn.js +1 -1
  14. package/dist/agent/loop/run-turn.js.map +1 -1
  15. package/dist/agent/loop/schedule.d.ts +5 -0
  16. package/dist/agent/loop/schedule.d.ts.map +1 -1
  17. package/dist/agent/loop/schedule.js +1 -1
  18. package/dist/agent/loop/schedule.js.map +1 -1
  19. package/dist/agent/loop/turn/model-round.js +1 -1
  20. package/dist/agent/loop/turn/model-round.js.map +1 -1
  21. package/dist/agent/mode/run-agent.d.ts +8 -15
  22. package/dist/agent/mode/run-agent.d.ts.map +1 -1
  23. package/dist/agent/mode/run-agent.js +2 -2
  24. package/dist/agent/mode/run-agent.js.map +1 -1
  25. package/dist/agent/team/contracts.d.ts +3 -1
  26. package/dist/agent/team/contracts.d.ts.map +1 -1
  27. package/dist/agent/team/managed.d.ts.map +1 -1
  28. package/dist/agent/team/managed.js +5 -5
  29. package/dist/agent/team/managed.js.map +1 -1
  30. package/dist/agent/team/team.d.ts.map +1 -1
  31. package/dist/agent/team/team.js +1 -1
  32. package/dist/agent/team/team.js.map +1 -1
  33. package/dist/agent/tool/pipeline.js +1 -1
  34. package/dist/agent/tool/pipeline.js.map +1 -1
  35. package/dist/agent.d.ts +2 -1
  36. package/dist/agent.js +1 -1
  37. package/dist/composition/agent/session.js +1 -1
  38. package/dist/composition/agent/session.js.map +1 -1
  39. package/dist/composition/agent/types.d.ts +3 -1
  40. package/dist/composition/agent/types.d.ts.map +1 -1
  41. package/dist/composition/embedding/retry.js +1 -1
  42. package/dist/composition/embedding/retry.js.map +1 -1
  43. package/dist/embedding/errors.d.ts +5 -1
  44. package/dist/embedding/errors.d.ts.map +1 -1
  45. package/dist/embedding/errors.js +1 -1
  46. package/dist/embedding/errors.js.map +1 -1
  47. package/dist/observability/bus.js +1 -1
  48. package/dist/primitives/version.d.ts +1 -1
  49. package/dist/primitives/version.js +1 -1
  50. package/dist/primitives/version.js.map +1 -1
  51. package/dist/runtime/registry.js +1 -1
  52. package/package.json +1 -1
@@ -1,2 +1,2 @@
1
- import{isJsonValue as e}from"../../primitives/json.js";import{detachedFrozen as t}from"../../primitives/snapshot.js";import{AgentSdkError as n}from"../../errors/agent-sdk-error.js";import{freezeMessage as r}from"../../message/message.js";import{capabilityIdentityError as i,inheritCapabilityIdentityConflict as a}from"../../errors/capability-identity.js";import{createRunTerminalRecord as o}from"../../agent/accounting/delivery/terminal.js";import{atDeadline as s}from"../lifecycle/bounded.js";import{AgentRunError as c}from"../../agent/accounting/error.js";import{TOOL_ERROR_CODES as l}from"../../agent/tool/errors.js";import{compactRuntimeSession as u,configureRuntimeSessionModel as d,streamPendingRuntimeSession as f,streamRuntimeSession as p}from"../../agent/define/session/runtime-binding.js";import{assertAgentIdentitySnapshot as m}from"../identity/agent.js";import{publicMessage as h}from"./public-message.js";import{finalizeRuntimeRunReport as g}from"../observation/final-report.js";import{snapshotToolSources as _}from"../tool-source/snapshot.js";import{createRuntimeMemoryPersistence as v}from"../memory/run.js";import{validateMemoryResumeBinding as y}from"../memory/resume.js";import{captureInvocationOptions as b,captureRuntimeSessionOptions as x}from"./options.js";import{projectNativeToolEvent as S}from"./native-event.js";const C=new WeakMap;function w(e,t){let n=Object.freeze({model:t.model,generate(n,r){return O(e,t).run(n,r)},stream(n,r){return O(e,t).stream(n,r)},createSession(n){return O(e,t,n)},resumeSession(n,r){return O(e,t,r,n)}});return C.set(n,Object.freeze({host:e,definition:t})),n}function T(e,t,r,i,a){let o=C.get(t);if(o?.host!==e)throw new n(`Runtime team members must be agents from the same runtime`,`TEAM_AGENT_OWNERSHIP_INVALID`);let s=O(e,o.definition,r,void 0,i,a);return Object.freeze({view:s,port:s.teamPort})}function E(e,t,r,i){let a=C.get(t);if(a?.host!==e)throw new n(`Runtime team members must be agents from the same runtime`,`TEAM_AGENT_OWNERSHIP_INVALID`);m({tools:[...a.definition.legacy.tools,...r.tools??[]],nativeTools:a.definition.legacy.nativeTools,skills:[...a.definition.legacy.skills,...r.skills??[]],...a.definition.legacy.skillIds===void 0?{}:{allowedSkillIds:a.definition.legacy.skillIds},additionalToolNames:i})}var D=class{host;session;nativeProvider;ownerSignal;active;observerTimeoutMs;teamPort;constructor(e,t,n,r,i=3e4,a){this.host=e,this.session=t,this.nativeProvider=n,this.ownerSignal=a,this.observerTimeoutMs=i;let o=this;this.teamPort=Object.freeze({definition:Object.freeze({id:r}),get conversationId(){return o.conversationId},get isRunning(){return o.isRunning},inject(e){return o.injectForTeam(e)},whenIdle(e){return o.whenIdle(e)},hasUnansweredInput(){return o.session.hasUnansweredInput()},runPending(e={}){return o.runPendingForTeam(e)}})}get conversationId(){return this.session.conversationId}get isRunning(){return this.active!==void 0}stream(e,t){if(typeof e!=`string`){if(typeof e!=`object`||!e||e.role!==`user`)throw TypeError(`Runtime input must be text or a user message`);e=r(e)}let n=b(t,this.host.selection),i=this.start(e,n);return j(i.legacy,i.report,i.result,this.nativeProvider,n.includeTraceEvents===!0)}start(n,r){let i=this.beginOperation(),a;try{let e=this.ownerSignal===void 0?r.signal:r.signal===void 0?this.ownerSignal:AbortSignal.any([r.signal,this.ownerSignal]);a=this.host.operations.acquire(`agent-run`,{...e===void 0?{}:{signal:e}})}catch(e){throw this.finishOperation(i),e}let o,s=r.structuredOutput,c;try{c=n===void 0?f(this.session,{signal:a.signal,...k(r)}):p(this.session,n,{signal:a.signal,...k(r),...s===void 0?{}:{outputFormat:{type:`json_schema`,name:s.name,schema:s.schema.jsonSchema},validateOutput:n=>{let r=s.schema.parse(n);if(!e(r))throw TypeError(`structured output parser must return lossless JSON synchronously`);o=t(r)}},...r.imagePolicy===void 0?{}:{imagePolicy:r.imagePolicy},...r.documentPolicy===void 0?{}:{documentPolicy:r.documentPolicy}},r.additionalInstructions)}catch(e){throw a.settle(),this.finishOperation(i),e}let l=()=>c.abort();a.signal.addEventListener(`abort`,l,{once:!0}),a.signal.aborted&&l(),a.whenSealed.then(()=>c.seal()).catch(()=>void 0);let u=this.runtimeReport(c.report,c.toolSourceSnapshots,a.signal),d=this.runtimeResult(c.result,u,()=>o),m=Promise.race([c.eventsSettled,a.whenSealed]),h=Promise.allSettled([m,d,u]).then(()=>{a.signal.removeEventListener(`abort`,l),a.settle(),this.finishOperation(i)}).then(()=>d);return h.catch(()=>void 0),u.catch(()=>void 0),Object.freeze({legacy:c,report:u,result:h})}async run(e,t){let n=b(t,this.host.selection),r=this.stream(e,n);try{for await(let e of r)if(n.onEvent!==void 0)try{await this.observe(n.onEvent,e,r)}catch(e){throw r.abort(),L(e,await r.report,`RUN_EVENT_OBSERVER_FAILED`)}}catch(e){if(I(e)===`RUN_EVENT_OBSERVER_FAILED`)throw e;return await r.result}return await r.result}inject(e){return this.host.operations.assertActive(),this.assertOwnerActive(),this.session.inject(e)}injectForTeam(e){return this.host.operations.assertActive(),this.assertOwnerActive(),this.session.inject(e)}snapshot(){return this.session.snapshot()}compact(e){let t=b(e,this.host.selection),n=this.beginOperation(),r;try{r=this.host.operations.execute(`manual-compaction`,{...this.ownerSignal===void 0?t.signal===void 0?{}:{signal:t.signal}:{signal:t.signal===void 0?this.ownerSignal:AbortSignal.any([t.signal,this.ownerSignal])}},async e=>{let n=await u(this.session,{signal:e.signal,...k(t)}),r=o(n.report),i=await this.host.observation.checkpointTerminal(r,e.signal),a=g(r,n.report.delivery,i,this.host.observation.mode,this.host.observation.requiredBoundary);if(n.failure!==void 0)throw L(n.failure,a,a.errors.at(-1)?.code??I(n.failure));return n.result===null?null:Object.freeze({...n.result,status:`completed`,report:a})})}catch(e){throw this.finishOperation(n),e}return r.finally(()=>this.finishOperation(n))}reset(){if(this.host.operations.assertActive(),this.assertOwnerActive(),this.active!==void 0)throw Error(`Cannot reset while a runtime session is active`);this.session.reset()}whenIdle(e){let t=this.active?.done;return t===void 0?Promise.resolve():e?.aborted?Promise.reject(new n(`Runtime idle wait was aborted`,`RUNTIME_OPERATION_ABORTED`)):new Promise((r,i)=>{let a=()=>void 0,o=e=>{a(),e===void 0?r():i(e)};e!==void 0&&(a=this.host.resources.onAbort(e,()=>o(new n(`Runtime idle wait was aborted`,`RUNTIME_OPERATION_ABORTED`)))),t.then(()=>o())})}async runPendingForTeam(e){let t=this.start(void 0,{...e.signal===void 0?{}:{signal:e.signal}});try{for await(let n of t.legacy)await e.onEvent?.(n)}catch(e){throw t.legacy.abort(),await t.result.catch(()=>void 0),e}return await t.result}beginOperation(){if(this.assertOwnerActive(),this.active!==void 0)throw Error(`Cannot start while a runtime session is active`);let e,t={done:new Promise(t=>{e=t}),resolve:e};return this.active=t,t}finishOperation(e){this.active===e&&(this.active=void 0,e.resolve())}assertOwnerActive(){if(this.ownerSignal?.aborted===!0)throw new n(`Runtime team session is closed`,`TEAM_CLOSED`)}async runtimeReport(e,t,n){let[r,i]=await Promise.all([e,t]),a=o(r,i),s=await this.host.observation.checkpointTerminal(a,n);return g(a,r.delivery,s,this.host.observation.mode,this.host.observation.requiredBoundary)}async runtimeResult(e,t,n){try{let r=await e,i=await t;if(i.status!==`success`)throw L(void 0,i,i.errors.at(-1)?.code??`AGENT_RUN_FAILED`);let a=n();return Object.freeze({runId:i.runId,traceId:i.traceId,completed:r.outcome.completed,stopReason:r.outcome.reason.kind,text:r.text,...a===void 0?{}:{output:a},...r.message===void 0?{}:{message:h(r.message)},usage:i.usage,report:i})}catch(e){throw L(e,await t,I(e))}}async observe(e,t,r){let i=this.host.resources.platform.monotonicNow()+this.observerTimeoutMs;try{await s(this.host.resources,i,()=>e(t),void 0)}catch{throw r.abort(),new n(`Runtime event observer did not complete`,`RUN_EVENT_OBSERVER_FAILED`)}}};function O(e,t,n={},r,i,a){e.operations.assertActive(),n=x(n),m({tools:[...t.legacy.tools,...n.tools??[]],nativeTools:t.legacy.nativeTools,skills:[...t.legacy.skills,...n.skills??[]],...t.legacy.skillIds===void 0?{}:{allowedSkillIds:t.legacy.skillIds}});let o=n.memory===!1?void 0:n.memory??t.memory;r!==void 0&&y(r,o);let s=A(t.toolSources,n.toolSources??[]),c=n.runtimeLimits,{maxSteps:l,maxToolCalls:u,...f}=c??{},p=c?.maxSteps===void 0&&c?.maxToolCalls===void 0?t.legacy:t.legacy.with({...c.maxSteps===void 0?{}:{maxTurns:c.maxSteps},...c.maxToolCalls===void 0?{}:{maxToolCalls:c.maxToolCalls}}),h={registry:e.registry,observation:e.observation,observationResource:e.resource,...n.tools===void 0?{}:{tools:n.tools},...n.skills===void 0?{}:{skills:n.skills},...n.skillCwd===void 0?{}:{skillCwd:n.skillCwd},...n.userInput===void 0?{}:{userInput:n.userInput},...n.approvals===void 0?{}:{approvals:n.approvals},...n.spillStore===void 0?{}:{spillStore:n.spillStore},...n.experimentalPrograms===void 0?{}:{experimentalPrograms:n.experimentalPrograms},...n.interceptors===void 0?{}:{interceptors:n.interceptors},...n.contextSections===void 0?{}:{contextSections:n.contextSections},...n.hooks===void 0?{}:{hooks:n.hooks},...n.usagePolicy===void 0?{}:{usagePolicy:n.usagePolicy},...n.historyLimits===void 0?{}:{historyLimits:n.historyLimits},...n.ledgerLimits===void 0?{}:{ledgerLimits:n.ledgerLimits},...n.eventBufferLimits===void 0?{}:{eventBufferLimits:n.eventBufferLimits},...n.compaction===void 0?{}:{compaction:n.compaction},...i===void 0?{}:{team:i},...Object.keys(f).length===0?{}:{runtimeLimits:f}},g=r===void 0?p.createSession({...h,...n.conversationId===void 0?{}:{conversationId:n.conversationId}}):p.resumeSession({...h,snapshot:r});return d(g,{provider:t.model.provider,model:t.model.id,...t.effort===void 0?{}:{reasoningEffort:t.effort},...t.maxTokens===void 0?{}:{maxTokens:t.maxTokens},logger:t=>e.observation.correlatedLogger(t,{scope:`sdk.agent.run`}),...s.length===0?{}:{prepareTools:(e,t,n)=>_(s,e,t,n)},...o===void 0?{}:{memory:v(o,t.legacy.id,f.memoryOperationTimeoutMs)}}),new D(e,g,t.model.provider,t.legacy.id,c?.observerTimeoutMs,a)}function k(e){return{...e.model===void 0?{}:{model:{provider:e.model.provider,model:e.model.id}},...e.maxTokens===void 0?{}:{maxTokens:e.maxTokens}}}function A(e,t){let n=[...e,...t],r=new Map;for(let[e,t]of n.entries()){let n=r.get(t.id);if(n!==void 0)throw i(`TOOL_SOURCE_ID_CONFLICT`,`tool-source-id`,n,e);r.set(t.id,e)}return Object.freeze(n)}function j(e,t,n,r,i){let a=!1;return Object.freeze({runId:e.runId,report:t,result:n,abort:()=>e.abort(),[Symbol.asyncIterator](){return a?(async function*(){throw Error(`A runtime run handle can only be iterated once`)})():(a=!0,M(e,t,r,i))}})}async function*M(e,t,n,r){let i=0,a=!1,o=()=>({runId:e.runId,traceId:e.traceId,sequence:++i,schemaVersion:1});try{for await(let t of e){let e=N(t,n,r);e!==void 0&&(yield Object.freeze({...o(),...e}))}let i=await t;if(i.status===`success`)yield Object.freeze({...o(),type:`usage`,usage:i.usage,report:i});else{let e=i.errors.at(-1)??R(i);yield Object.freeze({...o(),type:`error`,error:e,report:i})}a=!0}catch{let e=await t,n=e.errors.at(-1)??R(e);yield Object.freeze({...o(),type:`error`,error:n,report:e}),a=!0}finally{a||e.abort()}}function N(e,t,n){if(e.type===`usage-progress`)return{type:`usage-progress`,usage:e.usage,...e.attemptId===void 0?{}:{attemptId:e.attemptId}};if(n&&(e.type===`span-start`||e.type===`span-end`))return e;if(e.type===`text-delta`)return{type:e.phase===`commentary`?`commentary-delta`:`assistant-delta`,text:e.text,index:e.index,phase:e.phase,blockId:`${e.trace.spanId}:${e.index}`};if(e.type===`assistant-message`)return{type:`assistant-message`,message:h(e.message)};if(e.type===`text-end`||e.type===`reasoning-delta`){let{trace:t,...n}=e;return{...n,blockId:`${t.spanId}:${e.index}`}}if(e.type===`image-delta`){let{trace:t,...n}=e;return{...n,blockId:`${t.spanId}:${e.itemId}`}}if(e.type===`compaction-start`||e.type===`compaction-end`||e.type===`turn-start`||e.type===`step-start`||e.type===`step-end`||e.type===`assistant-text`||e.type===`assistant-reasoning`){let{trace:t,...n}=e;return n}if(e.type===`tool-call`)return{type:`tool-call`,callId:e.call.callId,name:e.call.toolName,input:F(e.call.rawArguments)};if(e.type===`tool-result`)return{type:`tool-result`,callId:e.call.callId,name:e.call.toolName,status:P(e.result),output:e.result};if(e.type===`assistant-native-tool`)return S(e.call,t);if(e.type===`approval-request`)return{type:`approval-request`,request:e.request};if(e.type===`user-input-request`)return{type:`user-input-request`,request:e.request};if(e.type===`user-input-response`)return{type:`user-input-response`,requestId:e.request.requestId,response:e.response}}function P(e){return e.isError?e.error.code===l.ABORTED||e.error.code===l.ABORTED_BEFORE_DISPATCH?`aborted`:e.error.code===l.UNKNOWN_TOOL||e.error.code===l.INVALID_ARGUMENTS||e.error.code===l.MALFORMED_ARGUMENTS||e.error.code===l.DENIED||e.error.code===l.BUDGET_EXHAUSTED||e.error.code===l.CHECKPOINT_FAILED?`rejected`:`failed`:e.meta?.declined===!0?`declined`:`completed`}function F(e){try{return JSON.parse(e)}catch{return e}}function I(e){return e instanceof n?e.code:`AGENT_RUN_FAILED`}function L(e,t,n){return a(new c(`Agent run did not complete`,n,t),e)}function R(e){return Object.freeze({code:`AGENT_RUN_FAILED`,stage:`agent-run`,message:`Agent operation failed`,usageCoverage:e.usage.coverage,possiblyBilledAttemptsWithoutUsage:e.usage.coverage.possiblyBilledAttemptsWithoutUsage})}export{w as createRuntimeAgent,T as createRuntimeTeamMemberSession,E as preflightRuntimeTeamMember};
1
+ import{isJsonValue as e}from"../../primitives/json.js";import{detachedFrozen as t}from"../../primitives/snapshot.js";import{AgentSdkError as n}from"../../errors/agent-sdk-error.js";import{freezeMessage as r}from"../../message/message.js";import{capabilityIdentityError as i,inheritCapabilityIdentityConflict as a}from"../../errors/capability-identity.js";import{createRunTerminalRecord as o}from"../../agent/accounting/delivery/terminal.js";import{atDeadline as s}from"../lifecycle/bounded.js";import{AgentRunError as c}from"../../agent/accounting/error.js";import{TOOL_ERROR_CODES as l}from"../../agent/tool/errors.js";import{compactRuntimeSession as u,configureRuntimeSessionModel as d,streamPendingRuntimeSession as f,streamRuntimeSession as p}from"../../agent/define/session/runtime-binding.js";import{assertAgentIdentitySnapshot as m}from"../identity/agent.js";import{publicMessage as h}from"./public-message.js";import{finalizeRuntimeRunReport as g}from"../observation/final-report.js";import{snapshotToolSources as _}from"../tool-source/snapshot.js";import{createRuntimeMemoryPersistence as v}from"../memory/run.js";import{validateMemoryResumeBinding as y}from"../memory/resume.js";import{captureInvocationOptions as b,captureRuntimeSessionOptions as x}from"./options.js";import{projectNativeToolEvent as S}from"./native-event.js";const C=new WeakMap;function w(e,t){let n=Object.freeze({model:t.model,generate(n,r){return O(e,t).run(n,r)},stream(n,r){return O(e,t).stream(n,r)},createSession(n){return O(e,t,n)},resumeSession(n,r){return O(e,t,r,n)}});return C.set(n,Object.freeze({host:e,definition:t})),n}function T(e,t,r,i,a){let o=C.get(t);if(o?.host!==e)throw new n(`Runtime team members must be agents from the same runtime`,`TEAM_AGENT_OWNERSHIP_INVALID`);let s=O(e,o.definition,r,void 0,i,a);return Object.freeze({view:s,port:s.teamPort})}function E(e,t,r,i){let a=C.get(t);if(a?.host!==e)throw new n(`Runtime team members must be agents from the same runtime`,`TEAM_AGENT_OWNERSHIP_INVALID`);m({tools:[...a.definition.legacy.tools,...r.tools??[]],nativeTools:a.definition.legacy.nativeTools,skills:[...a.definition.legacy.skills,...r.skills??[]],...a.definition.legacy.skillIds===void 0?{}:{allowedSkillIds:a.definition.legacy.skillIds},additionalToolNames:i})}var D=class{host;session;nativeProvider;ownerSignal;active;observerTimeoutMs;teamPort;constructor(e,t,n,r,i=3e4,a){this.host=e,this.session=t,this.nativeProvider=n,this.ownerSignal=a,this.observerTimeoutMs=i;let o=this;this.teamPort=Object.freeze({definition:Object.freeze({id:r}),get conversationId(){return o.conversationId},get isRunning(){return o.isRunning},inject(e){return o.injectForTeam(e)},whenIdle(e){return o.whenIdle(e)},hasUnansweredInput(){return o.session.hasUnansweredInput()},lastOutcome(){return o.session.lastOutcome()},runPending(e={}){return o.runPendingForTeam(e)}})}get conversationId(){return this.session.conversationId}get isRunning(){return this.active!==void 0}stream(e,t){if(typeof e!=`string`){if(typeof e!=`object`||!e||e.role!==`user`)throw TypeError(`Runtime input must be text or a user message`);e=r(e)}let n=b(t,this.host.selection),i=this.start(e,n);return j(i.legacy,i.report,i.result,this.nativeProvider,n.includeTraceEvents===!0)}start(n,r){let i=this.beginOperation(),a;try{let e=this.ownerSignal===void 0?r.signal:r.signal===void 0?this.ownerSignal:AbortSignal.any([r.signal,this.ownerSignal]);a=this.host.operations.acquire(`agent-run`,{...e===void 0?{}:{signal:e}})}catch(e){throw this.finishOperation(i),e}let o,s=r.structuredOutput,c;try{c=n===void 0?f(this.session,{signal:a.signal,...k(r)}):p(this.session,n,{signal:a.signal,...k(r),...s===void 0?{}:{outputFormat:{type:`json_schema`,name:s.name,schema:s.schema.jsonSchema},validateOutput:n=>{let r=s.schema.parse(n);if(!e(r))throw TypeError(`structured output parser must return lossless JSON synchronously`);o=t(r)}},...r.imagePolicy===void 0?{}:{imagePolicy:r.imagePolicy},...r.documentPolicy===void 0?{}:{documentPolicy:r.documentPolicy}},r.additionalInstructions)}catch(e){throw a.settle(),this.finishOperation(i),e}let l=()=>c.abort();a.signal.addEventListener(`abort`,l,{once:!0}),a.signal.aborted&&l(),a.whenSealed.then(()=>c.seal()).catch(()=>void 0);let u=this.runtimeReport(c.report,c.toolSourceSnapshots,a.signal),d=this.runtimeResult(c.result,u,()=>o),m=Promise.race([c.eventsSettled,a.whenSealed]),h=Promise.allSettled([m,d,u]).then(()=>{a.signal.removeEventListener(`abort`,l),a.settle(),this.finishOperation(i)}).then(()=>d);return h.catch(()=>void 0),u.catch(()=>void 0),Object.freeze({legacy:c,report:u,result:h})}async run(e,t){let n=b(t,this.host.selection),r=this.stream(e,n);try{for await(let e of r)if(n.onEvent!==void 0)try{await this.observe(n.onEvent,e,r)}catch(e){throw r.abort(),L(e,await r.report,`RUN_EVENT_OBSERVER_FAILED`)}}catch(e){if(I(e)===`RUN_EVENT_OBSERVER_FAILED`)throw e;return await r.result}return await r.result}inject(e){return this.host.operations.assertActive(),this.assertOwnerActive(),this.session.inject(e)}injectForTeam(e){return this.host.operations.assertActive(),this.assertOwnerActive(),this.session.inject(e)}hasUnansweredInput(){return this.session.hasUnansweredInput()}async runPending(e){let t=b(e,this.host.selection),n=this.start(void 0,t),r=j(n.legacy,n.report,n.result,this.nativeProvider,t.includeTraceEvents===!0);try{for await(let e of r)t.onEvent!==void 0&&await this.observe(t.onEvent,e,r)}catch(e){throw r.abort(),await r.result.catch(()=>void 0),e}return await r.result}snapshot(){return this.session.snapshot()}compact(e){let t=b(e,this.host.selection),n=this.beginOperation(),r;try{r=this.host.operations.execute(`manual-compaction`,{...this.ownerSignal===void 0?t.signal===void 0?{}:{signal:t.signal}:{signal:t.signal===void 0?this.ownerSignal:AbortSignal.any([t.signal,this.ownerSignal])}},async e=>{let n=await u(this.session,{signal:e.signal,...k(t)}),r=o(n.report),i=await this.host.observation.checkpointTerminal(r,e.signal),a=g(r,n.report.delivery,i,this.host.observation.mode,this.host.observation.requiredBoundary);if(n.failure!==void 0)throw L(n.failure,a,a.errors.at(-1)?.code??I(n.failure));return n.result===null?null:Object.freeze({...n.result,status:`completed`,report:a})})}catch(e){throw this.finishOperation(n),e}return r.finally(()=>this.finishOperation(n))}reset(){if(this.host.operations.assertActive(),this.assertOwnerActive(),this.active!==void 0)throw Error(`Cannot reset while a runtime session is active`);this.session.reset()}whenIdle(e){let t=this.active?.done;return t===void 0?Promise.resolve():e?.aborted?Promise.reject(new n(`Runtime idle wait was aborted`,`RUNTIME_OPERATION_ABORTED`)):new Promise((r,i)=>{let a=()=>void 0,o=e=>{a(),e===void 0?r():i(e)};e!==void 0&&(a=this.host.resources.onAbort(e,()=>o(new n(`Runtime idle wait was aborted`,`RUNTIME_OPERATION_ABORTED`)))),t.then(()=>o())})}async runPendingForTeam(e){let t=this.start(void 0,{...e.signal===void 0?{}:{signal:e.signal}});try{for await(let n of t.legacy)await e.onEvent?.(n)}catch(e){throw t.legacy.abort(),await t.result.catch(()=>void 0),e}return await t.result}beginOperation(){if(this.assertOwnerActive(),this.active!==void 0)throw Error(`Cannot start while a runtime session is active`);let e,t={done:new Promise(t=>{e=t}),resolve:e};return this.active=t,t}finishOperation(e){this.active===e&&(this.active=void 0,e.resolve())}assertOwnerActive(){if(this.ownerSignal?.aborted===!0)throw new n(`Runtime team session is closed`,`TEAM_CLOSED`)}async runtimeReport(e,t,n){let[r,i]=await Promise.all([e,t]),a=o(r,i),s=await this.host.observation.checkpointTerminal(a,n);return g(a,r.delivery,s,this.host.observation.mode,this.host.observation.requiredBoundary)}async runtimeResult(e,t,n){try{let r=await e,i=await t;if(i.status!==`success`)throw L(void 0,i,i.errors.at(-1)?.code??`AGENT_RUN_FAILED`);let a=n();return Object.freeze({runId:i.runId,traceId:i.traceId,completed:r.outcome.completed,stopReason:r.outcome.reason.kind,text:r.text,...a===void 0?{}:{output:a},...r.message===void 0?{}:{message:h(r.message)},usage:i.usage,report:i})}catch(e){throw L(e,await t,I(e))}}async observe(e,t,r){let i=this.host.resources.platform.monotonicNow()+this.observerTimeoutMs;try{await s(this.host.resources,i,()=>e(t),void 0)}catch{throw r.abort(),new n(`Runtime event observer did not complete`,`RUN_EVENT_OBSERVER_FAILED`)}}};function O(e,t,n={},r,i,a){e.operations.assertActive(),n=x(n),m({tools:[...t.legacy.tools,...n.tools??[]],nativeTools:t.legacy.nativeTools,skills:[...t.legacy.skills,...n.skills??[]],...t.legacy.skillIds===void 0?{}:{allowedSkillIds:t.legacy.skillIds}});let o=n.memory===!1?void 0:n.memory??t.memory;r!==void 0&&y(r,o);let s=A(t.toolSources,n.toolSources??[]),c=n.runtimeLimits,{maxSteps:l,maxToolCalls:u,...f}=c??{},p=c?.maxSteps===void 0&&c?.maxToolCalls===void 0?t.legacy:t.legacy.with({...c.maxSteps===void 0?{}:{maxTurns:c.maxSteps},...c.maxToolCalls===void 0?{}:{maxToolCalls:c.maxToolCalls}}),h={registry:e.registry,observation:e.observation,observationResource:e.resource,...n.tools===void 0?{}:{tools:n.tools},...n.skills===void 0?{}:{skills:n.skills},...n.skillCwd===void 0?{}:{skillCwd:n.skillCwd},...n.userInput===void 0?{}:{userInput:n.userInput},...n.approvals===void 0?{}:{approvals:n.approvals},...n.spillStore===void 0?{}:{spillStore:n.spillStore},...n.experimentalPrograms===void 0?{}:{experimentalPrograms:n.experimentalPrograms},...n.interceptors===void 0?{}:{interceptors:n.interceptors},...n.contextSections===void 0?{}:{contextSections:n.contextSections},...n.hooks===void 0?{}:{hooks:n.hooks},...n.usagePolicy===void 0?{}:{usagePolicy:n.usagePolicy},...n.historyLimits===void 0?{}:{historyLimits:n.historyLimits},...n.ledgerLimits===void 0?{}:{ledgerLimits:n.ledgerLimits},...n.eventBufferLimits===void 0?{}:{eventBufferLimits:n.eventBufferLimits},...n.compaction===void 0?{}:{compaction:n.compaction},...i===void 0?{}:{team:i},...Object.keys(f).length===0?{}:{runtimeLimits:f}},g=r===void 0?p.createSession({...h,...n.conversationId===void 0?{}:{conversationId:n.conversationId}}):p.resumeSession({...h,snapshot:r});return d(g,{provider:t.model.provider,model:t.model.id,...t.effort===void 0?{}:{reasoningEffort:t.effort},...t.maxTokens===void 0?{}:{maxTokens:t.maxTokens},logger:t=>e.observation.correlatedLogger(t,{scope:`sdk.agent.run`}),...s.length===0?{}:{prepareTools:(e,t,n)=>_(s,e,t,n)},...o===void 0?{}:{memory:v(o,t.legacy.id,f.memoryOperationTimeoutMs)}}),new D(e,g,t.model.provider,t.legacy.id,c?.observerTimeoutMs,a)}function k(e){return{...e.model===void 0?{}:{model:{provider:e.model.provider,model:e.model.id}},...e.maxTokens===void 0?{}:{maxTokens:e.maxTokens}}}function A(e,t){let n=[...e,...t],r=new Map;for(let[e,t]of n.entries()){let n=r.get(t.id);if(n!==void 0)throw i(`TOOL_SOURCE_ID_CONFLICT`,`tool-source-id`,n,e);r.set(t.id,e)}return Object.freeze(n)}function j(e,t,n,r,i){let a=!1;return Object.freeze({runId:e.runId,report:t,result:n,abort:()=>e.abort(),[Symbol.asyncIterator](){return a?(async function*(){throw Error(`A runtime run handle can only be iterated once`)})():(a=!0,M(e,t,r,i))}})}async function*M(e,t,n,r){let i=0,a=!1,o=()=>({runId:e.runId,traceId:e.traceId,sequence:++i,schemaVersion:1});try{for await(let t of e){let e=N(t,n,r);e!==void 0&&(yield Object.freeze({...o(),...e}))}let i=await t;if(i.status===`success`)yield Object.freeze({...o(),type:`usage`,usage:i.usage,report:i});else{let e=i.errors.at(-1)??R(i);yield Object.freeze({...o(),type:`error`,error:e,report:i})}a=!0}catch{let e=await t,n=e.errors.at(-1)??R(e);yield Object.freeze({...o(),type:`error`,error:n,report:e}),a=!0}finally{a||e.abort()}}function N(e,t,n){if(e.type===`usage-progress`)return{type:`usage-progress`,usage:e.usage,...e.attemptId===void 0?{}:{attemptId:e.attemptId}};if(n&&(e.type===`span-start`||e.type===`span-end`))return e;if(e.type===`text-delta`)return{type:e.phase===`commentary`?`commentary-delta`:`assistant-delta`,text:e.text,index:e.index,phase:e.phase,blockId:`${e.trace.spanId}:${e.index}`};if(e.type===`assistant-message`)return{type:`assistant-message`,message:h(e.message)};if(e.type===`assistant-replacement`)return{...e,message:h(e.message)};if(e.type===`text-end`||e.type===`reasoning-delta`){let{trace:t,...n}=e;return{...n,blockId:`${t.spanId}:${e.index}`}}if(e.type===`image-delta`){let{trace:t,...n}=e;return{...n,blockId:`${t.spanId}:${e.itemId}`}}if(e.type===`compaction-start`||e.type===`compaction-end`||e.type===`turn-start`||e.type===`step-start`||e.type===`step-end`||e.type===`assistant-text`||e.type===`assistant-reasoning`){let{trace:t,...n}=e;return n}if(e.type===`tool-call`)return{type:`tool-call`,callId:e.call.callId,name:e.call.toolName,input:F(e.call.rawArguments)};if(e.type===`tool-result`)return{type:`tool-result`,callId:e.call.callId,name:e.call.toolName,status:P(e.result),output:e.result};if(e.type===`assistant-native-tool`)return S(e.call,t);if(e.type===`approval-request`)return{type:`approval-request`,request:e.request};if(e.type===`user-input-request`)return{type:`user-input-request`,request:e.request};if(e.type===`user-input-response`)return{type:`user-input-response`,requestId:e.request.requestId,response:e.response}}function P(e){return e.isError?e.error.code===l.ABORTED||e.error.code===l.ABORTED_BEFORE_DISPATCH?`aborted`:e.error.code===l.UNKNOWN_TOOL||e.error.code===l.INVALID_ARGUMENTS||e.error.code===l.MALFORMED_ARGUMENTS||e.error.code===l.DENIED||e.error.code===l.BUDGET_EXHAUSTED||e.error.code===l.CHECKPOINT_FAILED?`rejected`:`failed`:e.meta?.declined===!0?`declined`:`completed`}function F(e){try{return JSON.parse(e)}catch{return e}}function I(e){return e instanceof n?e.code:`AGENT_RUN_FAILED`}function L(e,t,n){return a(new c(`Agent run did not complete`,n,t),e)}function R(e){return Object.freeze({code:`AGENT_RUN_FAILED`,stage:`agent-run`,message:`Agent operation failed`,usageCoverage:e.usage.coverage,possiblyBilledAttemptsWithoutUsage:e.usage.coverage.possiblyBilledAttemptsWithoutUsage})}export{w as createRuntimeAgent,T as createRuntimeTeamMemberSession,E as preflightRuntimeTeamMember};
2
2
  //# sourceMappingURL=session.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"session.js","names":[],"sources":["../../../src/composition/agent/session.ts"],"sourcesContent":["import { publicMessage } from './public-message.ts'\nimport type { AgentInput } from '../../agent/define/session/types.ts'\nimport { isJsonValue, detachedFrozen, type JsonValue } from '../../primitives/index.ts'\nimport { freezeMessage } from '../../message/index.ts'\nimport { AgentRunError } from '../../agent/accounting/error.ts'\nimport type { RunReport } from '../exporter/delivery-types.ts'\nimport { configureRuntimeSessionModel, streamRuntimeSession, type AgentSession } from '../../agent/define/session.ts'\nimport {\n compactRuntimeSession, streamPendingRuntimeSession, type RuntimeSessionRunHandle,\n} from '../../agent/define/session/runtime-binding.ts'\nimport type { AgentRunHandle as LegacyRunHandle } from '../../agent/define/session/types.ts'\nimport type { AgentRunEvent } from '../../agent/mode/run-agent.ts'\nimport type { ToolExecutionResult } from '../../agent/tool/definition.ts'\nimport { TOOL_ERROR_CODES } from '../../agent/tool/errors.ts'\nimport { AgentSdkError } from '../../errors/agent-sdk-error.ts'\nimport type { ModelRegistry } from '../../runtime/registry.ts'\nimport type { ProviderSelection } from '../provider/types.ts'\nimport { atDeadline } from '../lifecycle/bounded.ts'\nimport type { RuntimeOperations } from '../lifecycle/operations.ts'\nimport type { RuntimeObservationPort } from '../observation/port.ts'\nimport { createRunTerminalRecord } from '../delivery/terminal.ts'\nimport { finalizeRuntimeRunReport, type RuntimeRunReport } from '../observation/final-report.ts'\nimport type { RuntimeObservationResource } from '../delivery/resource.ts'\nimport type { RuntimeResources } from '../../platform/resources.ts'\nimport { snapshotToolSources } from '../tool-source/snapshot.ts'\nimport { capabilityIdentityError, inheritCapabilityIdentityConflict } from '../identity/error.ts'\nimport type { CapturedToolSource } from '../tool-source/types.ts'\nimport type { ToolSourceRunReference } from '../tool-source/types.ts'\nimport { createRuntimeMemoryPersistence } from '../memory/run.ts'\nimport { validateMemoryResumeBinding } from '../memory/resume.ts'\nimport type { BoundRuntimeAgentDefinition } from './definition.ts'\nimport { captureInvocationOptions, captureRuntimeSessionOptions, type CapturedInvocationOptions } from './options.ts'\nimport { projectNativeToolEvent } from './native-event.ts'\nimport type {\n RuntimeAgent, RuntimeAgentInvocationOptions, RuntimeAgentResponse, RuntimeAgentRunEvent,\n RuntimeAgentRunHandle, RuntimeAgentSession, RuntimeAgentSessionOptions, RuntimeAgentSessionSnapshot,\n} from './types.ts'\nimport type { CompactionResult } from '../../agent/memory/compaction.ts'\nimport type { AgentTeamMemberOptions } from '../../agent/define/session/types.ts'\nimport type { TeamSessionPort } from '../../agent/team/contracts.ts'\nimport { assertAgentIdentitySnapshot } from '../identity/agent.ts'\n\nexport interface RuntimeAgentHost {\n readonly registry: ModelRegistry\n /**\n * The runtime's captured provider routes.\n *\n * Held so a per-invocation model override resolves against exactly the same\n * configuration the agent binding used, rather than a second view of it.\n */\n readonly selection: ProviderSelection\n readonly operations: RuntimeOperations\n readonly observation: RuntimeObservationPort\n readonly resource: RuntimeObservationResource\n readonly resources: RuntimeResources\n}\n\ninterface RuntimeAgentBinding {\n readonly host: RuntimeAgentHost\n readonly definition: BoundRuntimeAgentDefinition\n}\n\nconst runtimeAgentBindings = new WeakMap<RuntimeAgent, RuntimeAgentBinding>()\n\nexport function createRuntimeAgent(host: RuntimeAgentHost, definition: BoundRuntimeAgentDefinition): RuntimeAgent {\n const agent = Object.freeze({\n model: definition.model,\n generate(input: AgentInput, options?: RuntimeAgentInvocationOptions) { return createRuntimeSession(host, definition).run(input, options) },\n stream(input: AgentInput, options?: RuntimeAgentInvocationOptions) { return createRuntimeSession(host, definition).stream(input, options) },\n createSession(options?: RuntimeAgentSessionOptions) { return createRuntimeSession(host, definition, options) },\n resumeSession(snapshot: RuntimeAgentSessionSnapshot, options?: RuntimeAgentSessionOptions) {\n return createRuntimeSession(host, definition, options, snapshot)\n },\n })\n runtimeAgentBindings.set(agent, Object.freeze({ host, definition }))\n return agent\n}\n\nexport function createRuntimeTeamMemberSession(\n host: RuntimeAgentHost,\n agent: RuntimeAgent,\n options: RuntimeAgentSessionOptions,\n team: AgentTeamMemberOptions,\n ownerSignal: AbortSignal,\n): { readonly view: RuntimeAgentSession; readonly port: TeamSessionPort } {\n const binding = runtimeAgentBindings.get(agent)\n if (binding?.host !== host) throw new AgentSdkError(\n 'Runtime team members must be agents from the same runtime', 'TEAM_AGENT_OWNERSHIP_INVALID',\n )\n const view = createRuntimeSession(host, binding.definition, options, undefined, team, ownerSignal)\n return Object.freeze({ view, port: view.teamPort })\n}\n\nexport function preflightRuntimeTeamMember(\n host: RuntimeAgentHost,\n agent: RuntimeAgent,\n options: RuntimeAgentSessionOptions,\n additionalToolNames: readonly string[],\n): void {\n const binding = runtimeAgentBindings.get(agent)\n if (binding?.host !== host) throw new AgentSdkError(\n 'Runtime team members must be agents from the same runtime', 'TEAM_AGENT_OWNERSHIP_INVALID',\n )\n assertAgentIdentitySnapshot({\n tools: [...binding.definition.legacy.tools, ...options.tools ?? []],\n nativeTools: binding.definition.legacy.nativeTools,\n skills: [...binding.definition.legacy.skills, ...options.skills ?? []] as never,\n ...(binding.definition.legacy.skillIds === undefined ? {} : {\n allowedSkillIds: binding.definition.legacy.skillIds,\n }),\n additionalToolNames,\n })\n}\n\nexport function runtimeOwnsAgent(host: RuntimeAgentHost, agent: unknown): agent is RuntimeAgent {\n return typeof agent === 'object' && agent !== null && runtimeAgentBindings.get(agent as RuntimeAgent)?.host === host\n}\n\nclass RuntimeAgentSessionValue implements RuntimeAgentSession {\n private active: SessionOperation | undefined\n private readonly observerTimeoutMs: number\n readonly teamPort: TeamSessionPort\n\n constructor(\n private readonly host: RuntimeAgentHost,\n private readonly session: AgentSession,\n private readonly nativeProvider: string,\n definitionId: string,\n observerTimeoutMs = 30_000,\n private readonly ownerSignal?: AbortSignal,\n ) {\n this.observerTimeoutMs = observerTimeoutMs\n const owner = this\n this.teamPort = Object.freeze({\n definition: Object.freeze({ id: definitionId }),\n get conversationId() { return owner.conversationId },\n get isRunning() { return owner.isRunning },\n inject(input: Parameters<TeamSessionPort['inject']>[0]) { return owner.injectForTeam(input) },\n whenIdle(signal?: AbortSignal) { return owner.whenIdle(signal) },\n hasUnansweredInput() { return owner.session.hasUnansweredInput() },\n runPending(invocation = {}) { return owner.runPendingForTeam(invocation) },\n })\n }\n\n get conversationId(): string { return this.session.conversationId }\n get isRunning(): boolean { return this.active !== undefined }\n\n stream(input: AgentInput, rawOptions?: RuntimeAgentInvocationOptions): RuntimeAgentRunHandle {\n if (typeof input !== 'string') {\n if (input === null || typeof input !== 'object' || input.role !== 'user') throw new TypeError('Runtime input must be text or a user message')\n input = freezeMessage(input)\n }\n const options = captureInvocationOptions(rawOptions, this.host.selection)\n const started = this.start(input, options)\n return runtimeHandle(started.legacy, started.report, started.result, this.nativeProvider, options.includeTraceEvents === true)\n }\n\n private start(input: AgentInput | undefined, options: CapturedInvocationOptions): StartedRuntimeRun {\n const operation = this.beginOperation()\n let lease: ReturnType<RuntimeOperations['acquire']>\n try {\n const signal = this.ownerSignal === undefined\n ? options.signal\n : options.signal === undefined ? this.ownerSignal : AbortSignal.any([options.signal, this.ownerSignal])\n lease = this.host.operations.acquire('agent-run', {\n ...(signal === undefined ? {} : { signal }),\n })\n } catch (error) { this.finishOperation(operation); throw error }\n let output: JsonValue | undefined\n const structured = options.structuredOutput\n let legacy: RuntimeSessionRunHandle\n try {\n legacy = input === undefined\n ? streamPendingRuntimeSession(this.session, { signal: lease.signal, ...modelOverlay(options) })\n : streamRuntimeSession(this.session, input, { signal: lease.signal, ...modelOverlay(options),\n ...(structured === undefined ? {} : {\n outputFormat: { type: 'json_schema' as const, name: structured.name, schema: structured.schema.jsonSchema },\n validateOutput: (value: unknown) => {\n const parsed = structured.schema.parse(value)\n if (!isJsonValue(parsed)) throw new TypeError('structured output parser must return lossless JSON synchronously')\n output = detachedFrozen(parsed)\n },\n }), ...(options.imagePolicy === undefined ? {} : { imagePolicy: options.imagePolicy }),\n ...(options.documentPolicy === undefined ? {} : { documentPolicy: options.documentPolicy }) }, options.additionalInstructions)\n } catch (error) { lease.settle(); this.finishOperation(operation); throw error }\n const abort = (): void => legacy.abort()\n lease.signal.addEventListener('abort', abort, { once: true })\n if (lease.signal.aborted) abort()\n void lease.whenSealed.then(() => legacy.seal()).catch(() => undefined)\n const report = this.runtimeReport(legacy.report, legacy.toolSourceSnapshots, lease.signal)\n const internalResult = this.runtimeResult(legacy.result, report, () => output)\n const eventsSettled = Promise.race([legacy.eventsSettled, lease.whenSealed])\n const released = Promise.allSettled([eventsSettled, internalResult, report]).then(() => {\n lease.signal.removeEventListener('abort', abort)\n lease.settle()\n this.finishOperation(operation)\n })\n const result = released.then(() => internalResult)\n void result.catch(() => undefined)\n void report.catch(() => undefined)\n return Object.freeze({ legacy, report, result })\n }\n\n async run(input: AgentInput, rawOptions?: RuntimeAgentInvocationOptions): Promise<RuntimeAgentResponse> {\n const options = captureInvocationOptions(rawOptions, this.host.selection)\n const handle = this.stream(input, options)\n try {\n for await (const event of handle) {\n if (options.onEvent !== undefined) {\n try { await this.observe(options.onEvent, event, handle) }\n catch (error) {\n handle.abort()\n const report = await handle.report\n throw runtimeFailure(error, report, 'RUN_EVENT_OBSERVER_FAILED')\n }\n }\n }\n } catch (error) { if (codeOf(error) === 'RUN_EVENT_OBSERVER_FAILED') throw error; return await handle.result }\n return await handle.result\n }\n\n inject(input: AgentInput): number {\n this.host.operations.assertActive()\n this.assertOwnerActive()\n // A run in flight is the case steering exists for. The underlying session\n // holds the message until the round that could not see it has finished,\n // then delivers it in arrival order. Refusing here left the runtime\n // surface unable to steer at all, while the same call on a bare session\n // (and injectForTeam below) is accepted.\n return this.session.inject(input)\n }\n\n private injectForTeam(input: Parameters<TeamSessionPort['inject']>[0]): number {\n this.host.operations.assertActive()\n this.assertOwnerActive()\n return this.session.inject(input)\n }\n\n snapshot(): RuntimeAgentSessionSnapshot { return this.session.snapshot() }\n\n compact(rawOptions?: RuntimeAgentInvocationOptions): Promise<CompactionResult | null> {\n const options = captureInvocationOptions(rawOptions, this.host.selection)\n const operation = this.beginOperation()\n let pending: Promise<CompactionResult | null>\n try {\n pending = this.host.operations.execute('manual-compaction', {\n ...(this.ownerSignal === undefined\n ? options.signal === undefined ? {} : { signal: options.signal }\n : { signal: options.signal === undefined ? this.ownerSignal : AbortSignal.any([options.signal, this.ownerSignal]) }),\n }, async lease => {\n const outcome = await compactRuntimeSession(this.session, { signal: lease.signal, ...modelOverlay(options) })\n const record = createRunTerminalRecord(outcome.report)\n const terminal = await this.host.observation.checkpointTerminal(record, lease.signal)\n const report = finalizeRuntimeRunReport(record, outcome.report.delivery, terminal,\n this.host.observation.mode, this.host.observation.requiredBoundary)\n if (outcome.failure !== undefined) throw runtimeFailure(\n outcome.failure,\n report,\n report.errors.at(-1)?.code ?? codeOf(outcome.failure),\n )\n return outcome.result === null ? null : Object.freeze({ ...outcome.result, status: 'completed' as const, report })\n })\n } catch (error) { this.finishOperation(operation); throw error }\n return pending.finally(() => this.finishOperation(operation))\n }\n\n reset(): void {\n this.host.operations.assertActive()\n this.assertOwnerActive()\n if (this.active !== undefined) throw new Error('Cannot reset while a runtime session is active')\n this.session.reset()\n }\n\n whenIdle(signal?: AbortSignal): Promise<void> {\n const pending = this.active?.done\n if (pending === undefined) return Promise.resolve()\n if (signal?.aborted) return Promise.reject(new AgentSdkError('Runtime idle wait was aborted', 'RUNTIME_OPERATION_ABORTED'))\n return new Promise((resolve, reject) => {\n let release = (): void => undefined\n const finish = (error?: Error): void => { release(); error === undefined ? resolve() : reject(error) }\n if (signal !== undefined) release = this.host.resources.onAbort(signal,\n () => finish(new AgentSdkError('Runtime idle wait was aborted', 'RUNTIME_OPERATION_ABORTED')))\n void pending.then(() => finish())\n })\n }\n\n private async runPendingForTeam(invocation: {\n readonly signal?: AbortSignal\n readonly onEvent?: (event: AgentRunEvent) => void | Promise<void>\n }): Promise<unknown> {\n const started = this.start(undefined, {\n ...(invocation.signal === undefined ? {} : { signal: invocation.signal }),\n })\n try {\n for await (const event of started.legacy) await invocation.onEvent?.(event)\n } catch (error) {\n started.legacy.abort()\n await started.result.catch(() => undefined)\n throw error\n }\n return await started.result\n }\n\n private beginOperation(): SessionOperation {\n this.assertOwnerActive()\n if (this.active !== undefined) throw new Error('Cannot start while a runtime session is active')\n let resolve!: () => void\n const operation: SessionOperation = { done: new Promise(done => { resolve = done }), resolve }\n this.active = operation\n return operation\n }\n\n private finishOperation(operation: SessionOperation): void {\n if (this.active !== operation) return\n this.active = undefined\n operation.resolve()\n }\n\n private assertOwnerActive(): void {\n if (this.ownerSignal?.aborted === true) {\n throw new AgentSdkError('Runtime team session is closed', 'TEAM_CLOSED')\n }\n }\n\n private async runtimeReport(\n legacy: Promise<RunReport>,\n sourceSnapshots: Promise<readonly ToolSourceRunReference[]>,\n signal: AbortSignal,\n ): Promise<RuntimeRunReport> {\n const [previous, sources] = await Promise.all([legacy, sourceSnapshots])\n const record = createRunTerminalRecord(previous, sources)\n const terminal = await this.host.observation.checkpointTerminal(record, signal)\n return finalizeRuntimeRunReport(record, previous.delivery, terminal,\n this.host.observation.mode, this.host.observation.requiredBoundary)\n }\n\n private async runtimeResult(\n legacy: Promise<Awaited<LegacyRunHandle['result']>>,\n report: Promise<RuntimeRunReport>,\n output: () => JsonValue | undefined,\n ): Promise<RuntimeAgentResponse> {\n try {\n const response = await legacy\n const final = await report\n if (final.status !== 'success') {\n throw runtimeFailure(undefined, final, final.errors.at(-1)?.code ?? 'AGENT_RUN_FAILED')\n }\n const parsedOutput = output()\n return Object.freeze({ runId: final.runId, traceId: final.traceId,\n completed: response.outcome.completed, stopReason: response.outcome.reason.kind,\n text: response.text, ...(parsedOutput === undefined ? {} : { output: parsedOutput }),\n ...(response.message === undefined ? {} : { message: publicMessage(response.message) }),\n usage: final.usage, report: final })\n } catch (error) {\n const final = await report\n throw runtimeFailure(error, final, codeOf(error))\n }\n }\n\n private async observe(\n observer: NonNullable<RuntimeAgentInvocationOptions['onEvent']>,\n event: RuntimeAgentRunEvent,\n handle: RuntimeAgentRunHandle,\n ): Promise<void> {\n const deadlineAt = this.host.resources.platform.monotonicNow() + this.observerTimeoutMs\n try { await atDeadline(this.host.resources, deadlineAt, () => observer(event), undefined) }\n catch { handle.abort(); throw new AgentSdkError('Runtime event observer did not complete', 'RUN_EVENT_OBSERVER_FAILED') }\n }\n}\n\nfunction createRuntimeSession(\n host: RuntimeAgentHost,\n definition: BoundRuntimeAgentDefinition,\n options: RuntimeAgentSessionOptions = {},\n snapshot?: RuntimeAgentSessionSnapshot,\n team?: AgentTeamMemberOptions,\n ownerSignal?: AbortSignal,\n): RuntimeAgentSessionValue {\n host.operations.assertActive()\n options = captureRuntimeSessionOptions(options)\n assertAgentIdentitySnapshot({\n tools: [...definition.legacy.tools, ...options.tools ?? []],\n nativeTools: definition.legacy.nativeTools,\n skills: [...definition.legacy.skills, ...options.skills ?? []] as never,\n ...(definition.legacy.skillIds === undefined ? {} : { allowedSkillIds: definition.legacy.skillIds }),\n })\n const memory = options.memory === false ? undefined : options.memory ?? definition.memory\n if (snapshot !== undefined) validateMemoryResumeBinding(snapshot, memory)\n const toolSources = combineToolSources(definition.toolSources, options.toolSources ?? [])\n const limits = options.runtimeLimits\n const { maxSteps: _maxSteps, maxToolCalls: _maxToolCalls, ...agentRuntimeLimits } = limits ?? {}\n const selected = limits?.maxSteps === undefined && limits?.maxToolCalls === undefined\n ? definition.legacy : definition.legacy.with({\n ...(limits.maxSteps === undefined ? {} : { maxTurns: limits.maxSteps }),\n ...(limits.maxToolCalls === undefined ? {} : { maxToolCalls: limits.maxToolCalls }),\n })\n const shared = { registry: host.registry, observation: host.observation, observationResource: host.resource,\n ...(options.tools === undefined ? {} : { tools: options.tools }),\n ...(options.skills === undefined ? {} : { skills: options.skills as never }),\n ...(options.skillCwd === undefined ? {} : { skillCwd: options.skillCwd }),\n ...(options.userInput === undefined ? {} : { userInput: options.userInput }),\n ...(options.approvals === undefined ? {} : { approvals: options.approvals }),\n ...(options.spillStore === undefined ? {} : { spillStore: options.spillStore }),\n ...(options.experimentalPrograms === undefined ? {} : { experimentalPrograms: options.experimentalPrograms }),\n ...(options.interceptors === undefined ? {} : { interceptors: options.interceptors }),\n ...(options.contextSections === undefined ? {} : { contextSections: options.contextSections }),\n ...(options.hooks === undefined ? {} : { hooks: options.hooks }),\n ...(options.usagePolicy === undefined ? {} : { usagePolicy: options.usagePolicy }),\n ...(options.historyLimits === undefined ? {} : { historyLimits: options.historyLimits }),\n ...(options.ledgerLimits === undefined ? {} : { ledgerLimits: options.ledgerLimits }),\n ...(options.eventBufferLimits === undefined ? {} : { eventBufferLimits: options.eventBufferLimits }),\n ...(options.compaction === undefined ? {} : { compaction: options.compaction }),\n ...(team === undefined ? {} : { team }),\n ...(Object.keys(agentRuntimeLimits).length === 0 ? {} : { runtimeLimits: agentRuntimeLimits }),\n }\n const session = snapshot === undefined\n ? selected.createSession({ ...shared, ...(options.conversationId === undefined ? {} : { conversationId: options.conversationId }) })\n : selected.resumeSession({ ...shared, snapshot })\n configureRuntimeSessionModel(session, { provider: definition.model.provider, model: definition.model.id,\n ...(definition.effort === undefined ? {} : { reasoningEffort: definition.effort }),\n ...(definition.maxTokens === undefined ? {} : { maxTokens: definition.maxTokens }),\n logger: correlation => host.observation.correlatedLogger(correlation, { scope: 'sdk.agent.run' }),\n ...(toolSources.length === 0 ? {} : {\n prepareTools: (signal, logger, occupiedNames) => snapshotToolSources(\n toolSources, signal, logger, occupiedNames,\n ),\n }),\n ...(memory === undefined ? {} : {\n memory: createRuntimeMemoryPersistence(\n memory,\n definition.legacy.id,\n agentRuntimeLimits.memoryOperationTimeoutMs,\n ),\n }),\n })\n return new RuntimeAgentSessionValue(\n host, session, definition.model.provider, definition.legacy.id, limits?.observerTimeoutMs, ownerSignal,\n )\n}\n\n/** Project one captured invocation onto the low-level per-run model overlay. */\nfunction modelOverlay(options: CapturedInvocationOptions): {\n readonly model?: { readonly provider: string; readonly model: string }\n readonly maxTokens?: number\n} {\n return {\n ...(options.model === undefined ? {} : { model: { provider: options.model.provider, model: options.model.id } }),\n ...(options.maxTokens === undefined ? {} : { maxTokens: options.maxTokens }),\n }\n}\n\ninterface SessionOperation {\n readonly done: Promise<void>\n readonly resolve: () => void\n}\n\ninterface StartedRuntimeRun {\n readonly legacy: RuntimeSessionRunHandle\n readonly report: Promise<RuntimeRunReport>\n readonly result: Promise<RuntimeAgentResponse>\n}\n\nfunction combineToolSources(\n defined: readonly CapturedToolSource[],\n additional: readonly CapturedToolSource[],\n): readonly CapturedToolSource[] {\n const all = [...defined, ...additional]\n const seen = new Map<string, number>()\n for (const [index, source] of all.entries()) {\n const first = seen.get(source.id)\n if (first !== undefined) throw capabilityIdentityError(\n 'TOOL_SOURCE_ID_CONFLICT', 'tool-source-id', first, index,\n )\n seen.set(source.id, index)\n }\n return Object.freeze(all)\n}\n\nfunction runtimeHandle(\n source: LegacyRunHandle & { readonly traceId: string; abort(reason?: unknown): void },\n report: Promise<RuntimeRunReport>, result: Promise<RuntimeAgentResponse>, nativeProvider: string,\n includeTraceEvents: boolean,\n): RuntimeAgentRunHandle {\n let iterated = false\n return Object.freeze({ runId: source.runId, report, result, abort: () => source.abort(),\n [Symbol.asyncIterator](): AsyncIterator<RuntimeAgentRunEvent> {\n if (iterated) return (async function* () { throw new Error('A runtime run handle can only be iterated once') })()\n iterated = true\n return projectEvents(source, report, nativeProvider, includeTraceEvents)\n } })\n}\n\nasync function* projectEvents(\n source: LegacyRunHandle & { readonly traceId: string; abort(reason?: unknown): void },\n report: Promise<RuntimeRunReport>,\n nativeProvider: string,\n includeTraceEvents: boolean,\n): AsyncGenerator<RuntimeAgentRunEvent> {\n let sequence = 0, completed = false\n const context = () => ({ runId: source.runId, traceId: source.traceId, sequence: ++sequence, schemaVersion: 1 as const })\n try {\n for await (const event of source) {\n const projected = projectEvent(event, nativeProvider, includeTraceEvents)\n if (projected !== undefined) yield Object.freeze({ ...context(), ...projected }) as RuntimeAgentRunEvent\n }\n const terminal = await report\n if (terminal.status === 'success') {\n yield Object.freeze({ ...context(), type: 'usage', usage: terminal.usage, report: terminal })\n } else {\n const error = terminal.errors.at(-1) ?? fallbackError(terminal)\n yield Object.freeze({ ...context(), type: 'error', error, report: terminal })\n }\n completed = true\n } catch {\n const terminal = await report\n const error = terminal.errors.at(-1) ?? fallbackError(terminal)\n yield Object.freeze({ ...context(), type: 'error', error, report: terminal })\n completed = true\n } finally { if (!completed) source.abort() }\n}\n\ntype WithoutEventContext<T> = T extends unknown ? Omit<T, 'runId' | 'traceId' | 'sequence' | 'schemaVersion'> : never\ntype ProjectedEvent = WithoutEventContext<RuntimeAgentRunEvent>\n\nfunction projectEvent(event: AgentRunEvent, nativeProvider: string, includeTraceEvents: boolean): ProjectedEvent | undefined {\n if (event.type === 'usage-progress') return { type: 'usage-progress', usage: event.usage,\n ...(event.attemptId === undefined ? {} : { attemptId: event.attemptId }) }\n // Runtime consumers such as Edge hosts may persist an execution trace. Keep\n // the SDK's span lifecycle intact; unlike transcript events, spans carry the\n // identity and nesting needed to reconstruct the call tree.\n if (includeTraceEvents && (event.type === 'span-start' || event.type === 'span-end')) return event\n if (event.type === 'text-delta') return {\n type: event.phase === 'commentary' ? 'commentary-delta' : 'assistant-delta',\n text: event.text, index: event.index, phase: event.phase, blockId: `${event.trace.spanId}:${event.index}`,\n }\n if (event.type === 'assistant-message') return { type: 'assistant-message', message: publicMessage(event.message) }\n if (event.type === 'text-end' || event.type === 'reasoning-delta') {\n const { trace, ...content } = event\n return { ...content, blockId: `${trace.spanId}:${event.index}` }\n }\n if (event.type === 'image-delta') {\n const { trace, ...content } = event\n return { ...content, blockId: `${trace.spanId}:${event.itemId}` }\n }\n if (event.type === 'compaction-start' || event.type === 'compaction-end'\n || event.type === 'turn-start' || event.type === 'step-start' || event.type === 'step-end'\n || event.type === 'assistant-text' || event.type === 'assistant-reasoning') {\n const { trace: _trace, ...content } = event\n return content\n }\n if (event.type === 'tool-call') return { type: 'tool-call', callId: event.call.callId,\n name: event.call.toolName, input: parseInput(event.call.rawArguments) }\n if (event.type === 'tool-result') return { type: 'tool-result', callId: event.call.callId,\n name: event.call.toolName, status: toolResultStatus(event.result), output: event.result }\n if (event.type === 'assistant-native-tool') return projectNativeToolEvent(event.call, nativeProvider)\n if (event.type === 'approval-request') return { type: 'approval-request', request: event.request }\n if (event.type === 'user-input-request') return { type: 'user-input-request', request: event.request }\n if (event.type === 'user-input-response') return { type: 'user-input-response', requestId: event.request.requestId,\n response: event.response }\n return undefined\n}\n\nfunction toolResultStatus(\n result: ToolExecutionResult,\n): 'completed' | 'failed' | 'aborted' | 'rejected' | 'declined' {\n // A call the loop refused to run is neither success nor failure: nothing\n // broke, and nothing was done. Reporting it as either misleads a UI — and a\n // red row for a budget decision is what makes a finished run look crashed.\n if (!result.isError) return result.meta?.['declined'] === true ? 'declined' : 'completed'\n if (result.error.code === TOOL_ERROR_CODES.ABORTED\n || result.error.code === TOOL_ERROR_CODES.ABORTED_BEFORE_DISPATCH) return 'aborted'\n if (result.error.code === TOOL_ERROR_CODES.UNKNOWN_TOOL\n || result.error.code === TOOL_ERROR_CODES.INVALID_ARGUMENTS\n || result.error.code === TOOL_ERROR_CODES.MALFORMED_ARGUMENTS\n || result.error.code === TOOL_ERROR_CODES.DENIED\n || result.error.code === TOOL_ERROR_CODES.BUDGET_EXHAUSTED\n || result.error.code === TOOL_ERROR_CODES.CHECKPOINT_FAILED) return 'rejected'\n return 'failed'\n}\n\nfunction parseInput(value: string): unknown { try { return JSON.parse(value) as unknown } catch { return value } }\nfunction codeOf(value: unknown): string {\n return value instanceof AgentSdkError ? value.code : 'AGENT_RUN_FAILED'\n}\nfunction runtimeFailure(value: unknown, report: RuntimeRunReport, code: string): AgentRunError {\n return inheritCapabilityIdentityConflict(\n new AgentRunError('Agent run did not complete', code, report as never), value,\n )\n}\nfunction fallbackError(report: RuntimeRunReport): RuntimeRunReport['errors'][number] {\n return Object.freeze({ code: 'AGENT_RUN_FAILED', stage: 'agent-run', message: 'Agent operation failed',\n usageCoverage: report.usage.coverage,\n possiblyBilledAttemptsWithoutUsage: report.usage.coverage.possiblyBilledAttemptsWithoutUsage })\n}\n"],"mappings":"0zCA8DA,MAAM,EAAuB,IAAI,QAEjC,SAAgB,EAAmB,EAAwB,EAAuD,CAChH,IAAM,E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"sources":["../../../src/composition/agent/session.ts"],"sourcesContent":["import { publicMessage } from './public-message.ts'\nimport type { AgentInput } from '../../agent/define/session/types.ts'\nimport { isJsonValue, detachedFrozen, type JsonValue } from '../../primitives/index.ts'\nimport { freezeMessage } from '../../message/index.ts'\nimport { AgentRunError } from '../../agent/accounting/error.ts'\nimport type { RunReport } from '../exporter/delivery-types.ts'\nimport { configureRuntimeSessionModel, streamRuntimeSession, type AgentSession } from '../../agent/define/session.ts'\nimport {\n compactRuntimeSession, streamPendingRuntimeSession, type RuntimeSessionRunHandle,\n} from '../../agent/define/session/runtime-binding.ts'\nimport type { AgentRunHandle as LegacyRunHandle } from '../../agent/define/session/types.ts'\nimport type { AgentRunEvent } from '../../agent/mode/run-agent.ts'\nimport type { ToolExecutionResult } from '../../agent/tool/definition.ts'\nimport { TOOL_ERROR_CODES } from '../../agent/tool/errors.ts'\nimport { AgentSdkError } from '../../errors/agent-sdk-error.ts'\nimport type { ModelRegistry } from '../../runtime/registry.ts'\nimport type { ProviderSelection } from '../provider/types.ts'\nimport { atDeadline } from '../lifecycle/bounded.ts'\nimport type { RuntimeOperations } from '../lifecycle/operations.ts'\nimport type { RuntimeObservationPort } from '../observation/port.ts'\nimport { createRunTerminalRecord } from '../delivery/terminal.ts'\nimport { finalizeRuntimeRunReport, type RuntimeRunReport } from '../observation/final-report.ts'\nimport type { RuntimeObservationResource } from '../delivery/resource.ts'\nimport type { RuntimeResources } from '../../platform/resources.ts'\nimport { snapshotToolSources } from '../tool-source/snapshot.ts'\nimport { capabilityIdentityError, inheritCapabilityIdentityConflict } from '../identity/error.ts'\nimport type { CapturedToolSource } from '../tool-source/types.ts'\nimport type { ToolSourceRunReference } from '../tool-source/types.ts'\nimport { createRuntimeMemoryPersistence } from '../memory/run.ts'\nimport { validateMemoryResumeBinding } from '../memory/resume.ts'\nimport type { BoundRuntimeAgentDefinition } from './definition.ts'\nimport { captureInvocationOptions, captureRuntimeSessionOptions, type CapturedInvocationOptions } from './options.ts'\nimport { projectNativeToolEvent } from './native-event.ts'\nimport type {\n RuntimeAgent, RuntimeAgentInvocationOptions, RuntimeAgentResponse, RuntimeAgentRunEvent,\n RuntimeAgentRunHandle, RuntimeAgentSession, RuntimeAgentSessionOptions, RuntimeAgentSessionSnapshot,\n} from './types.ts'\nimport type { CompactionResult } from '../../agent/memory/compaction.ts'\nimport type { AgentTeamMemberOptions } from '../../agent/define/session/types.ts'\nimport type { TeamSessionPort } from '../../agent/team/contracts.ts'\nimport { assertAgentIdentitySnapshot } from '../identity/agent.ts'\n\nexport interface RuntimeAgentHost {\n readonly registry: ModelRegistry\n /**\n * The runtime's captured provider routes.\n *\n * Held so a per-invocation model override resolves against exactly the same\n * configuration the agent binding used, rather than a second view of it.\n */\n readonly selection: ProviderSelection\n readonly operations: RuntimeOperations\n readonly observation: RuntimeObservationPort\n readonly resource: RuntimeObservationResource\n readonly resources: RuntimeResources\n}\n\ninterface RuntimeAgentBinding {\n readonly host: RuntimeAgentHost\n readonly definition: BoundRuntimeAgentDefinition\n}\n\nconst runtimeAgentBindings = new WeakMap<RuntimeAgent, RuntimeAgentBinding>()\n\nexport function createRuntimeAgent(host: RuntimeAgentHost, definition: BoundRuntimeAgentDefinition): RuntimeAgent {\n const agent = Object.freeze({\n model: definition.model,\n generate(input: AgentInput, options?: RuntimeAgentInvocationOptions) { return createRuntimeSession(host, definition).run(input, options) },\n stream(input: AgentInput, options?: RuntimeAgentInvocationOptions) { return createRuntimeSession(host, definition).stream(input, options) },\n createSession(options?: RuntimeAgentSessionOptions) { return createRuntimeSession(host, definition, options) },\n resumeSession(snapshot: RuntimeAgentSessionSnapshot, options?: RuntimeAgentSessionOptions) {\n return createRuntimeSession(host, definition, options, snapshot)\n },\n })\n runtimeAgentBindings.set(agent, Object.freeze({ host, definition }))\n return agent\n}\n\nexport function createRuntimeTeamMemberSession(\n host: RuntimeAgentHost,\n agent: RuntimeAgent,\n options: RuntimeAgentSessionOptions,\n team: AgentTeamMemberOptions,\n ownerSignal: AbortSignal,\n): { readonly view: RuntimeAgentSession; readonly port: TeamSessionPort } {\n const binding = runtimeAgentBindings.get(agent)\n if (binding?.host !== host) throw new AgentSdkError(\n 'Runtime team members must be agents from the same runtime', 'TEAM_AGENT_OWNERSHIP_INVALID',\n )\n const view = createRuntimeSession(host, binding.definition, options, undefined, team, ownerSignal)\n return Object.freeze({ view, port: view.teamPort })\n}\n\nexport function preflightRuntimeTeamMember(\n host: RuntimeAgentHost,\n agent: RuntimeAgent,\n options: RuntimeAgentSessionOptions,\n additionalToolNames: readonly string[],\n): void {\n const binding = runtimeAgentBindings.get(agent)\n if (binding?.host !== host) throw new AgentSdkError(\n 'Runtime team members must be agents from the same runtime', 'TEAM_AGENT_OWNERSHIP_INVALID',\n )\n assertAgentIdentitySnapshot({\n tools: [...binding.definition.legacy.tools, ...options.tools ?? []],\n nativeTools: binding.definition.legacy.nativeTools,\n skills: [...binding.definition.legacy.skills, ...options.skills ?? []] as never,\n ...(binding.definition.legacy.skillIds === undefined ? {} : {\n allowedSkillIds: binding.definition.legacy.skillIds,\n }),\n additionalToolNames,\n })\n}\n\nexport function runtimeOwnsAgent(host: RuntimeAgentHost, agent: unknown): agent is RuntimeAgent {\n return typeof agent === 'object' && agent !== null && runtimeAgentBindings.get(agent as RuntimeAgent)?.host === host\n}\n\nclass RuntimeAgentSessionValue implements RuntimeAgentSession {\n private active: SessionOperation | undefined\n private readonly observerTimeoutMs: number\n readonly teamPort: TeamSessionPort\n\n constructor(\n private readonly host: RuntimeAgentHost,\n private readonly session: AgentSession,\n private readonly nativeProvider: string,\n definitionId: string,\n observerTimeoutMs = 30_000,\n private readonly ownerSignal?: AbortSignal,\n ) {\n this.observerTimeoutMs = observerTimeoutMs\n const owner = this\n this.teamPort = Object.freeze({\n definition: Object.freeze({ id: definitionId }),\n get conversationId() { return owner.conversationId },\n get isRunning() { return owner.isRunning },\n inject(input: Parameters<TeamSessionPort['inject']>[0]) { return owner.injectForTeam(input) },\n whenIdle(signal?: AbortSignal) { return owner.whenIdle(signal) },\n hasUnansweredInput() { return owner.session.hasUnansweredInput() },\n lastOutcome() { return owner.session.lastOutcome() },\n runPending(invocation = {}) { return owner.runPendingForTeam(invocation) },\n })\n }\n\n get conversationId(): string { return this.session.conversationId }\n get isRunning(): boolean { return this.active !== undefined }\n\n stream(input: AgentInput, rawOptions?: RuntimeAgentInvocationOptions): RuntimeAgentRunHandle {\n if (typeof input !== 'string') {\n if (input === null || typeof input !== 'object' || input.role !== 'user') throw new TypeError('Runtime input must be text or a user message')\n input = freezeMessage(input)\n }\n const options = captureInvocationOptions(rawOptions, this.host.selection)\n const started = this.start(input, options)\n return runtimeHandle(started.legacy, started.report, started.result, this.nativeProvider, options.includeTraceEvents === true)\n }\n\n private start(input: AgentInput | undefined, options: CapturedInvocationOptions): StartedRuntimeRun {\n const operation = this.beginOperation()\n let lease: ReturnType<RuntimeOperations['acquire']>\n try {\n const signal = this.ownerSignal === undefined\n ? options.signal\n : options.signal === undefined ? this.ownerSignal : AbortSignal.any([options.signal, this.ownerSignal])\n lease = this.host.operations.acquire('agent-run', {\n ...(signal === undefined ? {} : { signal }),\n })\n } catch (error) { this.finishOperation(operation); throw error }\n let output: JsonValue | undefined\n const structured = options.structuredOutput\n let legacy: RuntimeSessionRunHandle\n try {\n legacy = input === undefined\n ? streamPendingRuntimeSession(this.session, { signal: lease.signal, ...modelOverlay(options) })\n : streamRuntimeSession(this.session, input, { signal: lease.signal, ...modelOverlay(options),\n ...(structured === undefined ? {} : {\n outputFormat: { type: 'json_schema' as const, name: structured.name, schema: structured.schema.jsonSchema },\n validateOutput: (value: unknown) => {\n const parsed = structured.schema.parse(value)\n if (!isJsonValue(parsed)) throw new TypeError('structured output parser must return lossless JSON synchronously')\n output = detachedFrozen(parsed)\n },\n }), ...(options.imagePolicy === undefined ? {} : { imagePolicy: options.imagePolicy }),\n ...(options.documentPolicy === undefined ? {} : { documentPolicy: options.documentPolicy }) }, options.additionalInstructions)\n } catch (error) { lease.settle(); this.finishOperation(operation); throw error }\n const abort = (): void => legacy.abort()\n lease.signal.addEventListener('abort', abort, { once: true })\n if (lease.signal.aborted) abort()\n void lease.whenSealed.then(() => legacy.seal()).catch(() => undefined)\n const report = this.runtimeReport(legacy.report, legacy.toolSourceSnapshots, lease.signal)\n const internalResult = this.runtimeResult(legacy.result, report, () => output)\n const eventsSettled = Promise.race([legacy.eventsSettled, lease.whenSealed])\n const released = Promise.allSettled([eventsSettled, internalResult, report]).then(() => {\n lease.signal.removeEventListener('abort', abort)\n lease.settle()\n this.finishOperation(operation)\n })\n const result = released.then(() => internalResult)\n void result.catch(() => undefined)\n void report.catch(() => undefined)\n return Object.freeze({ legacy, report, result })\n }\n\n async run(input: AgentInput, rawOptions?: RuntimeAgentInvocationOptions): Promise<RuntimeAgentResponse> {\n const options = captureInvocationOptions(rawOptions, this.host.selection)\n const handle = this.stream(input, options)\n try {\n for await (const event of handle) {\n if (options.onEvent !== undefined) {\n try { await this.observe(options.onEvent, event, handle) }\n catch (error) {\n handle.abort()\n const report = await handle.report\n throw runtimeFailure(error, report, 'RUN_EVENT_OBSERVER_FAILED')\n }\n }\n }\n } catch (error) { if (codeOf(error) === 'RUN_EVENT_OBSERVER_FAILED') throw error; return await handle.result }\n return await handle.result\n }\n\n inject(input: AgentInput): number {\n this.host.operations.assertActive()\n this.assertOwnerActive()\n // A run in flight is the case steering exists for. The underlying session\n // holds the message until the round that could not see it has finished,\n // then delivers it in arrival order. Refusing here left the runtime\n // surface unable to steer at all, while the same call on a bare session\n // (and injectForTeam below) is accepted.\n return this.session.inject(input)\n }\n\n private injectForTeam(input: Parameters<TeamSessionPort['inject']>[0]): number {\n this.host.operations.assertActive()\n this.assertOwnerActive()\n return this.session.inject(input)\n }\n\n hasUnansweredInput(): boolean { return this.session.hasUnansweredInput() }\n\n async runPending(rawOptions?: RuntimeAgentInvocationOptions): Promise<RuntimeAgentResponse> {\n const options = captureInvocationOptions(rawOptions, this.host.selection)\n const started = this.start(undefined, options)\n const handle = runtimeHandle(started.legacy, started.report, started.result, this.nativeProvider, options.includeTraceEvents === true)\n try {\n for await (const event of handle) {\n if (options.onEvent !== undefined) await this.observe(options.onEvent, event, handle)\n }\n } catch (error) {\n handle.abort()\n await handle.result.catch(() => undefined)\n throw error\n }\n return await handle.result\n }\n\n snapshot(): RuntimeAgentSessionSnapshot { return this.session.snapshot() }\n\n compact(rawOptions?: RuntimeAgentInvocationOptions): Promise<CompactionResult | null> {\n const options = captureInvocationOptions(rawOptions, this.host.selection)\n const operation = this.beginOperation()\n let pending: Promise<CompactionResult | null>\n try {\n pending = this.host.operations.execute('manual-compaction', {\n ...(this.ownerSignal === undefined\n ? options.signal === undefined ? {} : { signal: options.signal }\n : { signal: options.signal === undefined ? this.ownerSignal : AbortSignal.any([options.signal, this.ownerSignal]) }),\n }, async lease => {\n const outcome = await compactRuntimeSession(this.session, { signal: lease.signal, ...modelOverlay(options) })\n const record = createRunTerminalRecord(outcome.report)\n const terminal = await this.host.observation.checkpointTerminal(record, lease.signal)\n const report = finalizeRuntimeRunReport(record, outcome.report.delivery, terminal,\n this.host.observation.mode, this.host.observation.requiredBoundary)\n if (outcome.failure !== undefined) throw runtimeFailure(\n outcome.failure,\n report,\n report.errors.at(-1)?.code ?? codeOf(outcome.failure),\n )\n return outcome.result === null ? null : Object.freeze({ ...outcome.result, status: 'completed' as const, report })\n })\n } catch (error) { this.finishOperation(operation); throw error }\n return pending.finally(() => this.finishOperation(operation))\n }\n\n reset(): void {\n this.host.operations.assertActive()\n this.assertOwnerActive()\n if (this.active !== undefined) throw new Error('Cannot reset while a runtime session is active')\n this.session.reset()\n }\n\n whenIdle(signal?: AbortSignal): Promise<void> {\n const pending = this.active?.done\n if (pending === undefined) return Promise.resolve()\n if (signal?.aborted) return Promise.reject(new AgentSdkError('Runtime idle wait was aborted', 'RUNTIME_OPERATION_ABORTED'))\n return new Promise((resolve, reject) => {\n let release = (): void => undefined\n const finish = (error?: Error): void => { release(); error === undefined ? resolve() : reject(error) }\n if (signal !== undefined) release = this.host.resources.onAbort(signal,\n () => finish(new AgentSdkError('Runtime idle wait was aborted', 'RUNTIME_OPERATION_ABORTED')))\n void pending.then(() => finish())\n })\n }\n\n private async runPendingForTeam(invocation: {\n readonly signal?: AbortSignal\n readonly onEvent?: (event: AgentRunEvent) => void | Promise<void>\n }): Promise<unknown> {\n const started = this.start(undefined, {\n ...(invocation.signal === undefined ? {} : { signal: invocation.signal }),\n })\n try {\n for await (const event of started.legacy) await invocation.onEvent?.(event)\n } catch (error) {\n started.legacy.abort()\n await started.result.catch(() => undefined)\n throw error\n }\n return await started.result\n }\n\n private beginOperation(): SessionOperation {\n this.assertOwnerActive()\n if (this.active !== undefined) throw new Error('Cannot start while a runtime session is active')\n let resolve!: () => void\n const operation: SessionOperation = { done: new Promise(done => { resolve = done }), resolve }\n this.active = operation\n return operation\n }\n\n private finishOperation(operation: SessionOperation): void {\n if (this.active !== operation) return\n this.active = undefined\n operation.resolve()\n }\n\n private assertOwnerActive(): void {\n if (this.ownerSignal?.aborted === true) {\n throw new AgentSdkError('Runtime team session is closed', 'TEAM_CLOSED')\n }\n }\n\n private async runtimeReport(\n legacy: Promise<RunReport>,\n sourceSnapshots: Promise<readonly ToolSourceRunReference[]>,\n signal: AbortSignal,\n ): Promise<RuntimeRunReport> {\n const [previous, sources] = await Promise.all([legacy, sourceSnapshots])\n const record = createRunTerminalRecord(previous, sources)\n const terminal = await this.host.observation.checkpointTerminal(record, signal)\n return finalizeRuntimeRunReport(record, previous.delivery, terminal,\n this.host.observation.mode, this.host.observation.requiredBoundary)\n }\n\n private async runtimeResult(\n legacy: Promise<Awaited<LegacyRunHandle['result']>>,\n report: Promise<RuntimeRunReport>,\n output: () => JsonValue | undefined,\n ): Promise<RuntimeAgentResponse> {\n try {\n const response = await legacy\n const final = await report\n if (final.status !== 'success') {\n throw runtimeFailure(undefined, final, final.errors.at(-1)?.code ?? 'AGENT_RUN_FAILED')\n }\n const parsedOutput = output()\n return Object.freeze({ runId: final.runId, traceId: final.traceId,\n completed: response.outcome.completed, stopReason: response.outcome.reason.kind,\n text: response.text, ...(parsedOutput === undefined ? {} : { output: parsedOutput }),\n ...(response.message === undefined ? {} : { message: publicMessage(response.message) }),\n usage: final.usage, report: final })\n } catch (error) {\n const final = await report\n throw runtimeFailure(error, final, codeOf(error))\n }\n }\n\n private async observe(\n observer: NonNullable<RuntimeAgentInvocationOptions['onEvent']>,\n event: RuntimeAgentRunEvent,\n handle: RuntimeAgentRunHandle,\n ): Promise<void> {\n const deadlineAt = this.host.resources.platform.monotonicNow() + this.observerTimeoutMs\n try { await atDeadline(this.host.resources, deadlineAt, () => observer(event), undefined) }\n catch { handle.abort(); throw new AgentSdkError('Runtime event observer did not complete', 'RUN_EVENT_OBSERVER_FAILED') }\n }\n}\n\nfunction createRuntimeSession(\n host: RuntimeAgentHost,\n definition: BoundRuntimeAgentDefinition,\n options: RuntimeAgentSessionOptions = {},\n snapshot?: RuntimeAgentSessionSnapshot,\n team?: AgentTeamMemberOptions,\n ownerSignal?: AbortSignal,\n): RuntimeAgentSessionValue {\n host.operations.assertActive()\n options = captureRuntimeSessionOptions(options)\n assertAgentIdentitySnapshot({\n tools: [...definition.legacy.tools, ...options.tools ?? []],\n nativeTools: definition.legacy.nativeTools,\n skills: [...definition.legacy.skills, ...options.skills ?? []] as never,\n ...(definition.legacy.skillIds === undefined ? {} : { allowedSkillIds: definition.legacy.skillIds }),\n })\n const memory = options.memory === false ? undefined : options.memory ?? definition.memory\n if (snapshot !== undefined) validateMemoryResumeBinding(snapshot, memory)\n const toolSources = combineToolSources(definition.toolSources, options.toolSources ?? [])\n const limits = options.runtimeLimits\n const { maxSteps: _maxSteps, maxToolCalls: _maxToolCalls, ...agentRuntimeLimits } = limits ?? {}\n const selected = limits?.maxSteps === undefined && limits?.maxToolCalls === undefined\n ? definition.legacy : definition.legacy.with({\n ...(limits.maxSteps === undefined ? {} : { maxTurns: limits.maxSteps }),\n ...(limits.maxToolCalls === undefined ? {} : { maxToolCalls: limits.maxToolCalls }),\n })\n const shared = { registry: host.registry, observation: host.observation, observationResource: host.resource,\n ...(options.tools === undefined ? {} : { tools: options.tools }),\n ...(options.skills === undefined ? {} : { skills: options.skills as never }),\n ...(options.skillCwd === undefined ? {} : { skillCwd: options.skillCwd }),\n ...(options.userInput === undefined ? {} : { userInput: options.userInput }),\n ...(options.approvals === undefined ? {} : { approvals: options.approvals }),\n ...(options.spillStore === undefined ? {} : { spillStore: options.spillStore }),\n ...(options.experimentalPrograms === undefined ? {} : { experimentalPrograms: options.experimentalPrograms }),\n ...(options.interceptors === undefined ? {} : { interceptors: options.interceptors }),\n ...(options.contextSections === undefined ? {} : { contextSections: options.contextSections }),\n ...(options.hooks === undefined ? {} : { hooks: options.hooks }),\n ...(options.usagePolicy === undefined ? {} : { usagePolicy: options.usagePolicy }),\n ...(options.historyLimits === undefined ? {} : { historyLimits: options.historyLimits }),\n ...(options.ledgerLimits === undefined ? {} : { ledgerLimits: options.ledgerLimits }),\n ...(options.eventBufferLimits === undefined ? {} : { eventBufferLimits: options.eventBufferLimits }),\n ...(options.compaction === undefined ? {} : { compaction: options.compaction }),\n ...(team === undefined ? {} : { team }),\n ...(Object.keys(agentRuntimeLimits).length === 0 ? {} : { runtimeLimits: agentRuntimeLimits }),\n }\n const session = snapshot === undefined\n ? selected.createSession({ ...shared, ...(options.conversationId === undefined ? {} : { conversationId: options.conversationId }) })\n : selected.resumeSession({ ...shared, snapshot })\n configureRuntimeSessionModel(session, { provider: definition.model.provider, model: definition.model.id,\n ...(definition.effort === undefined ? {} : { reasoningEffort: definition.effort }),\n ...(definition.maxTokens === undefined ? {} : { maxTokens: definition.maxTokens }),\n logger: correlation => host.observation.correlatedLogger(correlation, { scope: 'sdk.agent.run' }),\n ...(toolSources.length === 0 ? {} : {\n prepareTools: (signal, logger, occupiedNames) => snapshotToolSources(\n toolSources, signal, logger, occupiedNames,\n ),\n }),\n ...(memory === undefined ? {} : {\n memory: createRuntimeMemoryPersistence(\n memory,\n definition.legacy.id,\n agentRuntimeLimits.memoryOperationTimeoutMs,\n ),\n }),\n })\n return new RuntimeAgentSessionValue(\n host, session, definition.model.provider, definition.legacy.id, limits?.observerTimeoutMs, ownerSignal,\n )\n}\n\n/** Project one captured invocation onto the low-level per-run model overlay. */\nfunction modelOverlay(options: CapturedInvocationOptions): {\n readonly model?: { readonly provider: string; readonly model: string }\n readonly maxTokens?: number\n} {\n return {\n ...(options.model === undefined ? {} : { model: { provider: options.model.provider, model: options.model.id } }),\n ...(options.maxTokens === undefined ? {} : { maxTokens: options.maxTokens }),\n }\n}\n\ninterface SessionOperation {\n readonly done: Promise<void>\n readonly resolve: () => void\n}\n\ninterface StartedRuntimeRun {\n readonly legacy: RuntimeSessionRunHandle\n readonly report: Promise<RuntimeRunReport>\n readonly result: Promise<RuntimeAgentResponse>\n}\n\nfunction combineToolSources(\n defined: readonly CapturedToolSource[],\n additional: readonly CapturedToolSource[],\n): readonly CapturedToolSource[] {\n const all = [...defined, ...additional]\n const seen = new Map<string, number>()\n for (const [index, source] of all.entries()) {\n const first = seen.get(source.id)\n if (first !== undefined) throw capabilityIdentityError(\n 'TOOL_SOURCE_ID_CONFLICT', 'tool-source-id', first, index,\n )\n seen.set(source.id, index)\n }\n return Object.freeze(all)\n}\n\nfunction runtimeHandle(\n source: LegacyRunHandle & { readonly traceId: string; abort(reason?: unknown): void },\n report: Promise<RuntimeRunReport>, result: Promise<RuntimeAgentResponse>, nativeProvider: string,\n includeTraceEvents: boolean,\n): RuntimeAgentRunHandle {\n let iterated = false\n return Object.freeze({ runId: source.runId, report, result, abort: () => source.abort(),\n [Symbol.asyncIterator](): AsyncIterator<RuntimeAgentRunEvent> {\n if (iterated) return (async function* () { throw new Error('A runtime run handle can only be iterated once') })()\n iterated = true\n return projectEvents(source, report, nativeProvider, includeTraceEvents)\n } })\n}\n\nasync function* projectEvents(\n source: LegacyRunHandle & { readonly traceId: string; abort(reason?: unknown): void },\n report: Promise<RuntimeRunReport>,\n nativeProvider: string,\n includeTraceEvents: boolean,\n): AsyncGenerator<RuntimeAgentRunEvent> {\n let sequence = 0, completed = false\n const context = () => ({ runId: source.runId, traceId: source.traceId, sequence: ++sequence, schemaVersion: 1 as const })\n try {\n for await (const event of source) {\n const projected = projectEvent(event, nativeProvider, includeTraceEvents)\n if (projected !== undefined) yield Object.freeze({ ...context(), ...projected }) as RuntimeAgentRunEvent\n }\n const terminal = await report\n if (terminal.status === 'success') {\n yield Object.freeze({ ...context(), type: 'usage', usage: terminal.usage, report: terminal })\n } else {\n const error = terminal.errors.at(-1) ?? fallbackError(terminal)\n yield Object.freeze({ ...context(), type: 'error', error, report: terminal })\n }\n completed = true\n } catch {\n const terminal = await report\n const error = terminal.errors.at(-1) ?? fallbackError(terminal)\n yield Object.freeze({ ...context(), type: 'error', error, report: terminal })\n completed = true\n } finally { if (!completed) source.abort() }\n}\n\ntype WithoutEventContext<T> = T extends unknown ? Omit<T, 'runId' | 'traceId' | 'sequence' | 'schemaVersion'> : never\ntype ProjectedEvent = WithoutEventContext<RuntimeAgentRunEvent>\n\nfunction projectEvent(event: AgentRunEvent, nativeProvider: string, includeTraceEvents: boolean): ProjectedEvent | undefined {\n if (event.type === 'usage-progress') return { type: 'usage-progress', usage: event.usage,\n ...(event.attemptId === undefined ? {} : { attemptId: event.attemptId }) }\n // Runtime consumers such as Edge hosts may persist an execution trace. Keep\n // the SDK's span lifecycle intact; unlike transcript events, spans carry the\n // identity and nesting needed to reconstruct the call tree.\n if (includeTraceEvents && (event.type === 'span-start' || event.type === 'span-end')) return event\n if (event.type === 'text-delta') return {\n type: event.phase === 'commentary' ? 'commentary-delta' : 'assistant-delta',\n text: event.text, index: event.index, phase: event.phase, blockId: `${event.trace.spanId}:${event.index}`,\n }\n if (event.type === 'assistant-message') return { type: 'assistant-message', message: publicMessage(event.message) }\n if (event.type === 'assistant-replacement') return { ...event, message: publicMessage(event.message) }\n if (event.type === 'text-end' || event.type === 'reasoning-delta') {\n const { trace, ...content } = event\n return { ...content, blockId: `${trace.spanId}:${event.index}` }\n }\n if (event.type === 'image-delta') {\n const { trace, ...content } = event\n return { ...content, blockId: `${trace.spanId}:${event.itemId}` }\n }\n if (event.type === 'compaction-start' || event.type === 'compaction-end'\n || event.type === 'turn-start' || event.type === 'step-start' || event.type === 'step-end'\n || event.type === 'assistant-text' || event.type === 'assistant-reasoning') {\n const { trace: _trace, ...content } = event\n return content\n }\n if (event.type === 'tool-call') return { type: 'tool-call', callId: event.call.callId,\n name: event.call.toolName, input: parseInput(event.call.rawArguments) }\n if (event.type === 'tool-result') return { type: 'tool-result', callId: event.call.callId,\n name: event.call.toolName, status: toolResultStatus(event.result), output: event.result }\n if (event.type === 'assistant-native-tool') return projectNativeToolEvent(event.call, nativeProvider)\n if (event.type === 'approval-request') return { type: 'approval-request', request: event.request }\n if (event.type === 'user-input-request') return { type: 'user-input-request', request: event.request }\n if (event.type === 'user-input-response') return { type: 'user-input-response', requestId: event.request.requestId,\n response: event.response }\n return undefined\n}\n\nfunction toolResultStatus(\n result: ToolExecutionResult,\n): 'completed' | 'failed' | 'aborted' | 'rejected' | 'declined' {\n // A call the loop refused to run is neither success nor failure: nothing\n // broke, and nothing was done. Reporting it as either misleads a UI — and a\n // red row for a budget decision is what makes a finished run look crashed.\n if (!result.isError) return result.meta?.['declined'] === true ? 'declined' : 'completed'\n if (result.error.code === TOOL_ERROR_CODES.ABORTED\n || result.error.code === TOOL_ERROR_CODES.ABORTED_BEFORE_DISPATCH) return 'aborted'\n if (result.error.code === TOOL_ERROR_CODES.UNKNOWN_TOOL\n || result.error.code === TOOL_ERROR_CODES.INVALID_ARGUMENTS\n || result.error.code === TOOL_ERROR_CODES.MALFORMED_ARGUMENTS\n || result.error.code === TOOL_ERROR_CODES.DENIED\n || result.error.code === TOOL_ERROR_CODES.BUDGET_EXHAUSTED\n || result.error.code === TOOL_ERROR_CODES.CHECKPOINT_FAILED) return 'rejected'\n return 'failed'\n}\n\nfunction parseInput(value: string): unknown { try { return JSON.parse(value) as unknown } catch { return value } }\nfunction codeOf(value: unknown): string {\n return value instanceof AgentSdkError ? value.code : 'AGENT_RUN_FAILED'\n}\nfunction runtimeFailure(value: unknown, report: RuntimeRunReport, code: string): AgentRunError {\n return inheritCapabilityIdentityConflict(\n new AgentRunError('Agent run did not complete', code, report as never), value,\n )\n}\nfunction fallbackError(report: RuntimeRunReport): RuntimeRunReport['errors'][number] {\n return Object.freeze({ code: 'AGENT_RUN_FAILED', stage: 'agent-run', message: 'Agent operation failed',\n usageCoverage: report.usage.coverage,\n possiblyBilledAttemptsWithoutUsage: report.usage.coverage.possiblyBilledAttemptsWithoutUsage })\n}\n"],"mappings":"0zCA8DA,MAAM,EAAuB,IAAI,QAEjC,SAAgB,EAAmB,EAAwB,EAAuD,CAChH,IAAM,EAAQ,OAAO,OAAO,CAC1B,MAAO,EAAW,MAClB,SAAS,EAAmB,EAAyC,CAAE,OAAO,EAAqB,EAAM,CAAU,CAAC,CAAC,IAAI,EAAO,CAAO,CAAE,EACzI,OAAO,EAAmB,EAAyC,CAAE,OAAO,EAAqB,EAAM,CAAU,CAAC,CAAC,OAAO,EAAO,CAAO,CAAE,EAC1I,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,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O,EAAuB,EAAM,KAAM,CAAc,EACpG,GAAI,EAAM,OAAS,mBAAoB,MAAO,CAAE,KAAM,mBAAoB,QAAS,EAAM,OAAQ,EACjG,GAAI,EAAM,OAAS,qBAAsB,MAAO,CAAE,KAAM,qBAAsB,QAAS,EAAM,OAAQ,EACrG,GAAI,EAAM,OAAS,sBAAuB,MAAO,CAAE,KAAM,sBAAuB,UAAW,EAAM,QAAQ,UACvG,SAAU,EAAM,QAAS,CAE7B,CAEA,SAAS,EACP,EAC8D,CAa9D,OATK,EAAO,QACR,EAAO,MAAM,OAAS,EAAiB,SACtC,EAAO,MAAM,OAAS,EAAiB,wBAAgC,UACxE,EAAO,MAAM,OAAS,EAAiB,cACtC,EAAO,MAAM,OAAS,EAAiB,mBACvC,EAAO,MAAM,OAAS,EAAiB,qBACvC,EAAO,MAAM,OAAS,EAAiB,QACvC,EAAO,MAAM,OAAS,EAAiB,kBACvC,EAAO,MAAM,OAAS,EAAiB,kBAA0B,WAC/D,SATqB,EAAO,MAAO,WAAgB,GAAO,WAAa,WAUhF,CAEA,SAAS,EAAW,EAAwB,CAAE,GAAI,CAAE,OAAO,KAAK,MAAM,CAAK,CAAa,MAAQ,CAAE,OAAO,CAAM,CAAE,CACjH,SAAS,EAAO,EAAwB,CACtC,OAAO,aAAiB,EAAgB,EAAM,KAAO,kBACvD,CACA,SAAS,EAAe,EAAgB,EAA0B,EAA6B,CAC7F,OAAO,EACL,IAAI,EAAc,6BAA8B,EAAM,CAAe,EAAG,CAC1E,CACF,CACA,SAAS,EAAc,EAA8D,CACnF,OAAO,OAAO,OAAO,CAAE,KAAM,mBAAoB,MAAO,YAAa,QAAS,yBAC5E,cAAe,EAAO,MAAM,SAC5B,mCAAoC,EAAO,MAAM,SAAS,kCAAmC,CAAC,CAClG"}
@@ -160,7 +160,7 @@ interface RuntimeAgentRunEventContext {
160
160
  readonly sequence: number;
161
161
  }
162
162
  type PublicContentEvent = AgentRunEvent extends (infer E) ? E extends {
163
- type: 'text-end' | 'image-delta' | 'assistant-message' | 'compaction-start' | 'compaction-end' | 'turn-start' | 'step-start' | 'step-end' | 'assistant-text' | 'assistant-reasoning' | 'reasoning-delta';
163
+ type: 'text-end' | 'image-delta' | 'assistant-message' | 'assistant-replacement' | 'compaction-start' | 'compaction-end' | 'turn-start' | 'step-start' | 'step-end' | 'assistant-text' | 'assistant-reasoning' | 'reasoning-delta';
164
164
  } ? Omit<E, 'trace'> & {
165
165
  readonly blockId?: string;
166
166
  } : never : never;
@@ -250,6 +250,8 @@ interface RuntimeAgentSession {
250
250
  run(input: AgentInput, options?: RuntimeAgentInvocationOptions): Promise<RuntimeAgentResponse>;
251
251
  stream(input: AgentInput, options?: RuntimeAgentInvocationOptions): RuntimeAgentRunHandle;
252
252
  inject(input: AgentInput): number;
253
+ hasUnansweredInput(): boolean;
254
+ runPending(options?: RuntimeAgentInvocationOptions): Promise<RuntimeAgentResponse>;
253
255
  snapshot(): RuntimeAgentSessionSnapshot;
254
256
  compact(options?: RuntimeAgentInvocationOptions): Promise<CompactionResult | null>;
255
257
  reset(): void;
@@ -1 +1 @@
1
- {"version":3,"file":"types.d.ts","names":[],"sources":["../../../src/composition/agent/types.ts"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;UA0BiB;WACN;WACA;WACA;WACA,OAAO;WACP;WACA;WACA;;WAEA;;WAEA,2BAA2B;WAC3B;WACA,iBAAiB;WACjB,uBAAuB;WACvB,aAAa;WACb,eAAe;WACf,uBAAuB;WACvB,kBAAkB;WAClB;WACA,SAAS;;;;;;;;WAQT,2BAA2B;WAC3B,aAAa;;WAEb;WACA;WACA;;WAEA;aACE,UAAU,SAAS;aACnB,OAAO,SAAS;;;UAIZ,+BAA+B;UAE/B,iCAAiC,KAAK;WAC5C;aAAmB;aAA2B;;;UAGxC,2BAA2B;WACjC;WACA;;UAGM;WACN;WACA,iBAAiB;WACjB,uBAAuB;WACvB,kBAAkB;WAClB,SAAS;WACT;WACA,YAAY;WACZ,YAAY;;;;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;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":";;;;;;;;;;;;;;;;;;;;;;;;;;;UA0BiB;WACN;WACA;WACA;WACA,OAAO;WACP;WACA;WACA;;WAEA;;WAEA,2BAA2B;WAC3B;WACA,iBAAiB;WACjB,uBAAuB;WACvB,aAAa;WACb,eAAe;WACf,uBAAuB;WACvB,kBAAkB;WAClB;WACA,SAAS;;;;;;;;WAQT,2BAA2B;WAC3B,aAAa;;WAEb;WACA;WACA;;WAEA;aACE,UAAU,SAAS;aACnB,OAAO,SAAS;;;UAIZ,+BAA+B;UAE/B,iCAAiC,KAAK;WAC5C;aAAmB;aAA2B;;;UAGxC,2BAA2B;WACjC;WACA;;UAGM;WACN;WACA,iBAAiB;WACjB,uBAAuB;WACvB,kBAAkB;WAClB,SAAS;WACT;WACA,YAAY;WACZ,YAAY;;;;;;;WAOZ,aAAa;;;;;WAKb,gCAAgC;WAChC,wBAAwB;;;;;;;WAOxB,2BAA2B;WAC3B,QAAQ;WACR,cAAc;;WAEd,gBAAgB;;WAEhB,eAAe;;WAEf,oBAAoB;WACpB,gBAAgB;WAChB,aAAa;;UAGP;;;;;;;;;;;;;;;;WAgBN;aAAmB;aAA2B;;;WAE9C;;WAEA;aACE;aACA,QAA2D,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;EACA,WAAW,UAAU,gCAAgC,QAAQ;EAC7D,YAAY;EACZ,QAAQ,UAAU,gCAAgC,QAAQ;EAC1D;EACA,SAAS,SAAS,cAAc;;UAGjB;WACN,OAAO;EAChB,SAAS,OAAO,YAAY,UAAU,gCAAgC,QAAQ;EAC9E,OAAO,OAAO,YAAY,UAAU,gCAAgC;EACpE,cAAc,UAAU,6BAA6B;EACrD,cAAc,UAAU,6BAA6B,UAAU,6BAA6B"}
@@ -1,2 +1,2 @@
1
- import{MODEL_ERROR_CODES as e}from"../../errors/model-error.js";import{normalizeModelFailure as t}from"../../errors/failure.js";import{backoffDelayMs as n,resolveRetryPolicy as r}from"../../contract/retry-policy.js";import{EMBEDDING_ERROR_CODES as i,EmbeddingError as a}from"../../embedding/errors.js";const o=Object.freeze({phase:`pending`});function s(t){return t===e.ABORTED||t===i.ABORTED}function c(e,t,n){return e instanceof a?e:new a(t.message,t.code,{cause:e,provider:n.provider,model:n.model,itemIndexes:n.items.map(e=>e.index)})}function l(e,t){return t?.aborted===!0?Promise.resolve(!1):new Promise(n=>{let r=()=>{clearTimeout(i),n(!1)},i=setTimeout(()=>{t?.removeEventListener(`abort`,r),n(!0)},e);t?.addEventListener(`abort`,r,{once:!0})})}function u(e,t,r,i){let a=t.providerRetryAfterMs;return a!==void 0&&Number.isFinite(a)&&a>0?a<=e.maxDelayMs?a:e.mode===`always`?n(e,r,i):`give-up`:n(e,r,i)}function d(e,t){let n=e?.startProviderAttempt;return e===void 0||n===void 0?e:{...e,startProviderAttempt:async(e,r)=>{let i=await n(e,r);return{attemptId:i.attemptId,attemptNumber:i.attemptNumber,traceparent:i.traceparent,end:e=>(t(e.dispatchState),i.end(e))}}}}function f(e,n={}){let f=n.policy??r(void 0,`embedding.retryPolicy`);if(f.mode===`always`&&n.signal===void 0)throw new a(`an always retry policy requires an AbortSignal`,i.CONFIGURATION_INVALID);let p=n.random??Math.random,m=n.sleep??l,h=new Map,g=e=>n.signal?.aborted===!0||e.signal?.aborted===!0,_=(e,t,n,r,i)=>{let a=Object.freeze({phase:`failed`,error:r,retryable:!1,dispatch:i});return h.set(e,a),Object.freeze({batchIndex:e,itemIndexes:Object.freeze(t.items.map(e=>e.index)),state:a,attempts:n.length,attemptRecords:Object.freeze([...n]),warnings:Object.freeze([])})};return{stateOf(e){return h.get(e)??o},states(){return new Map(h)},async dispatch(r,o,l){let v=l??n.context,y=h.get(r);if(y!==void 0&&y.phase===`succeeded`)throw new a(`embedding batch ${r} already succeeded and must not be dispatched again`,i.CONFIGURATION_INVALID,{provider:o.provider,model:o.model});let b=Object.freeze(o.items.map(e=>e.index)),x=[],S=0;for(;;){let l=x.length+1;if(g(o))return _(r,o,x,new a(`embedding call aborted before dispatch`,i.ABORTED,{provider:o.provider,model:o.model,itemIndexes:[...b]}),x.length===0?`not-sent`:`unknown`);h.set(r,Object.freeze({phase:`in-flight`,attempt:l}));let y,C=d(v,e=>{y=e}),w;try{w=await e.embedBatch(o,C)}catch(e){let d=t(e),C=y??`unknown`;x.push(Object.freeze({attempt:l,outcome:`failure`,dispatch:C,failureCode:d.code}));let w=c(e,d,o);if(g(o)||s(d.code))return _(r,o,x,w,C);let T=f.mode===`always`||f.retryableCodes.includes(d.code)&&S<f.maxRetries,E=T?u(f,d,S+1,p):`give-up`;if(!T||E===`give-up`){let e=Object.freeze({phase:`failed`,error:w,retryable:f.mode===`always`||f.retryableCodes.includes(d.code),dispatch:C});return h.set(r,e),Object.freeze({batchIndex:r,itemIndexes:b,state:e,attempts:x.length,attemptRecords:Object.freeze([...x]),warnings:Object.freeze([])})}S+=1,v?.recordProviderRetry?.({nextAttemptNumber:S+1,delayMs:E,failureCode:d.code});try{n.onRetry?.({provider:o.provider,model:o.model,batchIndex:r,attempt:S,maxRetries:f.mode===`normal`?f.maxRetries:void 0,failureCode:d.code,dispatch:C,delayMs:E})}catch{}if(!await m(E,n.signal??o.signal))return _(r,o,x,new a(`embedding call aborted while waiting to retry`,i.ABORTED,{provider:o.provider,model:o.model,itemIndexes:[...b],cause:e}),C);continue}let T=y??`sent`;x.push(Object.freeze({attempt:l,outcome:`success`,dispatch:T}));let E=Object.freeze({phase:`succeeded`,vectors:w.vectors});return h.set(r,E),Object.freeze({batchIndex:r,itemIndexes:b,state:E,attempts:x.length,attemptRecords:Object.freeze([...x]),...w.usage===void 0?{}:{usage:w.usage},...w.providerRequestId===void 0?{}:{providerRequestId:w.providerRequestId},warnings:Object.freeze([...w.warnings??[]])})}}}}export{f as createEmbeddingRetryLedger};
1
+ import{MODEL_ERROR_CODES as e}from"../../errors/model-error.js";import{normalizeModelFailure as t}from"../../errors/failure.js";import{backoffDelayMs as n,resolveRetryPolicy as r}from"../../contract/retry-policy.js";import{EMBEDDING_ERROR_CODES as i,EmbeddingError as a}from"../../embedding/errors.js";const o=Object.freeze({phase:`pending`});function s(t){return t===e.ABORTED||t===i.ABORTED}function c(e,t,n){return e instanceof a?e:new a(t.message,t.code,{cause:e,...t.status===void 0?{}:{status:t.status},...t.providerRetryAfterMs===void 0?{}:{providerRetryAfterMs:t.providerRetryAfterMs},...t.requestId===void 0?{}:{requestId:t.requestId},provider:n.provider,model:n.model,itemIndexes:n.items.map(e=>e.index)})}function l(e,t){return t?.aborted===!0?Promise.resolve(!1):new Promise(n=>{let r=()=>{clearTimeout(i),n(!1)},i=setTimeout(()=>{t?.removeEventListener(`abort`,r),n(!0)},e);t?.addEventListener(`abort`,r,{once:!0})})}function u(e,t,r,i){let a=t.providerRetryAfterMs;return a!==void 0&&Number.isFinite(a)&&a>0?a<=e.maxDelayMs?a:e.mode===`always`?n(e,r,i):`give-up`:n(e,r,i)}function d(e,t){let n=e?.startProviderAttempt;return e===void 0||n===void 0?e:{...e,startProviderAttempt:async(e,r)=>{let i=await n(e,r);return{attemptId:i.attemptId,attemptNumber:i.attemptNumber,traceparent:i.traceparent,end:e=>(t(e.dispatchState),i.end(e))}}}}function f(e,n={}){let f=n.policy??r(void 0,`embedding.retryPolicy`);if(f.mode===`always`&&n.signal===void 0)throw new a(`an always retry policy requires an AbortSignal`,i.CONFIGURATION_INVALID);let p=n.random??Math.random,m=n.sleep??l,h=new Map,g=e=>n.signal?.aborted===!0||e.signal?.aborted===!0,_=(e,t,n,r,i)=>{let a=Object.freeze({phase:`failed`,error:r,retryable:!1,dispatch:i});return h.set(e,a),Object.freeze({batchIndex:e,itemIndexes:Object.freeze(t.items.map(e=>e.index)),state:a,attempts:n.length,attemptRecords:Object.freeze([...n]),warnings:Object.freeze([])})};return{stateOf(e){return h.get(e)??o},states(){return new Map(h)},async dispatch(r,o,l){let v=l??n.context,y=h.get(r);if(y!==void 0&&y.phase===`succeeded`)throw new a(`embedding batch ${r} already succeeded and must not be dispatched again`,i.CONFIGURATION_INVALID,{provider:o.provider,model:o.model});let b=Object.freeze(o.items.map(e=>e.index)),x=[],S=0;for(;;){let l=x.length+1;if(g(o))return _(r,o,x,new a(`embedding call aborted before dispatch`,i.ABORTED,{provider:o.provider,model:o.model,itemIndexes:[...b]}),x.length===0?`not-sent`:`unknown`);h.set(r,Object.freeze({phase:`in-flight`,attempt:l}));let y,C=d(v,e=>{y=e}),w;try{w=await e.embedBatch(o,C)}catch(e){let d=t(e),C=y??`unknown`;x.push(Object.freeze({attempt:l,outcome:`failure`,dispatch:C,failureCode:d.code}));let w=c(e,d,o);if(g(o)||s(d.code))return _(r,o,x,w,C);let T=f.mode===`always`||f.retryableCodes.includes(d.code)&&S<f.maxRetries,E=T?u(f,d,S+1,p):`give-up`;if(!T||E===`give-up`){let e=Object.freeze({phase:`failed`,error:w,retryable:f.mode===`always`||f.retryableCodes.includes(d.code),dispatch:C});return h.set(r,e),Object.freeze({batchIndex:r,itemIndexes:b,state:e,attempts:x.length,attemptRecords:Object.freeze([...x]),warnings:Object.freeze([])})}S+=1,v?.recordProviderRetry?.({nextAttemptNumber:S+1,delayMs:E,failureCode:d.code});try{n.onRetry?.({provider:o.provider,model:o.model,batchIndex:r,attempt:S,maxRetries:f.mode===`normal`?f.maxRetries:void 0,failureCode:d.code,dispatch:C,delayMs:E})}catch{}if(!await m(E,n.signal??o.signal))return _(r,o,x,new a(`embedding call aborted while waiting to retry`,i.ABORTED,{provider:o.provider,model:o.model,itemIndexes:[...b],cause:e}),C);continue}let T=y??`sent`;x.push(Object.freeze({attempt:l,outcome:`success`,dispatch:T}));let E=Object.freeze({phase:`succeeded`,vectors:w.vectors});return h.set(r,E),Object.freeze({batchIndex:r,itemIndexes:b,state:E,attempts:x.length,attemptRecords:Object.freeze([...x]),...w.usage===void 0?{}:{usage:w.usage},...w.providerRequestId===void 0?{}:{providerRequestId:w.providerRequestId},warnings:Object.freeze([...w.warnings??[]])})}}}}export{f as createEmbeddingRetryLedger};
2
2
  //# sourceMappingURL=retry.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"retry.js","names":[],"sources":["../../../src/composition/embedding/retry.ts"],"sourcesContent":["/**\n * The ONE retry layer for embedding.\n *\n * `Embedding_Runtime` owns retry; an `Embedding_Adapter` performs exactly one\n * `Provider_Attempt` per `embedBatch()` call and never retries inside\n * (Requirement 4.3). Keeping retry here is what makes a `Provider_Attempt`\n * countable: the number of attempts a caller is billed for equals the number of\n * times this file called the adapter.\n *\n * Four facts drive every branch below:\n *\n * 1. **Only unsuccessful batches are retried.** A batch that reached\n * `succeeded` is removed from every later retry pass of the same\n * `Logical_Call` — its vectors already exist, and re-sending it would be a\n * second charge for a result we hold (Requirement 4.7). The ledger enforces\n * this structurally: a terminal state is never re-entered.\n * 2. **Dispatch state comes from the transport, it is not re-derived.**\n * `Http_Transport` sets `dispatchState = 'unknown'` immediately before\n * `fetch` and only raises it to `'sent'` once a response exists, so this file\n * reads the value the transport reported through `attempt.end` instead of\n * guessing from the shape of the error. When nothing reported a state, the\n * record stays `'unknown'`: only the transport is in a position to claim\n * `'not-sent'`, and a timeout in particular is never that (Requirement 4.8).\n * 3. **No fallback model.** A failure of the primary model propagates to the\n * caller. Fallback is only ever configured within a group sharing one\n * `compatibilityIdentity`, and that condition is checked when the handle is\n * built, not after a failure has happened (Requirements 6.6, 6.7).\n * 4. **Order is not this file's business.** Vectors are handed back per batch and\n * the caller writes them at `item.index`, so retries and out-of-order\n * settlement cannot disturb output order (Requirement 4.6).\n *\n * Concurrency lives in `limiter.ts`; this file drives one batch at a time and is\n * composed underneath it.\n *\n * @module ai-agent-sdk/core/composition/embedding/retry\n */\n\nimport {\n backoffDelayMs,\n resolveRetryPolicy,\n type ResolvedRetryPolicy,\n} from '../../contract/retry-policy.ts'\nimport { EMBEDDING_ERROR_CODES, EmbeddingError } from '../../embedding/errors.ts'\nimport type { EmbeddingBatchRequest } from '../../embedding/request.ts'\nimport type { EmbeddingBatchResult, EmbeddingVector, EmbeddingWarning } from '../../embedding/result.ts'\nimport { normalizeModelFailure, type ModelFailure } from '../../errors/failure.ts'\nimport { MODEL_ERROR_CODES } from '../../errors/model-error.ts'\nimport type {\n EndProviderAttemptInput,\n ModelInvocationContext,\n ProviderAttemptHandle,\n} from '../../observation/report.ts'\nimport type { AttemptUsageReport, DispatchState } from '../../observation/usage.ts'\n\n/**\n * Lifecycle of one `Physical_Batch` inside a single `Logical_Call`.\n *\n * `succeeded` and `failed` are terminal. That is the whole mechanism behind\n * Requirement 4.7: retry only ever considers a batch that is not yet terminal.\n */\nexport type BatchState =\n | { readonly phase: 'pending' }\n | { readonly phase: 'in-flight'; readonly attempt: number }\n | { readonly phase: 'succeeded'; readonly vectors: readonly EmbeddingVector[] }\n | {\n readonly phase: 'failed'\n readonly error: EmbeddingError\n readonly retryable: boolean\n /** As reported by the transport; `'unknown'` whenever nothing reported. */\n readonly dispatch: DispatchState\n }\n\n/** One retry that is about to be waited out, for logging and metrics. */\nexport interface EmbeddingRetryAttempt {\n readonly provider: string\n readonly model: string\n /** Plan coordinate of the batch being retried. */\n readonly batchIndex: number\n /** 1-based retry number. */\n readonly attempt: number\n /** Retry ceiling, or `undefined` under an `always` policy. */\n readonly maxRetries: number | undefined\n /** Stable code of the failure being recovered from. */\n readonly failureCode: string\n /** Dispatch state the transport reported for the failed attempt. */\n readonly dispatch: DispatchState\n readonly delayMs: number\n}\n\n/** What one `Provider_Attempt` on a batch left behind. */\nexport interface EmbeddingAttemptRecord {\n /** 1-based attempt number within this batch. */\n readonly attempt: number\n readonly outcome: 'success' | 'failure'\n /** From the transport, never re-derived (Requirement 4.8). */\n readonly dispatch: DispatchState\n /** Stable failure code, absent on success. */\n readonly failureCode?: string\n}\n\n/** Everything a `Logical_Call` needs to know about one settled batch. */\nexport interface EmbeddingBatchOutcome {\n readonly batchIndex: number\n /** Input indexes this batch carried, in `Logical_Call` numbering. */\n readonly itemIndexes: readonly number[]\n /** Terminal state: `succeeded` or `failed`. */\n readonly state: BatchState\n /** `Provider_Attempt`s spent, retries included (Requirement 16.6). */\n readonly attempts: number\n /** One record per adapter call, in order. */\n readonly attemptRecords: readonly EmbeddingAttemptRecord[]\n /**\n * Raw provider usage evidence from the attempt that settled the batch.\n *\n * `unknown` on purpose: proving it is a usage shape belongs to\n * `validateEmbeddingUsage`, and absence must never become a zero.\n */\n readonly usage?: unknown\n readonly providerRequestId?: string\n readonly warnings: readonly EmbeddingWarning[]\n}\n\n/** Dispatch surface of a `Prepared_Embedding_Call`; the ledger needs nothing else. */\nexport interface EmbeddingBatchDispatcher {\n embedBatch(\n batch: EmbeddingBatchRequest,\n context?: ModelInvocationContext,\n ): Promise<EmbeddingBatchResult>\n}\n\n/** Knobs for {@link createEmbeddingRetryLedger}. */\nexport interface EmbeddingRetryOptions {\n /** Route policy; omission takes the shared SDK defaults. */\n readonly policy?: ResolvedRetryPolicy\n /** Sample in `[0, 1)` for jitter; injectable so tests can be deterministic. */\n readonly random?: () => number\n /** Caller signal or runtime `close()`; an abort is never a transient fault. */\n readonly signal?: AbortSignal\n /** Invocation context; wrapped so transport-reported dispatch states are observed. */\n readonly context?: ModelInvocationContext\n /** Observe each scheduled retry. Failures in the observer are swallowed. */\n readonly onRetry?: (attempt: EmbeddingRetryAttempt) => void\n /** Sleep hook; resolves `false` when the signal fired first. Injectable for tests. */\n readonly sleep?: (delayMs: number, signal?: AbortSignal) => Promise<boolean>\n}\n\n/**\n * Per-`Logical_Call` retry driver and state ledger.\n *\n * One ledger per `Logical_Call`, shared across every batch of that call, which\n * is what lets it guarantee that a `succeeded` batch is never dispatched again.\n */\nexport interface EmbeddingRetryLedger {\n /**\n * Dispatch one `Physical_Batch` and retry it until it settles.\n *\n * Resolves with a terminal outcome instead of throwing, because only the\n * caller knows whether a failed batch should abandon the whole call or leave\n * the batches that already succeeded intact. There is no fallback model: a\n * failure here is the failure the caller sees.\n *\n * @param context - overrides the ledger's context for this batch only. One\n * ledger spans the whole `Logical_Call` while observation is per-batch, so this\n * is how an attempt gets parented under the batch that provoked it. The\n * override is wrapped for dispatch-state observation exactly like the\n * ledger-wide context, so nothing about Requirement 4.8 changes.\n */\n dispatch(\n batchIndex: number,\n request: EmbeddingBatchRequest,\n context?: ModelInvocationContext,\n ): Promise<EmbeddingBatchOutcome>\n /** Current state of one batch; `pending` for a batch never dispatched. */\n stateOf(batchIndex: number): BatchState\n /** Immutable view of every batch state seen so far. */\n states(): ReadonlyMap<number, BatchState>\n}\n\nconst PENDING: BatchState = Object.freeze({ phase: 'pending' as const })\n\n/** Codes that mean \"the caller stopped this\", never \"the provider wobbled\". */\nfunction isAbortCode(code: string): boolean {\n return code === MODEL_ERROR_CODES.ABORTED || code === EMBEDDING_ERROR_CODES.ABORTED\n}\n\n/**\n * Turn any thrown value into an {@link EmbeddingError} without losing its code.\n *\n * An `EmbeddingError` from the adapter passes through untouched: it already\n * carries `itemIndexes` and `limit`, and re-wrapping would drop exactly the\n * facts a caller needs to re-chunk the offending inputs. Anything else keeps its\n * normalized stable code — a rate limit stays `MODEL_RATE_LIMIT` so the retry\n * allow-list still recognises it.\n */\nfunction asEmbeddingError(\n value: unknown,\n failure: ModelFailure,\n request: EmbeddingBatchRequest,\n): EmbeddingError {\n if (value instanceof EmbeddingError) return value\n return new EmbeddingError(failure.message, failure.code, {\n cause: value,\n provider: request.provider,\n model: request.model,\n itemIndexes: request.items.map(item => item.index),\n })\n}\n\n/** Sleep, resolving early and reporting `false` if the signal aborts first. */\nfunction cancellableDelay(delayMs: number, signal?: AbortSignal): Promise<boolean> {\n if (signal?.aborted === true) return Promise.resolve(false)\n return new Promise((resolve) => {\n const onAbort = (): void => {\n clearTimeout(timer)\n resolve(false)\n }\n const timer = setTimeout(() => {\n signal?.removeEventListener('abort', onAbort)\n resolve(true)\n }, delayMs)\n signal?.addEventListener('abort', onAbort, { once: true })\n })\n}\n\n/** Honour a sane provider-requested `retry-after`, else local bounded backoff. */\nfunction delayFor(\n policy: ResolvedRetryPolicy,\n failure: ModelFailure,\n attempt: number,\n random: () => number,\n): number | 'give-up' {\n const requested = failure.providerRetryAfterMs\n if (requested !== undefined && Number.isFinite(requested) && requested > 0) {\n if (requested <= policy.maxDelayMs) return requested\n // The provider asked for longer than this policy will wait. Under a bounded\n // policy that is a refusal: sleeping less than asked just earns another rate\n // limit. An `always` policy has nowhere to give up to.\n return policy.mode === 'always' ? backoffDelayMs(policy, attempt, random) : 'give-up'\n }\n return backoffDelayMs(policy, attempt, random)\n}\n\n/**\n * Wrap an invocation context so the dispatch state the TRANSPORT reports is\n * captured, rather than inferred from the error afterwards.\n *\n * The wrapper is transparent: it forwards `startProviderAttempt` untouched and\n * only tees the `dispatchState` passed to `attempt.end`. When a context has no\n * attempt accounting there is nothing to observe, and the record stays\n * `'unknown'` — that is the honest answer, and it is the answer Requirement 4.8\n * demands for a timeout.\n */\nfunction observeDispatchState(\n context: ModelInvocationContext | undefined,\n sink: (state: DispatchState) => void,\n): ModelInvocationContext | undefined {\n const start = context?.startProviderAttempt\n if (context === undefined || start === undefined) return context\n return {\n ...context,\n startProviderAttempt: async (input, signal): Promise<ProviderAttemptHandle> => {\n const handle = await start(input, signal)\n return {\n attemptId: handle.attemptId,\n attemptNumber: handle.attemptNumber,\n traceparent: handle.traceparent,\n end: (end: EndProviderAttemptInput): AttemptUsageReport => {\n sink(end.dispatchState)\n return handle.end(end)\n },\n }\n },\n }\n}\n\n/**\n * Create the retry ledger for one `Logical_Call`.\n *\n * An `always` policy without a signal is rejected here rather than at the first\n * failure: unbounded retry is bounded only by cancellation, so a call that\n * cannot be cancelled would never terminate.\n */\nexport function createEmbeddingRetryLedger(\n dispatcher: EmbeddingBatchDispatcher,\n options: EmbeddingRetryOptions = {},\n): EmbeddingRetryLedger {\n const policy = options.policy ?? resolveRetryPolicy(undefined, 'embedding.retryPolicy')\n if (policy.mode === 'always' && options.signal === undefined) {\n throw new EmbeddingError(\n 'an always retry policy requires an AbortSignal',\n EMBEDDING_ERROR_CODES.CONFIGURATION_INVALID,\n )\n }\n const random = options.random ?? Math.random\n const sleep = options.sleep ?? cancellableDelay\n const states = new Map<number, BatchState>()\n\n /**\n * Whether either signal has fired.\n *\n * A function rather than an inline check so the answer is re-read after every\n * `await`: a signal that aborts while a request is in flight is precisely the\n * case that matters.\n */\n const cancelled = (request: EmbeddingBatchRequest): boolean =>\n options.signal?.aborted === true || request.signal?.aborted === true\n\n const abortedOutcome = (\n batchIndex: number,\n request: EmbeddingBatchRequest,\n records: readonly EmbeddingAttemptRecord[],\n error: EmbeddingError,\n dispatch: DispatchState,\n ): EmbeddingBatchOutcome => {\n const state: BatchState = Object.freeze({\n phase: 'failed' as const,\n error,\n // An abort is the caller's decision, so it is terminal by definition.\n retryable: false,\n dispatch,\n })\n states.set(batchIndex, state)\n return Object.freeze({\n batchIndex,\n itemIndexes: Object.freeze(request.items.map(item => item.index)),\n state,\n attempts: records.length,\n attemptRecords: Object.freeze([...records]),\n warnings: Object.freeze([]),\n })\n }\n\n return {\n stateOf(batchIndex: number): BatchState {\n return states.get(batchIndex) ?? PENDING\n },\n\n states(): ReadonlyMap<number, BatchState> {\n return new Map(states)\n },\n\n async dispatch(\n batchIndex: number,\n request: EmbeddingBatchRequest,\n batchContext?: ModelInvocationContext,\n ): Promise<EmbeddingBatchOutcome> {\n const invocationContext = batchContext ?? options.context\n const existing = states.get(batchIndex)\n if (existing !== undefined && existing.phase === 'succeeded') {\n // Requirement 4.7 as an invariant rather than a convention: a batch whose\n // vectors are already held is never handed to the provider again.\n throw new EmbeddingError(\n `embedding batch ${batchIndex} already succeeded and must not be dispatched again`,\n EMBEDDING_ERROR_CODES.CONFIGURATION_INVALID,\n { provider: request.provider, model: request.model },\n )\n }\n\n const itemIndexes = Object.freeze(request.items.map(item => item.index))\n const records: EmbeddingAttemptRecord[] = []\n let retries = 0\n\n for (;;) {\n const attemptNumber = records.length + 1\n // Report the abort before spending an attempt on a call already cancelled.\n if (cancelled(request)) {\n return abortedOutcome(\n batchIndex,\n request,\n records,\n new EmbeddingError(\n 'embedding call aborted before dispatch',\n EMBEDDING_ERROR_CODES.ABORTED,\n { provider: request.provider, model: request.model, itemIndexes: [...itemIndexes] },\n ),\n // No adapter call was ever made on this pass, which the runtime knows\n // first-hand. Once an attempt HAS been made, the runtime stops\n // claiming anything and leaves the state `unknown`.\n records.length === 0 ? 'not-sent' : 'unknown',\n )\n }\n\n states.set(batchIndex, Object.freeze({ phase: 'in-flight' as const, attempt: attemptNumber }))\n\n // Reported by the transport through `attempt.end`; unreported stays unknown.\n let reportedDispatch: DispatchState | undefined\n const context = observeDispatchState(invocationContext, (state) => {\n reportedDispatch = state\n })\n\n let result: EmbeddingBatchResult\n try {\n result = await dispatcher.embedBatch(request, context)\n } catch (error: unknown) {\n const failure = normalizeModelFailure(error)\n const dispatch = reportedDispatch ?? 'unknown'\n records.push(Object.freeze({\n attempt: attemptNumber,\n outcome: 'failure' as const,\n dispatch,\n failureCode: failure.code,\n }))\n\n const embeddingError = asEmbeddingError(error, failure, request)\n if (cancelled(request) || isAbortCode(failure.code)) {\n return abortedOutcome(batchIndex, request, records, embeddingError, dispatch)\n }\n\n const eligible = policy.mode === 'always'\n || (policy.retryableCodes.includes(failure.code) && retries < policy.maxRetries)\n const delayMs = eligible ? delayFor(policy, failure, retries + 1, random) : 'give-up'\n if (!eligible || delayMs === 'give-up') {\n const state: BatchState = Object.freeze({\n phase: 'failed' as const,\n error: embeddingError,\n // `retryable` describes the failure, not the budget: a rate limit\n // that ran out of attempts is still a retryable KIND of failure,\n // and a caller deciding whether to re-run later needs that apart\n // from \"this call gave up\".\n retryable: policy.mode === 'always' || policy.retryableCodes.includes(failure.code),\n dispatch,\n })\n states.set(batchIndex, state)\n return Object.freeze({\n batchIndex,\n itemIndexes,\n state,\n attempts: records.length,\n attemptRecords: Object.freeze([...records]),\n warnings: Object.freeze([]),\n })\n }\n\n retries += 1\n invocationContext?.recordProviderRetry?.({\n nextAttemptNumber: retries + 1,\n delayMs,\n failureCode: failure.code,\n })\n try {\n options.onRetry?.({\n provider: request.provider,\n model: request.model,\n batchIndex,\n attempt: retries,\n maxRetries: policy.mode === 'normal' ? policy.maxRetries : undefined,\n failureCode: failure.code,\n dispatch,\n delayMs,\n })\n } catch {\n // Metrics and logging observers do not own request availability.\n }\n\n if (!await sleep(delayMs, options.signal ?? request.signal)) {\n return abortedOutcome(\n batchIndex,\n request,\n records,\n new EmbeddingError(\n 'embedding call aborted while waiting to retry',\n EMBEDDING_ERROR_CODES.ABORTED,\n { provider: request.provider, model: request.model, itemIndexes: [...itemIndexes], cause: error },\n ),\n dispatch,\n )\n }\n continue\n }\n\n // A response exists, so the request reached the provider. The transport's\n // own report still wins when it made one.\n const dispatch = reportedDispatch ?? 'sent'\n records.push(Object.freeze({\n attempt: attemptNumber,\n outcome: 'success' as const,\n dispatch,\n }))\n const state: BatchState = Object.freeze({\n phase: 'succeeded' as const,\n vectors: result.vectors,\n })\n states.set(batchIndex, state)\n return Object.freeze({\n batchIndex,\n itemIndexes,\n state,\n attempts: records.length,\n attemptRecords: Object.freeze([...records]),\n // Absent usage is left absent: the aggregator downgrades coverage\n // rather than counting an unreported batch as zero tokens.\n ...(result.usage === undefined ? {} : { usage: result.usage }),\n ...(result.providerRequestId === undefined\n ? {}\n : { providerRequestId: result.providerRequestId }),\n warnings: Object.freeze([...(result.warnings ?? [])]),\n })\n }\n },\n }\n}\n"],"mappings":"8SAkLA,MAAM,EAAsB,OAAO,OAAO,CAAE,MAAO,SAAmB,CAAC,EAGvE,SAAS,EAAY,EAAuB,CAC1C,OAAO,IAAS,EAAkB,SAAW,IAAS,EAAsB,OAC9E,CAWA,SAAS,EACP,EACA,EACA,EACgB,CAEhB,OADI,aAAiB,EAAuB,EACrC,IAAI,EAAe,EAAQ,QAAS,EAAQ,KAAM,CACvD,MAAO,EACP,SAAU,EAAQ,SAClB,MAAO,EAAQ,MACf,YAAa,EAAQ,MAAM,IAAI,GAAQ,EAAK,KAAK,CACnD,CAAC,CACH,CAGA,SAAS,EAAiB,EAAiB,EAAwC,CAEjF,OADI,GAAQ,UAAY,GAAa,QAAQ,QAAQ,EAAK,EACnD,IAAI,QAAS,GAAY,CAC9B,IAAM,MAAsB,CAC1B,aAAa,CAAK,EAClB,EAAQ,EAAK,CACf,EACM,EAAQ,e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M,CAClG,EACA,CACF,EAEF,QACF,CAIA,IAAM,EAAW,GAAoB,OACrC,EAAQ,KAAK,OAAO,OAAO,CACzB,QAAS,EACT,QAAS,UACT,UACF,CAAC,CAAC,EACF,IAAM,EAAoB,OAAO,OAAO,CACtC,MAAO,YACP,QAAS,EAAO,OAClB,CAAC,EAED,OADA,EAAO,IAAI,EAAY,CAAK,EACrB,OAAO,OAAO,CACnB,aACA,cACA,QACA,SAAU,EAAQ,OAClB,eAAgB,OAAO,OAAO,CAAC,GAAG,CAAO,CAAC,EAG1C,GAAI,EAAO,QAAU,IAAA,GAAY,CAAC,EAAI,CAAE,MAAO,EAAO,KAAM,EAC5D,GAAI,EAAO,oBAAsB,IAAA,GAC7B,CAAC,EACD,CAAE,kBAAmB,EAAO,iBAAkB,EAClD,SAAU,OAAO,OAAO,CAAC,GAAI,EAAO,UAAY,CAAC,CAAE,CAAC,CACtD,CAAC,CACH,CACF,CACF,CACF"}
1
+ {"version":3,"file":"retry.js","names":[],"sources":["../../../src/composition/embedding/retry.ts"],"sourcesContent":["/**\n * The ONE retry layer for embedding.\n *\n * `Embedding_Runtime` owns retry; an `Embedding_Adapter` performs exactly one\n * `Provider_Attempt` per `embedBatch()` call and never retries inside\n * (Requirement 4.3). Keeping retry here is what makes a `Provider_Attempt`\n * countable: the number of attempts a caller is billed for equals the number of\n * times this file called the adapter.\n *\n * Four facts drive every branch below:\n *\n * 1. **Only unsuccessful batches are retried.** A batch that reached\n * `succeeded` is removed from every later retry pass of the same\n * `Logical_Call` — its vectors already exist, and re-sending it would be a\n * second charge for a result we hold (Requirement 4.7). The ledger enforces\n * this structurally: a terminal state is never re-entered.\n * 2. **Dispatch state comes from the transport, it is not re-derived.**\n * `Http_Transport` sets `dispatchState = 'unknown'` immediately before\n * `fetch` and only raises it to `'sent'` once a response exists, so this file\n * reads the value the transport reported through `attempt.end` instead of\n * guessing from the shape of the error. When nothing reported a state, the\n * record stays `'unknown'`: only the transport is in a position to claim\n * `'not-sent'`, and a timeout in particular is never that (Requirement 4.8).\n * 3. **No fallback model.** A failure of the primary model propagates to the\n * caller. Fallback is only ever configured within a group sharing one\n * `compatibilityIdentity`, and that condition is checked when the handle is\n * built, not after a failure has happened (Requirements 6.6, 6.7).\n * 4. **Order is not this file's business.** Vectors are handed back per batch and\n * the caller writes them at `item.index`, so retries and out-of-order\n * settlement cannot disturb output order (Requirement 4.6).\n *\n * Concurrency lives in `limiter.ts`; this file drives one batch at a time and is\n * composed underneath it.\n *\n * @module ai-agent-sdk/core/composition/embedding/retry\n */\n\nimport {\n backoffDelayMs,\n resolveRetryPolicy,\n type ResolvedRetryPolicy,\n} from '../../contract/retry-policy.ts'\nimport { EMBEDDING_ERROR_CODES, EmbeddingError } from '../../embedding/errors.ts'\nimport type { EmbeddingBatchRequest } from '../../embedding/request.ts'\nimport type { EmbeddingBatchResult, EmbeddingVector, EmbeddingWarning } from '../../embedding/result.ts'\nimport { normalizeModelFailure, type ModelFailure } from '../../errors/failure.ts'\nimport { MODEL_ERROR_CODES } from '../../errors/model-error.ts'\nimport type {\n EndProviderAttemptInput,\n ModelInvocationContext,\n ProviderAttemptHandle,\n} from '../../observation/report.ts'\nimport type { AttemptUsageReport, DispatchState } from '../../observation/usage.ts'\n\n/**\n * Lifecycle of one `Physical_Batch` inside a single `Logical_Call`.\n *\n * `succeeded` and `failed` are terminal. That is the whole mechanism behind\n * Requirement 4.7: retry only ever considers a batch that is not yet terminal.\n */\nexport type BatchState =\n | { readonly phase: 'pending' }\n | { readonly phase: 'in-flight'; readonly attempt: number }\n | { readonly phase: 'succeeded'; readonly vectors: readonly EmbeddingVector[] }\n | {\n readonly phase: 'failed'\n readonly error: EmbeddingError\n readonly retryable: boolean\n /** As reported by the transport; `'unknown'` whenever nothing reported. */\n readonly dispatch: DispatchState\n }\n\n/** One retry that is about to be waited out, for logging and metrics. */\nexport interface EmbeddingRetryAttempt {\n readonly provider: string\n readonly model: string\n /** Plan coordinate of the batch being retried. */\n readonly batchIndex: number\n /** 1-based retry number. */\n readonly attempt: number\n /** Retry ceiling, or `undefined` under an `always` policy. */\n readonly maxRetries: number | undefined\n /** Stable code of the failure being recovered from. */\n readonly failureCode: string\n /** Dispatch state the transport reported for the failed attempt. */\n readonly dispatch: DispatchState\n readonly delayMs: number\n}\n\n/** What one `Provider_Attempt` on a batch left behind. */\nexport interface EmbeddingAttemptRecord {\n /** 1-based attempt number within this batch. */\n readonly attempt: number\n readonly outcome: 'success' | 'failure'\n /** From the transport, never re-derived (Requirement 4.8). */\n readonly dispatch: DispatchState\n /** Stable failure code, absent on success. */\n readonly failureCode?: string\n}\n\n/** Everything a `Logical_Call` needs to know about one settled batch. */\nexport interface EmbeddingBatchOutcome {\n readonly batchIndex: number\n /** Input indexes this batch carried, in `Logical_Call` numbering. */\n readonly itemIndexes: readonly number[]\n /** Terminal state: `succeeded` or `failed`. */\n readonly state: BatchState\n /** `Provider_Attempt`s spent, retries included (Requirement 16.6). */\n readonly attempts: number\n /** One record per adapter call, in order. */\n readonly attemptRecords: readonly EmbeddingAttemptRecord[]\n /**\n * Raw provider usage evidence from the attempt that settled the batch.\n *\n * `unknown` on purpose: proving it is a usage shape belongs to\n * `validateEmbeddingUsage`, and absence must never become a zero.\n */\n readonly usage?: unknown\n readonly providerRequestId?: string\n readonly warnings: readonly EmbeddingWarning[]\n}\n\n/** Dispatch surface of a `Prepared_Embedding_Call`; the ledger needs nothing else. */\nexport interface EmbeddingBatchDispatcher {\n embedBatch(\n batch: EmbeddingBatchRequest,\n context?: ModelInvocationContext,\n ): Promise<EmbeddingBatchResult>\n}\n\n/** Knobs for {@link createEmbeddingRetryLedger}. */\nexport interface EmbeddingRetryOptions {\n /** Route policy; omission takes the shared SDK defaults. */\n readonly policy?: ResolvedRetryPolicy\n /** Sample in `[0, 1)` for jitter; injectable so tests can be deterministic. */\n readonly random?: () => number\n /** Caller signal or runtime `close()`; an abort is never a transient fault. */\n readonly signal?: AbortSignal\n /** Invocation context; wrapped so transport-reported dispatch states are observed. */\n readonly context?: ModelInvocationContext\n /** Observe each scheduled retry. Failures in the observer are swallowed. */\n readonly onRetry?: (attempt: EmbeddingRetryAttempt) => void\n /** Sleep hook; resolves `false` when the signal fired first. Injectable for tests. */\n readonly sleep?: (delayMs: number, signal?: AbortSignal) => Promise<boolean>\n}\n\n/**\n * Per-`Logical_Call` retry driver and state ledger.\n *\n * One ledger per `Logical_Call`, shared across every batch of that call, which\n * is what lets it guarantee that a `succeeded` batch is never dispatched again.\n */\nexport interface EmbeddingRetryLedger {\n /**\n * Dispatch one `Physical_Batch` and retry it until it settles.\n *\n * Resolves with a terminal outcome instead of throwing, because only the\n * caller knows whether a failed batch should abandon the whole call or leave\n * the batches that already succeeded intact. There is no fallback model: a\n * failure here is the failure the caller sees.\n *\n * @param context - overrides the ledger's context for this batch only. One\n * ledger spans the whole `Logical_Call` while observation is per-batch, so this\n * is how an attempt gets parented under the batch that provoked it. The\n * override is wrapped for dispatch-state observation exactly like the\n * ledger-wide context, so nothing about Requirement 4.8 changes.\n */\n dispatch(\n batchIndex: number,\n request: EmbeddingBatchRequest,\n context?: ModelInvocationContext,\n ): Promise<EmbeddingBatchOutcome>\n /** Current state of one batch; `pending` for a batch never dispatched. */\n stateOf(batchIndex: number): BatchState\n /** Immutable view of every batch state seen so far. */\n states(): ReadonlyMap<number, BatchState>\n}\n\nconst PENDING: BatchState = Object.freeze({ phase: 'pending' as const })\n\n/** Codes that mean \"the caller stopped this\", never \"the provider wobbled\". */\nfunction isAbortCode(code: string): boolean {\n return code === MODEL_ERROR_CODES.ABORTED || code === EMBEDDING_ERROR_CODES.ABORTED\n}\n\n/**\n * Turn any thrown value into an {@link EmbeddingError} without losing its code.\n *\n * An `EmbeddingError` from the adapter passes through untouched: it already\n * carries `itemIndexes` and `limit`, and re-wrapping would drop exactly the\n * facts a caller needs to re-chunk the offending inputs. Anything else keeps its\n * normalized stable code — a rate limit stays `MODEL_RATE_LIMIT` so the retry\n * allow-list still recognises it.\n */\nfunction asEmbeddingError(\n value: unknown,\n failure: ModelFailure,\n request: EmbeddingBatchRequest,\n): EmbeddingError {\n if (value instanceof EmbeddingError) return value\n return new EmbeddingError(failure.message, failure.code, {\n cause: value,\n ...failure.status === undefined ? {} : { status: failure.status },\n ...failure.providerRetryAfterMs === undefined ? {} : { providerRetryAfterMs: failure.providerRetryAfterMs },\n ...failure.requestId === undefined ? {} : { requestId: failure.requestId },\n provider: request.provider,\n model: request.model,\n itemIndexes: request.items.map(item => item.index),\n })\n}\n\n/** Sleep, resolving early and reporting `false` if the signal aborts first. */\nfunction cancellableDelay(delayMs: number, signal?: AbortSignal): Promise<boolean> {\n if (signal?.aborted === true) return Promise.resolve(false)\n return new Promise((resolve) => {\n const onAbort = (): void => {\n clearTimeout(timer)\n resolve(false)\n }\n const timer = setTimeout(() => {\n signal?.removeEventListener('abort', onAbort)\n resolve(true)\n }, delayMs)\n signal?.addEventListener('abort', onAbort, { once: true })\n })\n}\n\n/** Honour a sane provider-requested `retry-after`, else local bounded backoff. */\nfunction delayFor(\n policy: ResolvedRetryPolicy,\n failure: ModelFailure,\n attempt: number,\n random: () => number,\n): number | 'give-up' {\n const requested = failure.providerRetryAfterMs\n if (requested !== undefined && Number.isFinite(requested) && requested > 0) {\n if (requested <= policy.maxDelayMs) return requested\n // The provider asked for longer than this policy will wait. Under a bounded\n // policy that is a refusal: sleeping less than asked just earns another rate\n // limit. An `always` policy has nowhere to give up to.\n return policy.mode === 'always' ? backoffDelayMs(policy, attempt, random) : 'give-up'\n }\n return backoffDelayMs(policy, attempt, random)\n}\n\n/**\n * Wrap an invocation context so the dispatch state the TRANSPORT reports is\n * captured, rather than inferred from the error afterwards.\n *\n * The wrapper is transparent: it forwards `startProviderAttempt` untouched and\n * only tees the `dispatchState` passed to `attempt.end`. When a context has no\n * attempt accounting there is nothing to observe, and the record stays\n * `'unknown'` — that is the honest answer, and it is the answer Requirement 4.8\n * demands for a timeout.\n */\nfunction observeDispatchState(\n context: ModelInvocationContext | undefined,\n sink: (state: DispatchState) => void,\n): ModelInvocationContext | undefined {\n const start = context?.startProviderAttempt\n if (context === undefined || start === undefined) return context\n return {\n ...context,\n startProviderAttempt: async (input, signal): Promise<ProviderAttemptHandle> => {\n const handle = await start(input, signal)\n return {\n attemptId: handle.attemptId,\n attemptNumber: handle.attemptNumber,\n traceparent: handle.traceparent,\n end: (end: EndProviderAttemptInput): AttemptUsageReport => {\n sink(end.dispatchState)\n return handle.end(end)\n },\n }\n },\n }\n}\n\n/**\n * Create the retry ledger for one `Logical_Call`.\n *\n * An `always` policy without a signal is rejected here rather than at the first\n * failure: unbounded retry is bounded only by cancellation, so a call that\n * cannot be cancelled would never terminate.\n */\nexport function createEmbeddingRetryLedger(\n dispatcher: EmbeddingBatchDispatcher,\n options: EmbeddingRetryOptions = {},\n): EmbeddingRetryLedger {\n const policy = options.policy ?? resolveRetryPolicy(undefined, 'embedding.retryPolicy')\n if (policy.mode === 'always' && options.signal === undefined) {\n throw new EmbeddingError(\n 'an always retry policy requires an AbortSignal',\n EMBEDDING_ERROR_CODES.CONFIGURATION_INVALID,\n )\n }\n const random = options.random ?? Math.random\n const sleep = options.sleep ?? cancellableDelay\n const states = new Map<number, BatchState>()\n\n /**\n * Whether either signal has fired.\n *\n * A function rather than an inline check so the answer is re-read after every\n * `await`: a signal that aborts while a request is in flight is precisely the\n * case that matters.\n */\n const cancelled = (request: EmbeddingBatchRequest): boolean =>\n options.signal?.aborted === true || request.signal?.aborted === true\n\n const abortedOutcome = (\n batchIndex: number,\n request: EmbeddingBatchRequest,\n records: readonly EmbeddingAttemptRecord[],\n error: EmbeddingError,\n dispatch: DispatchState,\n ): EmbeddingBatchOutcome => {\n const state: BatchState = Object.freeze({\n phase: 'failed' as const,\n error,\n // An abort is the caller's decision, so it is terminal by definition.\n retryable: false,\n dispatch,\n })\n states.set(batchIndex, state)\n return Object.freeze({\n batchIndex,\n itemIndexes: Object.freeze(request.items.map(item => item.index)),\n state,\n attempts: records.length,\n attemptRecords: Object.freeze([...records]),\n warnings: Object.freeze([]),\n })\n }\n\n return {\n stateOf(batchIndex: number): BatchState {\n return states.get(batchIndex) ?? PENDING\n },\n\n states(): ReadonlyMap<number, BatchState> {\n return new Map(states)\n },\n\n async dispatch(\n batchIndex: number,\n request: EmbeddingBatchRequest,\n batchContext?: ModelInvocationContext,\n ): Promise<EmbeddingBatchOutcome> {\n const invocationContext = batchContext ?? options.context\n const existing = states.get(batchIndex)\n if (existing !== undefined && existing.phase === 'succeeded') {\n // Requirement 4.7 as an invariant rather than a convention: a batch whose\n // vectors are already held is never handed to the provider again.\n throw new EmbeddingError(\n `embedding batch ${batchIndex} already succeeded and must not be dispatched again`,\n EMBEDDING_ERROR_CODES.CONFIGURATION_INVALID,\n { provider: request.provider, model: request.model },\n )\n }\n\n const itemIndexes = Object.freeze(request.items.map(item => item.index))\n const records: EmbeddingAttemptRecord[] = []\n let retries = 0\n\n for (;;) {\n const attemptNumber = records.length + 1\n // Report the abort before spending an attempt on a call already cancelled.\n if (cancelled(request)) {\n return abortedOutcome(\n batchIndex,\n request,\n records,\n new EmbeddingError(\n 'embedding call aborted before dispatch',\n EMBEDDING_ERROR_CODES.ABORTED,\n { provider: request.provider, model: request.model, itemIndexes: [...itemIndexes] },\n ),\n // No adapter call was ever made on this pass, which the runtime knows\n // first-hand. Once an attempt HAS been made, the runtime stops\n // claiming anything and leaves the state `unknown`.\n records.length === 0 ? 'not-sent' : 'unknown',\n )\n }\n\n states.set(batchIndex, Object.freeze({ phase: 'in-flight' as const, attempt: attemptNumber }))\n\n // Reported by the transport through `attempt.end`; unreported stays unknown.\n let reportedDispatch: DispatchState | undefined\n const context = observeDispatchState(invocationContext, (state) => {\n reportedDispatch = state\n })\n\n let result: EmbeddingBatchResult\n try {\n result = await dispatcher.embedBatch(request, context)\n } catch (error: unknown) {\n const failure = normalizeModelFailure(error)\n const dispatch = reportedDispatch ?? 'unknown'\n records.push(Object.freeze({\n attempt: attemptNumber,\n outcome: 'failure' as const,\n dispatch,\n failureCode: failure.code,\n }))\n\n const embeddingError = asEmbeddingError(error, failure, request)\n if (cancelled(request) || isAbortCode(failure.code)) {\n return abortedOutcome(batchIndex, request, records, embeddingError, dispatch)\n }\n\n const eligible = policy.mode === 'always'\n || (policy.retryableCodes.includes(failure.code) && retries < policy.maxRetries)\n const delayMs = eligible ? delayFor(policy, failure, retries + 1, random) : 'give-up'\n if (!eligible || delayMs === 'give-up') {\n const state: BatchState = Object.freeze({\n phase: 'failed' as const,\n error: embeddingError,\n // `retryable` describes the failure, not the budget: a rate limit\n // that ran out of attempts is still a retryable KIND of failure,\n // and a caller deciding whether to re-run later needs that apart\n // from \"this call gave up\".\n retryable: policy.mode === 'always' || policy.retryableCodes.includes(failure.code),\n dispatch,\n })\n states.set(batchIndex, state)\n return Object.freeze({\n batchIndex,\n itemIndexes,\n state,\n attempts: records.length,\n attemptRecords: Object.freeze([...records]),\n warnings: Object.freeze([]),\n })\n }\n\n retries += 1\n invocationContext?.recordProviderRetry?.({\n nextAttemptNumber: retries + 1,\n delayMs,\n failureCode: failure.code,\n })\n try {\n options.onRetry?.({\n provider: request.provider,\n model: request.model,\n batchIndex,\n attempt: retries,\n maxRetries: policy.mode === 'normal' ? policy.maxRetries : undefined,\n failureCode: failure.code,\n dispatch,\n delayMs,\n })\n } catch {\n // Metrics and logging observers do not own request availability.\n }\n\n if (!await sleep(delayMs, options.signal ?? request.signal)) {\n return abortedOutcome(\n batchIndex,\n request,\n records,\n new EmbeddingError(\n 'embedding call aborted while waiting to retry',\n EMBEDDING_ERROR_CODES.ABORTED,\n { provider: request.provider, model: request.model, itemIndexes: [...itemIndexes], cause: error },\n ),\n dispatch,\n )\n }\n continue\n }\n\n // A response exists, so the request reached the provider. The transport's\n // own report still wins when it made one.\n const dispatch = reportedDispatch ?? 'sent'\n records.push(Object.freeze({\n attempt: attemptNumber,\n outcome: 'success' as const,\n dispatch,\n }))\n const state: BatchState = Object.freeze({\n phase: 'succeeded' as const,\n vectors: result.vectors,\n })\n states.set(batchIndex, state)\n return Object.freeze({\n batchIndex,\n itemIndexes,\n state,\n attempts: records.length,\n attemptRecords: Object.freeze([...records]),\n // Absent usage is left absent: the aggregator downgrades coverage\n // rather than counting an unreported batch as zero tokens.\n ...(result.usage === undefined ? {} : { usage: result.usage }),\n ...(result.providerRequestId === undefined\n ? {}\n : { providerRequestId: result.providerRequestId }),\n warnings: Object.freeze([...(result.warnings ?? [])]),\n })\n }\n },\n }\n}\n"],"mappings":"8SAkLA,MAAM,EAAsB,OAAO,OAAO,CAAE,MAAO,SAAmB,CAAC,EAGvE,SAAS,EAAY,EAAuB,CAC1C,OAAO,IAAS,EAAkB,SAAW,IAAS,EAAsB,OAC9E,CAWA,SAAS,EACP,EACA,EACA,EACgB,CAEhB,OADI,aAAiB,EAAuB,EACrC,IAAI,EAAe,EAAQ,QAAS,EAAQ,KAAM,CACvD,MAAO,EACP,GAAG,EAAQ,SAAW,IAAA,GAAY,CAAC,EAAI,CAAE,OAAQ,EAAQ,MAAO,EAChE,GAAG,EAAQ,uBAAyB,IAAA,GAAY,CAAC,EAAI,CAAE,qBAAsB,EAAQ,oBAAqB,EAC1G,GAAG,EAAQ,YAAc,IAAA,GAAY,CAAC,EAAI,CAAE,UAAW,EAAQ,SAAU,EACzE,SAAU,EAAQ,SAClB,MAAO,EAAQ,MACf,YAAa,EAAQ,MAAM,IAAI,GAAQ,EAAK,KAAK,CACnD,CAAC,CACH,CAGA,SAAS,EAAiB,EAAiB,EAAwC,CAEjF,OADI,GAAQ,UAAY,GAAa,QAAQ,QAAQ,EAAK,EACnD,IAAI,QAAS,GAAY,CAC9B,IAAM,MAAsB,CAC1B,aAAa,CAAK,EAClB,EAAQ,EAAK,CACf,EACM,EAAQ,eAAiB,CAC7B,GAAQ,oBAAoB,QAAS,CAAO,EAC5C,EAAQ,EAAI,CACd,EAAG,CAAO,EACV,GAAQ,iBAAiB,QAAS,EAAS,CAAE,KAAM,EAAK,CAAC,CAC3D,CAAC,CACH,CAGA,SAAS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C,MAAO,YACP,QAAS,EAAO,OAClB,CAAC,EAED,OADA,EAAO,IAAI,EAAY,CAAK,EACrB,OAAO,OAAO,CACnB,aACA,cACA,QACA,SAAU,EAAQ,OAClB,eAAgB,OAAO,OAAO,CAAC,GAAG,CAAO,CAAC,EAG1C,GAAI,EAAO,QAAU,IAAA,GAAY,CAAC,EAAI,CAAE,MAAO,EAAO,KAAM,EAC5D,GAAI,EAAO,oBAAsB,IAAA,GAC7B,CAAC,EACD,CAAE,kBAAmB,EAAO,iBAAkB,EAClD,SAAU,OAAO,OAAO,CAAC,GAAI,EAAO,UAAY,CAAC,CAAE,CAAC,CACtD,CAAC,CACH,CACF,CACF,CACF"}
@@ -1,4 +1,6 @@
1
+ import { ModelFailure } from "../errors/failure.js";
1
2
  import { AgentSdkError } from "../errors/agent-sdk-error.js";
3
+ import { ModelErrorOptions } from "../errors/model-error.js";
2
4
  import { EmbeddingSpaceId } from "./profile.js";
3
5
  //#region src/embedding/errors.d.ts
4
6
  /**
@@ -44,7 +46,7 @@ declare const EMBEDDING_ERROR_CODES: Readonly<{
44
46
  /** Any value of {@link EMBEDDING_ERROR_CODES}; a foreign adapter may still use its own `string`. */
45
47
  type EmbeddingErrorCode = typeof EMBEDDING_ERROR_CODES[keyof typeof EMBEDDING_ERROR_CODES];
46
48
  /** Structured embedding facts and cause accepted by {@link EmbeddingError}. */
47
- interface EmbeddingErrorOptions extends ErrorOptions {
49
+ interface EmbeddingErrorOptions extends ModelErrorOptions {
48
50
  /**
49
51
  * Zero-based indexes of the request items this failure belongs to.
50
52
  *
@@ -76,6 +78,8 @@ interface EmbeddingErrorOptions extends ErrorOptions {
76
78
  * out of errors and traces alike.
77
79
  */
78
80
  declare class EmbeddingError extends AgentSdkError {
81
+ /** Validated provider facts survive the embedding wrapper and normalization. */
82
+ readonly failure: ModelFailure;
79
83
  /** Request item indexes this failure belongs to, when input-specific. */
80
84
  readonly itemIndexes?: readonly number[];
81
85
  /** The applied limit, when the failure is a limit violation. */
@@ -1 +1 @@
1
- {"version":3,"file":"errors.d.ts","names":[],"sources":["../../src/embedding/errors.ts"],"mappings":";;;;;;;;;;;cA2Ba,uBAAqB;;WAEf;;WAEA;;WAEO;;WAEP;;WAEG;;WAEC;;WAEG;;WAED;;WAED;;WAEA;;WAEM;;WAER;;WAEX;;WAEc;;WAEd;;;KAIC,4BAA4B,mCAAmC;;UAG1D,8BAA8B;;;;;;;EAO7C;;EAEA;;EAEA;;EAEA;;EAEA,QAAQ;;;;;;;;;;;;;;;;cAiBG,uBAAuB;;WAEzB;;WAEA;;WAEA;;WAEA;;WAEA,QAAQ;;;;;;EAOjB,YAAY,iBAAiB,cAAc,UAAU"}
1
+ {"version":3,"file":"errors.d.ts","names":[],"sources":["../../src/embedding/errors.ts"],"mappings":";;;;;;;;;;;;;cA6Ba,uBAAqB;;WAEf;;WAEA;;WAEO;;WAEP;;WAEG;;WAEC;;WAEG;;WAED;;WAED;;WAEA;;WAEM;;WAER;;WAEX;;WAEc;;WAEd;;;KAIC,4BAA4B,mCAAmC;;UAG1D,8BAA8B;;;;;;;EAO7C;;EAEA;;EAEA;;EAEA;;EAEA,QAAQ;;;;;;;;;;;;;;;;cAiBG,uBAAuB;;WAEzB,SAAS;;WAET;;WAEA;;WAEA;;WAEA;;WAEA,QAAQ;;;;;;EAOjB,YAAY,iBAAiB,cAAc,UAAU"}
@@ -1,2 +1,2 @@
1
- import{AgentSdkError as e}from"../errors/agent-sdk-error.js";const t=Object.freeze({ADAPTER_MISSING:`EMBEDDING_ADAPTER_MISSING`,REQUEST_INVALID:`EMBEDDING_REQUEST_INVALID`,DIMENSIONS_UNSUPPORTED:`EMBEDDING_DIMENSIONS_UNSUPPORTED`,INPUT_TOO_LARGE:`EMBEDDING_INPUT_TOO_LARGE`,SPACE_INCOMPATIBLE:`EMBEDDING_SPACE_INCOMPATIBLE`,PURPOSE_UNSUPPORTED:`EMBEDDING_PURPOSE_UNSUPPORTED`,TRUNCATION_UNSUPPORTED:`EMBEDDING_TRUNCATION_UNSUPPORTED`,VECTOR_COUNT_MISMATCH:`EMBEDDING_VECTOR_COUNT_MISMATCH`,VECTOR_INDEX_INVALID:`EMBEDDING_VECTOR_INDEX_INVALID`,VECTOR_VALUE_INVALID:`EMBEDDING_VECTOR_VALUE_INVALID`,VECTOR_DIMENSIONS_MISMATCH:`EMBEDDING_VECTOR_DIMENSIONS_MISMATCH`,RESPONSE_MALFORMED:`EMBEDDING_RESPONSE_MALFORMED`,ABORTED:`EMBEDDING_ABORTED`,CONFIGURATION_INVALID:`EMBEDDING_CONFIGURATION_INVALID`,UNKNOWN:`EMBEDDING_UNKNOWN`});var n=class extends e{itemIndexes;limit;provider;model;space;constructor(e,t,n){if(typeof e!=`string`||e.length===0)throw Error(`EmbeddingError message must be a non-empty string`);if(typeof t!=`string`||t.length===0)throw Error(`EmbeddingError code must be a non-empty string`);if(n?.itemIndexes!==void 0&&(!Array.isArray(n.itemIndexes)||n.itemIndexes.some(e=>!Number.isInteger(e)||e<0)))throw Error(`EmbeddingError itemIndexes must be an array of non-negative integers`);if(n?.limit!==void 0&&(!Number.isFinite(n.limit)||n.limit<=0))throw Error(`EmbeddingError limit must be a positive finite number`);if(n?.provider!==void 0&&(typeof n.provider!=`string`||n.provider.length===0))throw Error(`EmbeddingError provider must be a non-empty string`);if(n?.model!==void 0&&(typeof n.model!=`string`||n.model.length===0))throw Error(`EmbeddingError model must be a non-empty string`);if(n?.space!==void 0&&(typeof n.space!=`string`||n.space.length===0))throw Error(`EmbeddingError space must be a non-empty string`);super(e,t,n),this.name=`EmbeddingError`,n?.itemIndexes!==void 0&&(this.itemIndexes=Object.freeze([...n.itemIndexes])),n?.limit!==void 0&&(this.limit=n.limit),n?.provider!==void 0&&(this.provider=n.provider),n?.model!==void 0&&(this.model=n.model),n?.space!==void 0&&(this.space=n.space)}};export{t as EMBEDDING_ERROR_CODES,n as EmbeddingError};
1
+ import{AgentSdkError as e}from"../errors/agent-sdk-error.js";import{ModelError as t}from"../errors/model-error.js";const n=Object.freeze({ADAPTER_MISSING:`EMBEDDING_ADAPTER_MISSING`,REQUEST_INVALID:`EMBEDDING_REQUEST_INVALID`,DIMENSIONS_UNSUPPORTED:`EMBEDDING_DIMENSIONS_UNSUPPORTED`,INPUT_TOO_LARGE:`EMBEDDING_INPUT_TOO_LARGE`,SPACE_INCOMPATIBLE:`EMBEDDING_SPACE_INCOMPATIBLE`,PURPOSE_UNSUPPORTED:`EMBEDDING_PURPOSE_UNSUPPORTED`,TRUNCATION_UNSUPPORTED:`EMBEDDING_TRUNCATION_UNSUPPORTED`,VECTOR_COUNT_MISMATCH:`EMBEDDING_VECTOR_COUNT_MISMATCH`,VECTOR_INDEX_INVALID:`EMBEDDING_VECTOR_INDEX_INVALID`,VECTOR_VALUE_INVALID:`EMBEDDING_VECTOR_VALUE_INVALID`,VECTOR_DIMENSIONS_MISMATCH:`EMBEDDING_VECTOR_DIMENSIONS_MISMATCH`,RESPONSE_MALFORMED:`EMBEDDING_RESPONSE_MALFORMED`,ABORTED:`EMBEDDING_ABORTED`,CONFIGURATION_INVALID:`EMBEDDING_CONFIGURATION_INVALID`,UNKNOWN:`EMBEDDING_UNKNOWN`});var r=class extends e{failure;itemIndexes;limit;provider;model;space;constructor(e,n,r){if(typeof e!=`string`||e.length===0)throw Error(`EmbeddingError message must be a non-empty string`);if(typeof n!=`string`||n.length===0)throw Error(`EmbeddingError code must be a non-empty string`);if(r?.itemIndexes!==void 0&&(!Array.isArray(r.itemIndexes)||r.itemIndexes.some(e=>!Number.isInteger(e)||e<0)))throw Error(`EmbeddingError itemIndexes must be an array of non-negative integers`);if(r?.limit!==void 0&&(!Number.isFinite(r.limit)||r.limit<=0))throw Error(`EmbeddingError limit must be a positive finite number`);if(r?.provider!==void 0&&(typeof r.provider!=`string`||r.provider.length===0))throw Error(`EmbeddingError provider must be a non-empty string`);if(r?.model!==void 0&&(typeof r.model!=`string`||r.model.length===0))throw Error(`EmbeddingError model must be a non-empty string`);if(r?.space!==void 0&&(typeof r.space!=`string`||r.space.length===0))throw Error(`EmbeddingError space must be a non-empty string`);let i=new t(e,n,r).failure;super(e,n,r),this.name=`EmbeddingError`,this.failure=i,r?.itemIndexes!==void 0&&(this.itemIndexes=Object.freeze([...r.itemIndexes])),r?.limit!==void 0&&(this.limit=r.limit),r?.provider!==void 0&&(this.provider=r.provider),r?.model!==void 0&&(this.model=r.model),r?.space!==void 0&&(this.space=r.space)}};export{n as EMBEDDING_ERROR_CODES,r as EmbeddingError};
2
2
  //# sourceMappingURL=errors.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"errors.js","names":[],"sources":["../../src/embedding/errors.ts"],"sourcesContent":["/**\n * The stable embedding failure taxonomy, and the error the embedding layers throw.\n *\n * Codes here are owned by two layers only: `Embedding_Runtime` before dispatch\n * (dimensions, limits, space, configuration) and `Embedding_Adapter` when it\n * validates a response (vector count, index, values, width). Transport-level\n * faults keep using `MODEL_ERROR_CODES`, so a caller can tell \"the provider is\n * rate limiting us\" apart from \"the provider returned a vector of the wrong\n * width\" without parsing any message.\n *\n * Both provider adapters emit the SAME codes for mapping, dimensions and vector\n * faults. That is what lets one contract-test suite run against both.\n *\n * @module ai-agent-sdk/core/embedding/errors\n */\n\nimport { AgentSdkError } from '../errors/agent-sdk-error.ts'\nimport type { EmbeddingSpaceId } from './profile.ts'\n\n/**\n * Codes produced by the embedding contract and runtime.\n *\n * A frozen object rather than a TS enum, matching `MODEL_ERROR_CODES`, so a\n * third-party embedding adapter can emit its own code without this union having\n * to know about it. Values are prefixed `EMBEDDING_` because they travel beside\n * generation codes in the same failure envelopes.\n */\nexport const EMBEDDING_ERROR_CODES = Object.freeze({\n /** No `Embedding_Adapter` is registered for the requested route/model. */\n ADAPTER_MISSING: 'EMBEDDING_ADAPTER_MISSING',\n /** Malformed at the SDK boundary: missing purpose, empty values, empty item. */\n REQUEST_INVALID: 'EMBEDDING_REQUEST_INVALID',\n /** `dimensions` is not among the widths the route declares support for. */\n DIMENSIONS_UNSUPPORTED: 'EMBEDDING_DIMENSIONS_UNSUPPORTED',\n /** Input exceeds the declared max input tokens; carries `itemIndexes` and `limit`. */\n INPUT_TOO_LARGE: 'EMBEDDING_INPUT_TOO_LARGE',\n /** The expected `Space_Id` is incompatible with the `Prepared_Embedding_Call`. */\n SPACE_INCOMPATIBLE: 'EMBEDDING_SPACE_INCOMPATIBLE',\n /** The route has no way to express this purpose and the caller demands the distinction. */\n PURPOSE_UNSUPPORTED: 'EMBEDDING_PURPOSE_UNSUPPORTED',\n /** The caller asked for truncation but the provider has no equivalent parameter. */\n TRUNCATION_UNSUPPORTED: 'EMBEDDING_TRUNCATION_UNSUPPORTED',\n /** The response carried a different number of vectors than inputs sent. */\n VECTOR_COUNT_MISMATCH: 'EMBEDDING_VECTOR_COUNT_MISMATCH',\n /** A vector index is duplicated, missing, or out of range. */\n VECTOR_INDEX_INVALID: 'EMBEDDING_VECTOR_INDEX_INVALID',\n /** A vector contains `NaN` or `Infinity`. */\n VECTOR_VALUE_INVALID: 'EMBEDDING_VECTOR_VALUE_INVALID',\n /** A vector's width differs from the requested `dimensions`. */\n VECTOR_DIMENSIONS_MISMATCH: 'EMBEDDING_VECTOR_DIMENSIONS_MISMATCH',\n /** The response does not satisfy the embedding contract structurally. */\n RESPONSE_MALFORMED: 'EMBEDDING_RESPONSE_MALFORMED',\n /** The caller's signal or a runtime close aborted the call. */\n ABORTED: 'EMBEDDING_ABORTED',\n /** Invalid handle configuration: cache enabled without scope, fallback outside the group. */\n CONFIGURATION_INVALID: 'EMBEDDING_CONFIGURATION_INVALID',\n /** Nothing in this taxonomy classified the embedding failure. */\n UNKNOWN: 'EMBEDDING_UNKNOWN',\n} as const)\n\n/** Any value of {@link EMBEDDING_ERROR_CODES}; a foreign adapter may still use its own `string`. */\nexport type EmbeddingErrorCode = typeof EMBEDDING_ERROR_CODES[keyof typeof EMBEDDING_ERROR_CODES]\n\n/** Structured embedding facts and cause accepted by {@link EmbeddingError}. */\nexport interface EmbeddingErrorOptions extends ErrorOptions {\n /**\n * Zero-based indexes of the request items this failure belongs to.\n *\n * Present only when the fault is attributable to specific inputs, which is\n * what lets a caller drop or re-chunk those items instead of the whole call.\n */\n itemIndexes?: readonly number[]\n /** The limit that was applied, when the failure is a limit violation. */\n limit?: number\n /** Provider id of the route that produced the failure. */\n provider?: string\n /** Model id of the route that produced the failure. */\n model?: string\n /** The embedding space involved, when the failure concerns space compatibility. */\n space?: EmbeddingSpaceId\n}\n\n/**\n * Typed error for embedding failures, carrying a stable `code` plus the facts a\n * caller needs to act without re-deriving them.\n *\n * The constructor validates rather than trusts: `itemIndexes` must be\n * non-negative integers and `limit` a positive finite number. A negative index\n * or a `limit` of `-1` means a caller upstream miscomputed a bound, and letting\n * it through would surface a nonsense limit in a message that reads as\n * authoritative. Indexes are copied and frozen so the array cannot be mutated\n * after the error is thrown.\n *\n * No field carries raw input text or vector values: redaction rules keep those\n * out of errors and traces alike.\n */\nexport class EmbeddingError extends AgentSdkError {\n /** Request item indexes this failure belongs to, when input-specific. */\n readonly itemIndexes?: readonly number[]\n /** The applied limit, when the failure is a limit violation. */\n readonly limit?: number\n /** Provider id of the failing route. */\n readonly provider?: string\n /** Model id of the failing route. */\n readonly model?: string\n /** The embedding space involved in the failure. */\n readonly space?: EmbeddingSpaceId\n\n /**\n * @param message - non-empty human-readable failure summary, free of credentials and raw input.\n * @param code - non-empty stable machine code, normally from {@link EMBEDDING_ERROR_CODES}.\n * @param options - optional cause and validated embedding facts.\n */\n constructor(message: string, code: string, options?: EmbeddingErrorOptions) {\n if (typeof message !== 'string' || message.length === 0) {\n throw new Error('EmbeddingError message must be a non-empty string')\n }\n if (typeof code !== 'string' || code.length === 0) {\n throw new Error('EmbeddingError code must be a non-empty string')\n }\n if (options?.itemIndexes !== undefined\n && (!Array.isArray(options.itemIndexes)\n || options.itemIndexes.some(index => !Number.isInteger(index) || index < 0))) {\n throw new Error('EmbeddingError itemIndexes must be an array of non-negative integers')\n }\n if (options?.limit !== undefined\n && (!Number.isFinite(options.limit) || options.limit <= 0)) {\n throw new Error('EmbeddingError limit must be a positive finite number')\n }\n if (options?.provider !== undefined\n && (typeof options.provider !== 'string' || options.provider.length === 0)) {\n throw new Error('EmbeddingError provider must be a non-empty string')\n }\n if (options?.model !== undefined\n && (typeof options.model !== 'string' || options.model.length === 0)) {\n throw new Error('EmbeddingError model must be a non-empty string')\n }\n if (options?.space !== undefined\n && (typeof options.space !== 'string' || options.space.length === 0)) {\n throw new Error('EmbeddingError space must be a non-empty string')\n }\n super(message, code, options)\n this.name = 'EmbeddingError'\n if (options?.itemIndexes !== undefined) {\n this.itemIndexes = Object.freeze([...options.itemIndexes])\n }\n if (options?.limit !== undefined) this.limit = options.limit\n if (options?.provider !== undefined) this.provider = options.provider\n if (options?.model !== undefined) this.model = options.model\n if (options?.space !== undefined) this.space = options.space\n }\n}\n"],"mappings":"6DA2BA,MAAa,EAAwB,OAAO,OAAO,CAEjD,gBAAiB,4BAEjB,gBAAiB,4BAEjB,uBAAwB,mCAExB,gBAAiB,4BAEjB,mBAAoB,+BAEpB,oBAAqB,gCAErB,uBAAwB,mCAExB,sBAAuB,kCAEvB,qBAAsB,iCAEtB,qBAAsB,iCAEtB,2BAA4B,uCAE5B,mBAAoB,+BAEpB,QAAS,oBAET,sBAAuB,kCAEvB,QAAS,mBACX,CAAU,EAsCV,IAAa,EAAb,cAAoC,CAAc,CAEhD,YAEA,MAEA,SAEA,MAEA,MAOA,YAAY,EAAiB,EAAc,EAAiC,CAC1E,GAAI,OAAO,GAAY,UAAY,EAAQ,SAAW,EACpD,MAAU,MAAM,mDAAmD,EAErE,GAAI,OAAO,GAAS,UAAY,EAAK,SAAW,EAC9C,MAAU,MAAM,gDAAgD,EAElE,GAAI,GAAS,cAAgB,IAAA,KACvB,CAAC,MAAM,QAAQ,EAAQ,WAAW,GACjC,EAAQ,YAAY,KAAK,GAAS,CAAC,OAAO,UAAU,CAAK,GAAK,EAAQ,CAAC,GAC5E,MAAU,MAAM,sEAAsE,EAExF,GAAI,GAAS,QAAU,IAAA,KACjB,CAAC,OAAO,SAAS,EAAQ,KAAK,GAAK,EAAQ,OAAS,GACxD,MAAU,MAAM,uDAAuD,EAEzE,GAAI,GAAS,WAAa,IAAA,KACpB,OAAO,EAAQ,UAAa,UAAY,EAAQ,SAAS,SAAW,GACxE,MAAU,MAAM,oDAAoD,EAEtE,GAAI,GAAS,QAAU,IAAA,KACjB,OAAO,EAAQ,OAAU,UAAY,EAAQ,MAAM,SAAW,GAClE,MAAU,MAAM,iDAAiD,EAEnE,GAAI,GAAS,QAAU,IAAA,KACjB,OAAO,EAAQ,OAAU,UAAY,EAAQ,MAAM,SAAW,GAClE,MAAU,MAAM,iDAAiD,EAEnE,MAAM,EAAS,EAAM,CAAO,EAC5B,KAAK,KAAO,iBACR,GAAS,cAAgB,IAAA,KAC3B,KAAK,YAAc,OAAO,OAAO,CAAC,GAAG,EAAQ,WAAW,CAAC,GAEvD,GAAS,QAAU,IAAA,KAAW,KAAK,MAAQ,EAAQ,OACnD,GAAS,WAAa,IAAA,KAAW,KAAK,SAAW,EAAQ,UACzD,GAAS,QAAU,IAAA,KAAW,KAAK,MAAQ,EAAQ,OACnD,GAAS,QAAU,IAAA,KAAW,KAAK,MAAQ,EAAQ,MACzD,CACF"}
1
+ {"version":3,"file":"errors.js","names":[],"sources":["../../src/embedding/errors.ts"],"sourcesContent":["/**\n * The stable embedding failure taxonomy, and the error the embedding layers throw.\n *\n * Codes here are owned by two layers only: `Embedding_Runtime` before dispatch\n * (dimensions, limits, space, configuration) and `Embedding_Adapter` when it\n * validates a response (vector count, index, values, width). Transport-level\n * faults keep using `MODEL_ERROR_CODES`, so a caller can tell \"the provider is\n * rate limiting us\" apart from \"the provider returned a vector of the wrong\n * width\" without parsing any message.\n *\n * Both provider adapters emit the SAME codes for mapping, dimensions and vector\n * faults. That is what lets one contract-test suite run against both.\n *\n * @module ai-agent-sdk/core/embedding/errors\n */\n\nimport { AgentSdkError } from '../errors/agent-sdk-error.ts'\nimport { ModelError, type ModelErrorOptions } from '../errors/model-error.ts'\nimport type { ModelFailure } from '../errors/failure.ts'\nimport type { EmbeddingSpaceId } from './profile.ts'\n\n/**\n * Codes produced by the embedding contract and runtime.\n *\n * A frozen object rather than a TS enum, matching `MODEL_ERROR_CODES`, so a\n * third-party embedding adapter can emit its own code without this union having\n * to know about it. Values are prefixed `EMBEDDING_` because they travel beside\n * generation codes in the same failure envelopes.\n */\nexport const EMBEDDING_ERROR_CODES = Object.freeze({\n /** No `Embedding_Adapter` is registered for the requested route/model. */\n ADAPTER_MISSING: 'EMBEDDING_ADAPTER_MISSING',\n /** Malformed at the SDK boundary: missing purpose, empty values, empty item. */\n REQUEST_INVALID: 'EMBEDDING_REQUEST_INVALID',\n /** `dimensions` is not among the widths the route declares support for. */\n DIMENSIONS_UNSUPPORTED: 'EMBEDDING_DIMENSIONS_UNSUPPORTED',\n /** Input exceeds the declared max input tokens; carries `itemIndexes` and `limit`. */\n INPUT_TOO_LARGE: 'EMBEDDING_INPUT_TOO_LARGE',\n /** The expected `Space_Id` is incompatible with the `Prepared_Embedding_Call`. */\n SPACE_INCOMPATIBLE: 'EMBEDDING_SPACE_INCOMPATIBLE',\n /** The route has no way to express this purpose and the caller demands the distinction. */\n PURPOSE_UNSUPPORTED: 'EMBEDDING_PURPOSE_UNSUPPORTED',\n /** The caller asked for truncation but the provider has no equivalent parameter. */\n TRUNCATION_UNSUPPORTED: 'EMBEDDING_TRUNCATION_UNSUPPORTED',\n /** The response carried a different number of vectors than inputs sent. */\n VECTOR_COUNT_MISMATCH: 'EMBEDDING_VECTOR_COUNT_MISMATCH',\n /** A vector index is duplicated, missing, or out of range. */\n VECTOR_INDEX_INVALID: 'EMBEDDING_VECTOR_INDEX_INVALID',\n /** A vector contains `NaN` or `Infinity`. */\n VECTOR_VALUE_INVALID: 'EMBEDDING_VECTOR_VALUE_INVALID',\n /** A vector's width differs from the requested `dimensions`. */\n VECTOR_DIMENSIONS_MISMATCH: 'EMBEDDING_VECTOR_DIMENSIONS_MISMATCH',\n /** The response does not satisfy the embedding contract structurally. */\n RESPONSE_MALFORMED: 'EMBEDDING_RESPONSE_MALFORMED',\n /** The caller's signal or a runtime close aborted the call. */\n ABORTED: 'EMBEDDING_ABORTED',\n /** Invalid handle configuration: cache enabled without scope, fallback outside the group. */\n CONFIGURATION_INVALID: 'EMBEDDING_CONFIGURATION_INVALID',\n /** Nothing in this taxonomy classified the embedding failure. */\n UNKNOWN: 'EMBEDDING_UNKNOWN',\n} as const)\n\n/** Any value of {@link EMBEDDING_ERROR_CODES}; a foreign adapter may still use its own `string`. */\nexport type EmbeddingErrorCode = typeof EMBEDDING_ERROR_CODES[keyof typeof EMBEDDING_ERROR_CODES]\n\n/** Structured embedding facts and cause accepted by {@link EmbeddingError}. */\nexport interface EmbeddingErrorOptions extends ModelErrorOptions {\n /**\n * Zero-based indexes of the request items this failure belongs to.\n *\n * Present only when the fault is attributable to specific inputs, which is\n * what lets a caller drop or re-chunk those items instead of the whole call.\n */\n itemIndexes?: readonly number[]\n /** The limit that was applied, when the failure is a limit violation. */\n limit?: number\n /** Provider id of the route that produced the failure. */\n provider?: string\n /** Model id of the route that produced the failure. */\n model?: string\n /** The embedding space involved, when the failure concerns space compatibility. */\n space?: EmbeddingSpaceId\n}\n\n/**\n * Typed error for embedding failures, carrying a stable `code` plus the facts a\n * caller needs to act without re-deriving them.\n *\n * The constructor validates rather than trusts: `itemIndexes` must be\n * non-negative integers and `limit` a positive finite number. A negative index\n * or a `limit` of `-1` means a caller upstream miscomputed a bound, and letting\n * it through would surface a nonsense limit in a message that reads as\n * authoritative. Indexes are copied and frozen so the array cannot be mutated\n * after the error is thrown.\n *\n * No field carries raw input text or vector values: redaction rules keep those\n * out of errors and traces alike.\n */\nexport class EmbeddingError extends AgentSdkError {\n /** Validated provider facts survive the embedding wrapper and normalization. */\n readonly failure: ModelFailure\n /** Request item indexes this failure belongs to, when input-specific. */\n readonly itemIndexes?: readonly number[]\n /** The applied limit, when the failure is a limit violation. */\n readonly limit?: number\n /** Provider id of the failing route. */\n readonly provider?: string\n /** Model id of the failing route. */\n readonly model?: string\n /** The embedding space involved in the failure. */\n readonly space?: EmbeddingSpaceId\n\n /**\n * @param message - non-empty human-readable failure summary, free of credentials and raw input.\n * @param code - non-empty stable machine code, normally from {@link EMBEDDING_ERROR_CODES}.\n * @param options - optional cause and validated embedding facts.\n */\n constructor(message: string, code: string, options?: EmbeddingErrorOptions) {\n if (typeof message !== 'string' || message.length === 0) {\n throw new Error('EmbeddingError message must be a non-empty string')\n }\n if (typeof code !== 'string' || code.length === 0) {\n throw new Error('EmbeddingError code must be a non-empty string')\n }\n if (options?.itemIndexes !== undefined\n && (!Array.isArray(options.itemIndexes)\n || options.itemIndexes.some(index => !Number.isInteger(index) || index < 0))) {\n throw new Error('EmbeddingError itemIndexes must be an array of non-negative integers')\n }\n if (options?.limit !== undefined\n && (!Number.isFinite(options.limit) || options.limit <= 0)) {\n throw new Error('EmbeddingError limit must be a positive finite number')\n }\n if (options?.provider !== undefined\n && (typeof options.provider !== 'string' || options.provider.length === 0)) {\n throw new Error('EmbeddingError provider must be a non-empty string')\n }\n if (options?.model !== undefined\n && (typeof options.model !== 'string' || options.model.length === 0)) {\n throw new Error('EmbeddingError model must be a non-empty string')\n }\n if (options?.space !== undefined\n && (typeof options.space !== 'string' || options.space.length === 0)) {\n throw new Error('EmbeddingError space must be a non-empty string')\n }\n const failure = new ModelError(message, code, options).failure\n super(message, code, options)\n this.name = 'EmbeddingError'\n this.failure = failure\n if (options?.itemIndexes !== undefined) {\n this.itemIndexes = Object.freeze([...options.itemIndexes])\n }\n if (options?.limit !== undefined) this.limit = options.limit\n if (options?.provider !== undefined) this.provider = options.provider\n if (options?.model !== undefined) this.model = options.model\n if (options?.space !== undefined) this.space = options.space\n }\n}\n"],"mappings":"mHA6BA,MAAa,EAAwB,OAAO,OAAO,CAEjD,gBAAiB,4BAEjB,gBAAiB,4BAEjB,uBAAwB,mCAExB,gBAA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