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

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 (63) hide show
  1. package/dist/agent/accounting/ledger.js +1 -1
  2. package/dist/agent/accounting/ledger.js.map +1 -1
  3. package/dist/agent/accounting/report.d.ts +1 -1
  4. package/dist/agent/define/definition.d.ts +26 -5
  5. package/dist/agent/define/definition.d.ts.map +1 -1
  6. package/dist/agent/define/definition.js +1 -1
  7. package/dist/agent/define/definition.js.map +1 -1
  8. package/dist/agent/define/session/accounting.js +1 -1
  9. package/dist/agent/define/session/accounting.js.map +1 -1
  10. package/dist/agent/define/session/model-config.js +1 -1
  11. package/dist/agent/define/session/model-config.js.map +1 -1
  12. package/dist/agent/define/session/types.d.ts +0 -3
  13. package/dist/agent/define/session/types.d.ts.map +1 -1
  14. package/dist/agent/loop/turn/config.js +1 -1
  15. package/dist/agent/loop/turn/config.js.map +1 -1
  16. package/dist/agent/memory/compaction.d.ts.map +1 -1
  17. package/dist/agent/memory/compaction.js +1 -1
  18. package/dist/agent/memory/compaction.js.map +1 -1
  19. package/dist/composition/agent/definition.js +1 -1
  20. package/dist/composition/agent/definition.js.map +1 -1
  21. package/dist/composition/agent/options.js +1 -1
  22. package/dist/composition/agent/options.js.map +1 -1
  23. package/dist/composition/agent/session.js +1 -1
  24. package/dist/composition/agent/session.js.map +1 -1
  25. package/dist/composition/agent/types.d.ts +11 -10
  26. package/dist/composition/agent/types.d.ts.map +1 -1
  27. package/dist/composition/runtime/owner.js +1 -1
  28. package/dist/composition/runtime/owner.js.map +1 -1
  29. package/dist/composition/runtime/types.d.ts +7 -1
  30. package/dist/composition/runtime/types.d.ts.map +1 -1
  31. package/dist/contract/adapter.d.ts +1 -1
  32. package/dist/contract/call-config.d.ts +8 -1
  33. package/dist/contract/call-config.d.ts.map +1 -1
  34. package/dist/contract/call-config.js +1 -1
  35. package/dist/contract/call-config.js.map +1 -1
  36. package/dist/contract/generate-options.d.ts +5 -0
  37. package/dist/contract/generate-options.d.ts.map +1 -1
  38. package/dist/contract/model-info.d.ts +26 -7
  39. package/dist/contract/model-info.d.ts.map +1 -1
  40. package/dist/errors/model-error.d.ts +0 -1
  41. package/dist/errors/model-error.d.ts.map +1 -1
  42. package/dist/errors/model-error.js +1 -1
  43. package/dist/errors/model-error.js.map +1 -1
  44. package/dist/index.d.ts +3 -3
  45. package/dist/observability/bus.js +1 -1
  46. package/dist/observation/report.d.ts +11 -0
  47. package/dist/observation/report.d.ts.map +1 -1
  48. package/dist/observation/report.js.map +1 -1
  49. package/dist/primitives/version.d.ts +1 -1
  50. package/dist/primitives/version.js +1 -1
  51. package/dist/primitives/version.js.map +1 -1
  52. package/dist/provider.d.ts +1 -1
  53. package/dist/runtime/model-call-handle.js +1 -1
  54. package/dist/runtime/model-call-handle.js.map +1 -1
  55. package/dist/runtime/model-metadata.js +1 -1
  56. package/dist/runtime/model-metadata.js.map +1 -1
  57. package/dist/runtime/model-stream.js +1 -1
  58. package/dist/runtime/model-stream.js.map +1 -1
  59. package/dist/runtime/registry.d.ts +7 -1
  60. package/dist/runtime/registry.d.ts.map +1 -1
  61. package/dist/runtime/registry.js +1 -1
  62. package/dist/runtime/registry.js.map +1 -1
  63. 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)},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){if(this.host.operations.assertActive(),this.assertOwnerActive(),this.active!==void 0)throw Error(`Cannot inject while a runtime session is active`);return 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.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.effort===void 0?{}:{reasoningEffort:e.effort},...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)},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){if(this.host.operations.assertActive(),this.assertOwnerActive(),this.active!==void 0)throw Error(`Cannot inject while a runtime session is active`);return 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.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};
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 type { ReasoningEffortId } from '../../primitives/brand.ts'\nimport { atDeadline } from '../lifecycle/bounded.ts'\nimport type { RuntimeOperations } from '../lifecycle/operations.ts'\nimport type { RuntimeObservationPort } from '../observation/port.ts'\nimport { createRunTerminalRecord } from '../delivery/terminal.ts'\nimport { finalizeRuntimeRunReport, type RuntimeRunReport } from '../observation/final-report.ts'\nimport type { RuntimeObservationResource } from '../delivery/resource.ts'\nimport type { RuntimeResources } from '../../platform/resources.ts'\nimport { snapshotToolSources } from '../tool-source/snapshot.ts'\nimport { capabilityIdentityError, inheritCapabilityIdentityConflict } from '../identity/error.ts'\nimport type { CapturedToolSource } from '../tool-source/types.ts'\nimport type { ToolSourceRunReference } from '../tool-source/types.ts'\nimport { createRuntimeMemoryPersistence } from '../memory/run.ts'\nimport { validateMemoryResumeBinding } from '../memory/resume.ts'\nimport type { BoundRuntimeAgentDefinition } from './definition.ts'\nimport { captureInvocationOptions, captureRuntimeSessionOptions, type CapturedInvocationOptions } from './options.ts'\nimport { projectNativeToolEvent } from './native-event.ts'\nimport type {\n RuntimeAgent, RuntimeAgentInvocationOptions, RuntimeAgentResponse, RuntimeAgentRunEvent,\n RuntimeAgentRunHandle, RuntimeAgentSession, RuntimeAgentSessionOptions, RuntimeAgentSessionSnapshot,\n} from './types.ts'\nimport type { CompactionResult } from '../../agent/memory/compaction.ts'\nimport type { AgentTeamMemberOptions } from '../../agent/define/session/types.ts'\nimport type { TeamSessionPort } from '../../agent/team/contracts.ts'\nimport { assertAgentIdentitySnapshot } from '../identity/agent.ts'\n\nexport interface RuntimeAgentHost {\n readonly registry: ModelRegistry\n /**\n * The runtime's captured provider routes.\n *\n * Held so a per-invocation model override resolves against exactly the same\n * configuration the agent binding used, rather than a second view of it.\n */\n readonly selection: ProviderSelection\n readonly operations: RuntimeOperations\n readonly observation: RuntimeObservationPort\n readonly resource: RuntimeObservationResource\n readonly resources: RuntimeResources\n}\n\ninterface RuntimeAgentBinding {\n readonly host: RuntimeAgentHost\n readonly definition: BoundRuntimeAgentDefinition\n}\n\nconst runtimeAgentBindings = new WeakMap<RuntimeAgent, RuntimeAgentBinding>()\n\nexport function createRuntimeAgent(host: RuntimeAgentHost, definition: BoundRuntimeAgentDefinition): RuntimeAgent {\n const agent = Object.freeze({\n model: definition.model,\n generate(input: AgentInput, options?: RuntimeAgentInvocationOptions) { return createRuntimeSession(host, definition).run(input, options) },\n stream(input: AgentInput, options?: RuntimeAgentInvocationOptions) { return createRuntimeSession(host, definition).stream(input, options) },\n createSession(options?: RuntimeAgentSessionOptions) { return createRuntimeSession(host, definition, options) },\n resumeSession(snapshot: RuntimeAgentSessionSnapshot, options?: RuntimeAgentSessionOptions) {\n return createRuntimeSession(host, definition, options, snapshot)\n },\n })\n runtimeAgentBindings.set(agent, Object.freeze({ host, definition }))\n return agent\n}\n\nexport function createRuntimeTeamMemberSession(\n host: RuntimeAgentHost,\n agent: RuntimeAgent,\n options: RuntimeAgentSessionOptions,\n team: AgentTeamMemberOptions,\n ownerSignal: AbortSignal,\n): { readonly view: RuntimeAgentSession; readonly port: TeamSessionPort } {\n const binding = runtimeAgentBindings.get(agent)\n if (binding?.host !== host) throw new AgentSdkError(\n 'Runtime team members must be agents from the same runtime', 'TEAM_AGENT_OWNERSHIP_INVALID',\n )\n const view = createRuntimeSession(host, binding.definition, options, undefined, team, ownerSignal)\n return Object.freeze({ view, port: view.teamPort })\n}\n\nexport function preflightRuntimeTeamMember(\n host: RuntimeAgentHost,\n agent: RuntimeAgent,\n options: RuntimeAgentSessionOptions,\n additionalToolNames: readonly string[],\n): void {\n const binding = runtimeAgentBindings.get(agent)\n if (binding?.host !== host) throw new AgentSdkError(\n 'Runtime team members must be agents from the same runtime', 'TEAM_AGENT_OWNERSHIP_INVALID',\n )\n assertAgentIdentitySnapshot({\n tools: [...binding.definition.legacy.tools, ...options.tools ?? []],\n nativeTools: binding.definition.legacy.nativeTools,\n skills: [...binding.definition.legacy.skills, ...options.skills ?? []] as never,\n ...(binding.definition.legacy.skillIds === undefined ? {} : {\n allowedSkillIds: binding.definition.legacy.skillIds,\n }),\n additionalToolNames,\n })\n}\n\nexport function runtimeOwnsAgent(host: RuntimeAgentHost, agent: unknown): agent is RuntimeAgent {\n return typeof agent === 'object' && agent !== null && runtimeAgentBindings.get(agent as RuntimeAgent)?.host === host\n}\n\nclass RuntimeAgentSessionValue implements RuntimeAgentSession {\n private active: SessionOperation | undefined\n private readonly observerTimeoutMs: number\n readonly teamPort: TeamSessionPort\n\n constructor(\n private readonly host: RuntimeAgentHost,\n private readonly session: AgentSession,\n private readonly nativeProvider: string,\n definitionId: string,\n observerTimeoutMs = 30_000,\n private readonly ownerSignal?: AbortSignal,\n ) {\n this.observerTimeoutMs = observerTimeoutMs\n const owner = this\n this.teamPort = Object.freeze({\n definition: Object.freeze({ id: definitionId }),\n get conversationId() { return owner.conversationId },\n get isRunning() { return owner.isRunning },\n inject(input: Parameters<TeamSessionPort['inject']>[0]) { return owner.injectForTeam(input) },\n whenIdle(signal?: AbortSignal) { return owner.whenIdle(signal) },\n runPending(invocation = {}) { return owner.runPendingForTeam(invocation) },\n })\n }\n\n get conversationId(): string { return this.session.conversationId }\n get isRunning(): boolean { return this.active !== undefined }\n\n stream(input: AgentInput, rawOptions?: RuntimeAgentInvocationOptions): RuntimeAgentRunHandle {\n if (typeof input !== 'string') {\n if (input === null || typeof input !== 'object' || input.role !== 'user') throw new TypeError('Runtime input must be text or a user message')\n input = freezeMessage(input)\n }\n const options = captureInvocationOptions(rawOptions, this.host.selection)\n const started = this.start(input, options)\n return runtimeHandle(started.legacy, started.report, started.result, this.nativeProvider, options.includeTraceEvents === true)\n }\n\n private start(input: AgentInput | undefined, options: CapturedInvocationOptions): StartedRuntimeRun {\n const operation = this.beginOperation()\n let lease: ReturnType<RuntimeOperations['acquire']>\n try {\n const signal = this.ownerSignal === undefined\n ? options.signal\n : options.signal === undefined ? this.ownerSignal : AbortSignal.any([options.signal, this.ownerSignal])\n lease = this.host.operations.acquire('agent-run', {\n ...(signal === undefined ? {} : { signal }),\n })\n } catch (error) { this.finishOperation(operation); throw error }\n let output: JsonValue | undefined\n const structured = options.structuredOutput\n let legacy: RuntimeSessionRunHandle\n try {\n legacy = input === undefined\n ? streamPendingRuntimeSession(this.session, { signal: lease.signal, ...modelOverlay(options) })\n : streamRuntimeSession(this.session, input, { signal: lease.signal, ...modelOverlay(options),\n ...(structured === undefined ? {} : {\n outputFormat: { type: 'json_schema' as const, name: structured.name, schema: structured.schema.jsonSchema },\n validateOutput: (value: unknown) => {\n const parsed = structured.schema.parse(value)\n if (!isJsonValue(parsed)) throw new TypeError('structured output parser must return lossless JSON synchronously')\n output = detachedFrozen(parsed)\n },\n }), ...(options.imagePolicy === undefined ? {} : { imagePolicy: options.imagePolicy }),\n ...(options.documentPolicy === undefined ? {} : { documentPolicy: options.documentPolicy }) }, options.additionalInstructions)\n } catch (error) { lease.settle(); this.finishOperation(operation); throw error }\n const abort = (): void => legacy.abort()\n lease.signal.addEventListener('abort', abort, { once: true })\n if (lease.signal.aborted) abort()\n void lease.whenSealed.then(() => legacy.seal()).catch(() => undefined)\n const report = this.runtimeReport(legacy.report, legacy.toolSourceSnapshots, lease.signal)\n const internalResult = this.runtimeResult(legacy.result, report, () => output)\n const eventsSettled = Promise.race([legacy.eventsSettled, lease.whenSealed])\n const released = Promise.allSettled([eventsSettled, internalResult, report]).then(() => {\n lease.signal.removeEventListener('abort', abort)\n lease.settle()\n this.finishOperation(operation)\n })\n const result = released.then(() => internalResult)\n void result.catch(() => undefined)\n void report.catch(() => undefined)\n return Object.freeze({ legacy, report, result })\n }\n\n async run(input: AgentInput, rawOptions?: RuntimeAgentInvocationOptions): Promise<RuntimeAgentResponse> {\n const options = captureInvocationOptions(rawOptions, this.host.selection)\n const handle = this.stream(input, options)\n try {\n for await (const event of handle) {\n if (options.onEvent !== undefined) {\n try { await this.observe(options.onEvent, event, handle) }\n catch (error) {\n handle.abort()\n const report = await handle.report\n throw runtimeFailure(error, report, 'RUN_EVENT_OBSERVER_FAILED')\n }\n }\n }\n } catch (error) { if (codeOf(error) === 'RUN_EVENT_OBSERVER_FAILED') throw error; return await handle.result }\n return await handle.result\n }\n\n inject(input: AgentInput): number {\n this.host.operations.assertActive()\n this.assertOwnerActive()\n if (this.active !== undefined) throw new Error('Cannot inject while a runtime session is active')\n return this.session.inject(input)\n }\n\n private injectForTeam(input: Parameters<TeamSessionPort['inject']>[0]): number {\n this.host.operations.assertActive()\n this.assertOwnerActive()\n return this.session.inject(input)\n }\n\n snapshot(): RuntimeAgentSessionSnapshot { return this.session.snapshot() }\n\n compact(rawOptions?: RuntimeAgentInvocationOptions): Promise<CompactionResult | null> {\n const options = captureInvocationOptions(rawOptions, this.host.selection)\n const operation = this.beginOperation()\n let pending: Promise<CompactionResult | null>\n try {\n pending = this.host.operations.execute('manual-compaction', {\n ...(this.ownerSignal === undefined\n ? options.signal === undefined ? {} : { signal: options.signal }\n : { signal: options.signal === undefined ? this.ownerSignal : AbortSignal.any([options.signal, this.ownerSignal]) }),\n }, async lease => {\n const outcome = await compactRuntimeSession(this.session, { signal: lease.signal, ...modelOverlay(options) })\n const record = createRunTerminalRecord(outcome.report)\n const terminal = await this.host.observation.checkpointTerminal(record, lease.signal)\n const report = finalizeRuntimeRunReport(record, outcome.report.delivery, terminal,\n this.host.observation.mode, this.host.observation.requiredBoundary)\n if (outcome.failure !== undefined) throw runtimeFailure(\n outcome.failure,\n report,\n report.errors.at(-1)?.code ?? codeOf(outcome.failure),\n )\n return outcome.result === null ? null : Object.freeze({ ...outcome.result, status: 'completed' as const, report })\n })\n } catch (error) { this.finishOperation(operation); throw error }\n return pending.finally(() => this.finishOperation(operation))\n }\n\n reset(): void {\n this.host.operations.assertActive()\n this.assertOwnerActive()\n if (this.active !== undefined) throw new Error('Cannot reset while a runtime session is active')\n this.session.reset()\n }\n\n whenIdle(signal?: AbortSignal): Promise<void> {\n const pending = this.active?.done\n if (pending === undefined) return Promise.resolve()\n if (signal?.aborted) return Promise.reject(new AgentSdkError('Runtime idle wait was aborted', 'RUNTIME_OPERATION_ABORTED'))\n return new Promise((resolve, reject) => {\n let release = (): void => undefined\n const finish = (error?: Error): void => { release(); error === undefined ? resolve() : reject(error) }\n if (signal !== undefined) release = this.host.resources.onAbort(signal,\n () => finish(new AgentSdkError('Runtime idle wait was aborted', 'RUNTIME_OPERATION_ABORTED')))\n void pending.then(() => finish())\n })\n }\n\n private async runPendingForTeam(invocation: {\n readonly signal?: AbortSignal\n readonly onEvent?: (event: AgentRunEvent) => void | Promise<void>\n }): Promise<unknown> {\n const started = this.start(undefined, {\n ...(invocation.signal === undefined ? {} : { signal: invocation.signal }),\n })\n try {\n for await (const event of started.legacy) await invocation.onEvent?.(event)\n } catch (error) {\n started.legacy.abort()\n await started.result.catch(() => undefined)\n throw error\n }\n return await started.result\n }\n\n private beginOperation(): SessionOperation {\n this.assertOwnerActive()\n if (this.active !== undefined) throw new Error('Cannot start while a runtime session is active')\n let resolve!: () => void\n const operation: SessionOperation = { done: new Promise(done => { resolve = done }), resolve }\n this.active = operation\n return operation\n }\n\n private finishOperation(operation: SessionOperation): void {\n if (this.active !== operation) return\n this.active = undefined\n operation.resolve()\n }\n\n private assertOwnerActive(): void {\n if (this.ownerSignal?.aborted === true) {\n throw new AgentSdkError('Runtime team session is closed', 'TEAM_CLOSED')\n }\n }\n\n private async runtimeReport(\n legacy: Promise<RunReport>,\n sourceSnapshots: Promise<readonly ToolSourceRunReference[]>,\n signal: AbortSignal,\n ): Promise<RuntimeRunReport> {\n const [previous, sources] = await Promise.all([legacy, sourceSnapshots])\n const record = createRunTerminalRecord(previous, sources)\n const terminal = await this.host.observation.checkpointTerminal(record, signal)\n return finalizeRuntimeRunReport(record, previous.delivery, terminal,\n this.host.observation.mode, this.host.observation.requiredBoundary)\n }\n\n private async runtimeResult(\n legacy: Promise<Awaited<LegacyRunHandle['result']>>,\n report: Promise<RuntimeRunReport>,\n output: () => JsonValue | undefined,\n ): Promise<RuntimeAgentResponse> {\n try {\n const response = await legacy\n const final = await report\n if (final.status !== 'success') {\n throw runtimeFailure(undefined, final, final.errors.at(-1)?.code ?? 'AGENT_RUN_FAILED')\n }\n const parsedOutput = output()\n return Object.freeze({ runId: final.runId, traceId: final.traceId,\n completed: response.outcome.completed, stopReason: response.outcome.reason.kind,\n text: response.text, ...(parsedOutput === undefined ? {} : { output: parsedOutput }),\n ...(response.message === undefined ? {} : { message: publicMessage(response.message) }),\n usage: final.usage, report: final })\n } catch (error) {\n const final = await report\n throw runtimeFailure(error, final, codeOf(error))\n }\n }\n\n private async observe(\n observer: NonNullable<RuntimeAgentInvocationOptions['onEvent']>,\n event: RuntimeAgentRunEvent,\n handle: RuntimeAgentRunHandle,\n ): Promise<void> {\n const deadlineAt = this.host.resources.platform.monotonicNow() + this.observerTimeoutMs\n try { await atDeadline(this.host.resources, deadlineAt, () => observer(event), undefined) }\n catch { handle.abort(); throw new AgentSdkError('Runtime event observer did not complete', 'RUN_EVENT_OBSERVER_FAILED') }\n }\n}\n\nfunction createRuntimeSession(\n host: RuntimeAgentHost,\n definition: BoundRuntimeAgentDefinition,\n options: RuntimeAgentSessionOptions = {},\n snapshot?: RuntimeAgentSessionSnapshot,\n team?: AgentTeamMemberOptions,\n ownerSignal?: AbortSignal,\n): RuntimeAgentSessionValue {\n host.operations.assertActive()\n options = captureRuntimeSessionOptions(options)\n assertAgentIdentitySnapshot({\n tools: [...definition.legacy.tools, ...options.tools ?? []],\n nativeTools: definition.legacy.nativeTools,\n skills: [...definition.legacy.skills, ...options.skills ?? []] as never,\n ...(definition.legacy.skillIds === undefined ? {} : { allowedSkillIds: definition.legacy.skillIds }),\n })\n const memory = options.memory === false ? undefined : options.memory ?? definition.memory\n if (snapshot !== undefined) validateMemoryResumeBinding(snapshot, memory)\n const toolSources = combineToolSources(definition.toolSources, options.toolSources ?? [])\n const limits = options.runtimeLimits\n const { maxSteps: _maxSteps, maxToolCalls: _maxToolCalls, ...agentRuntimeLimits } = limits ?? {}\n const selected = limits?.maxSteps === undefined && limits?.maxToolCalls === undefined\n ? definition.legacy : definition.legacy.with({\n ...(limits.maxSteps === undefined ? {} : { maxTurns: limits.maxSteps }),\n ...(limits.maxToolCalls === undefined ? {} : { maxToolCalls: limits.maxToolCalls }),\n })\n const shared = { registry: host.registry, observation: host.observation, observationResource: host.resource,\n ...(options.tools === undefined ? {} : { tools: options.tools }),\n ...(options.skills === undefined ? {} : { skills: options.skills as never }),\n ...(options.skillCwd === undefined ? {} : { skillCwd: options.skillCwd }),\n ...(options.userInput === undefined ? {} : { userInput: options.userInput }),\n ...(options.approvals === undefined ? {} : { approvals: options.approvals }),\n ...(options.spillStore === undefined ? {} : { spillStore: options.spillStore }),\n ...(options.interceptors === undefined ? {} : { interceptors: options.interceptors }),\n ...(options.contextSections === undefined ? {} : { contextSections: options.contextSections }),\n ...(options.hooks === undefined ? {} : { hooks: options.hooks }),\n ...(options.usagePolicy === undefined ? {} : { usagePolicy: options.usagePolicy }),\n ...(options.historyLimits === undefined ? {} : { historyLimits: options.historyLimits }),\n ...(options.ledgerLimits === undefined ? {} : { ledgerLimits: options.ledgerLimits }),\n ...(options.eventBufferLimits === undefined ? {} : { eventBufferLimits: options.eventBufferLimits }),\n ...(options.compaction === undefined ? {} : { compaction: options.compaction }),\n ...(team === undefined ? {} : { team }),\n ...(Object.keys(agentRuntimeLimits).length === 0 ? {} : { runtimeLimits: agentRuntimeLimits }),\n }\n const session = snapshot === undefined\n ? selected.createSession({ ...shared, ...(options.conversationId === undefined ? {} : { conversationId: options.conversationId }) })\n : selected.resumeSession({ ...shared, snapshot })\n configureRuntimeSessionModel(session, { provider: definition.model.provider, model: definition.model.id,\n ...(definition.effort === undefined ? {} : { reasoningEffort: definition.effort }),\n ...(definition.maxTokens === undefined ? {} : { maxTokens: definition.maxTokens }),\n logger: correlation => host.observation.correlatedLogger(correlation, { scope: 'sdk.agent.run' }),\n ...(toolSources.length === 0 ? {} : {\n prepareTools: (signal, logger, occupiedNames) => snapshotToolSources(\n toolSources, signal, logger, occupiedNames,\n ),\n }),\n ...(memory === undefined ? {} : {\n memory: createRuntimeMemoryPersistence(\n memory,\n definition.legacy.id,\n agentRuntimeLimits.memoryOperationTimeoutMs,\n ),\n }),\n })\n return new RuntimeAgentSessionValue(\n host, session, definition.model.provider, definition.legacy.id, limits?.observerTimeoutMs, ownerSignal,\n )\n}\n\n/** Project one captured invocation onto the low-level per-run model overlay. */\nfunction modelOverlay(options: CapturedInvocationOptions): {\n readonly model?: { readonly provider: string; readonly model: string }\n readonly reasoningEffort?: ReturnType<typeof ReasoningEffortId>\n readonly maxTokens?: number\n} {\n return {\n ...(options.model === undefined ? {} : { model: { provider: options.model.provider, model: options.model.id } }),\n ...(options.effort === undefined ? {} : { reasoningEffort: options.effort }),\n ...(options.maxTokens === undefined ? {} : { maxTokens: options.maxTokens }),\n }\n}\n\ninterface SessionOperation {\n readonly done: Promise<void>\n readonly resolve: () => void\n}\n\ninterface StartedRuntimeRun {\n readonly legacy: RuntimeSessionRunHandle\n readonly report: Promise<RuntimeRunReport>\n readonly result: Promise<RuntimeAgentResponse>\n}\n\nfunction combineToolSources(\n defined: readonly CapturedToolSource[],\n additional: readonly CapturedToolSource[],\n): readonly CapturedToolSource[] {\n const all = [...defined, ...additional]\n const seen = new Map<string, number>()\n for (const [index, source] of all.entries()) {\n const first = seen.get(source.id)\n if (first !== undefined) throw capabilityIdentityError(\n 'TOOL_SOURCE_ID_CONFLICT', 'tool-source-id', first, index,\n )\n seen.set(source.id, index)\n }\n return Object.freeze(all)\n}\n\nfunction runtimeHandle(\n source: LegacyRunHandle & { readonly traceId: string; abort(reason?: unknown): void },\n report: Promise<RuntimeRunReport>, result: Promise<RuntimeAgentResponse>, nativeProvider: string,\n includeTraceEvents: boolean,\n): RuntimeAgentRunHandle {\n let iterated = false\n return Object.freeze({ runId: source.runId, report, result, abort: () => source.abort(),\n [Symbol.asyncIterator](): AsyncIterator<RuntimeAgentRunEvent> {\n if (iterated) return (async function* () { throw new Error('A runtime run handle can only be iterated once') })()\n iterated = true\n return projectEvents(source, report, nativeProvider, includeTraceEvents)\n } })\n}\n\nasync function* projectEvents(\n source: LegacyRunHandle & { readonly traceId: string; abort(reason?: unknown): void },\n report: Promise<RuntimeRunReport>,\n nativeProvider: string,\n includeTraceEvents: boolean,\n): AsyncGenerator<RuntimeAgentRunEvent> {\n let sequence = 0, completed = false\n const context = () => ({ runId: source.runId, traceId: source.traceId, sequence: ++sequence, schemaVersion: 1 as const })\n try {\n for await (const event of source) {\n const projected = projectEvent(event, nativeProvider, includeTraceEvents)\n if (projected !== undefined) yield Object.freeze({ ...context(), ...projected }) as RuntimeAgentRunEvent\n }\n const terminal = await report\n if (terminal.status === 'success') {\n yield Object.freeze({ ...context(), type: 'usage', usage: terminal.usage, report: terminal })\n } else {\n const error = terminal.errors.at(-1) ?? fallbackError(terminal)\n yield Object.freeze({ ...context(), type: 'error', error, report: terminal })\n }\n completed = true\n } catch {\n const terminal = await report\n const error = terminal.errors.at(-1) ?? fallbackError(terminal)\n yield Object.freeze({ ...context(), type: 'error', error, report: terminal })\n completed = true\n } finally { if (!completed) source.abort() }\n}\n\ntype WithoutEventContext<T> = T extends unknown ? Omit<T, 'runId' | 'traceId' | 'sequence' | 'schemaVersion'> : never\ntype ProjectedEvent = WithoutEventContext<RuntimeAgentRunEvent>\n\nfunction projectEvent(event: AgentRunEvent, nativeProvider: string, includeTraceEvents: boolean): ProjectedEvent | undefined {\n if (event.type === 'usage-progress') return { type: 'usage-progress', usage: event.usage,\n ...(event.attemptId === undefined ? {} : { attemptId: event.attemptId }) }\n // Runtime consumers such as Edge hosts may persist an execution trace. Keep\n // the SDK's span lifecycle intact; unlike transcript events, spans carry the\n // identity and nesting needed to reconstruct the call tree.\n if (includeTraceEvents && (event.type === 'span-start' || event.type === 'span-end')) return event\n if (event.type === 'text-delta') return {\n type: event.phase === 'commentary' ? 'commentary-delta' : 'assistant-delta',\n text: event.text, index: event.index, phase: event.phase, blockId: `${event.trace.spanId}:${event.index}`,\n }\n if (event.type === 'assistant-message') return { type: 'assistant-message', message: publicMessage(event.message) }\n if (event.type === 'text-end' || event.type === 'reasoning-delta') {\n const { trace, ...content } = event\n return { ...content, blockId: `${trace.spanId}:${event.index}` }\n }\n if (event.type === 'image-delta') {\n const { trace, ...content } = event\n return { ...content, blockId: `${trace.spanId}:${event.itemId}` }\n }\n if (event.type === 'compaction-start' || event.type === 'compaction-end'\n || event.type === 'turn-start' || event.type === 'step-start' || event.type === 'step-end'\n || event.type === 'assistant-text' || event.type === 'assistant-reasoning') {\n const { trace: _trace, ...content } = event\n return content\n }\n if (event.type === 'tool-call') return { type: 'tool-call', callId: event.call.callId,\n name: event.call.toolName, input: parseInput(event.call.rawArguments) }\n if (event.type === 'tool-result') return { type: 'tool-result', callId: event.call.callId,\n name: event.call.toolName, status: toolResultStatus(event.result), output: event.result }\n if (event.type === 'assistant-native-tool') return projectNativeToolEvent(event.call, nativeProvider)\n if (event.type === 'approval-request') return { type: 'approval-request', request: event.request }\n if (event.type === 'user-input-request') return { type: 'user-input-request', request: event.request }\n if (event.type === 'user-input-response') return { type: 'user-input-response', requestId: event.request.requestId,\n response: event.response }\n return undefined\n}\n\nfunction toolResultStatus(\n result: ToolExecutionResult,\n): 'completed' | 'failed' | 'aborted' | 'rejected' | 'declined' {\n // A call the loop refused to run is neither success nor failure: nothing\n // broke, and nothing was done. Reporting it as either misleads a UI — and a\n // red row for a budget decision is what makes a finished run look crashed.\n if (!result.isError) return result.meta?.['declined'] === true ? 'declined' : 'completed'\n if (result.error.code === TOOL_ERROR_CODES.ABORTED\n || result.error.code === TOOL_ERROR_CODES.ABORTED_BEFORE_DISPATCH) return 'aborted'\n if (result.error.code === TOOL_ERROR_CODES.UNKNOWN_TOOL\n || result.error.code === TOOL_ERROR_CODES.INVALID_ARGUMENTS\n || result.error.code === TOOL_ERROR_CODES.MALFORMED_ARGUMENTS\n || result.error.code === TOOL_ERROR_CODES.DENIED\n || result.error.code === TOOL_ERROR_CODES.BUDGET_EXHAUSTED\n || result.error.code === TOOL_ERROR_CODES.CHECKPOINT_FAILED) return 'rejected'\n return 'failed'\n}\n\nfunction parseInput(value: string): unknown { try { return JSON.parse(value) as unknown } catch { return value } }\nfunction codeOf(value: unknown): string {\n return value instanceof AgentSdkError ? value.code : 'AGENT_RUN_FAILED'\n}\nfunction runtimeFailure(value: unknown, report: RuntimeRunReport, code: string): AgentRunError {\n return inheritCapabilityIdentityConflict(\n new AgentRunError('Agent run did not complete', code, report as never), value,\n )\n}\nfunction fallbackError(report: RuntimeRunReport): RuntimeRunReport['errors'][number] {\n return Object.freeze({ code: 'AGENT_RUN_FAILED', stage: 'agent-run', message: 'Agent operation failed',\n usageCoverage: report.usage.coverage,\n possiblyBilledAttemptsWithoutUsage: report.usage.coverage.possiblyBilledAttemptsWithoutUsage })\n}\n"],"mappings":"0zCA+DA,MAAM,EAAuB,IAAI,QAEjC,SAAgB,EAAmB,EAAwB,EAAuD,CAChH,IAAM,EAAQ,OAAO,OAAO,CAC1B,MAAO,EAAW,MAClB,SAAS,EAAmB,EA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1F,GAAI,EAAM,OAAS,wBAAyB,OAAO,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"}
1
+ {"version":3,"file":"session.js","names":[],"sources":["../../../src/composition/agent/session.ts"],"sourcesContent":["import { publicMessage } from './public-message.ts'\nimport type { AgentInput } from '../../agent/define/session/types.ts'\nimport { isJsonValue, detachedFrozen, type JsonValue } from '../../primitives/index.ts'\nimport { freezeMessage } from '../../message/index.ts'\nimport { AgentRunError } from '../../agent/accounting/error.ts'\nimport type { RunReport } from '../exporter/delivery-types.ts'\nimport { configureRuntimeSessionModel, streamRuntimeSession, type AgentSession } from '../../agent/define/session.ts'\nimport {\n compactRuntimeSession, streamPendingRuntimeSession, type RuntimeSessionRunHandle,\n} from '../../agent/define/session/runtime-binding.ts'\nimport type { AgentRunHandle as LegacyRunHandle } from '../../agent/define/session/types.ts'\nimport type { AgentRunEvent } from '../../agent/mode/run-agent.ts'\nimport type { ToolExecutionResult } from '../../agent/tool/definition.ts'\nimport { TOOL_ERROR_CODES } from '../../agent/tool/errors.ts'\nimport { AgentSdkError } from '../../errors/agent-sdk-error.ts'\nimport type { ModelRegistry } from '../../runtime/registry.ts'\nimport type { ProviderSelection } from '../provider/types.ts'\nimport { atDeadline } from '../lifecycle/bounded.ts'\nimport type { RuntimeOperations } from '../lifecycle/operations.ts'\nimport type { RuntimeObservationPort } from '../observation/port.ts'\nimport { createRunTerminalRecord } from '../delivery/terminal.ts'\nimport { finalizeRuntimeRunReport, type RuntimeRunReport } from '../observation/final-report.ts'\nimport type { RuntimeObservationResource } from '../delivery/resource.ts'\nimport type { RuntimeResources } from '../../platform/resources.ts'\nimport { snapshotToolSources } from '../tool-source/snapshot.ts'\nimport { capabilityIdentityError, inheritCapabilityIdentityConflict } from '../identity/error.ts'\nimport type { CapturedToolSource } from '../tool-source/types.ts'\nimport type { ToolSourceRunReference } from '../tool-source/types.ts'\nimport { createRuntimeMemoryPersistence } from '../memory/run.ts'\nimport { validateMemoryResumeBinding } from '../memory/resume.ts'\nimport type { BoundRuntimeAgentDefinition } from './definition.ts'\nimport { captureInvocationOptions, captureRuntimeSessionOptions, type CapturedInvocationOptions } from './options.ts'\nimport { projectNativeToolEvent } from './native-event.ts'\nimport type {\n RuntimeAgent, RuntimeAgentInvocationOptions, RuntimeAgentResponse, RuntimeAgentRunEvent,\n RuntimeAgentRunHandle, RuntimeAgentSession, RuntimeAgentSessionOptions, RuntimeAgentSessionSnapshot,\n} from './types.ts'\nimport type { CompactionResult } from '../../agent/memory/compaction.ts'\nimport type { AgentTeamMemberOptions } from '../../agent/define/session/types.ts'\nimport type { TeamSessionPort } from '../../agent/team/contracts.ts'\nimport { assertAgentIdentitySnapshot } from '../identity/agent.ts'\n\nexport interface RuntimeAgentHost {\n readonly registry: ModelRegistry\n /**\n * The runtime's captured provider routes.\n *\n * Held so a per-invocation model override resolves against exactly the same\n * configuration the agent binding used, rather than a second view of it.\n */\n readonly selection: ProviderSelection\n readonly operations: RuntimeOperations\n readonly observation: RuntimeObservationPort\n readonly resource: RuntimeObservationResource\n readonly resources: RuntimeResources\n}\n\ninterface RuntimeAgentBinding {\n readonly host: RuntimeAgentHost\n readonly definition: BoundRuntimeAgentDefinition\n}\n\nconst runtimeAgentBindings = new WeakMap<RuntimeAgent, RuntimeAgentBinding>()\n\nexport function createRuntimeAgent(host: RuntimeAgentHost, definition: BoundRuntimeAgentDefinition): RuntimeAgent {\n const agent = Object.freeze({\n model: definition.model,\n generate(input: AgentInput, options?: RuntimeAgentInvocationOptions) { return createRuntimeSession(host, definition).run(input, options) },\n stream(input: AgentInput, options?: RuntimeAgentInvocationOptions) { return createRuntimeSession(host, definition).stream(input, options) },\n createSession(options?: RuntimeAgentSessionOptions) { return createRuntimeSession(host, definition, options) },\n resumeSession(snapshot: RuntimeAgentSessionSnapshot, options?: RuntimeAgentSessionOptions) {\n return createRuntimeSession(host, definition, options, snapshot)\n },\n })\n runtimeAgentBindings.set(agent, Object.freeze({ host, definition }))\n return agent\n}\n\nexport function createRuntimeTeamMemberSession(\n host: RuntimeAgentHost,\n agent: RuntimeAgent,\n options: RuntimeAgentSessionOptions,\n team: AgentTeamMemberOptions,\n ownerSignal: AbortSignal,\n): { readonly view: RuntimeAgentSession; readonly port: TeamSessionPort } {\n const binding = runtimeAgentBindings.get(agent)\n if (binding?.host !== host) throw new AgentSdkError(\n 'Runtime team members must be agents from the same runtime', 'TEAM_AGENT_OWNERSHIP_INVALID',\n )\n const view = createRuntimeSession(host, binding.definition, options, undefined, team, ownerSignal)\n return Object.freeze({ view, port: view.teamPort })\n}\n\nexport function preflightRuntimeTeamMember(\n host: RuntimeAgentHost,\n agent: RuntimeAgent,\n options: RuntimeAgentSessionOptions,\n additionalToolNames: readonly string[],\n): void {\n const binding = runtimeAgentBindings.get(agent)\n if (binding?.host !== host) throw new AgentSdkError(\n 'Runtime team members must be agents from the same runtime', 'TEAM_AGENT_OWNERSHIP_INVALID',\n )\n assertAgentIdentitySnapshot({\n tools: [...binding.definition.legacy.tools, ...options.tools ?? []],\n nativeTools: binding.definition.legacy.nativeTools,\n skills: [...binding.definition.legacy.skills, ...options.skills ?? []] as never,\n ...(binding.definition.legacy.skillIds === undefined ? {} : {\n allowedSkillIds: binding.definition.legacy.skillIds,\n }),\n additionalToolNames,\n })\n}\n\nexport function runtimeOwnsAgent(host: RuntimeAgentHost, agent: unknown): agent is RuntimeAgent {\n return typeof agent === 'object' && agent !== null && runtimeAgentBindings.get(agent as RuntimeAgent)?.host === host\n}\n\nclass RuntimeAgentSessionValue implements RuntimeAgentSession {\n private active: SessionOperation | undefined\n private readonly observerTimeoutMs: number\n readonly teamPort: TeamSessionPort\n\n constructor(\n private readonly host: RuntimeAgentHost,\n private readonly session: AgentSession,\n private readonly nativeProvider: string,\n definitionId: string,\n observerTimeoutMs = 30_000,\n private readonly ownerSignal?: AbortSignal,\n ) {\n this.observerTimeoutMs = observerTimeoutMs\n const owner = this\n this.teamPort = Object.freeze({\n definition: Object.freeze({ id: definitionId }),\n get conversationId() { return owner.conversationId },\n get isRunning() { return owner.isRunning },\n inject(input: Parameters<TeamSessionPort['inject']>[0]) { return owner.injectForTeam(input) },\n whenIdle(signal?: AbortSignal) { return owner.whenIdle(signal) },\n runPending(invocation = {}) { return owner.runPendingForTeam(invocation) },\n })\n }\n\n get conversationId(): string { return this.session.conversationId }\n get isRunning(): boolean { return this.active !== undefined }\n\n stream(input: AgentInput, rawOptions?: RuntimeAgentInvocationOptions): RuntimeAgentRunHandle {\n if (typeof input !== 'string') {\n if (input === null || typeof input !== 'object' || input.role !== 'user') throw new TypeError('Runtime input must be text or a user message')\n input = freezeMessage(input)\n }\n const options = captureInvocationOptions(rawOptions, this.host.selection)\n const started = this.start(input, options)\n return runtimeHandle(started.legacy, started.report, started.result, this.nativeProvider, options.includeTraceEvents === true)\n }\n\n private start(input: AgentInput | undefined, options: CapturedInvocationOptions): StartedRuntimeRun {\n const operation = this.beginOperation()\n let lease: ReturnType<RuntimeOperations['acquire']>\n try {\n const signal = this.ownerSignal === undefined\n ? options.signal\n : options.signal === undefined ? this.ownerSignal : AbortSignal.any([options.signal, this.ownerSignal])\n lease = this.host.operations.acquire('agent-run', {\n ...(signal === undefined ? {} : { signal }),\n })\n } catch (error) { this.finishOperation(operation); throw error }\n let output: JsonValue | undefined\n const structured = options.structuredOutput\n let legacy: RuntimeSessionRunHandle\n try {\n legacy = input === undefined\n ? streamPendingRuntimeSession(this.session, { signal: lease.signal, ...modelOverlay(options) })\n : streamRuntimeSession(this.session, input, { signal: lease.signal, ...modelOverlay(options),\n ...(structured === undefined ? {} : {\n outputFormat: { type: 'json_schema' as const, name: structured.name, schema: structured.schema.jsonSchema },\n validateOutput: (value: unknown) => {\n const parsed = structured.schema.parse(value)\n if (!isJsonValue(parsed)) throw new TypeError('structured output parser must return lossless JSON synchronously')\n output = detachedFrozen(parsed)\n },\n }), ...(options.imagePolicy === undefined ? {} : { imagePolicy: options.imagePolicy }),\n ...(options.documentPolicy === undefined ? {} : { documentPolicy: options.documentPolicy }) }, options.additionalInstructions)\n } catch (error) { lease.settle(); this.finishOperation(operation); throw error }\n const abort = (): void => legacy.abort()\n lease.signal.addEventListener('abort', abort, { once: true })\n if (lease.signal.aborted) abort()\n void lease.whenSealed.then(() => legacy.seal()).catch(() => undefined)\n const report = this.runtimeReport(legacy.report, legacy.toolSourceSnapshots, lease.signal)\n const internalResult = this.runtimeResult(legacy.result, report, () => output)\n const eventsSettled = Promise.race([legacy.eventsSettled, lease.whenSealed])\n const released = Promise.allSettled([eventsSettled, internalResult, report]).then(() => {\n lease.signal.removeEventListener('abort', abort)\n lease.settle()\n this.finishOperation(operation)\n })\n const result = released.then(() => internalResult)\n void result.catch(() => undefined)\n void report.catch(() => undefined)\n return Object.freeze({ legacy, report, result })\n }\n\n async run(input: AgentInput, rawOptions?: RuntimeAgentInvocationOptions): Promise<RuntimeAgentResponse> {\n const options = captureInvocationOptions(rawOptions, this.host.selection)\n const handle = this.stream(input, options)\n try {\n for await (const event of handle) {\n if (options.onEvent !== undefined) {\n try { await this.observe(options.onEvent, event, handle) }\n catch (error) {\n handle.abort()\n const report = await handle.report\n throw runtimeFailure(error, report, 'RUN_EVENT_OBSERVER_FAILED')\n }\n }\n }\n } catch (error) { if (codeOf(error) === 'RUN_EVENT_OBSERVER_FAILED') throw error; return await handle.result }\n return await handle.result\n }\n\n inject(input: AgentInput): number {\n this.host.operations.assertActive()\n this.assertOwnerActive()\n if (this.active !== undefined) throw new Error('Cannot inject while a runtime session is active')\n return this.session.inject(input)\n }\n\n private injectForTeam(input: Parameters<TeamSessionPort['inject']>[0]): number {\n this.host.operations.assertActive()\n this.assertOwnerActive()\n return this.session.inject(input)\n }\n\n snapshot(): RuntimeAgentSessionSnapshot { return this.session.snapshot() }\n\n compact(rawOptions?: RuntimeAgentInvocationOptions): Promise<CompactionResult | null> {\n const options = captureInvocationOptions(rawOptions, this.host.selection)\n const operation = this.beginOperation()\n let pending: Promise<CompactionResult | null>\n try {\n pending = this.host.operations.execute('manual-compaction', {\n ...(this.ownerSignal === undefined\n ? options.signal === undefined ? {} : { signal: options.signal }\n : { signal: options.signal === undefined ? this.ownerSignal : AbortSignal.any([options.signal, this.ownerSignal]) }),\n }, async lease => {\n const outcome = await compactRuntimeSession(this.session, { signal: lease.signal, ...modelOverlay(options) })\n const record = createRunTerminalRecord(outcome.report)\n const terminal = await this.host.observation.checkpointTerminal(record, lease.signal)\n const report = finalizeRuntimeRunReport(record, outcome.report.delivery, terminal,\n this.host.observation.mode, this.host.observation.requiredBoundary)\n if (outcome.failure !== undefined) throw runtimeFailure(\n outcome.failure,\n report,\n report.errors.at(-1)?.code ?? codeOf(outcome.failure),\n )\n return outcome.result === null ? null : Object.freeze({ ...outcome.result, status: 'completed' as const, report })\n })\n } catch (error) { this.finishOperation(operation); throw error }\n return pending.finally(() => this.finishOperation(operation))\n }\n\n reset(): void {\n this.host.operations.assertActive()\n this.assertOwnerActive()\n if (this.active !== undefined) throw new Error('Cannot reset while a runtime session is active')\n this.session.reset()\n }\n\n whenIdle(signal?: AbortSignal): Promise<void> {\n const pending = this.active?.done\n if (pending === undefined) return Promise.resolve()\n if (signal?.aborted) return Promise.reject(new AgentSdkError('Runtime idle wait was aborted', 'RUNTIME_OPERATION_ABORTED'))\n return new Promise((resolve, reject) => {\n let release = (): void => undefined\n const finish = (error?: Error): void => { release(); error === undefined ? resolve() : reject(error) }\n if (signal !== undefined) release = this.host.resources.onAbort(signal,\n () => finish(new AgentSdkError('Runtime idle wait was aborted', 'RUNTIME_OPERATION_ABORTED')))\n void pending.then(() => finish())\n })\n }\n\n private async runPendingForTeam(invocation: {\n readonly signal?: AbortSignal\n readonly onEvent?: (event: AgentRunEvent) => void | Promise<void>\n }): Promise<unknown> {\n const started = this.start(undefined, {\n ...(invocation.signal === undefined ? {} : { signal: invocation.signal }),\n })\n try {\n for await (const event of started.legacy) await invocation.onEvent?.(event)\n } catch (error) {\n started.legacy.abort()\n await started.result.catch(() => undefined)\n throw error\n }\n return await started.result\n }\n\n private beginOperation(): SessionOperation {\n this.assertOwnerActive()\n if (this.active !== undefined) throw new Error('Cannot start while a runtime session is active')\n let resolve!: () => void\n const operation: SessionOperation = { done: new Promise(done => { resolve = done }), resolve }\n this.active = operation\n return operation\n }\n\n private finishOperation(operation: SessionOperation): void {\n if (this.active !== operation) return\n this.active = undefined\n operation.resolve()\n }\n\n private assertOwnerActive(): void {\n if (this.ownerSignal?.aborted === true) {\n throw new AgentSdkError('Runtime team session is closed', 'TEAM_CLOSED')\n }\n }\n\n private async runtimeReport(\n legacy: Promise<RunReport>,\n sourceSnapshots: Promise<readonly ToolSourceRunReference[]>,\n signal: AbortSignal,\n ): Promise<RuntimeRunReport> {\n const [previous, sources] = await Promise.all([legacy, sourceSnapshots])\n const record = createRunTerminalRecord(previous, sources)\n const terminal = await this.host.observation.checkpointTerminal(record, signal)\n return finalizeRuntimeRunReport(record, previous.delivery, terminal,\n this.host.observation.mode, this.host.observation.requiredBoundary)\n }\n\n private async runtimeResult(\n legacy: Promise<Awaited<LegacyRunHandle['result']>>,\n report: Promise<RuntimeRunReport>,\n output: () => JsonValue | undefined,\n ): Promise<RuntimeAgentResponse> {\n try {\n const response = await legacy\n const final = await report\n if (final.status !== 'success') {\n throw runtimeFailure(undefined, final, final.errors.at(-1)?.code ?? 'AGENT_RUN_FAILED')\n }\n const parsedOutput = output()\n return Object.freeze({ runId: final.runId, traceId: final.traceId,\n completed: response.outcome.completed, stopReason: response.outcome.reason.kind,\n text: response.text, ...(parsedOutput === undefined ? {} : { output: parsedOutput }),\n ...(response.message === undefined ? {} : { message: publicMessage(response.message) }),\n usage: final.usage, report: final })\n } catch (error) {\n const final = await report\n throw runtimeFailure(error, final, codeOf(error))\n }\n }\n\n private async observe(\n observer: NonNullable<RuntimeAgentInvocationOptions['onEvent']>,\n event: RuntimeAgentRunEvent,\n handle: RuntimeAgentRunHandle,\n ): Promise<void> {\n const deadlineAt = this.host.resources.platform.monotonicNow() + this.observerTimeoutMs\n try { await atDeadline(this.host.resources, deadlineAt, () => observer(event), undefined) }\n catch { handle.abort(); throw new AgentSdkError('Runtime event observer did not complete', 'RUN_EVENT_OBSERVER_FAILED') }\n }\n}\n\nfunction createRuntimeSession(\n host: RuntimeAgentHost,\n definition: BoundRuntimeAgentDefinition,\n options: RuntimeAgentSessionOptions = {},\n snapshot?: RuntimeAgentSessionSnapshot,\n team?: AgentTeamMemberOptions,\n ownerSignal?: AbortSignal,\n): RuntimeAgentSessionValue {\n host.operations.assertActive()\n options = captureRuntimeSessionOptions(options)\n assertAgentIdentitySnapshot({\n tools: [...definition.legacy.tools, ...options.tools ?? []],\n nativeTools: definition.legacy.nativeTools,\n skills: [...definition.legacy.skills, ...options.skills ?? []] as never,\n ...(definition.legacy.skillIds === undefined ? {} : { allowedSkillIds: definition.legacy.skillIds }),\n })\n const memory = options.memory === false ? undefined : options.memory ?? definition.memory\n if (snapshot !== undefined) validateMemoryResumeBinding(snapshot, memory)\n const toolSources = combineToolSources(definition.toolSources, options.toolSources ?? [])\n const limits = options.runtimeLimits\n const { maxSteps: _maxSteps, maxToolCalls: _maxToolCalls, ...agentRuntimeLimits } = limits ?? {}\n const selected = limits?.maxSteps === undefined && limits?.maxToolCalls === undefined\n ? definition.legacy : definition.legacy.with({\n ...(limits.maxSteps === undefined ? {} : { maxTurns: limits.maxSteps }),\n ...(limits.maxToolCalls === undefined ? {} : { maxToolCalls: limits.maxToolCalls }),\n })\n const shared = { registry: host.registry, observation: host.observation, observationResource: host.resource,\n ...(options.tools === undefined ? {} : { tools: options.tools }),\n ...(options.skills === undefined ? {} : { skills: options.skills as never }),\n ...(options.skillCwd === undefined ? {} : { skillCwd: options.skillCwd }),\n ...(options.userInput === undefined ? {} : { userInput: options.userInput }),\n ...(options.approvals === undefined ? {} : { approvals: options.approvals }),\n ...(options.spillStore === undefined ? {} : { spillStore: options.spillStore }),\n ...(options.interceptors === undefined ? {} : { interceptors: options.interceptors }),\n ...(options.contextSections === undefined ? {} : { contextSections: options.contextSections }),\n ...(options.hooks === undefined ? {} : { hooks: options.hooks }),\n ...(options.usagePolicy === undefined ? {} : { usagePolicy: options.usagePolicy }),\n ...(options.historyLimits === undefined ? {} : { historyLimits: options.historyLimits }),\n ...(options.ledgerLimits === undefined ? {} : { ledgerLimits: options.ledgerLimits }),\n ...(options.eventBufferLimits === undefined ? {} : { eventBufferLimits: options.eventBufferLimits }),\n ...(options.compaction === undefined ? {} : { compaction: options.compaction }),\n ...(team === undefined ? {} : { team }),\n ...(Object.keys(agentRuntimeLimits).length === 0 ? {} : { runtimeLimits: agentRuntimeLimits }),\n }\n const session = snapshot === undefined\n ? selected.createSession({ ...shared, ...(options.conversationId === undefined ? {} : { conversationId: options.conversationId }) })\n : selected.resumeSession({ ...shared, snapshot })\n configureRuntimeSessionModel(session, { provider: definition.model.provider, model: definition.model.id,\n ...(definition.effort === undefined ? {} : { reasoningEffort: definition.effort }),\n ...(definition.maxTokens === undefined ? {} : { maxTokens: definition.maxTokens }),\n logger: correlation => host.observation.correlatedLogger(correlation, { scope: 'sdk.agent.run' }),\n ...(toolSources.length === 0 ? {} : {\n prepareTools: (signal, logger, occupiedNames) => snapshotToolSources(\n toolSources, signal, logger, occupiedNames,\n ),\n }),\n ...(memory === undefined ? {} : {\n memory: createRuntimeMemoryPersistence(\n memory,\n definition.legacy.id,\n agentRuntimeLimits.memoryOperationTimeoutMs,\n ),\n }),\n })\n return new RuntimeAgentSessionValue(\n host, session, definition.model.provider, definition.legacy.id, limits?.observerTimeoutMs, ownerSignal,\n )\n}\n\n/** Project one captured invocation onto the low-level per-run model overlay. */\nfunction modelOverlay(options: CapturedInvocationOptions): {\n readonly model?: { readonly provider: string; readonly model: string }\n readonly maxTokens?: number\n} {\n return {\n ...(options.model === undefined ? {} : { model: { provider: options.model.provider, model: options.model.id } }),\n ...(options.maxTokens === undefined ? {} : { maxTokens: options.maxTokens }),\n }\n}\n\ninterface SessionOperation {\n readonly done: Promise<void>\n readonly resolve: () => void\n}\n\ninterface StartedRuntimeRun {\n readonly legacy: RuntimeSessionRunHandle\n readonly report: Promise<RuntimeRunReport>\n readonly result: Promise<RuntimeAgentResponse>\n}\n\nfunction combineToolSources(\n defined: readonly CapturedToolSource[],\n additional: readonly CapturedToolSource[],\n): readonly CapturedToolSource[] {\n const all = [...defined, ...additional]\n const seen = new Map<string, number>()\n for (const [index, source] of all.entries()) {\n const first = seen.get(source.id)\n if (first !== undefined) throw capabilityIdentityError(\n 'TOOL_SOURCE_ID_CONFLICT', 'tool-source-id', first, index,\n )\n seen.set(source.id, index)\n }\n return Object.freeze(all)\n}\n\nfunction runtimeHandle(\n source: LegacyRunHandle & { readonly traceId: string; abort(reason?: unknown): void },\n report: Promise<RuntimeRunReport>, result: Promise<RuntimeAgentResponse>, nativeProvider: string,\n includeTraceEvents: boolean,\n): RuntimeAgentRunHandle {\n let iterated = false\n return Object.freeze({ runId: source.runId, report, result, abort: () => source.abort(),\n [Symbol.asyncIterator](): AsyncIterator<RuntimeAgentRunEvent> {\n if (iterated) return (async function* () { throw new Error('A runtime run handle can only be iterated once') })()\n iterated = true\n return projectEvents(source, report, nativeProvider, includeTraceEvents)\n } })\n}\n\nasync function* projectEvents(\n source: LegacyRunHandle & { readonly traceId: string; abort(reason?: unknown): void },\n report: Promise<RuntimeRunReport>,\n nativeProvider: string,\n includeTraceEvents: boolean,\n): AsyncGenerator<RuntimeAgentRunEvent> {\n let sequence = 0, completed = false\n const context = () => ({ runId: source.runId, traceId: source.traceId, sequence: ++sequence, schemaVersion: 1 as const })\n try {\n for await (const event of source) {\n const projected = projectEvent(event, nativeProvider, includeTraceEvents)\n if (projected !== undefined) yield Object.freeze({ ...context(), ...projected }) as RuntimeAgentRunEvent\n }\n const terminal = await report\n if (terminal.status === 'success') {\n yield Object.freeze({ ...context(), type: 'usage', usage: terminal.usage, report: terminal })\n } else {\n const error = terminal.errors.at(-1) ?? fallbackError(terminal)\n yield Object.freeze({ ...context(), type: 'error', error, report: terminal })\n }\n completed = true\n } catch {\n const terminal = await report\n const error = terminal.errors.at(-1) ?? fallbackError(terminal)\n yield Object.freeze({ ...context(), type: 'error', error, report: terminal })\n completed = true\n } finally { if (!completed) source.abort() }\n}\n\ntype WithoutEventContext<T> = T extends unknown ? Omit<T, 'runId' | 'traceId' | 'sequence' | 'schemaVersion'> : never\ntype ProjectedEvent = WithoutEventContext<RuntimeAgentRunEvent>\n\nfunction projectEvent(event: AgentRunEvent, nativeProvider: string, includeTraceEvents: boolean): ProjectedEvent | undefined {\n if (event.type === 'usage-progress') return { type: 'usage-progress', usage: event.usage,\n ...(event.attemptId === undefined ? {} : { attemptId: event.attemptId }) }\n // Runtime consumers such as Edge hosts may persist an execution trace. Keep\n // the SDK's span lifecycle intact; unlike transcript events, spans carry the\n // identity and nesting needed to reconstruct the call tree.\n if (includeTraceEvents && (event.type === 'span-start' || event.type === 'span-end')) return event\n if (event.type === 'text-delta') return {\n type: event.phase === 'commentary' ? 'commentary-delta' : 'assistant-delta',\n text: event.text, index: event.index, phase: event.phase, blockId: `${event.trace.spanId}:${event.index}`,\n }\n if (event.type === 'assistant-message') return { type: 'assistant-message', message: publicMessage(event.message) }\n if (event.type === 'text-end' || event.type === 'reasoning-delta') {\n const { trace, ...content } = event\n return { ...content, blockId: `${trace.spanId}:${event.index}` }\n }\n if (event.type === 'image-delta') {\n const { trace, ...content } = event\n return { ...content, blockId: `${trace.spanId}:${event.itemId}` }\n }\n if (event.type === 'compaction-start' || event.type === 'compaction-end'\n || event.type === 'turn-start' || event.type === 'step-start' || event.type === 'step-end'\n || event.type === 'assistant-text' || event.type === 'assistant-reasoning') {\n const { trace: _trace, ...content } = event\n return content\n }\n if (event.type === 'tool-call') return { type: 'tool-call', callId: event.call.callId,\n name: event.call.toolName, input: parseInput(event.call.rawArguments) }\n if (event.type === 'tool-result') return { type: 'tool-result', callId: event.call.callId,\n name: event.call.toolName, status: toolResultStatus(event.result), output: event.result }\n if (event.type === 'assistant-native-tool') return projectNativeToolEvent(event.call, nativeProvider)\n if (event.type === 'approval-request') return { type: 'approval-request', request: event.request }\n if (event.type === 'user-input-request') return { type: 'user-input-request', request: event.request }\n if (event.type === 'user-input-response') return { type: 'user-input-response', requestId: event.request.requestId,\n response: event.response }\n return undefined\n}\n\nfunction toolResultStatus(\n result: ToolExecutionResult,\n): 'completed' | 'failed' | 'aborted' | 'rejected' | 'declined' {\n // A call the loop refused to run is neither success nor failure: nothing\n // broke, and nothing was done. Reporting it as either misleads a UI — and a\n // red row for a budget decision is what makes a finished run look crashed.\n if (!result.isError) return result.meta?.['declined'] === true ? 'declined' : 'completed'\n if (result.error.code === TOOL_ERROR_CODES.ABORTED\n || result.error.code === TOOL_ERROR_CODES.ABORTED_BEFORE_DISPATCH) return 'aborted'\n if (result.error.code === TOOL_ERROR_CODES.UNKNOWN_TOOL\n || result.error.code === TOOL_ERROR_CODES.INVALID_ARGUMENTS\n || result.error.code === TOOL_ERROR_CODES.MALFORMED_ARGUMENTS\n || result.error.code === TOOL_ERROR_CODES.DENIED\n || result.error.code === TOOL_ERROR_CODES.BUDGET_EXHAUSTED\n || result.error.code === TOOL_ERROR_CODES.CHECKPOINT_FAILED) return 'rejected'\n return 'failed'\n}\n\nfunction parseInput(value: string): unknown { try { return JSON.parse(value) as unknown } catch { return value } }\nfunction codeOf(value: unknown): string {\n return value instanceof AgentSdkError ? value.code : 'AGENT_RUN_FAILED'\n}\nfunction runtimeFailure(value: unknown, report: RuntimeRunReport, code: string): AgentRunError {\n return inheritCapabilityIdentityConflict(\n new AgentRunError('Agent run did not complete', code, report as never), value,\n )\n}\nfunction fallbackError(report: RuntimeRunReport): RuntimeRunReport['errors'][number] {\n return Object.freeze({ code: 'AGENT_RUN_FAILED', stage: 'agent-run', message: 'Agent operation failed',\n usageCoverage: report.usage.coverage,\n possiblyBilledAttemptsWithoutUsage: report.usage.coverage.possiblyBilledAttemptsWithoutUsage })\n}\n"],"mappings":"0zCA8DA,MAAM,EAAuB,IAAI,QAEjC,SAAgB,EAAmB,EAAwB,EAAuD,CAChH,IAAM,EAAQ,OAAO,OAAO,CAC1B,MAAO,EAAW,MAClB,SAAS,EAAmB,EAAyC,CAAE,OAAO,EAAqB,EAAM,CAAU,CAAC,CAAC,IAAI,EAAO,CAAO,CAAE,EACzI,OAAO,EAAmB,EAAyC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O,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"}
@@ -3,6 +3,7 @@ import { UsageCounters } from "../../observation/usage.js";
3
3
  import { Message } from "../../message/message.js";
4
4
  import { NativeToolSchema, ToolChoice } from "../../contract/tool.js";
5
5
  import { ModelOutputFormat } from "../../contract/output-format.js";
6
+ import { ModelModality } from "../../contract/model-info.js";
6
7
  import { ToolDefinition } from "../../agent/tool/definition.js";
7
8
  import { SpillStore } from "../../agent/tool/output-budget.js";
8
9
  import { HistoryLimits } from "../../agent/history/types.js";
@@ -31,6 +32,10 @@ interface RuntimeAgentDefinitionInput {
31
32
  readonly instructions: string;
32
33
  readonly effort?: string;
33
34
  readonly maxTokens?: number;
35
+ /** Overrides the model/route/runtime-defaults tiers, same precedence as `maxTokens`. */
36
+ readonly contextWindow?: number;
37
+ /** Overrides the model/route/runtime-defaults tiers, same precedence as `maxTokens`. */
38
+ readonly inputModalities?: readonly ModelModality[];
34
39
  readonly mode?: 'basic' | 'deep' | 'deep-human-in-loop';
35
40
  readonly tools?: readonly ToolDefinition[];
36
41
  readonly nativeTools?: readonly NativeToolSchema[];
@@ -53,6 +58,11 @@ interface RuntimeAgentDefinitionInput {
53
58
  readonly maxTurns?: number | 'auto';
54
59
  readonly maxToolCalls?: number;
55
60
  readonly commentary?: 'auto' | 'concise' | 'off';
61
+ /** Extra headers/body fields for this agent's provider requests; this agent's value wins where it collides with the route's own. */
62
+ readonly providerOptions?: {
63
+ readonly headers?: Readonly<Record<string, string>>;
64
+ readonly body?: Readonly<Record<string, unknown>>;
65
+ };
56
66
  }
57
67
  interface RuntimeAgentDefinition extends RuntimeAgentDefinitionInput {}
58
68
  interface RuntimeAgentBindingInput extends Omit<RuntimeAgentDefinitionInput, 'model'> {
@@ -120,16 +130,7 @@ interface RuntimeAgentInvocationOptions {
120
130
  readonly provider: string;
121
131
  readonly id?: string;
122
132
  };
123
- /**
124
- * Reasoning effort for this invocation only.
125
- *
126
- * Alone it re-runs the agent's own model at a different effort. With `model`
127
- * it applies to that model. Omitted alongside a `model` that differs from the
128
- * binding, the agent's effort is NOT carried over: an effort belongs to the
129
- * ladder of the model that offers it, and the route decides the default.
130
- */
131
- readonly effort?: string;
132
- /** Output ceiling for this invocation only; dropped like `effort` on a model switch. */
133
+ /** Output ceiling for this invocation only; dropped, like effort, on a model switch. */
133
134
  readonly maxTokens?: number;
134
135
  /** One schema adapter supplies the provider schema and a synchronous runtime validator. */
135
136
  readonly structuredOutput?: {
@@ -1 +1 @@
1
- {"version":3,"file":"types.d.ts","names":[],"sources":["../../../src/composition/agent/types.ts"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;UAyBiB;WACN;WACA;WACA;WACA,OAAO;WACP;WACA;WACA;WACA;WACA,iBAAiB;WACjB,uBAAuB;WACvB,aAAa;WACb,eAAe;WACf,uBAAuB;WACvB,kBAAkB;WAClB;WACA,SAAS;;;;;;;;WAQT,2BAA2B;WAC3B,aAAa;;WAEb;WACA;WACA;;UAGM,+BAA+B;UAE/B,iCAAiC,KAAK;WAC5C;aAAmB;aAA2B;;;UAGxC,2BAA2B;WACjC;WACA;;UAGM;WACN;WACA,iBAAiB;WACjB,uBAAuB;WACvB,kBAAkB;WAClB,SAAS;WACT;WACA,YAAY;WACZ,YAAY;;;;;;;WAOZ,aAAa;WACb,wBAAwB;;;;;;;WAOxB,2BAA2B;WAC3B,QAAQ;WACR,cAAc;;WAEd,gBAAgB;;WAEhB,eAAe;;WAEf,oBAAoB;WACpB,gBAAgB;WAChB,aAAa;;UAGP;;;;;;;;;;;;;;;;WAgBN;aAAmB;aAA2B;;;;;;;;;;WAS9C;;WAEA;;WAEA;aACE;aACA,QAA2D,cAAA;;;WAG7D;;WAEA;WACA,SAAS;WACT;;WAEA;WACA,WAAW,OAAO,gCAAgC;;UAG5C;WACN;WACA;WACA;WACA;;KAGN,qBAAqB,6BAA4B,KAClD;EAAY;IACV,KAAK;WAAyB;;KAG/B,mBAAmB,QAAQ;EAAiB;;KAErC,uBAAuB,+BAC/B,qBACA;WACW;WAAmC;WAAuB;WAAwB;WAA0B,OADvH;;WAEW;WAAkC;WAAuB;WAAwB;WAA0B,OAD6C;;WAExJ;WAA4B;WAAyB;WAAuB;;WAC5E;WAA8B;WAAyB;WACvD;WACA;;WACA;WAAwC;WAAyB;WACjE;WAAuB;WACvB,QAAQ;WAAoB,SAAS;;WACrC;WAAmC,SAAS;;WAC5C;WAAqC,SAAS;;WAC9C;WAAsC;WAA4B,UAAU;;WAC5E;WAAwB,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C,QAAQ;EAC9E,OAAO,OAAO,YAAY,UAAU,gCAAgC;EACpE,cAAc,UAAU,6BAA6B;EACrD,cAAc,UAAU,6BAA6B,UAAU,6BAA6B"}
@@ -1,2 +1,2 @@
1
- import{createRuntimePlatform as e}from"../../platform/adapter.js";import{ModelRegistry as t}from"../../runtime/registry.js";import{EmbeddingRegistry as n}from"../embedding/registry.js";import{RuntimeEmbedding as r}from"../embedding/manager.js";import{RuntimeResources as i}from"../../platform/resources.js";import{createRuntimeResource as a}from"../delivery/resource.js";import{RuntimeObservationPort as o}from"../observation/port.js";import{providerTopology as s}from"../provider/model-selection.js";import{preflightRuntimeCapabilities as c}from"../preflight.js";import{activateRuntimeCapabilities as l}from"../startup.js";import{RuntimeOperations as u}from"../lifecycle/operations.js";import{captureCloseSignal as d,captureRuntimeOwnerOptions as f}from"./config.js";import{bindRuntimeAgentDefinition as p}from"../agent/definition.js";import{createRuntimeAgent as m}from"../agent/session.js";import{RuntimeModelCatalog as h}from"../model-catalog/manager.js";import{createRuntimeAgentTeam as g}from"../team/runtime.js";var _=class{platform;resources;observation;resource;topology;selection;providersOwned;exporters;closeTimeoutMs;embeddingRegistry;registry;operations;closing;catalogs;embeddings;teams=[];closedTeams=[];constructor(e,t,i,a,o,s,c,l,u,d,f,p=new n){this.platform=i,this.resources=a,this.observation=o,this.resource=s,this.topology=c,this.selection=l,this.providersOwned=u,this.exporters=d,this.closeTimeoutMs=f,this.embeddingRegistry=p,this.registry=e,this.operations=t,this.catalogs=new h(e,t,a,c),this.embeddings=new r({registry:this.embeddingRegistry,operations:t,observation:o,resource:s})}providers(){return this.topology}modelCatalog(e,t){return this.catalogs.get(e,t)}embeddingModel(e){return this.embeddings.model(e)}agent(e){return this.operations.assertActive(),m(this,p(e,this.selection))}team(e){let t=g(this,e,e=>this.retireTeam(e));return this.teams.push(t),t.view}logger(e){return this.observation.logger(e)}diagnostics(){return this.observation.diagnostics()}close(e){if(this.closing!==void 0)return this.closing;let t=d(e),n,r;this.closing=new Promise((e,t)=>{n=e,r=t});let i=this.closing;try{let e=this.operations.beginClose({timeoutMs:this.closeTimeoutMs,...t===void 0?{}:{signal:t}});return this.observation.stopAdmission(),this.finishClose(e).then(n,r),i}catch(e){throw this.closing=void 0,e}}async finishClose(e){let t=await e;this.embeddings.dispose();let n=this.operations.closeDeadlineAt(),r=[...this.closedTeams];for(let e of[...this.teams].reverse())r.push(await e.closeForRuntime(n));for(let[e,t]of[...this.providersOwned].reverse().entries()){let i=this.providersOwned.length-e-1;this.platform.monotonicNow()>=n?r.push(y(i)):r.push(t.close({at:n,now:()=>this.platform.monotonicNow()}))}let i=this.observation.observationDeadline(n);return await this.observation.flushUntil(i),this.observation.seal(),r.push(...await this.exporters.close(i)),this.operations.finishClose(),Object.freeze({state:`closed`,...t,components:Object.freeze(r),observationHealth:this.observation.health()})}retireTeam(e){let t=this.teams.indexOf(e);t<0||(this.teams.splice(t,1),this.closedTeams.push(Object.freeze({kind:`agent-team`,id:e.id,status:`closed`})),this.closedTeams.length>1024&&this.closedTeams.shift())}};async function v(n,r=globalThis){let d=e(r),p=f(n),m=c(p.providers,p.observability.exporters,p.defaultProvider,p.signal),h=new i(d),g;try{let e=a(p.resource,d);g=new o(e,m.exporters,d,h,{mode:p.observability.mode,...p.observability.content===void 0?{}:{content:p.observability.content},...p.observability.minimumLogLevel===void 0?{}:{minimumLogLevel:p.observability.minimumLogLevel},...p.observability.processors===void 0?{}:{processors:p.observability.processors},...p.observability.redactors===void 0?{}:{redactors:p.observability.redactors},...p.observability.includeErrorStacks===void 0?{}:{includeErrorStacks:p.observability.includeErrorStacks},...p.observability.openSpan===void 0?{}:{openSpan:p.observability.openSpan},...p.observability.maxQueueEvents===void 0?{}:{maxEvents:p.observability.maxQueueEvents},...p.observability.maxQueueBytes===void 0?{}:{maxBytes:p.observability.maxQueueBytes},...p.observability.maxBatchEvents===void 0?{}:{maxBatchEvents:p.observability.maxBatchEvents},...p.observability.maxBatchBytes===void 0?{}:{maxBatchBytes:p.observability.maxBatchBytes},...p.observability.flushTimeoutMs===void 0?{}:{flushTimeoutMs:p.observability.flushTimeoutMs},...p.observability.shutdownTimeoutMs===void 0?{}:{shutdownTimeoutMs:p.observability.shutdownTimeoutMs},...p.diagnosticMaxEvents===void 0?{}:{diagnosticMaxEvents:p.diagnosticMaxEvents},...p.diagnosticMaxBytes===void 0?{}:{diagnosticMaxBytes:p.diagnosticMaxBytes}});let n=new t({observation:g,observationResource:e}),r=await l(m,n,g.logger({scope:`sdk.provider.setup`}),h,{startupTimeoutMs:p.startupTimeoutMs,rollbackTimeoutMs:p.closeTimeoutMs,...p.signal===void 0?{}:{signal:p.signal}});return new _(n,new u(h),d,h,g,e,s(m.selection),m.selection,r.providers,r.exporters,p.closeTimeoutMs,r.embeddingRegistry)}catch(e){throw g?.seal(),h.close(),e}}function y(e){return Object.freeze({kind:`provider-registration`,id:`provider-${e}`,status:`timed-out`,error:Object.freeze({code:`CAPABILITY_CLEANUP_TIMEOUT`,stage:`provider-cleanup`,message:`Provider cleanup did not start before the runtime close deadline`})})}export{_ as RuntimeCompositionOwner,v as createRuntimeCompositionOwner};
1
+ import{createRuntimePlatform as e}from"../../platform/adapter.js";import{ModelRegistry as t}from"../../runtime/registry.js";import{EmbeddingRegistry as n}from"../embedding/registry.js";import{RuntimeEmbedding as r}from"../embedding/manager.js";import{RuntimeResources as i}from"../../platform/resources.js";import{createRuntimeResource as a}from"../delivery/resource.js";import{RuntimeObservationPort as o}from"../observation/port.js";import{providerTopology as s}from"../provider/model-selection.js";import{preflightRuntimeCapabilities as c}from"../preflight.js";import{activateRuntimeCapabilities as l}from"../startup.js";import{RuntimeOperations as u}from"../lifecycle/operations.js";import{captureCloseSignal as d,captureRuntimeOwnerOptions as f}from"./config.js";import{bindRuntimeAgentDefinition as p}from"../agent/definition.js";import{createRuntimeAgent as m}from"../agent/session.js";import{RuntimeModelCatalog as h}from"../model-catalog/manager.js";import{createRuntimeAgentTeam as g}from"../team/runtime.js";var _=class{platform;resources;observation;resource;topology;selection;providersOwned;exporters;closeTimeoutMs;embeddingRegistry;registry;operations;closing;catalogs;embeddings;teams=[];closedTeams=[];constructor(e,t,i,a,o,s,c,l,u,d,f,p=new n){this.platform=i,this.resources=a,this.observation=o,this.resource=s,this.topology=c,this.selection=l,this.providersOwned=u,this.exporters=d,this.closeTimeoutMs=f,this.embeddingRegistry=p,this.registry=e,this.operations=t,this.catalogs=new h(e,t,a,c),this.embeddings=new r({registry:this.embeddingRegistry,operations:t,observation:o,resource:s})}providers(){return this.topology}modelCatalog(e,t){return this.catalogs.get(e,t)}embeddingModel(e){return this.embeddings.model(e)}agent(e){return this.operations.assertActive(),m(this,p(e,this.selection))}team(e){let t=g(this,e,e=>this.retireTeam(e));return this.teams.push(t),t.view}logger(e){return this.observation.logger(e)}diagnostics(){return this.observation.diagnostics()}close(e){if(this.closing!==void 0)return this.closing;let t=d(e),n,r;this.closing=new Promise((e,t)=>{n=e,r=t});let i=this.closing;try{let e=this.operations.beginClose({timeoutMs:this.closeTimeoutMs,...t===void 0?{}:{signal:t}});return this.observation.stopAdmission(),this.finishClose(e).then(n,r),i}catch(e){throw this.closing=void 0,e}}async finishClose(e){let t=await e;this.embeddings.dispose();let n=this.operations.closeDeadlineAt(),r=[...this.closedTeams];for(let e of[...this.teams].reverse())r.push(await e.closeForRuntime(n));for(let[e,t]of[...this.providersOwned].reverse().entries()){let i=this.providersOwned.length-e-1;this.platform.monotonicNow()>=n?r.push(y(i)):r.push(t.close({at:n,now:()=>this.platform.monotonicNow()}))}let i=this.observation.observationDeadline(n);return await this.observation.flushUntil(i),this.observation.seal(),r.push(...await this.exporters.close(i)),this.operations.finishClose(),Object.freeze({state:`closed`,...t,components:Object.freeze(r),observationHealth:this.observation.health()})}retireTeam(e){let t=this.teams.indexOf(e);t<0||(this.teams.splice(t,1),this.closedTeams.push(Object.freeze({kind:`agent-team`,id:e.id,status:`closed`})),this.closedTeams.length>1024&&this.closedTeams.shift())}};async function v(n,r=globalThis){let d=e(r),p=f(n),m=c(p.providers,p.observability.exporters,p.defaultProvider,p.signal),h=new i(d),g;try{let e=a(p.resource,d);g=new o(e,m.exporters,d,h,{mode:p.observability.mode,...p.observability.content===void 0?{}:{content:p.observability.content},...p.observability.minimumLogLevel===void 0?{}:{minimumLogLevel:p.observability.minimumLogLevel},...p.observability.processors===void 0?{}:{processors:p.observability.processors},...p.observability.redactors===void 0?{}:{redactors:p.observability.redactors},...p.observability.includeErrorStacks===void 0?{}:{includeErrorStacks:p.observability.includeErrorStacks},...p.observability.openSpan===void 0?{}:{openSpan:p.observability.openSpan},...p.observability.maxQueueEvents===void 0?{}:{maxEvents:p.observability.maxQueueEvents},...p.observability.maxQueueBytes===void 0?{}:{maxBytes:p.observability.maxQueueBytes},...p.observability.maxBatchEvents===void 0?{}:{maxBatchEvents:p.observability.maxBatchEvents},...p.observability.maxBatchBytes===void 0?{}:{maxBatchBytes:p.observability.maxBatchBytes},...p.observability.flushTimeoutMs===void 0?{}:{flushTimeoutMs:p.observability.flushTimeoutMs},...p.observability.shutdownTimeoutMs===void 0?{}:{shutdownTimeoutMs:p.observability.shutdownTimeoutMs},...p.diagnosticMaxEvents===void 0?{}:{diagnosticMaxEvents:p.diagnosticMaxEvents},...p.diagnosticMaxBytes===void 0?{}:{diagnosticMaxBytes:p.diagnosticMaxBytes}});let n=new t({observation:g,observationResource:e,...p.defaults===void 0?{}:{defaults:p.defaults}}),r=await l(m,n,g.logger({scope:`sdk.provider.setup`}),h,{startupTimeoutMs:p.startupTimeoutMs,rollbackTimeoutMs:p.closeTimeoutMs,...p.signal===void 0?{}:{signal:p.signal}});return new _(n,new u(h),d,h,g,e,s(m.selection),m.selection,r.providers,r.exporters,p.closeTimeoutMs,r.embeddingRegistry)}catch(e){throw g?.seal(),h.close(),e}}function y(e){return Object.freeze({kind:`provider-registration`,id:`provider-${e}`,status:`timed-out`,error:Object.freeze({code:`CAPABILITY_CLEANUP_TIMEOUT`,stage:`provider-cleanup`,message:`Provider cleanup did not start before the runtime close deadline`})})}export{_ as RuntimeCompositionOwner,v as createRuntimeCompositionOwner};
2
2
  //# sourceMappingURL=owner.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"owner.js","names":[],"sources":["../../../src/composition/runtime/owner.ts"],"sourcesContent":["import { ModelRegistry } from '../../runtime/registry.ts'\nimport { EmbeddingRegistry } from '../embedding/registry.ts'\nimport { RuntimeEmbedding } from '../embedding/manager.ts'\nimport type { EmbeddingModelHandle, EmbeddingModelOptions } from '../../embedding/handle.ts'\nimport { createRuntimePlatform, type RuntimePlatform } from '../../platform/adapter.ts'\nimport { RuntimeResources } from '../../platform/resources.ts'\nimport { createRuntimeResource } from '../delivery/resource.ts'\nimport { RuntimeObservationPort, type RuntimeDiagnosticSnapshot } from '../observation/port.ts'\nimport { preflightRuntimeCapabilities } from '../preflight.ts'\nimport { providerTopology } from '../provider/model-selection.ts'\nimport type { ProviderRegistration } from '../provider/activation.ts'\nimport type { RuntimeProviderInfo } from '../provider/types.ts'\nimport { activateRuntimeCapabilities } from '../startup.ts'\nimport { RuntimeOperations } from '../lifecycle/operations.ts'\nimport type { QuiescenceReport } from '../lifecycle/types.ts'\nimport type { RuntimeComponentCloseReport } from '../common/errors.ts'\nimport type { SdkLogger } from '../../logging/types.ts'\nimport type { RuntimeLoggerContext } from '../logging/logger.ts'\nimport { captureCloseSignal, captureRuntimeOwnerOptions } from './config.ts'\nimport type { RuntimeCloseReport, RuntimeCompositionView, RuntimeOwnerOptions } from './types.ts'\nimport { bindRuntimeAgentDefinition } from '../agent/definition.ts'\nimport { createRuntimeAgent } from '../agent/session.ts'\nimport type { RuntimeAgent, RuntimeAgentBindingInput } from '../agent/types.ts'\nimport type { ProviderSelection } from '../provider/types.ts'\nimport { RuntimeModelCatalog } from '../model-catalog/manager.ts'\nimport type { ModelCatalogOptions } from '../../contract/model-info.ts'\nimport type { RuntimeModelCatalogSnapshot } from '../model-catalog/types.ts'\nimport { createRuntimeAgentTeam } from '../team/runtime.ts'\nimport type { RuntimeAgentTeam, RuntimeAgentTeamOptions, RuntimeTeamRegistration } from '../team/types.ts'\n\n/** Internal composition owner used to finish lifecycle semantics before the public agent surface is exported. */\nexport class RuntimeCompositionOwner implements RuntimeCompositionView {\n readonly registry: ModelRegistry\n readonly operations: RuntimeOperations\n private closing: Promise<RuntimeCloseReport> | undefined\n private readonly catalogs: RuntimeModelCatalog\n private readonly embeddings: RuntimeEmbedding\n private readonly teams: RuntimeTeamRegistration[] = []\n private readonly closedTeams: RuntimeComponentCloseReport[] = []\n\n constructor(\n registry: ModelRegistry,\n operations: RuntimeOperations,\n private readonly platform: RuntimePlatform,\n readonly resources: RuntimeResources,\n readonly observation: RuntimeObservationPort,\n readonly resource: import('../delivery/resource.ts').RuntimeObservationResource,\n private readonly topology: readonly RuntimeProviderInfo[],\n /** Read by the agent surface so a per-invocation model override resolves against these routes. */\n readonly selection: ProviderSelection,\n private readonly providersOwned: readonly ProviderRegistration[],\n private readonly exporters: Awaited<ReturnType<typeof activateRuntimeCapabilities>>['exporters'],\n private readonly closeTimeoutMs: number,\n /**\n * Runtime-owned embedding topology. Present even with zero embedding plugins,\n * so a generation-only runtime resolves nothing rather than failing on a\n * missing registry (Requirement 11.8).\n */\n readonly embeddingRegistry: EmbeddingRegistry = new EmbeddingRegistry(),\n ) {\n this.registry = registry\n this.operations = operations\n this.catalogs = new RuntimeModelCatalog(registry, operations, resources, topology)\n // Constructed unconditionally, exactly like the catalog manager: a runtime\n // with zero embedding plugins resolves nothing and reports\n // `EMBEDDING_ADAPTER_MISSING`, which is a better answer than a missing\n // manager (Requirement 11.8). The runtime observation port and resource are\n // forwarded so every handle emits its call and batch spans into this\n // runtime's trace when the caller supplies no context of its own.\n this.embeddings = new RuntimeEmbedding({\n registry: this.embeddingRegistry, operations, observation, resource,\n })\n }\n\n providers(): readonly RuntimeProviderInfo[] { return this.topology }\n modelCatalog(route: string, options?: ModelCatalogOptions): Promise<RuntimeModelCatalogSnapshot> {\n return this.catalogs.get(route, options)\n }\n /**\n * Synchronous adapter resolution; admission is checked by the manager FIRST,\n * before any option is read, and nothing agent-shaped is constructed.\n */\n embeddingModel(options: EmbeddingModelOptions): EmbeddingModelHandle {\n return this.embeddings.model(options)\n }\n agent(input: RuntimeAgentBindingInput): RuntimeAgent {\n this.operations.assertActive()\n return createRuntimeAgent(this, bindRuntimeAgentDefinition(input, this.selection))\n }\n team(input: RuntimeAgentTeamOptions): RuntimeAgentTeam {\n const registration = createRuntimeAgentTeam(this, input, closed => this.retireTeam(closed))\n this.teams.push(registration)\n return registration.view\n }\n logger(context?: RuntimeLoggerContext): SdkLogger { return this.observation.logger(context) }\n diagnostics(): RuntimeDiagnosticSnapshot { return this.observation.diagnostics() }\n\n close(input?: { readonly signal?: AbortSignal }): Promise<RuntimeCloseReport> {\n if (this.closing !== undefined) return this.closing\n const signal = captureCloseSignal(input)\n let resolve!: (report: RuntimeCloseReport) => void\n let reject!: (error: unknown) => void\n this.closing = new Promise((done, fail) => { resolve = done; reject = fail })\n const shared = this.closing\n try {\n const quiescence = this.operations.beginClose({ timeoutMs: this.closeTimeoutMs, ...(signal === undefined ? {} : { signal }) })\n this.observation.stopAdmission()\n void this.finishClose(quiescence).then(resolve, reject)\n return shared\n } catch (error) {\n this.closing = undefined\n throw error\n }\n }\n\n private async finishClose(quiescenceTask: Promise<QuiescenceReport>): Promise<RuntimeCloseReport> {\n const quiescence = await quiescenceTask\n // Every embedding operation has settled or been abandoned by now, so the\n // remembered handles and the registry subscription behind them are dead\n // weight. Dropping them here — before provider registrations unwind — keeps\n // no handle pointing at an adapter that is about to be torn down.\n this.embeddings.dispose()\n const deadlineAt = this.operations.closeDeadlineAt()\n const components: RuntimeComponentCloseReport[] = [...this.closedTeams]\n for (const team of [...this.teams].reverse()) components.push(await team.closeForRuntime(deadlineAt))\n for (const [reverseIndex, registration] of [...this.providersOwned].reverse().entries()) {\n const originalIndex = this.providersOwned.length - reverseIndex - 1\n if (this.platform.monotonicNow() >= deadlineAt) components.push(timedOutProvider(originalIndex))\n else components.push(registration.close({ at: deadlineAt, now: () => this.platform.monotonicNow() }))\n }\n const observationDeadline = this.observation.observationDeadline(deadlineAt)\n await this.observation.flushUntil(observationDeadline)\n this.observation.seal()\n components.push(...await this.exporters.close(observationDeadline))\n this.operations.finishClose()\n return Object.freeze({ state: 'closed', ...quiescence, components: Object.freeze(components),\n observationHealth: this.observation.health() })\n }\n\n private retireTeam(registration: RuntimeTeamRegistration): void {\n const index = this.teams.indexOf(registration)\n if (index < 0) return\n this.teams.splice(index, 1)\n this.closedTeams.push(Object.freeze({ kind: 'agent-team', id: registration.id, status: 'closed' }))\n // Reporting metadata is intentionally bounded independently of heavyweight\n // team state. Older tombstones can be omitted from a later runtime report.\n if (this.closedTeams.length > 1_024) this.closedTeams.shift()\n }\n}\n\n/** Web preflight and whole-input identity validation both precede runtime-owned allocations. */\nexport async function createRuntimeCompositionOwner(\n input: RuntimeOwnerOptions,\n host: typeof globalThis = globalThis,\n): Promise<RuntimeCompositionOwner> {\n const platform = createRuntimePlatform(host)\n const options = captureRuntimeOwnerOptions(input)\n const plan = preflightRuntimeCapabilities(options.providers, options.observability.exporters,\n options.defaultProvider, options.signal)\n const resources = new RuntimeResources(platform)\n let observation: RuntimeObservationPort | undefined\n try {\n const resource = createRuntimeResource(options.resource, platform)\n observation = new RuntimeObservationPort(resource, plan.exporters, platform, resources, {\n mode: options.observability.mode,\n ...(options.observability.content === undefined ? {} : { content: options.observability.content }),\n ...(options.observability.minimumLogLevel === undefined ? {} : { minimumLogLevel: options.observability.minimumLogLevel }),\n ...(options.observability.processors === undefined ? {} : { processors: options.observability.processors }),\n ...(options.observability.redactors === undefined ? {} : { redactors: options.observability.redactors }),\n ...(options.observability.includeErrorStacks === undefined ? {} : { includeErrorStacks: options.observability.includeErrorStacks }),\n ...(options.observability.openSpan === undefined ? {} : { openSpan: options.observability.openSpan }),\n ...(options.observability.maxQueueEvents === undefined ? {} : { maxEvents: options.observability.maxQueueEvents }),\n ...(options.observability.maxQueueBytes === undefined ? {} : { maxBytes: options.observability.maxQueueBytes }),\n ...(options.observability.maxBatchEvents === undefined ? {} : { maxBatchEvents: options.observability.maxBatchEvents }),\n ...(options.observability.maxBatchBytes === undefined ? {} : { maxBatchBytes: options.observability.maxBatchBytes }),\n ...(options.observability.flushTimeoutMs === undefined ? {} : { flushTimeoutMs: options.observability.flushTimeoutMs }),\n ...(options.observability.shutdownTimeoutMs === undefined ? {} : { shutdownTimeoutMs: options.observability.shutdownTimeoutMs }),\n ...(options.diagnosticMaxEvents === undefined ? {} : { diagnosticMaxEvents: options.diagnosticMaxEvents }),\n ...(options.diagnosticMaxBytes === undefined ? {} : { diagnosticMaxBytes: options.diagnosticMaxBytes }),\n })\n const registry = new ModelRegistry({ observation, observationResource: resource })\n const capabilities = await activateRuntimeCapabilities(plan, registry,\n observation.logger({ scope: 'sdk.provider.setup' }), resources, {\n startupTimeoutMs: options.startupTimeoutMs, rollbackTimeoutMs: options.closeTimeoutMs,\n ...(options.signal === undefined ? {} : { signal: options.signal }),\n })\n return new RuntimeCompositionOwner(registry, new RuntimeOperations(resources), platform, resources,\n observation, resource, providerTopology(plan.selection), plan.selection,\n capabilities.providers, capabilities.exporters, options.closeTimeoutMs,\n capabilities.embeddingRegistry)\n } catch (error) {\n observation?.seal()\n resources.close()\n throw error\n }\n}\n\nfunction timedOutProvider(index: number): RuntimeComponentCloseReport {\n return Object.freeze({ kind: 'provider-registration', id: `provider-${index}`, status: 'timed-out',\n error: Object.freeze({ code: 'CAPABILITY_CLEANUP_TIMEOUT', stage: 'provider-cleanup',\n message: 'Provider cleanup did not start before the runtime close deadline' }) })\n}\n"],"mappings":"2/BA+BA,IAAa,EAAb,KAAuE,CAYlD,SACR,UACA,YACA,SACQ,SAER,UACQ,eACA,UACA,eAMR,kBA1BX,SACA,WACA,QACA,SACA,WACA,MAAoD,CAAC,EACrD,YAA8D,CAAC,EAE/D,YACE,EACA,EACA,EACA,EACA,EACA,EACA,EAEA,EACA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AAC,CACtF"}
1
+ {"version":3,"file":"owner.js","names":[],"sources":["../../../src/composition/runtime/owner.ts"],"sourcesContent":["import { ModelRegistry } from '../../runtime/registry.ts'\nimport { EmbeddingRegistry } from '../embedding/registry.ts'\nimport { RuntimeEmbedding } from '../embedding/manager.ts'\nimport type { EmbeddingModelHandle, EmbeddingModelOptions } from '../../embedding/handle.ts'\nimport { createRuntimePlatform, type RuntimePlatform } from '../../platform/adapter.ts'\nimport { RuntimeResources } from '../../platform/resources.ts'\nimport { createRuntimeResource } from '../delivery/resource.ts'\nimport { RuntimeObservationPort, type RuntimeDiagnosticSnapshot } from '../observation/port.ts'\nimport { preflightRuntimeCapabilities } from '../preflight.ts'\nimport { providerTopology } from '../provider/model-selection.ts'\nimport type { ProviderRegistration } from '../provider/activation.ts'\nimport type { RuntimeProviderInfo } from '../provider/types.ts'\nimport { activateRuntimeCapabilities } from '../startup.ts'\nimport { RuntimeOperations } from '../lifecycle/operations.ts'\nimport type { QuiescenceReport } from '../lifecycle/types.ts'\nimport type { RuntimeComponentCloseReport } from '../common/errors.ts'\nimport type { SdkLogger } from '../../logging/types.ts'\nimport type { RuntimeLoggerContext } from '../logging/logger.ts'\nimport { captureCloseSignal, captureRuntimeOwnerOptions } from './config.ts'\nimport type { RuntimeCloseReport, RuntimeCompositionView, RuntimeOwnerOptions } from './types.ts'\nimport { bindRuntimeAgentDefinition } from '../agent/definition.ts'\nimport { createRuntimeAgent } from '../agent/session.ts'\nimport type { RuntimeAgent, RuntimeAgentBindingInput } from '../agent/types.ts'\nimport type { ProviderSelection } from '../provider/types.ts'\nimport { RuntimeModelCatalog } from '../model-catalog/manager.ts'\nimport type { ModelCatalogOptions } from '../../contract/model-info.ts'\nimport type { RuntimeModelCatalogSnapshot } from '../model-catalog/types.ts'\nimport { createRuntimeAgentTeam } from '../team/runtime.ts'\nimport type { RuntimeAgentTeam, RuntimeAgentTeamOptions, RuntimeTeamRegistration } from '../team/types.ts'\n\n/** Internal composition owner used to finish lifecycle semantics before the public agent surface is exported. */\nexport class RuntimeCompositionOwner implements RuntimeCompositionView {\n readonly registry: ModelRegistry\n readonly operations: RuntimeOperations\n private closing: Promise<RuntimeCloseReport> | undefined\n private readonly catalogs: RuntimeModelCatalog\n private readonly embeddings: RuntimeEmbedding\n private readonly teams: RuntimeTeamRegistration[] = []\n private readonly closedTeams: RuntimeComponentCloseReport[] = []\n\n constructor(\n registry: ModelRegistry,\n operations: RuntimeOperations,\n private readonly platform: RuntimePlatform,\n readonly resources: RuntimeResources,\n readonly observation: RuntimeObservationPort,\n readonly resource: import('../delivery/resource.ts').RuntimeObservationResource,\n private readonly topology: readonly RuntimeProviderInfo[],\n /** Read by the agent surface so a per-invocation model override resolves against these routes. */\n readonly selection: ProviderSelection,\n private readonly providersOwned: readonly ProviderRegistration[],\n private readonly exporters: Awaited<ReturnType<typeof activateRuntimeCapabilities>>['exporters'],\n private readonly closeTimeoutMs: number,\n /**\n * Runtime-owned embedding topology. Present even with zero embedding plugins,\n * so a generation-only runtime resolves nothing rather than failing on a\n * missing registry (Requirement 11.8).\n */\n readonly embeddingRegistry: EmbeddingRegistry = new EmbeddingRegistry(),\n ) {\n this.registry = registry\n this.operations = operations\n this.catalogs = new RuntimeModelCatalog(registry, operations, resources, topology)\n // Constructed unconditionally, exactly like the catalog manager: a runtime\n // with zero embedding plugins resolves nothing and reports\n // `EMBEDDING_ADAPTER_MISSING`, which is a better answer than a missing\n // manager (Requirement 11.8). The runtime observation port and resource are\n // forwarded so every handle emits its call and batch spans into this\n // runtime's trace when the caller supplies no context of its own.\n this.embeddings = new RuntimeEmbedding({\n registry: this.embeddingRegistry, operations, observation, resource,\n })\n }\n\n providers(): readonly RuntimeProviderInfo[] { return this.topology }\n modelCatalog(route: string, options?: ModelCatalogOptions): Promise<RuntimeModelCatalogSnapshot> {\n return this.catalogs.get(route, options)\n }\n /**\n * Synchronous adapter resolution; admission is checked by the manager FIRST,\n * before any option is read, and nothing agent-shaped is constructed.\n */\n embeddingModel(options: EmbeddingModelOptions): EmbeddingModelHandle {\n return this.embeddings.model(options)\n }\n agent(input: RuntimeAgentBindingInput): RuntimeAgent {\n this.operations.assertActive()\n return createRuntimeAgent(this, bindRuntimeAgentDefinition(input, this.selection))\n }\n team(input: RuntimeAgentTeamOptions): RuntimeAgentTeam {\n const registration = createRuntimeAgentTeam(this, input, closed => this.retireTeam(closed))\n this.teams.push(registration)\n return registration.view\n }\n logger(context?: RuntimeLoggerContext): SdkLogger { return this.observation.logger(context) }\n diagnostics(): RuntimeDiagnosticSnapshot { return this.observation.diagnostics() }\n\n close(input?: { readonly signal?: AbortSignal }): Promise<RuntimeCloseReport> {\n if (this.closing !== undefined) return this.closing\n const signal = captureCloseSignal(input)\n let resolve!: (report: RuntimeCloseReport) => void\n let reject!: (error: unknown) => void\n this.closing = new Promise((done, fail) => { resolve = done; reject = fail })\n const shared = this.closing\n try {\n const quiescence = this.operations.beginClose({ timeoutMs: this.closeTimeoutMs, ...(signal === undefined ? {} : { signal }) })\n this.observation.stopAdmission()\n void this.finishClose(quiescence).then(resolve, reject)\n return shared\n } catch (error) {\n this.closing = undefined\n throw error\n }\n }\n\n private async finishClose(quiescenceTask: Promise<QuiescenceReport>): Promise<RuntimeCloseReport> {\n const quiescence = await quiescenceTask\n // Every embedding operation has settled or been abandoned by now, so the\n // remembered handles and the registry subscription behind them are dead\n // weight. Dropping them here — before provider registrations unwind — keeps\n // no handle pointing at an adapter that is about to be torn down.\n this.embeddings.dispose()\n const deadlineAt = this.operations.closeDeadlineAt()\n const components: RuntimeComponentCloseReport[] = [...this.closedTeams]\n for (const team of [...this.teams].reverse()) components.push(await team.closeForRuntime(deadlineAt))\n for (const [reverseIndex, registration] of [...this.providersOwned].reverse().entries()) {\n const originalIndex = this.providersOwned.length - reverseIndex - 1\n if (this.platform.monotonicNow() >= deadlineAt) components.push(timedOutProvider(originalIndex))\n else components.push(registration.close({ at: deadlineAt, now: () => this.platform.monotonicNow() }))\n }\n const observationDeadline = this.observation.observationDeadline(deadlineAt)\n await this.observation.flushUntil(observationDeadline)\n this.observation.seal()\n components.push(...await this.exporters.close(observationDeadline))\n this.operations.finishClose()\n return Object.freeze({ state: 'closed', ...quiescence, components: Object.freeze(components),\n observationHealth: this.observation.health() })\n }\n\n private retireTeam(registration: RuntimeTeamRegistration): void {\n const index = this.teams.indexOf(registration)\n if (index < 0) return\n this.teams.splice(index, 1)\n this.closedTeams.push(Object.freeze({ kind: 'agent-team', id: registration.id, status: 'closed' }))\n // Reporting metadata is intentionally bounded independently of heavyweight\n // team state. Older tombstones can be omitted from a later runtime report.\n if (this.closedTeams.length > 1_024) this.closedTeams.shift()\n }\n}\n\n/** Web preflight and whole-input identity validation both precede runtime-owned allocations. */\nexport async function createRuntimeCompositionOwner(\n input: RuntimeOwnerOptions,\n host: typeof globalThis = globalThis,\n): Promise<RuntimeCompositionOwner> {\n const platform = createRuntimePlatform(host)\n const options = captureRuntimeOwnerOptions(input)\n const plan = preflightRuntimeCapabilities(options.providers, options.observability.exporters,\n options.defaultProvider, options.signal)\n const resources = new RuntimeResources(platform)\n let observation: RuntimeObservationPort | undefined\n try {\n const resource = createRuntimeResource(options.resource, platform)\n observation = new RuntimeObservationPort(resource, plan.exporters, platform, resources, {\n mode: options.observability.mode,\n ...(options.observability.content === undefined ? {} : { content: options.observability.content }),\n ...(options.observability.minimumLogLevel === undefined ? {} : { minimumLogLevel: options.observability.minimumLogLevel }),\n ...(options.observability.processors === undefined ? {} : { processors: options.observability.processors }),\n ...(options.observability.redactors === undefined ? {} : { redactors: options.observability.redactors }),\n ...(options.observability.includeErrorStacks === undefined ? {} : { includeErrorStacks: options.observability.includeErrorStacks }),\n ...(options.observability.openSpan === undefined ? {} : { openSpan: options.observability.openSpan }),\n ...(options.observability.maxQueueEvents === undefined ? {} : { maxEvents: options.observability.maxQueueEvents }),\n ...(options.observability.maxQueueBytes === undefined ? {} : { maxBytes: options.observability.maxQueueBytes }),\n ...(options.observability.maxBatchEvents === undefined ? {} : { maxBatchEvents: options.observability.maxBatchEvents }),\n ...(options.observability.maxBatchBytes === undefined ? {} : { maxBatchBytes: options.observability.maxBatchBytes }),\n ...(options.observability.flushTimeoutMs === undefined ? {} : { flushTimeoutMs: options.observability.flushTimeoutMs }),\n ...(options.observability.shutdownTimeoutMs === undefined ? {} : { shutdownTimeoutMs: options.observability.shutdownTimeoutMs }),\n ...(options.diagnosticMaxEvents === undefined ? {} : { diagnosticMaxEvents: options.diagnosticMaxEvents }),\n ...(options.diagnosticMaxBytes === undefined ? {} : { diagnosticMaxBytes: options.diagnosticMaxBytes }),\n })\n const registry = new ModelRegistry({ observation, observationResource: resource,\n ...(options.defaults === undefined ? {} : { defaults: options.defaults }) })\n const capabilities = await activateRuntimeCapabilities(plan, registry,\n observation.logger({ scope: 'sdk.provider.setup' }), resources, {\n startupTimeoutMs: options.startupTimeoutMs, rollbackTimeoutMs: options.closeTimeoutMs,\n ...(options.signal === undefined ? {} : { signal: options.signal }),\n })\n return new RuntimeCompositionOwner(registry, new RuntimeOperations(resources), platform, resources,\n observation, resource, providerTopology(plan.selection), plan.selection,\n capabilities.providers, capabilities.exporters, options.closeTimeoutMs,\n capabilities.embeddingRegistry)\n } catch (error) {\n observation?.seal()\n resources.close()\n throw error\n }\n}\n\nfunction timedOutProvider(index: number): RuntimeComponentCloseReport {\n return Object.freeze({ kind: 'provider-registration', id: `provider-${index}`, status: 'timed-out',\n error: Object.freeze({ code: 'CAPABILITY_CLEANUP_TIMEOUT', stage: 'provider-cleanup',\n message: 'Provider cleanup did not start before the runtime close deadline' }) })\n}\n"],"mappings":"2/BA+BA,IAAa,EAAb,KAAuE,CAYlD,SACR,UACA,YACA,SACQ,SAER,UACQ,eACA,UACA,eAMR,kBA1BX,SACA,WACA,QACA,SACA,WACA,MAAoD,CAAC,EACrD,YAA8D,CAAC,EAE/D,YACE,EACA,EACA,EACA,EACA,EACA,EACA,EAEA,EACA,EACA,EACA,EAMA,EAAgD,IAAI,EACpD,CAhBiB,KAAA,S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kEAAmE,CAAC,CAAE,CAAC,CACtF"}
@@ -2,7 +2,7 @@ import { JsonObject } from "../../primitives/json.js";
2
2
  import { ObservationResourceInput } from "../../observation/event.js";
3
3
  import { DeliveryMode, ObservationSpan, OpenObservationSpanInput } from "../../observation/port.js";
4
4
  import { LogLevel, SdkLogger } from "../../logging/types.js";
5
- import { ModelCatalogOptions } from "../../contract/model-info.js";
5
+ import { ModelCatalogOptions, RuntimeDefaults } from "../../contract/model-info.js";
6
6
  import { RuntimeProviderInfo } from "../provider/types.js";
7
7
  import { RuntimeObservationExporterRegistration } from "../exporter/types.js";
8
8
  import { ContentRedactor, ObservationProcessor } from "../../observation/telemetry-types.js";
@@ -45,6 +45,12 @@ interface RuntimeOwnerOptions {
45
45
  */
46
46
  readonly providers: readonly ComposableRuntimeProviderPlugin[];
47
47
  readonly defaultProvider?: string;
48
+ /**
49
+ * SDK-wide fallbacks (context window, output cap, accepted modalities) for
50
+ * every route this runtime owns, used only when neither a model nor its
51
+ * route names a value. See {@link RuntimeDefaults}.
52
+ */
53
+ readonly defaults?: RuntimeDefaults;
48
54
  readonly signal?: AbortSignal;
49
55
  readonly resource?: RuntimeObservationResourceInput;
50
56
  readonly observability?: RuntimeOwnerObservabilityOptions;
@@ -1 +1 @@
1
- {"version":3,"file":"types.d.ts","names":[],"sources":["../../../src/composition/runtime/types.ts"],"mappings":";;;;;;;;;;;;;;;;;;UAkBiB;WACN,OAAO;WACP;WACA,kBAAkB;WAClB,qBAAqB;WACrB,sBAAsB;WACtB,qBAAqB;WACrB;WACA,YAAY,OAAO,6BAA6B;WAChD;WACA;WACA;WACA;WACA;WACA;;UAGM,wCAAwC;;UAGxC;;;;;;;;;WASN,oBAAoB;WACpB;WACA,SAAS;WACT,WAAW;WACX,gBAAgB;WAChB;WACA;WACA;WACA;;UAGM;WACN;WACA;WACA;WACA;WACA;WACA;WACA,qBAAqB;WACrB,qBAAqB;WACrB,mBAAmB;;UAGb;EACf,sBAAsB;EACtB,aAAa,eAAe,UAAU,sBAAsB,QAAQ;;;;;;;;;;;;;EAapE,eAAe,SAAS,wBAAwB;EAChD,MAAM,YAAY,2BAA2B;EAC7C,KAAK,SAAS,0BAA0B;EACxC,OAAO;aAAqB;aAAyB,SAAS,SAAS;MAAgB;EACvF,eAAe;EACf,MAAM;aAAqB,SAAS;MAAgB,QAAQ;;UAG7C,qBAAqB;UACrB,4BAA4B;KACjC,qBAAqB"}
1
+ {"version":3,"file":"types.d.ts","names":[],"sources":["../../../src/composition/runtime/types.ts"],"mappings":";;;;;;;;;;;;;;;;;;UAmBiB;WACN,OAAO;WACP;WACA,kBAAkB;WAClB,qBAAqB;WACrB,sBAAsB;WACtB,qBAAqB;WACrB;WACA,YAAY,OAAO,6BAA6B;WAChD;WACA;WACA;WACA;WACA;WACA;;UAGM,wCAAwC;;UAGxC;;;;;;;;;WASN,oBAAoB;WACpB;;;;;;WAMA,WAAW;WACX,SAAS;WACT,WAAW;WACX,gBAAgB;WAChB;WACA;WACA;WACA;;UAGM;WACN;WACA;WACA;WACA;WACA;WACA;WACA,qBAAqB;WACrB,qBAAqB;WACrB,mBAAmB;;UAGb;EACf,sBAAsB;EACtB,aAAa,eAAe,UAAU,sBAAsB,QAAQ;;;;;;;;;;;;;EAapE,eAAe,SAAS,wBAAwB;EAChD,MAAM,YAAY,2BAA2B;EAC7C,KAAK,SAAS,0BAA0B;EACxC,OAAO;aAAqB;aAAyB,SAAS,SAAS;MAAgB;EACvF,eAAe;EACf,MAAM;aAAqB,SAAS;MAAgB,QAAQ;;UAG7C,qBAAqB;UACrB,4BAA4B;KACjC,qBAAqB"}
@@ -1,7 +1,7 @@
1
1
  import { StreamChunk } from "../stream/chunk.js";
2
2
  import { ModelInvocationContext } from "../observation/report.js";
3
- import { GenerateOptions } from "./generate-options.js";
4
3
  import { ModelCatalogOptions, ModelCatalogSnapshot, ModelInfo, ProviderInfo, ResolvedModelInfo } from "./model-info.js";
4
+ import { GenerateOptions } from "./generate-options.js";
5
5
  import { ResolvedRetryPolicy } from "./retry-policy.js";
6
6
  //#region src/contract/adapter.d.ts
7
7
  /**
@@ -1,4 +1,5 @@
1
1
  import { ReasoningEffortId } from "../primitives/brand.js";
2
+ import { ModelModality } from "./model-info.js";
2
3
  //#region src/contract/call-config.d.ts
3
4
  /**
4
5
  * Route, model, effort, and sampling scalars of one request. Every field maps
@@ -12,6 +13,10 @@ interface CallConfig {
12
13
  topP?: number;
13
14
  maxTokens?: number;
14
15
  stop?: readonly string[];
16
+ /** Overrides the model/route/runtime-defaults tiers, same precedence as `maxTokens`. */
17
+ contextWindow?: number;
18
+ /** Overrides the model/route/runtime-defaults tiers, same precedence as `maxTokens`. */
19
+ inputModalities?: readonly ModelModality[];
15
20
  }
16
21
  /**
17
22
  * Which effective config fields came from adapter resolution rather than from
@@ -19,9 +24,11 @@ interface CallConfig {
19
24
  *
20
25
  * Reported so a caller can tell "I chose 4096 output tokens" from "the adapter
21
26
  * chose 4096 for me", which matters when surfacing effective settings.
27
+ *
28
+ * `reasoningEffort` has no entry here: effort is pure pass-through, so the
29
+ * registry never materializes one the caller omitted.
22
30
  */
23
31
  interface CallConfigAdapterDefaults {
24
- reasoningEffort?: true;
25
32
  maxTokens?: true;
26
33
  }
27
34
  /**
@@ -1 +1 @@
1
- {"version":3,"file":"call-config.d.ts","names":[],"sources":["../../src/contract/call-config.ts"],"mappings":";;;;;;UAiBiB;EACf;EACA;EACA,kBAAkB;EAClB;EACA;EACA;EACA;;;;;;;;;UAUe;EACf;EACA;;;;;;;;iBASc,iBAAiB,GAAG,YAAY,GAAG"}
1
+ {"version":3,"file":"call-config.d.ts","names":[],"sources":["../../src/contract/call-config.ts"],"mappings":";;;;;;;UAkBiB;EACf;EACA;EACA,kBAAkB;EAClB;EACA;EACA;EACA;;EAEA;;EAEA,2BAA2B;;;;;;;;;;;;UAaZ;EACf;;;;;;;;iBASc,iBAAiB,GAAG,YAAY,GAAG"}
@@ -1,2 +1,2 @@
1
- function e(e,t){return e.provider!==t.provider||e.model!==t.model||e.reasoningEffort!==t.reasoningEffort||e.temperature!==t.temperature||e.topP!==t.topP||e.maxTokens!==t.maxTokens?!1:e.stop===void 0||t.stop===void 0?e.stop===t.stop:e.stop.length===t.stop.length&&e.stop.every((e,n)=>e===t.stop?.[n])}export{e as callConfigEquals};
1
+ function e(e,t){if(e.provider!==t.provider||e.model!==t.model||e.reasoningEffort!==t.reasoningEffort||e.temperature!==t.temperature||e.topP!==t.topP||e.maxTokens!==t.maxTokens||e.contextWindow!==t.contextWindow)return!1;if(e.stop===void 0||t.stop===void 0){if(e.stop!==t.stop)return!1}else if(e.stop.length!==t.stop.length||!e.stop.every((e,n)=>e===t.stop?.[n]))return!1;return e.inputModalities===void 0||t.inputModalities===void 0?e.inputModalities===t.inputModalities:e.inputModalities.length===t.inputModalities.length&&e.inputModalities.every((e,n)=>e===t.inputModalities?.[n])}export{e as callConfigEquals};
2
2
  //# sourceMappingURL=call-config.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"call-config.js","names":[],"sources":["../../src/contract/call-config.ts"],"sourcesContent":["/**\n * The subset of a request that behaves like connection state rather than\n * per-message content: route, model, effort, and sampling scalars.\n *\n * Isolating these is what makes the prepare/dispatch split in the registry\n * meaningful  Ethe registry can prove that the configuration it resolved\n * capabilities against is the same one being dispatched.\n *\n * @module ai-agent-sdk/core/contract/call-config\n */\n\nimport type { ReasoningEffortId } from '../primitives/brand.ts'\n\n/**\n * Route, model, effort, and sampling scalars of one request. Every field maps\n * 1:1 onto the same-named {@link GenerateOptions} field.\n */\nexport interface CallConfig {\n provider: string\n model: string\n reasoningEffort?: ReasoningEffortId\n temperature?: number\n topP?: number\n maxTokens?: number\n stop?: readonly string[]\n}\n\n/**\n * Which effective config fields came from adapter resolution rather than from\n * the caller's request.\n *\n * Reported so a caller can tell \"I chose 4096 output tokens\" from \"the adapter\n * chose 4096 for me\", which matters when surfacing effective settings.\n */\nexport interface CallConfigAdapterDefaults {\n reasoningEffort?: true\n maxTokens?: true\n}\n\n/**\n * Field-wise equality over {@link CallConfig}.\n * @param a - one configuration.\n * @param b - the other.\n * @returns whether every field matches, comparing `stop` element-wise.\n */\nexport function callConfigEquals(a: CallConfig, b: CallConfig): boolean {\n if (\n a.provider !== b.provider\n || a.model !== b.model\n || a.reasoningEffort !== b.reasoningEffort\n || a.temperature !== b.temperature\n || a.topP !== b.topP\n || a.maxTokens !== b.maxTokens\n ) return false\n if (a.stop === undefined || b.stop === undefined) return a.stop === b.stop\n return a.stop.length === b.stop.length && a.stop.every((value, index) => value === b.stop?.[index])\n}\n"],"mappings":"AA6CA,SAAgB,EAAiB,EAAe,EAAwB,CAUtE,OARE,EAAE,WAAa,EAAE,UACd,EAAE,QAAU,EAAE,OACd,EAAE,kBAAoB,EAAE,iBACxB,EAAE,cAAgB,EAAE,aACpB,EAAE,OAAS,EAAE,MACb,EAAE,YAAc,EAAE,UACd,GACL,EAAE,OAAS,IAAA,IAAa,EAAE,OAAS,IAAA,GAAkB,EAAE,OAAS,EAAE,KAC/D,EAAE,KAAK,SAAW,EAAE,KAAK,QAAU,EAAE,KAAK,OAAO,EAAO,IAAU,IAAU,EAAE,OAAO,EAAM,CACpG"}
1
+ {"version":3,"file":"call-config.js","names":[],"sources":["../../src/contract/call-config.ts"],"sourcesContent":["/**\n * The subset of a request that behaves like connection state rather than\n * per-message content: route, model, effort, and sampling scalars.\n *\n * Isolating these is what makes the prepare/dispatch split in the registry\n * meaningful  Ethe registry can prove that the configuration it resolved\n * capabilities against is the same one being dispatched.\n *\n * @module ai-agent-sdk/core/contract/call-config\n */\n\nimport type { ReasoningEffortId } from '../primitives/brand.ts'\nimport type { ModelModality } from './model-info.ts'\n\n/**\n * Route, model, effort, and sampling scalars of one request. Every field maps\n * 1:1 onto the same-named {@link GenerateOptions} field.\n */\nexport interface CallConfig {\n provider: string\n model: string\n reasoningEffort?: ReasoningEffortId\n temperature?: number\n topP?: number\n maxTokens?: number\n stop?: readonly string[]\n /** Overrides the model/route/runtime-defaults tiers, same precedence as `maxTokens`. */\n contextWindow?: number\n /** Overrides the model/route/runtime-defaults tiers, same precedence as `maxTokens`. */\n inputModalities?: readonly ModelModality[]\n}\n\n/**\n * Which effective config fields came from adapter resolution rather than from\n * the caller's request.\n *\n * Reported so a caller can tell \"I chose 4096 output tokens\" from \"the adapter\n * chose 4096 for me\", which matters when surfacing effective settings.\n *\n * `reasoningEffort` has no entry here: effort is pure pass-through, so the\n * registry never materializes one the caller omitted.\n */\nexport interface CallConfigAdapterDefaults {\n maxTokens?: true\n}\n\n/**\n * Field-wise equality over {@link CallConfig}.\n * @param a - one configuration.\n * @param b - the other.\n * @returns whether every field matches, comparing `stop` element-wise.\n */\nexport function callConfigEquals(a: CallConfig, b: CallConfig): boolean {\n if (\n a.provider !== b.provider\n || a.model !== b.model\n || a.reasoningEffort !== b.reasoningEffort\n || a.temperature !== b.temperature\n || a.topP !== b.topP\n || a.maxTokens !== b.maxTokens\n || a.contextWindow !== b.contextWindow\n ) return false\n if (a.stop === undefined || b.stop === undefined) {\n if (a.stop !== b.stop) return false\n } else if (a.stop.length !== b.stop.length || !a.stop.every((value, index) => value === b.stop?.[index])) {\n return false\n }\n if (a.inputModalities === undefined || b.inputModalities === undefined) return a.inputModalities === b.inputModalities\n return a.inputModalities.length === b.inputModalities.length\n && a.inputModalities.every((value, index) => value === b.inputModalities?.[index])\n}\n"],"mappings":"AAoDA,SAAgB,EAAiB,EAAe,EAAwB,CACtE,GACE,EAAE,WAAa,EAAE,UACd,EAAE,QAAU,EAAE,OACd,EAAE,kBAAoB,EAAE,iBACxB,EAAE,cAAgB,EAAE,aACpB,EAAE,OAAS,EAAE,MACb,EAAE,YAAc,EAAE,WAClB,EAAE,gBAAkB,EAAE,cACzB,MAAO,GACT,GAAI,EAAE,OAAS,IAAA,IAAa,EAAE,OAAS,IAAA,GACjC,IAAA,EAAE,OAAS,EAAE,KAAM,MAAO,EAAA,MACzB,GAAI,EAAE,KAAK,SAAW,EAAE,KAAK,QAAU,CAAC,EAAE,KAAK,OAAO,EAAO,IAAU,IAAU,EAAE,OAAO,EAAM,EACrG,MAAO,GAGT,OADI,EAAE,kBAAoB,IAAA,IAAa,EAAE,kBAAoB,IAAA,GAAkB,EAAE,kBAAoB,EAAE,gBAChG,EAAE,gBAAgB,SAAW,EAAE,gBAAgB,QACjD,EAAE,gBAAgB,OAAO,EAAO,IAAU,IAAU,EAAE,kBAAkB,EAAM,CACrF"}
@@ -2,6 +2,7 @@ import { ReasoningEffortId } from "../primitives/brand.js";
2
2
  import { Message } from "../message/message.js";
3
3
  import { ModelToolSchema, ToolChoice } from "./tool.js";
4
4
  import { ModelOutputFormat } from "./output-format.js";
5
+ import { ModelModality } from "./model-info.js";
5
6
  //#region src/contract/generate-options.d.ts
6
7
  /** One fully assembled model request. */
7
8
  interface GenerateOptions {
@@ -36,6 +37,10 @@ interface GenerateOptions {
36
37
  maxTokens?: number;
37
38
  /** Stop sequences; generation halts on any of them, and the string is excluded from output. */
38
39
  stop?: readonly string[];
40
+ /** Overrides the model/route/runtime-defaults tiers, same precedence as `maxTokens`. */
41
+ contextWindow?: number;
42
+ /** Overrides the model/route/runtime-defaults tiers, same precedence as `maxTokens`. */
43
+ inputModalities?: readonly ModelModality[];
39
44
  signal?: AbortSignal;
40
45
  }
41
46
  //#endregion
@@ -1 +1 @@
1
- {"version":3,"file":"generate-options.d.ts","names":[],"sources":["../../src/contract/generate-options.ts"],"mappings":";;;;;;UAYiB;;WAEN;;WAEA;;EAET;;;;;;;;EAQA;;EAEA,kBAAkB;;EAElB,mBAAmB;;EAEnB;;EAEA,iBAAiB;;EAEjB,aAAa;;EAEb,eAAe;EACf;EACA;EACA;;EAEA;EACA,SAAS"}
1
+ {"version":3,"file":"generate-options.d.ts","names":[],"sources":["../../src/contract/generate-options.ts"],"mappings":";;;;;;;UAaiB;;WAEN;;WAEA;;EAET;;;;;;;;EAQA;;EAEA,kBAAkB;;EAElB,mBAAmB;;EAEnB;;EAEA,iBAAiB;;EAEjB,aAAa;;EAEb,eAAe;EACf;EACA;EACA;;EAEA;;EAEA;;EAEA,2BAA2B;EAC3B,SAAS"}