@alvin0/ai-agent-sdk-core 0.1.6 → 0.1.7
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +6 -1
- package/dist/agent/define/session.d.ts +5 -2
- package/dist/agent/define/session.d.ts.map +1 -1
- package/dist/agent/define/session.js +1 -1
- package/dist/agent/define/session.js.map +1 -1
- package/dist/agent/history/input-work.js +2 -0
- package/dist/agent/history/input-work.js.map +1 -0
- package/dist/agent/loop/control-text.d.ts +6 -0
- package/dist/agent/loop/control-text.d.ts.map +1 -0
- package/dist/agent/loop/control-text.js +2 -0
- package/dist/agent/loop/control-text.js.map +1 -0
- package/dist/agent/loop/run-turn.js +1 -1
- package/dist/agent/loop/run-turn.js.map +1 -1
- package/dist/agent/loop/turn/model-round.js +1 -1
- package/dist/agent/loop/turn/model-round.js.map +1 -1
- package/dist/agent/mode/run-agent.d.ts +8 -15
- package/dist/agent/mode/run-agent.d.ts.map +1 -1
- package/dist/agent/mode/run-agent.js +2 -2
- package/dist/agent/mode/run-agent.js.map +1 -1
- package/dist/agent/team/contracts.d.ts +3 -1
- package/dist/agent/team/contracts.d.ts.map +1 -1
- package/dist/agent/team/managed.d.ts.map +1 -1
- package/dist/agent/team/managed.js +5 -5
- package/dist/agent/team/managed.js.map +1 -1
- package/dist/agent/team/team.d.ts.map +1 -1
- package/dist/agent/team/team.js +1 -1
- package/dist/agent/team/team.js.map +1 -1
- package/dist/agent/tool/pipeline.js +1 -1
- package/dist/agent/tool/pipeline.js.map +1 -1
- package/dist/agent.d.ts +2 -1
- package/dist/agent.js +1 -1
- package/dist/composition/agent/session.js +1 -1
- package/dist/composition/agent/session.js.map +1 -1
- package/dist/composition/agent/types.d.ts +3 -1
- package/dist/composition/agent/types.d.ts.map +1 -1
- package/dist/observability/bus.js +1 -1
- package/dist/primitives/version.d.ts +1 -1
- package/dist/primitives/version.js +1 -1
- package/dist/primitives/version.js.map +1 -1
- package/dist/runtime/registry.js +1 -1
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -51,7 +51,7 @@ The documented root plus `/agent`, `/memory`, `/observability`, `/provider`,
|
|
|
51
51
|
`/skills`, `/tools`, `/embedding`, and `./package.json` are public. Internal source paths are
|
|
52
52
|
not compatibility contracts.
|
|
53
53
|
|
|
54
|
-
Opt-in optimization helpers added in 0.1.5
|
|
54
|
+
Opt-in optimization helpers added in 0.1.5 include `defineActionFusion` and
|
|
55
55
|
`createModelEvidenceReducer` from `/tools`, and `createContextOptimizer` from
|
|
56
56
|
`/memory`. Applications select pipeline steps, milestone summaries, log storage,
|
|
57
57
|
and reducer models. See the [application guide](https://github.com/alvin0/ai-agent-sdk/blob/main/docs/context-optimization.md)
|
|
@@ -62,3 +62,8 @@ Existing agent, tool, and session imports remain available. Review the
|
|
|
62
62
|
for narration defaults, queued steering receipts, and managed-team validation
|
|
63
63
|
changes after the published 0.1.4 release. Program tools additionally require
|
|
64
64
|
session-level `experimentalPrograms` grants; ordinary tools do not.
|
|
65
|
+
|
|
66
|
+
For 0.1.7 completion, pending input, stream replacement and Stop behavior, see
|
|
67
|
+
the [upgrade guide](https://github.com/alvin0/ai-agent-sdk/blob/main/docs/upgrading-from-0.1.6.md).
|
|
68
|
+
`RuntimeAgentSession.hasUnansweredInput()` and `runPending()` expose work left
|
|
69
|
+
after a terminal round. Use `response.completed` for objective completion.
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { History } from "../history/history.js";
|
|
2
|
+
import { AgentRunOutcome } from "../mode/run-agent.js";
|
|
2
3
|
import { CompactionResult } from "../memory/compaction.js";
|
|
3
4
|
import { AgentMemory } from "../memory/memory.js";
|
|
4
5
|
import { SkillCatalog } from "../skill/catalog.js";
|
|
@@ -31,6 +32,7 @@ declare class AgentSession {
|
|
|
31
32
|
* then read "steer, then the work that ignored it" as work that answered it.
|
|
32
33
|
*/
|
|
33
34
|
private pendingInjections;
|
|
35
|
+
private lastRunOutcome;
|
|
34
36
|
/**
|
|
35
37
|
* A model request has been built and its output is not yet fully recorded.
|
|
36
38
|
* Only then is an injection held: hooks and team notices that inject between
|
|
@@ -83,11 +85,12 @@ declare class AgentSession {
|
|
|
83
85
|
/** Deliver held injections, in arrival order, at the chronological tail. */
|
|
84
86
|
private drainInjections;
|
|
85
87
|
/**
|
|
86
|
-
* Whether
|
|
87
|
-
*
|
|
88
|
+
* Whether attributed input or a tool result still awaits the model. App
|
|
89
|
+
* notices do not create work, except managed-team coordination. False once the model has answered everything,
|
|
88
90
|
* which lets a scheduler skip a run that would only repeat that answer.
|
|
89
91
|
*/
|
|
90
92
|
hasUnansweredInput(): boolean;
|
|
93
|
+
lastOutcome(): AgentRunOutcome | undefined;
|
|
91
94
|
/** Resolve after the current run releases the session. */
|
|
92
95
|
whenIdle(signal?: AbortSignal): Promise<void>;
|
|
93
96
|
/** Start an eager run and expose both public events and its canonical terminal report. */
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"session.d.ts","names":[],"sources":["../../../src/agent/define/session.ts"],"mappings":"
|
|
1
|
+
{"version":3,"file":"session.d.ts","names":[],"sources":["../../../src/agent/define/session.ts"],"mappings":";;;;;;;;cAqDa;WACF,YAAY;mBACJ;mBACA;UACT;mBACS;mBACA;;mBAEA;UACT;UACA;UACA;UACA;UACA;UACA;UACA;;UAEA;mBACS;;;;;;;UAOT;UACA;;;;;;UAMA;;UAEA;EAER,YAAY,YAAY,iBAAiB,SAAS;;SA0F3C,aACL,YAAY,iBACZ,SAAS,4BACR;;MAcC;;MAGA,WAAW;;MAGX,UAAU;;MAGV,UAAU;;MAGV;;EAGJ,YAAY;;EA6BZ;;EAaM,QAAQ,aAAY,yBAA8B,QAAQ;UAYlD;;;;;;;;EA0Bd,OAAO,OAAO;;;;;;;;;;;;;UAkCN;;UAuBA;;;;;;EAcR;EAYA,eAAe;;EAGf,SAAS,SAAS,cAAc;;EAyBhC,OAAO,OAAO,YAAY,aAAY,yBAA8B;;EAKpE,cAAc,aAAY,yBAA8B;;EAKlD,IAAI,OAAO,YAAY,aAAY,yBAA8B,QAAQ;;EAOzE,WAAW,aAAY,yBAA8B,QAAQ;UAM3D;UAqOA;UAmBA;UAWA;UA2GA;UAuBA;UAIA;UA8CA;UAIA;UAeA;UAOA;UAkBM"}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{waitForSettlement as e}from"../../async/settlement.js";import{ModelError as t}from"../../errors/model-error.js";import{contentHasDocument as n,contentHasImage as r}from"../../message/projection.js";import{AgentMemory as i}from"../memory/memory.js";import{normalizeToolPairing as a}from"../history/normalize.js";import{bindCompactionAccounting as o}from"../memory/accounting-binding.js";import{ContextCompactor as s}from"../memory/compaction.js";import{resolveCompactionConfig as c}from"../memory/compaction-config.js";import{bindSkillProviderLogger as l}from"../skill/provider/context.js";import{SkillCatalog as u}from"../skill/catalog.js";import{createSkillTools as d,renderSkillCatalog as f}from"../skill/tools.js";import{createRunTerminalRecord as p,withTerminalDelivery as m}from"../accounting/delivery/terminal.js";import{captureContextSections as h}from"../context/section.js";import{History as g}from"../history/history.js";import{bindModelRequestBoundary as _,bindQueuedInput as v}from"../loop/turn/model-request-boundary.js";import{bindStepProjectionSources as y}from"../loop/turn/step-projection.js";import{AGENT_ACCOUNTING_ERROR_CODES as b,AgentRunError as x}from"../accounting/error.js";import{runAgent as S}from"../mode/run-agent.js";import{RunEventBuffer as C}from"../accounting/event-buffer.js";import{validateSessionSnapshot as w}from"./session/validation.js";import{resolveRuntimeLimits as T}from"./session/config.js";import{conversationId as E,deferred as D,errorCodeOf as O,messageOf as k,newConversationId as A,toolCatalog as j,userMessage as M}from"./session/common.js";import{captureResumedSkillActivations as N,prepareSkills as P}from"./session/skills.js";import{appendRunInstructions as F}from"./instructions.js";import{accountTraceEvent as I}from"./session/trace-accounting.js";import{captureResumedObjective as L,commitRuntimeMemory as R,loadRuntimeMemory as z,renderRuntimeMemory as B}from"./session/runtime-memory.js";import{attachRuntimeSession as V,configureRuntimeSessionModel as H,runtimeSessionConfiguration as U,streamRuntimeSession as W}from"./session/runtime-binding.js";import{createSessionLedger as G}from"./session/accounting.js";import{runRuntimeCompaction as K}from"./session/runtime-compaction.js";import{sessionCallConfig as q}from"./session/model-config.js";import{consumeSessionEvents as J}from"./session/observer.js";import{sealRuntimeRun as Y}from"./session/run-seal.js";var X=class H{definition;options;catalog;activeRuntimeCatalog;skillCatalog;runtimeLimits;contextSections;currentHistory;currentMemory;currentConversationId;compactor;pendingSkillActivations=Object.freeze([]);active=!1;activeAdditionalInstructions;activeInvocation;idleWaiters=new Set;pendingInjections;roundInFlight=!1;roundCalledTools=!1;constructor(e,t){if(e.mode===`deep-human-in-loop`&&t.userInput===void 0)throw TypeError(`agent '${e.id}' requires a userInput broker in deep-human-in-loop mode`);this.definition=e;let n=t.historyLimits===void 0?void 0:Object.freeze({...t.historyLimits});t.history!==void 0&&n!==void 0&&new g(n);let r=t.compaction===void 0||t.compaction===!1?t.compaction:Object.freeze({...t.compaction}),a=t.trace===void 0?void 0:Object.freeze({...t.trace}),o=t.team===void 0?void 0:Object.freeze({...t.team}),s=t.ledgerLimits===void 0?void 0:Object.freeze({...t.ledgerLimits}),c=t.eventBufferLimits===void 0?void 0:Object.freeze({...t.eventBufferLimits});this.options=Object.freeze({...t,...n===void 0?{}:{historyLimits:n},...r===void 0?{}:{compaction:r},...a===void 0?{}:{trace:a},...o===void 0?{}:{team:o},...s===void 0?{}:{ledgerLimits:s},...c===void 0?{}:{eventBufferLimits:c},...t.skills===void 0?{}:{skills:Object.freeze([...t.skills])},...Array.isArray(t.tools)?{tools:Object.freeze([...t.tools])}:{},...t.interceptors===void 0?{}:{interceptors:Object.freeze([...t.interceptors])}}),this.runtimeLimits=T(t.runtimeLimits);let l=h(t.contextSections)??[],f=h(e.contextSections)??[],p=[...f.map(e=>l.find(t=>t.id===e.id)??e),...l.filter(e=>!f.some(t=>t.id===e.id))];this.contextSections=p.length===0?void 0:Object.freeze(p),this.currentConversationId=E(t.conversationId),this.currentHistory=t.history??new g(n);let m=[...e.skills,...t.skills??[]],_=e.skillIds?.length===0,v=m.length>0||(e.skillIds?.length??0)>0;this.skillCatalog=_||!v?void 0:new u(m,{...e.skillIds===void 0?{}:{allowedSkillIds:e.skillIds},maxSkills:e.skillOptions.maxSkills,maxCatalogBytes:e.skillOptions.maxDiscoveryBytes});let y=this.skillCatalog===void 0?[]:d(this.skillCatalog,e.skillOptions,()=>this.skillLookup()),b=t.team?.tools===`reporting`?`reporting`:`full`,x=t.team?.tools===!1?[]:t.team?.team.toolsFor(t.team.name??e.id,b)??[];this.catalog=j(e.tools,t.tools,[...y,...x]),this.currentMemory=t.memory instanceof i?t.memory:t.memory===void 0?new i(e.memory.seed,e.memory):i.fromSnapshot(t.memory,e.memory),L(this.currentMemory,this.currentHistory,this.definition.memory.autoCaptureObjective),this.compactor=this.createCompactor(),V(this,(e,t,n)=>this.createRunHandle(e,t,n),e=>this.createRunHandle(void 0,e),e=>this.compactForRuntime(e),()=>{this.compactor=this.createCompactor()}),t.team?.team.attach(this,{...t.team.name===void 0?{}:{name:t.team.name},...t.team.description===void 0?{}:{description:t.team.description},...t.team.instructions===void 0?{}:{instructions:t.team.instructions},...t.team.role===void 0?{}:{role:t.team.role},...t.team.tools===void 0?{}:{tools:t.team.tools}})}static fromSnapshot(e,t){let{snapshot:n,...r}=t;w(n,e.id,e.skillOptions.maxSkills);let a=new H(e,{...r,conversationId:n.conversationId,history:g.fromSnapshot(n.history,r.historyLimits),memory:i.fromSnapshot(n.memory,e.memory)});return a.pendingSkillActivations=N(n.skills,a.skillCatalog),a}get conversationId(){return this.currentConversationId}get history(){return this.currentHistory}get memory(){return this.currentMemory}get skills(){return this.skillCatalog}get isRunning(){return this.active}snapshot(){let e=this.activationSnapshot(),t=this.currentHistory.snapshot(),n=this.pendingInjections?.entries()??[],r=n.length===0?t:Object.freeze({version:1,entries:Object.freeze([...t.entries,...n.map((e,n)=>Object.freeze({...e,seq:t.entries.length+n+1}))])});return Object.freeze({version:1,conversationId:this.currentConversationId,agentId:this.definition.id,history:r,memory:this.currentMemory.snapshot(),...U(this)?.memory===void 0?{}:{memoryBindingId:U(this).memory.bindingId},...e.length===0?{}:{skills:Object.freeze({activated:e})}})}reset(){if(this.active)throw Error(`cannot reset an agent session while a run is active`);this.currentConversationId=A(),this.currentHistory=new g(this.options.historyLimits),this.currentMemory=new i(this.definition.memory.seed,this.definition.memory),this.pendingInjections=void 0,this.pendingSkillActivations=Object.freeze([]),this.skillCatalog?.clearActivations(),this.compactor=this.createCompactor()}async compact(e={}){if(this.active)throw Error(`cannot compact an agent session while a run is active`);this.active=!0,this.activeInvocation=e;try{return await this.prepareSkills(e.signal),await this.compactor?.compactNow(e.signal)??null}finally{this.releaseRun()}}async compactForRuntime(e){if(this.active)throw Error(`cannot compact an agent session while a run is active`);let t=this.createLedger();this.active=!0,this.activeInvocation=e,this.compactor!==void 0&&o(this.compactor,t),this.skillCatalog!==void 0&&l(this.skillCatalog,t.modelInvocation.logger);try{return await K({...this.compactor===void 0?{}:{compactor:this.compactor},invocation:e,accounting:t,prepare:()=>this.prepareSkills(e.signal,t)})}finally{this.releaseRun()}}inject(e){let t=M(e);if(this.active&&this.roundInFlight){let e=this.pendingInjections??=new g(this.options.historyLimits);return e.append({kind:`user`,message:t}),this.currentHistory.entries().length+e.entries().length}return this.drainInjections(),this.currentHistory.append({kind:`user`,message:t}),this.currentHistory.entries().length}observeRoundBoundary(e){if(e.type===`span-start`&&e.kind===`chat`){this.roundInFlight=!0,this.roundCalledTools=!1;return}this.roundInFlight&&((e.type===`tool-call`||e.type===`assistant-message`&&e.message?.content.some(e=>e.type===`tool-call`)===!0)&&(this.roundCalledTools=!0),(e.type===`step-end`&&this.roundCalledTools||e.type===`turn-end`||e.type===`agent-end`)&&(this.roundInFlight=!1,this.drainInjections()))}drainInjections(){if(this.pendingInjections===void 0)return;let e=this.pendingInjections;this.currentHistory.appendBatch(e.entries().map(e=>({event:e.event}))),this.pendingInjections=void 0}hasUnansweredInput(){return(this.pendingInjections?.entries().length??0)>0||this.currentHistory.messages().at(-1)?.role===`user`}whenIdle(e){return this.active?e?.aborted?Promise.reject(e.reason):new Promise((t,n)=>{let r=!1,i=()=>{r||(r=!0,this.idleWaiters.delete(i),e?.removeEventListener(`abort`,a),t())},a=()=>{r||(r=!0,this.idleWaiters.delete(i),n(e?.reason))};this.idleWaiters.add(i),e?.addEventListener(`abort`,a,{once:!0}),this.active||i()}):Promise.resolve()}stream(e,t={}){return this.createRunHandle(e,t)}streamPending(e={}){return this.createRunHandle(void 0,e)}async run(e,t={}){let n=this.stream(e,t);return await J(n,t.onEvent,this.runtimeLimits.observerTimeoutMs??3e4),await n.result}async runPending(e={}){let t=this.streamPending(e);return await J(t,e.onEvent,this.runtimeLimits.observerTimeoutMs??3e4),await t.result}createRunHandle(i,a,s){if(this.active)throw Error(`agent session '${this.definition.id}' is already running`);this.drainInjections();let c=this.currentHistory.entries().length+1,u=new AbortController,d=!1,f=a.signal===void 0?u.signal:AbortSignal.any([a.signal,u.signal]),h=new C(this.options.eventBufferLimits?.maxEvents,this.options.eventBufferLimits?.maxBytes),g=D(),y=D(),S=D(),w=this.createLedger(),T=Object.freeze([]);this.compactor!==void 0&&o(this.compactor,w),this.skillCatalog!==void 0&&l(this.skillCatalog,w.modelInvocation.logger),this.active=!0,_(this.currentHistory,e=>{this.roundInFlight=e,e||this.drainInjections()}),v(this.currentHistory,()=>{let e=this.pendingInjections?.entries()??[];return e.length===0||!e.some(e=>e.event.kind===`user`&&e.event.message.source.kind===`user`)?!1:(this.roundInFlight=!1,this.drainInjections(),!0)}),this.activeAdditionalInstructions=s,this.activeInvocation=a;let E=new Map,A=(async()=>{let e,o,s;try{let e=U(this);if(e?.memory!==void 0){let t=await z(e.memory,this.currentConversationId,this.definition.memory,f,w);s=t.state,t.memory!==void 0&&(this.currentMemory=t.memory)}if(e?.prepareTools!==void 0){let t=w.modelInvocation.logger;if(t===void 0)throw Error(`runtime tool source logger is unavailable`);let n=e.prepareTools(f,t,[...this.catalog?.names()??[],...this.definition.nativeTools.map(e=>e.name)]);this.activeRuntimeCatalog=j([],this.catalog,n.tools),T=n.references}if(S.resolve(T),await this.prepareSkills(f,w),i!==void 0){let e=M(i);if(this.definition.memory.autoCaptureObjective){let t=w.startOperation(`memory`,{data:{action:`capture-objective`}});try{this.currentMemory.captureOriginalObjective(e),w.endOperation(t,`success`)}catch(e){throw w.endOperation(t,`error`,{error:e}),e}}this.currentHistory.append({kind:`user`,message:e})}if(a.imagePolicy===`strict`&&this.history.messages().some(e=>r(e.content))){let e=this.callConfig(a),n=await this.options.registry.resolveModelInfo(e.provider,e.model,f);if(n.inputModalities!==void 0&&!n.inputModalities.includes(`image`))throw new t(`model ${n.id} does not support required image input`,`UNSUPPORTED_IMAGE_INPUT`)}if(a.documentPolicy===`strict`&&this.history.messages().some(e=>n(e.content))){let e=this.callConfig(a),n=await this.options.registry.resolveModelInfo(e.provider,e.model,f);if(n.inputModalities!==void 0&&!n.inputModalities.includes(`document`))throw new t(`model ${n.id} does not support required document input`,`UNSUPPORTED_DOCUMENT_INPUT`)}for await(let e of this.runDefinition({...a,signal:f},w))this.observeRoundBoundary(e),I(w,E,e),e.type===`agent-end`&&(o=e.outcome),h.push(e);if(o===void 0)throw Error(`agent session '${this.definition.id}' ended without agent-end`);if(f.aborted)throw f.reason??Error(`agent run was aborted`);if(o.reason.kind===`error`&&o.reason.failure.code===`USAGE_REQUIRED`){let e=Error(o.reason.failure.message);throw e.code=`USAGE_REQUIRED`,e}e?.memory!==void 0&&s!==void 0&&s.status!==`disabled`&&await R(e.memory,this.currentConversationId,this.currentMemory.snapshot(),s,f,w)}catch(t){e=t,S.resolve(T)}try{this.drainInjections()}catch(t){e??=t}let l;try{let t=f.aborted||o?.reason.kind===`aborted`?`aborted`:e!==void 0||o?.reason.kind===`error`?`error`:`success`,n=await w.finalize(t,o?.completed??!1,e);l=m(p(n),n.delivery),g.resolve(l)}catch(e){g.reject(e),y.reject(e),h.fail(e),d=!0,this.releaseRun();return}if(!d){if(e===void 0&&w.terminalAuditFailure){let t=Error(`audit observation checkpoint failed after run finalization`);t.code=`OBSERVABILITY_AUDIT_UNAVAILABLE`,e=t}if(e!==void 0){let t=new x(k(e),O(e)??b.RUN_FAILED,l,{cause:e});y.reject(t),h.fail(t)}else{let e=o,t=[...this.currentHistory.entries()].reverse().find(e=>e.seq>=c&&e.event.kind===`assistant`)?.event,n=t?.kind===`assistant`?t.message:void 0,r=Object.freeze({text:e.text,outcome:e,report:l,...n===void 0?{}:{message:n}});y.resolve(r),h.close()}d=!0,this.releaseRun()}})();A.catch(e=>{d||(g.reject(e),y.reject(e),h.fail(e),d=!0,this.releaseRun())}),y.promise.catch(()=>void 0),g.promise.catch(()=>void 0);let N=!1;return Object.freeze({runId:w.runId,traceId:w.traceId,toolSourceSnapshots:S.promise,eventsSettled:A.then(()=>void 0,()=>void 0),result:y.promise,report:g.promise,seal:()=>Y({ledger:w,buffer:h,report:g,result:y,toolSources:S,currentToolSources:()=>T,isTerminal:()=>d,markTerminal:()=>{d=!0},abort:()=>u.abort(Error(`Agent run was sealed`)),release:()=>this.releaseRun()}),abort(e){!d&&!u.signal.aborted&&u.abort(Error(`Agent run was aborted`))},[Symbol.asyncIterator](){return N?(async function*(){throw Error(`an agent run handle can only be iterated once`)})():(N=!0,(async function*(){let t=!1;try{for(;;){let e=await h.take();if(e.done){t=!0;break}yield e.value}}finally{t||(u.abort(Error(`agent event consumer stopped`)),h.stop(),await e(A,3e4))}})())}})}releaseRun(){try{this.drainInjections()}finally{_(this.currentHistory),v(this.currentHistory),this.roundInFlight=!1,this.active=!1,this.activeAdditionalInstructions=void 0,this.activeInvocation=void 0,this.activeRuntimeCatalog=void 0,this.skillCatalog!==void 0&&l(this.skillCatalog,void 0),this.compactor!==void 0&&o(this.compactor,void 0);let e=[...this.idleWaiters];this.idleWaiters.clear();for(let t of e)t()}}createLedger(){let e=U(this);return G({definition:this.definition,options:this.options,runtimeLimits:this.runtimeLimits,conversationId:this.currentConversationId,...e===void 0?{}:{runtime:e}})}runDefinition(e,t){let n=this.definition,r=this.combinedHooks(t),i=this.effectiveCatalog(),a=e.outputFormat??n.outputFormat,o={registry:this.options.registry,config:this.callConfig(e),history:this.history,...i===void 0?{}:{tools:i},...n.nativeTools.length===0?{}:{nativeTools:n.nativeTools},...n.toolChoice===void 0?{}:{toolChoice:n.toolChoice},...e.imagePolicy===void 0?{}:{imagePolicy:e.imagePolicy},...e.documentPolicy===void 0?{}:{documentPolicy:e.documentPolicy},...a===void 0?{}:{outputFormat:a},...e.validateOutput===void 0?{}:{validateOutput:e.validateOutput},system:this.systemInstructions(this.activeAdditionalInstructions),maxTurns:n.maxTurns,bounds:{maxToolCalls:n.maxToolCalls,...this.runtimeLimits.maxParallelToolCalls===void 0?{}:{maxParallel:this.runtimeLimits.maxParallelToolCalls},...this.runtimeLimits.maxConsecutiveToolErrors===void 0?{}:{maxConsecutiveToolErrors:this.runtimeLimits.maxConsecutiveToolErrors},...this.runtimeLimits.repeatToolWarningAt===void 0?{}:{repeatToolWarningAt:this.runtimeLimits.repeatToolWarningAt},...this.runtimeLimits.repeatToolLimit===void 0?{}:{repeatToolLimit:this.runtimeLimits.repeatToolLimit},...this.runtimeLimits.toolCycleWarningAt===void 0?{}:{toolCycleWarningAt:this.runtimeLimits.toolCycleWarningAt},...this.runtimeLimits.toolCycleLimit===void 0?{}:{toolCycleLimit:this.runtimeLimits.toolCycleLimit},...this.runtimeLimits.onExhausted===void 0?{}:{onExhausted:this.runtimeLimits.onExhausted},...this.runtimeLimits.maxToolResultTokens===void 0?{}:{maxToolResultTokens:this.runtimeLimits.maxToolResultTokens},...this.runtimeLimits.toolResultOverflow===void 0?{}:{toolResultOverflow:this.runtimeLimits.toolResultOverflow},...this.runtimeLimits.maxToolCycleLength===void 0?{}:{maxToolCycleLength:this.runtimeLimits.maxToolCycleLength},...this.runtimeLimits.finalReportReserveTokens===void 0?{}:{finalReportReserveTokens:this.runtimeLimits.finalReportReserveTokens},...this.runtimeLimits.maxTotalTokens===void 0?{}:{maxTotalTokens:this.runtimeLimits.maxTotalTokens},...this.runtimeLimits.maxToolResultBytes===void 0?{}:{maxToolResultBytes:this.runtimeLimits.maxToolResultBytes},...this.runtimeLimits.maxToolDurationMs===void 0?{}:{maxToolDurationMs:this.runtimeLimits.maxToolDurationMs},...this.runtimeLimits.toolTeardownTimeoutMs===void 0?{}:{toolTeardownTimeoutMs:this.runtimeLimits.toolTeardownTimeoutMs}},commentary:n.commentary,...this.runtimeLimits.teardownTimeoutMs===void 0?{}:{teardownTimeoutMs:this.runtimeLimits.teardownTimeoutMs},...this.runtimeLimits.modelTimeoutMs===void 0?{}:{modelTimeoutMs:this.runtimeLimits.modelTimeoutMs},...this.runtimeLimits.maxModelRequestBytes===void 0?{}:{maxModelRequestBytes:this.runtimeLimits.maxModelRequestBytes},...this.runtimeLimits.maxModelResponseBytes===void 0?{}:{maxModelResponseBytes:this.runtimeLimits.maxModelResponseBytes},...this.runtimeLimits.maxModelStreamEvents===void 0?{}:{maxModelStreamEvents:this.runtimeLimits.maxModelStreamEvents},...this.runtimeLimits.hookTimeoutMs===void 0?{}:{hookTimeoutMs:this.runtimeLimits.hookTimeoutMs},...this.runtimeLimits.hookTeardownTimeoutMs===void 0?{}:{hookTeardownTimeoutMs:this.runtimeLimits.hookTeardownTimeoutMs},...this.options.approvals===void 0?{}:{approvals:this.options.approvals},...this.options.spillStore===void 0?{}:{spillStore:this.options.spillStore},...this.options.experimentalPrograms===void 0?{}:{experimentalPrograms:this.options.experimentalPrograms},...this.options.interceptors===void 0?{}:{interceptors:this.options.interceptors},...this.contextSections===void 0?{}:{contextSections:this.contextSections},...r===void 0?{}:{hooks:r},...e.signal===void 0?{}:{signal:e.signal},...t===void 0?{}:{accounting:t},...t?.modelInvocation.logger===void 0?{}:{logger:t.modelInvocation.logger},trace:{...this.options.trace,conversationId:this.currentConversationId,agentId:n.id,agentName:n.name}};return n.mode===`deep-human-in-loop`?S({...o,mode:n.mode,userInput:this.options.userInput}):n.mode===`deep`?S({...o,mode:n.mode,...this.options.userInput===void 0?{}:{userInput:this.options.userInput}}):S({...o,mode:`basic`})}createCompactor(){let e=this.options.compaction===!1?!1:this.options.compaction===void 0?this.definition.compaction:c(this.options.compaction);if(e!==!1)return new s({registry:this.options.registry,config:()=>this.callConfig(this.activeInvocation),history:()=>this.currentHistory,system:()=>this.systemInstructions(this.activeAdditionalInstructions),pinnedMessages:()=>B(this.currentMemory,this.definition.memory.maxInjectedChars),tools:()=>[...this.effectiveCatalog()?.schemas()??[],...this.definition.nativeTools],policy:e})}effectiveCatalog(){return this.activeRuntimeCatalog??this.catalog}combinedHooks(e){let t=this.options.hooks;return{...t,beforeStep:async n=>{let r=this.currentHistory.generation(),i=this.currentHistory.entries().length;this.drainInjections();let s=this.currentHistory.entries().length===i?n:{...n,messages:a(this.currentHistory.messages()),snapshot:this.currentHistory.snapshot()};if(this.compactor!==void 0&&o(this.compactor,e),await this.compactor?.beforeStep(s),e?.usageStop!==void 0)return{kind:`proceed`};let c=this.currentHistory.generation()===r&&this.currentHistory.entries().length===i?n:{...n,messages:a(this.currentHistory.messages()),snapshot:this.currentHistory.snapshot()},l=B(this.currentMemory,this.definition.memory.maxInjectedChars,e),u=l.length===0?c:{...c,messages:Object.freeze([...l,...c.messages])},d=await t?.beforeStep?.(u)??{kind:`proceed`};if(d.kind===`reject`)return d;let f=[...d.messages===void 0?l:[],...d.prepend??[]];return y(f.length===0?d:{...d,prepend:f},c.messages)},onRequestError:async n=>{this.compactor!==void 0&&o(this.compactor,e);let r=await this.compactor?.onRequestError(n);return e?.usageStop===void 0?r===`retry`?`retry`:await t?.onRequestError?.(n)??`fail`:`fail`}}}callConfig(e){return q(this.definition,U(this),e)}systemInstructions(e){let t=this.skillCatalog===void 0?this.definition.instructions:f(this.definition.instructions,this.skillCatalog.summaries(),this.definition.skillOptions),n=this.options.team,r=n===void 0?t:`${t}\n\n${n.team.instructionsFor(n.name??this.definition.id)}`;return F(r,e)}skillLookup(e){return{...this.options.skillCwd===void 0?{}:{cwd:this.options.skillCwd},...e===void 0?{}:{signal:e}}}activationSnapshot(){let e=new Map;for(let t of this.pendingSkillActivations)e.set(t.id,t);for(let t of this.skillCatalog?.activatedSkillReferences()??[])e.set(t.id,t);for(let t of this.skillCatalog?.activatedSummaries()??[])e.has(t.id)||e.set(t.id,Object.freeze({id:t.id,provider:t.provider,source:t.source,...t.resourceBase===void 0?{}:{resourceBase:Object.freeze({...t.resourceBase})}}));return Object.freeze([...e.values()].sort((e,t)=>e.id.localeCompare(t.id)))}async prepareSkills(e,t){await P(this.definition,this.skillCatalog,this.pendingSkillActivations,e=>this.skillLookup(e),()=>{this.pendingSkillActivations=Object.freeze([])},e,t)}};export{X as AgentSession,H as configureRuntimeSessionModel,W as streamRuntimeSession};
|
|
1
|
+
import{waitForSettlement as e}from"../../async/settlement.js";import{ModelError as t}from"../../errors/model-error.js";import{contentHasDocument as n,contentHasImage as r}from"../../message/projection.js";import{AgentMemory as i}from"../memory/memory.js";import{normalizeToolPairing as a}from"../history/normalize.js";import{bindCompactionAccounting as o}from"../memory/accounting-binding.js";import{ContextCompactor as s}from"../memory/compaction.js";import{resolveCompactionConfig as c}from"../memory/compaction-config.js";import{bindSkillProviderLogger as l}from"../skill/provider/context.js";import{SkillCatalog as u}from"../skill/catalog.js";import{createSkillTools as d,renderSkillCatalog as f}from"../skill/tools.js";import{createRunTerminalRecord as p,withTerminalDelivery as m}from"../accounting/delivery/terminal.js";import{captureContextSections as h}from"../context/section.js";import{History as g}from"../history/history.js";import{isManagedTeamNotice as _}from"../history/input-work.js";import{bindModelRequestBoundary as v,bindQueuedInput as y}from"../loop/turn/model-request-boundary.js";import{bindStepProjectionSources as b}from"../loop/turn/step-projection.js";import{AGENT_ACCOUNTING_ERROR_CODES as x,AgentRunError as S}from"../accounting/error.js";import{runAgent as C}from"../mode/run-agent.js";import{RunEventBuffer as w}from"../accounting/event-buffer.js";import{validateSessionSnapshot as T}from"./session/validation.js";import{resolveRuntimeLimits as E}from"./session/config.js";import{conversationId as D,deferred as O,errorCodeOf as k,messageOf as A,newConversationId as j,toolCatalog as M,userMessage as N}from"./session/common.js";import{captureResumedSkillActivations as P,prepareSkills as F}from"./session/skills.js";import{appendRunInstructions as I}from"./instructions.js";import{accountTraceEvent as L}from"./session/trace-accounting.js";import{captureResumedObjective as R,commitRuntimeMemory as z,loadRuntimeMemory as B,renderRuntimeMemory as V}from"./session/runtime-memory.js";import{attachRuntimeSession as H,configureRuntimeSessionModel as U,runtimeSessionConfiguration as W,streamRuntimeSession as G}from"./session/runtime-binding.js";import{createSessionLedger as K}from"./session/accounting.js";import{runRuntimeCompaction as q}from"./session/runtime-compaction.js";import{sessionCallConfig as J}from"./session/model-config.js";import{consumeSessionEvents as Y}from"./session/observer.js";import{sealRuntimeRun as X}from"./session/run-seal.js";var Z=class U{definition;options;catalog;activeRuntimeCatalog;skillCatalog;runtimeLimits;contextSections;currentHistory;currentMemory;currentConversationId;compactor;pendingSkillActivations=Object.freeze([]);active=!1;activeAdditionalInstructions;activeInvocation;idleWaiters=new Set;pendingInjections;lastRunOutcome;roundInFlight=!1;roundCalledTools=!1;constructor(e,t){if(e.mode===`deep-human-in-loop`&&t.userInput===void 0)throw TypeError(`agent '${e.id}' requires a userInput broker in deep-human-in-loop mode`);this.definition=e;let n=t.historyLimits===void 0?void 0:Object.freeze({...t.historyLimits});t.history!==void 0&&n!==void 0&&new g(n);let r=t.compaction===void 0||t.compaction===!1?t.compaction:Object.freeze({...t.compaction}),a=t.trace===void 0?void 0:Object.freeze({...t.trace}),o=t.team===void 0?void 0:Object.freeze({...t.team}),s=t.ledgerLimits===void 0?void 0:Object.freeze({...t.ledgerLimits}),c=t.eventBufferLimits===void 0?void 0:Object.freeze({...t.eventBufferLimits});this.options=Object.freeze({...t,...n===void 0?{}:{historyLimits:n},...r===void 0?{}:{compaction:r},...a===void 0?{}:{trace:a},...o===void 0?{}:{team:o},...s===void 0?{}:{ledgerLimits:s},...c===void 0?{}:{eventBufferLimits:c},...t.skills===void 0?{}:{skills:Object.freeze([...t.skills])},...Array.isArray(t.tools)?{tools:Object.freeze([...t.tools])}:{},...t.interceptors===void 0?{}:{interceptors:Object.freeze([...t.interceptors])}}),this.runtimeLimits=E(t.runtimeLimits);let l=h(t.contextSections)??[],f=h(e.contextSections)??[],p=[...f.map(e=>l.find(t=>t.id===e.id)??e),...l.filter(e=>!f.some(t=>t.id===e.id))];this.contextSections=p.length===0?void 0:Object.freeze(p),this.currentConversationId=D(t.conversationId),this.currentHistory=t.history??new g(n);let m=[...e.skills,...t.skills??[]],_=e.skillIds?.length===0,v=m.length>0||(e.skillIds?.length??0)>0;this.skillCatalog=_||!v?void 0:new u(m,{...e.skillIds===void 0?{}:{allowedSkillIds:e.skillIds},maxSkills:e.skillOptions.maxSkills,maxCatalogBytes:e.skillOptions.maxDiscoveryBytes});let y=this.skillCatalog===void 0?[]:d(this.skillCatalog,e.skillOptions,()=>this.skillLookup()),b=t.team?.tools===`reporting`?`reporting`:`full`,x=t.team?.tools===!1?[]:t.team?.team.toolsFor(t.team.name??e.id,b)??[];this.catalog=M(e.tools,t.tools,[...y,...x]),this.currentMemory=t.memory instanceof i?t.memory:t.memory===void 0?new i(e.memory.seed,e.memory):i.fromSnapshot(t.memory,e.memory),R(this.currentMemory,this.currentHistory,this.definition.memory.autoCaptureObjective),this.compactor=this.createCompactor(),H(this,(e,t,n)=>this.createRunHandle(e,t,n),e=>this.createRunHandle(void 0,e),e=>this.compactForRuntime(e),()=>{this.compactor=this.createCompactor()}),t.team?.team.attach(this,{...t.team.name===void 0?{}:{name:t.team.name},...t.team.description===void 0?{}:{description:t.team.description},...t.team.instructions===void 0?{}:{instructions:t.team.instructions},...t.team.role===void 0?{}:{role:t.team.role},...t.team.tools===void 0?{}:{tools:t.team.tools}})}static fromSnapshot(e,t){let{snapshot:n,...r}=t;T(n,e.id,e.skillOptions.maxSkills);let a=new U(e,{...r,conversationId:n.conversationId,history:g.fromSnapshot(n.history,r.historyLimits),memory:i.fromSnapshot(n.memory,e.memory)});return a.pendingSkillActivations=P(n.skills,a.skillCatalog),a}get conversationId(){return this.currentConversationId}get history(){return this.currentHistory}get memory(){return this.currentMemory}get skills(){return this.skillCatalog}get isRunning(){return this.active}snapshot(){let e=this.activationSnapshot(),t=this.currentHistory.snapshot(),n=this.pendingInjections?.entries()??[],r=n.length===0?t:Object.freeze({version:1,entries:Object.freeze([...t.entries,...n.map((e,n)=>Object.freeze({...e,seq:t.entries.length+n+1}))])});return Object.freeze({version:1,conversationId:this.currentConversationId,agentId:this.definition.id,history:r,memory:this.currentMemory.snapshot(),...W(this)?.memory===void 0?{}:{memoryBindingId:W(this).memory.bindingId},...e.length===0?{}:{skills:Object.freeze({activated:e})}})}reset(){if(this.active)throw Error(`cannot reset an agent session while a run is active`);this.currentConversationId=j(),this.currentHistory=new g(this.options.historyLimits),this.currentMemory=new i(this.definition.memory.seed,this.definition.memory),this.pendingInjections=void 0,this.pendingSkillActivations=Object.freeze([]),this.lastRunOutcome=void 0,this.skillCatalog?.clearActivations(),this.compactor=this.createCompactor()}async compact(e={}){if(this.active)throw Error(`cannot compact an agent session while a run is active`);this.active=!0,this.activeInvocation=e;try{return await this.prepareSkills(e.signal),await this.compactor?.compactNow(e.signal)??null}finally{this.releaseRun()}}async compactForRuntime(e){if(this.active)throw Error(`cannot compact an agent session while a run is active`);let t=this.createLedger();this.active=!0,this.activeInvocation=e,this.compactor!==void 0&&o(this.compactor,t),this.skillCatalog!==void 0&&l(this.skillCatalog,t.modelInvocation.logger);try{return await q({...this.compactor===void 0?{}:{compactor:this.compactor},invocation:e,accounting:t,prepare:()=>this.prepareSkills(e.signal,t)})}finally{this.releaseRun()}}inject(e){let t=N(e);if(this.active&&this.roundInFlight){g.fromSnapshot(this.currentHistory.snapshot(),this.options.historyLimits).appendBatch([...(this.pendingInjections?.entries()??[]).map(e=>({event:e.event})),{event:{kind:`user`,message:t}}]);let e=this.pendingInjections??=new g(this.options.historyLimits);return e.append({kind:`user`,message:t}),this.currentHistory.entries().length+e.entries().length}return this.drainInjections(),this.currentHistory.append({kind:`user`,message:t}),this.currentHistory.entries().length}observeRoundBoundary(e){if(e.type===`agent-end`&&(this.lastRunOutcome=e.outcome),e.type===`span-start`&&e.kind===`chat`){this.roundInFlight=!0,this.roundCalledTools=!1;return}this.roundInFlight&&((e.type===`tool-call`||e.type===`assistant-message`&&e.message?.content.some(e=>e.type===`tool-call`)===!0)&&(this.roundCalledTools=!0),(e.type===`step-end`&&this.roundCalledTools||e.type===`turn-end`||e.type===`agent-end`)&&(this.roundInFlight=!1,this.drainInjections()))}drainInjections(){if(this.pendingInjections===void 0)return;let e=this.pendingInjections;this.currentHistory.appendBatch(e.entries().map(e=>({event:e.event}))),this.pendingInjections=void 0}hasUnansweredInput(){if((this.pendingInjections?.entries().length??0)>0)return!0;for(let e of[...this.currentHistory.messages()].reverse()){if(e.source.kind===`app`){if(e.source.producer===`turn-interrupted`)return!1;if(e.role===`user`&&!_(e))continue}return e.role===`user`}return!1}lastOutcome(){return this.lastRunOutcome}whenIdle(e){return this.active?e?.aborted?Promise.reject(e.reason):new Promise((t,n)=>{let r=!1,i=()=>{r||(r=!0,this.idleWaiters.delete(i),e?.removeEventListener(`abort`,a),t())},a=()=>{r||(r=!0,this.idleWaiters.delete(i),n(e?.reason))};this.idleWaiters.add(i),e?.addEventListener(`abort`,a,{once:!0}),this.active||i()}):Promise.resolve()}stream(e,t={}){return this.createRunHandle(e,t)}streamPending(e={}){return this.createRunHandle(void 0,e)}async run(e,t={}){let n=this.stream(e,t);return await Y(n,t.onEvent,this.runtimeLimits.observerTimeoutMs??3e4),await n.result}async runPending(e={}){let t=this.streamPending(e);return await Y(t,e.onEvent,this.runtimeLimits.observerTimeoutMs??3e4),await t.result}createRunHandle(i,a,s){if(this.active)throw Error(`agent session '${this.definition.id}' is already running`);this.drainInjections();let c=this.currentHistory.entries().length+1,u=new AbortController,d=!1,f=a.signal===void 0?u.signal:AbortSignal.any([a.signal,u.signal]),h=new w(this.options.eventBufferLimits?.maxEvents,this.options.eventBufferLimits?.maxBytes),g=O(),b=O(),C=O(),T=this.createLedger(),E=Object.freeze([]);this.compactor!==void 0&&o(this.compactor,T),this.skillCatalog!==void 0&&l(this.skillCatalog,T.modelInvocation.logger),this.active=!0,v(this.currentHistory,e=>{this.roundInFlight=e,e||this.drainInjections()}),y(this.currentHistory,()=>{let e=this.pendingInjections?.entries()??[];return e.length===0||!e.some(e=>e.event.kind===`user`&&(e.event.message.source.kind===`user`||_(e.event.message)))?!1:(this.roundInFlight=!1,this.drainInjections(),!0)}),this.activeAdditionalInstructions=s,this.activeInvocation=a;let D=new Map,j=(async()=>{let e,o,s;try{let e=W(this);if(e?.memory!==void 0){let t=await B(e.memory,this.currentConversationId,this.definition.memory,f,T);s=t.state,t.memory!==void 0&&(this.currentMemory=t.memory)}if(e?.prepareTools!==void 0){let t=T.modelInvocation.logger;if(t===void 0)throw Error(`runtime tool source logger is unavailable`);let n=e.prepareTools(f,t,[...this.catalog?.names()??[],...this.definition.nativeTools.map(e=>e.name)]);this.activeRuntimeCatalog=M([],this.catalog,n.tools),E=n.references}if(C.resolve(E),await this.prepareSkills(f,T),i!==void 0){let e=N(i);if(this.definition.memory.autoCaptureObjective){let t=T.startOperation(`memory`,{data:{action:`capture-objective`}});try{this.currentMemory.captureOriginalObjective(e),T.endOperation(t,`success`)}catch(e){throw T.endOperation(t,`error`,{error:e}),e}}this.currentHistory.append({kind:`user`,message:e})}if(a.imagePolicy===`strict`&&this.history.messages().some(e=>r(e.content))){let e=this.callConfig(a),n=await this.options.registry.resolveModelInfo(e.provider,e.model,f);if(n.inputModalities!==void 0&&!n.inputModalities.includes(`image`))throw new t(`model ${n.id} does not support required image input`,`UNSUPPORTED_IMAGE_INPUT`)}if(a.documentPolicy===`strict`&&this.history.messages().some(e=>n(e.content))){let e=this.callConfig(a),n=await this.options.registry.resolveModelInfo(e.provider,e.model,f);if(n.inputModalities!==void 0&&!n.inputModalities.includes(`document`))throw new t(`model ${n.id} does not support required document input`,`UNSUPPORTED_DOCUMENT_INPUT`)}for await(let e of this.runDefinition({...a,signal:f},T))this.observeRoundBoundary(e),L(T,D,e),e.type===`agent-end`&&(o=e.outcome),h.push(e);if(o===void 0)throw Error(`agent session '${this.definition.id}' ended without agent-end`);if(f.aborted)throw f.reason??Error(`agent run was aborted`);if(o.reason.kind===`error`&&o.reason.failure.code===`USAGE_REQUIRED`){let e=Error(o.reason.failure.message);throw e.code=`USAGE_REQUIRED`,e}e?.memory!==void 0&&s!==void 0&&s.status!==`disabled`&&await z(e.memory,this.currentConversationId,this.currentMemory.snapshot(),s,f,T)}catch(t){e=t,C.resolve(E)}try{this.drainInjections()}catch(t){e??=t}let l;try{let t=f.aborted||o?.reason.kind===`aborted`?`aborted`:e!==void 0||o?.reason.kind===`error`?`error`:`success`,n=await T.finalize(t,o?.completed??!1,e);l=m(p(n),n.delivery),g.resolve(l)}catch(e){g.reject(e),b.reject(e),h.fail(e),d=!0,this.releaseRun();return}if(!d){if(e===void 0&&T.terminalAuditFailure){let t=Error(`audit observation checkpoint failed after run finalization`);t.code=`OBSERVABILITY_AUDIT_UNAVAILABLE`,e=t}if(e!==void 0){let t=new S(A(e),k(e)??x.RUN_FAILED,l,{cause:e});b.reject(t),h.fail(t)}else{let e=o,t=[...this.currentHistory.entries()].reverse().find(e=>e.seq>=c&&e.event.kind===`assistant`)?.event,n=t?.kind===`assistant`?t.message:void 0,r=Object.freeze({text:e.text,outcome:e,report:l,...n===void 0?{}:{message:n}});b.resolve(r),h.close()}d=!0,this.releaseRun()}})();j.catch(e=>{d||(g.reject(e),b.reject(e),h.fail(e),d=!0,this.releaseRun())}),b.promise.catch(()=>void 0),g.promise.catch(()=>void 0);let P=!1;return Object.freeze({runId:T.runId,traceId:T.traceId,toolSourceSnapshots:C.promise,eventsSettled:j.then(()=>void 0,()=>void 0),result:b.promise,report:g.promise,seal:()=>X({ledger:T,buffer:h,report:g,result:b,toolSources:C,currentToolSources:()=>E,isTerminal:()=>d,markTerminal:()=>{d=!0},abort:()=>u.abort(Error(`Agent run was sealed`)),release:()=>this.releaseRun()}),abort(e){!d&&!u.signal.aborted&&u.abort(Error(`Agent run was aborted`))},[Symbol.asyncIterator](){return P?(async function*(){throw Error(`an agent run handle can only be iterated once`)})():(P=!0,(async function*(){let t=!1;try{for(;;){let e=await h.take();if(e.done){t=!0;break}yield e.value}}finally{t||(u.abort(Error(`agent event consumer stopped`)),h.stop(),await e(j,3e4))}})())}})}releaseRun(){try{this.drainInjections()}finally{v(this.currentHistory),y(this.currentHistory),this.roundInFlight=!1,this.active=!1,this.activeAdditionalInstructions=void 0,this.activeInvocation=void 0,this.activeRuntimeCatalog=void 0,this.skillCatalog!==void 0&&l(this.skillCatalog,void 0),this.compactor!==void 0&&o(this.compactor,void 0);let e=[...this.idleWaiters];this.idleWaiters.clear();for(let t of e)t()}}createLedger(){let e=W(this);return K({definition:this.definition,options:this.options,runtimeLimits:this.runtimeLimits,conversationId:this.currentConversationId,...e===void 0?{}:{runtime:e}})}runDefinition(e,t){let n=this.definition,r=this.combinedHooks(t),i=this.effectiveCatalog(),a=e.outputFormat??n.outputFormat,o={registry:this.options.registry,config:this.callConfig(e),history:this.history,...i===void 0?{}:{tools:i},...n.nativeTools.length===0?{}:{nativeTools:n.nativeTools},...n.toolChoice===void 0?{}:{toolChoice:n.toolChoice},...e.imagePolicy===void 0?{}:{imagePolicy:e.imagePolicy},...e.documentPolicy===void 0?{}:{documentPolicy:e.documentPolicy},...a===void 0?{}:{outputFormat:a},...e.validateOutput===void 0?{}:{validateOutput:e.validateOutput},system:this.systemInstructions(this.activeAdditionalInstructions),maxTurns:n.maxTurns,bounds:{maxToolCalls:n.maxToolCalls,...this.runtimeLimits.maxParallelToolCalls===void 0?{}:{maxParallel:this.runtimeLimits.maxParallelToolCalls},...this.runtimeLimits.maxConsecutiveToolErrors===void 0?{}:{maxConsecutiveToolErrors:this.runtimeLimits.maxConsecutiveToolErrors},...this.runtimeLimits.repeatToolWarningAt===void 0?{}:{repeatToolWarningAt:this.runtimeLimits.repeatToolWarningAt},...this.runtimeLimits.repeatToolLimit===void 0?{}:{repeatToolLimit:this.runtimeLimits.repeatToolLimit},...this.runtimeLimits.toolCycleWarningAt===void 0?{}:{toolCycleWarningAt:this.runtimeLimits.toolCycleWarningAt},...this.runtimeLimits.toolCycleLimit===void 0?{}:{toolCycleLimit:this.runtimeLimits.toolCycleLimit},...this.runtimeLimits.onExhausted===void 0?{}:{onExhausted:this.runtimeLimits.onExhausted},...this.runtimeLimits.maxToolResultTokens===void 0?{}:{maxToolResultTokens:this.runtimeLimits.maxToolResultTokens},...this.runtimeLimits.toolResultOverflow===void 0?{}:{toolResultOverflow:this.runtimeLimits.toolResultOverflow},...this.runtimeLimits.maxToolCycleLength===void 0?{}:{maxToolCycleLength:this.runtimeLimits.maxToolCycleLength},...this.runtimeLimits.finalReportReserveTokens===void 0?{}:{finalReportReserveTokens:this.runtimeLimits.finalReportReserveTokens},...this.runtimeLimits.maxTotalTokens===void 0?{}:{maxTotalTokens:this.runtimeLimits.maxTotalTokens},...this.runtimeLimits.maxToolResultBytes===void 0?{}:{maxToolResultBytes:this.runtimeLimits.maxToolResultBytes},...this.runtimeLimits.maxToolDurationMs===void 0?{}:{maxToolDurationMs:this.runtimeLimits.maxToolDurationMs},...this.runtimeLimits.toolTeardownTimeoutMs===void 0?{}:{toolTeardownTimeoutMs:this.runtimeLimits.toolTeardownTimeoutMs}},commentary:n.commentary,...this.runtimeLimits.teardownTimeoutMs===void 0?{}:{teardownTimeoutMs:this.runtimeLimits.teardownTimeoutMs},...this.runtimeLimits.modelTimeoutMs===void 0?{}:{modelTimeoutMs:this.runtimeLimits.modelTimeoutMs},...this.runtimeLimits.maxModelRequestBytes===void 0?{}:{maxModelRequestBytes:this.runtimeLimits.maxModelRequestBytes},...this.runtimeLimits.maxModelResponseBytes===void 0?{}:{maxModelResponseBytes:this.runtimeLimits.maxModelResponseBytes},...this.runtimeLimits.maxModelStreamEvents===void 0?{}:{maxModelStreamEvents:this.runtimeLimits.maxModelStreamEvents},...this.runtimeLimits.hookTimeoutMs===void 0?{}:{hookTimeoutMs:this.runtimeLimits.hookTimeoutMs},...this.runtimeLimits.hookTeardownTimeoutMs===void 0?{}:{hookTeardownTimeoutMs:this.runtimeLimits.hookTeardownTimeoutMs},...this.options.approvals===void 0?{}:{approvals:this.options.approvals},...this.options.spillStore===void 0?{}:{spillStore:this.options.spillStore},...this.options.experimentalPrograms===void 0?{}:{experimentalPrograms:this.options.experimentalPrograms},...this.options.interceptors===void 0?{}:{interceptors:this.options.interceptors},...this.contextSections===void 0?{}:{contextSections:this.contextSections},...r===void 0?{}:{hooks:r},...e.signal===void 0?{}:{signal:e.signal},...t===void 0?{}:{accounting:t},...t?.modelInvocation.logger===void 0?{}:{logger:t.modelInvocation.logger},trace:{...this.options.trace,conversationId:this.currentConversationId,agentId:n.id,agentName:n.name}};return n.mode===`deep-human-in-loop`?C({...o,mode:n.mode,userInput:this.options.userInput}):n.mode===`deep`?C({...o,mode:n.mode,...this.options.userInput===void 0?{}:{userInput:this.options.userInput}}):C({...o,mode:`basic`})}createCompactor(){let e=this.options.compaction===!1?!1:this.options.compaction===void 0?this.definition.compaction:c(this.options.compaction);if(e!==!1)return new s({registry:this.options.registry,config:()=>this.callConfig(this.activeInvocation),history:()=>this.currentHistory,system:()=>this.systemInstructions(this.activeAdditionalInstructions),pinnedMessages:()=>V(this.currentMemory,this.definition.memory.maxInjectedChars),tools:()=>[...this.effectiveCatalog()?.schemas()??[],...this.definition.nativeTools],policy:e})}effectiveCatalog(){return this.activeRuntimeCatalog??this.catalog}combinedHooks(e){let t=this.options.hooks;return{...t,beforeStep:async n=>{let r=this.currentHistory.generation(),i=this.currentHistory.entries().length;this.drainInjections();let s=this.currentHistory.entries().length===i?n:{...n,messages:a(this.currentHistory.messages()),snapshot:this.currentHistory.snapshot()};if(this.compactor!==void 0&&o(this.compactor,e),await this.compactor?.beforeStep(s),e?.usageStop!==void 0)return{kind:`proceed`};let c=this.currentHistory.generation()===r&&this.currentHistory.entries().length===i?n:{...n,messages:a(this.currentHistory.messages()),snapshot:this.currentHistory.snapshot()},l=V(this.currentMemory,this.definition.memory.maxInjectedChars,e),u=l.length===0?c:{...c,messages:Object.freeze([...l,...c.messages])},d=await t?.beforeStep?.(u)??{kind:`proceed`};if(d.kind===`reject`)return d;let f=[...d.messages===void 0?l:[],...d.prepend??[]];return b(f.length===0?d:{...d,prepend:f},c.messages)},onRequestError:async n=>{this.compactor!==void 0&&o(this.compactor,e);let r=await this.compactor?.onRequestError(n);return e?.usageStop===void 0?r===`retry`?`retry`:await t?.onRequestError?.(n)??`fail`:`fail`}}}callConfig(e){return J(this.definition,W(this),e)}systemInstructions(e){let t=this.skillCatalog===void 0?this.definition.instructions:f(this.definition.instructions,this.skillCatalog.summaries(),this.definition.skillOptions),n=this.options.team,r=n===void 0?t:`${t}\n\n${n.team.instructionsFor(n.name??this.definition.id)}`;return I(r,e)}skillLookup(e){return{...this.options.skillCwd===void 0?{}:{cwd:this.options.skillCwd},...e===void 0?{}:{signal:e}}}activationSnapshot(){let e=new Map;for(let t of this.pendingSkillActivations)e.set(t.id,t);for(let t of this.skillCatalog?.activatedSkillReferences()??[])e.set(t.id,t);for(let t of this.skillCatalog?.activatedSummaries()??[])e.has(t.id)||e.set(t.id,Object.freeze({id:t.id,provider:t.provider,source:t.source,...t.resourceBase===void 0?{}:{resourceBase:Object.freeze({...t.resourceBase})}}));return Object.freeze([...e.values()].sort((e,t)=>e.id.localeCompare(t.id)))}async prepareSkills(e,t){await F(this.definition,this.skillCatalog,this.pendingSkillActivations,e=>this.skillLookup(e),()=>{this.pendingSkillActivations=Object.freeze([])},e,t)}};export{Z as AgentSession,U as configureRuntimeSessionModel,G as streamRuntimeSession};
|
|
2
2
|
//# sourceMappingURL=session.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"session.js","names":[],"sources":["../../../src/agent/define/session.ts"],"sourcesContent":["import { contentHasDocument, contentHasImage } from '../../message/projection.ts'\nimport { ModelError } from '../../errors/model-error.ts'\nimport { type ToolCatalog } from '../tool/registry.ts'\nimport { History } from '../history/history.ts'\nimport { bindModelRequestBoundary, bindQueuedInput } from '../loop/turn/model-request-boundary.ts'\nimport { bindStepProjectionSources } from '../loop/turn/step-projection.ts'\nimport { normalizeToolPairing } from '../history/normalize.ts'\nimport type { TurnHooks } from '../loop/types.ts'\nimport { ContextCompactor, type CompactionResult } from '../memory/compaction.ts'\nimport { bindCompactionAccounting } from '../memory/accounting-binding.ts'\nimport { resolveCompactionConfig } from '../memory/compaction-config.ts'\nimport { AgentMemory } from '../memory/memory.ts'\nimport { captureContextSections } from '../context/section.ts'\nimport type { ContextSection } from '../context/types.ts'\nimport { runAgent, type AgentRunEvent, type AgentRunOutcome } from '../mode/run-agent.ts'\nimport type { UserInputBroker } from '../mode/user-input.ts'\nimport { waitForSettlement } from '../../async/index.ts'\nimport type { OperationStatus } from '../../observation/index.ts'\nimport { RunEventBuffer } from '../accounting/event-buffer.ts'\nimport { AgentRunError, AGENT_ACCOUNTING_ERROR_CODES } from '../accounting/error.ts'\nimport type { RunAccountingPort } from '../accounting/contracts.ts'\nimport type { LegacyRunReport } from '../accounting/report.ts'\nimport type { RunReport } from '../accounting/delivery-types.ts'\nimport { createRunTerminalRecord, withTerminalDelivery } from '../accounting/delivery/terminal.ts'\nimport { SkillCatalog, createSkillTools, renderSkillCatalog, type SkillLookupOptions } from '../skill/index.ts'\nimport type { AgentDefinition } from './definition.ts'\nimport {\n type AgentInput, type AgentRuntimeLimits, type AgentSessionOptions, type AgentSessionSnapshot,\n type AgentSessionActivatedSkillSnapshot, type AgentResumeSessionOptions,\n type AgentInvocationOptions, type AgentResponse, type AgentRunHandle,\n} from './session/types.ts'\nimport { validateSessionSnapshot } from './session/validation.ts'\nimport { resolveRuntimeLimits } from './session/config.ts'\nimport {\n conversationId, newConversationId, userMessage, deferred, messageOf, errorCodeOf,\n toolCatalog,\n} from './session/common.ts'\nimport { captureResumedSkillActivations, prepareSkills } from './session/skills.ts'\nimport { appendRunInstructions } from './instructions.ts'\nimport type { ToolSourceRunReference } from '../tool/source-types.ts'\nimport { accountTraceEvent } from './session/trace-accounting.ts'\nimport {\n captureResumedObjective, commitRuntimeMemory, loadRuntimeMemory, renderRuntimeMemory,\n} from './session/runtime-memory.ts'\nimport { attachRuntimeSession, runtimeSessionConfiguration } from './session/runtime-binding.ts'\nimport { bindSkillProviderLogger } from '../skill/provider/context.ts'\nimport { createSessionLedger } from './session/accounting.ts'\nimport { runRuntimeCompaction } from './session/runtime-compaction.ts'\nimport { sessionCallConfig } from './session/model-config.ts'\nimport { consumeSessionEvents } from './session/observer.ts'\nimport { sealRuntimeRun } from './session/run-seal.ts'\n\nexport class AgentSession {\n readonly definition: AgentDefinition\n private readonly options: AgentSessionOptions\n private readonly catalog: ToolCatalog | undefined\n private activeRuntimeCatalog: ToolCatalog | undefined\n private readonly skillCatalog: SkillCatalog | undefined\n private readonly runtimeLimits: Readonly<AgentRuntimeLimits>\n /** Definition sections first, then session sections; duplicate ids are rejected. */\n private readonly contextSections: readonly ContextSection[] | undefined\n private currentHistory: History\n private currentMemory: AgentMemory\n private currentConversationId: string\n private compactor: ContextCompactor | undefined\n private pendingSkillActivations: readonly AgentSessionActivatedSkillSnapshot[] = Object.freeze([])\n private active = false\n private activeAdditionalInstructions: string | undefined\n /** The overlay of the run that owns the session, so maintenance follows the same model. */\n private activeInvocation: AgentInvocationOptions | undefined\n private readonly idleWaiters = new Set<() => void>()\n /**\n * Messages injected while a run is in flight, waiting for the next model\n * request. Appending them at once put them AHEAD of the assistant output of\n * the round already streaming, a round that never saw them; the next round\n * then read \"steer, then the work that ignored it\" as work that answered it.\n */\n private pendingInjections: History | undefined\n /**\n * A model request has been built and its output is not yet fully recorded.\n * Only then is an injection held: hooks and team notices that inject between\n * rounds still append at once, as they always have.\n */\n private roundInFlight = false\n /** The round in flight called a tool, so its output ends at step-end. */\n private roundCalledTools = false\n\n constructor(definition: AgentDefinition, options: AgentSessionOptions) {\n if (definition.mode === 'deep-human-in-loop' && options.userInput === undefined) {\n throw new TypeError(`agent '${definition.id}' requires a userInput broker in deep-human-in-loop mode`)\n }\n this.definition = definition\n const historyLimits = options.historyLimits === undefined\n ? undefined\n : Object.freeze({ ...options.historyLimits })\n // Validate reset-time policy even when the initial History was supplied by\n // the host, and detach mutable option containers from the caller.\n if (options.history !== undefined && historyLimits !== undefined) void new History(historyLimits)\n const compaction = options.compaction === undefined || options.compaction === false\n ? options.compaction\n : Object.freeze({ ...options.compaction })\n const trace = options.trace === undefined ? undefined : Object.freeze({ ...options.trace })\n const team = options.team === undefined ? undefined : Object.freeze({ ...options.team })\n const ledgerLimits = options.ledgerLimits === undefined ? undefined : Object.freeze({ ...options.ledgerLimits })\n const eventBufferLimits = options.eventBufferLimits === undefined\n ? undefined\n : Object.freeze({ ...options.eventBufferLimits })\n this.options = Object.freeze({\n ...options,\n ...(historyLimits === undefined ? {} : { historyLimits }),\n ...(compaction === undefined ? {} : { compaction }),\n ...(trace === undefined ? {} : { trace }),\n ...(team === undefined ? {} : { team }),\n ...(ledgerLimits === undefined ? {} : { ledgerLimits }),\n ...(eventBufferLimits === undefined ? {} : { eventBufferLimits }),\n ...(options.skills === undefined ? {} : { skills: Object.freeze([...options.skills]) }),\n ...(Array.isArray(options.tools) ? { tools: Object.freeze([...options.tools]) } : {}),\n ...(options.interceptors === undefined ? {} : { interceptors: Object.freeze([...options.interceptors]) }),\n })\n this.runtimeLimits = resolveRuntimeLimits(options.runtimeLimits)\n // A session may replace a definition section by reusing its id: the\n // definition describes the agent, the session describes where it is\n // running, and the more specific one wins in place. Two sections with one\n // id inside the *same* list stays an error — a single live surface node\n // cannot have two owners.\n const overrides = captureContextSections(options.contextSections) ?? []\n const base = captureContextSections(definition.contextSections) ?? []\n const merged = [\n ...base.map(section => overrides.find(override => override.id === section.id) ?? section),\n ...overrides.filter(override => !base.some(section => section.id === override.id)),\n ]\n this.contextSections = merged.length === 0 ? undefined : Object.freeze(merged)\n this.currentConversationId = conversationId(options.conversationId)\n this.currentHistory = options.history ?? new History(historyLimits)\n const skillSources = [...definition.skills, ...options.skills ?? []]\n const skillRuntimeDisabled = definition.skillIds?.length === 0\n const skillRuntimeConfigured = skillSources.length > 0 || (definition.skillIds?.length ?? 0) > 0\n this.skillCatalog = skillRuntimeDisabled || !skillRuntimeConfigured\n ? undefined\n : new SkillCatalog(skillSources, {\n ...(definition.skillIds === undefined ? {} : { allowedSkillIds: definition.skillIds }),\n maxSkills: definition.skillOptions.maxSkills,\n maxCatalogBytes: definition.skillOptions.maxDiscoveryBytes,\n })\n const skillTools = this.skillCatalog === undefined ? [] : createSkillTools(\n this.skillCatalog,\n definition.skillOptions,\n () => this.skillLookup(),\n )\n const teamAccess = options.team?.tools === 'reporting' ? 'reporting' as const : 'full' as const\n const teamTools = options.team?.tools === false\n ? []\n : options.team?.team.toolsFor(options.team.name ?? definition.id, teamAccess) ?? []\n this.catalog = toolCatalog(definition.tools, options.tools, [...skillTools, ...teamTools])\n this.currentMemory = options.memory instanceof AgentMemory\n ? options.memory\n : options.memory === undefined\n ? new AgentMemory(definition.memory.seed, definition.memory)\n : AgentMemory.fromSnapshot(options.memory, definition.memory)\n captureResumedObjective(this.currentMemory, this.currentHistory, this.definition.memory.autoCaptureObjective)\n this.compactor = this.createCompactor()\n attachRuntimeSession(this, (input, invocation, additionalInstructions) =>\n this.createRunHandle(input, invocation, additionalInstructions), invocation =>\n this.createRunHandle(undefined, invocation), invocation =>\n this.compactForRuntime(invocation), () => {\n this.compactor = this.createCompactor()\n })\n options.team?.team.attach(this, {\n ...(options.team.name === undefined ? {} : { name: options.team.name }),\n ...(options.team.description === undefined ? {} : { description: options.team.description }),\n ...(options.team.instructions === undefined ? {} : { instructions: options.team.instructions }),\n ...(options.team.role === undefined ? {} : { role: options.team.role }),\n ...(options.team.tools === undefined ? {} : { tools: options.team.tools }),\n })\n }\n\n /** Restore a JSON-round-tripped session snapshot with fresh runtime dependencies. */\n static fromSnapshot(\n definition: AgentDefinition,\n options: AgentResumeSessionOptions,\n ): AgentSession {\n const { snapshot, ...runtime } = options\n validateSessionSnapshot(snapshot, definition.id, definition.skillOptions.maxSkills)\n const session = new AgentSession(definition, {\n ...runtime,\n conversationId: snapshot.conversationId,\n history: History.fromSnapshot(snapshot.history, runtime.historyLimits),\n memory: AgentMemory.fromSnapshot(snapshot.memory, definition.memory),\n })\n session.pendingSkillActivations = captureResumedSkillActivations(snapshot.skills, session.skillCatalog)\n return session\n }\n\n /** Stable identity for persistence keys, URLs, logs, and GUI trace grouping. */\n get conversationId(): string { return this.currentConversationId }\n\n /** Mutable append-only history owned by this conversation. */\n get history(): History { return this.currentHistory }\n\n /** Durable task facts injected into every request outside compactable history. */\n get memory(): AgentMemory { return this.currentMemory }\n\n /** Refreshable skill catalog for host UIs and explicit user invocation surfaces. */\n get skills(): SkillCatalog | undefined { return this.skillCatalog }\n\n /** Whether a model/tool turn currently owns this session. */\n get isRunning(): boolean { return this.active }\n\n /** Capture one JSON-safe envelope that can be passed to `agent.resumeSession()`. */\n snapshot(): AgentSessionSnapshot {\n const activated = this.activationSnapshot()\n const history = this.currentHistory.snapshot()\n const pending = this.pendingInjections?.entries() ?? []\n // An accepted input must survive a snapshot taken before its model round\n // finishes. Project pending inputs at the known tail without delivering\n // them early to the live model or changing the persisted v1 schema.\n const persistedHistory = pending.length === 0 ? history : Object.freeze({\n version: 1 as const,\n entries: Object.freeze([...history.entries, ...pending.map((entry, index) => Object.freeze({\n ...entry, seq: history.entries.length + index + 1,\n }))]),\n })\n return Object.freeze({\n version: 1 as const,\n conversationId: this.currentConversationId,\n agentId: this.definition.id,\n history: persistedHistory,\n memory: this.currentMemory.snapshot(),\n ...runtimeSessionConfiguration(this)?.memory === undefined ? {} : {\n memoryBindingId: runtimeSessionConfiguration(this)!.memory!.bindingId,\n },\n ...activated.length === 0 ? {} : {\n skills: Object.freeze({ activated }),\n },\n })\n }\n\n /** Start a fresh conversation without rebuilding provider/tool configuration. */\n reset(): void {\n if (this.active) throw new Error('cannot reset an agent session while a run is active')\n this.currentConversationId = newConversationId()\n this.currentHistory = new History(this.options.historyLimits)\n this.currentMemory = new AgentMemory(this.definition.memory.seed, this.definition.memory)\n this.pendingInjections = undefined\n this.pendingSkillActivations = Object.freeze([])\n this.skillCatalog?.clearActivations()\n this.compactor = this.createCompactor()\n }\n\n /** Create one explicit context checkpoint while the session is idle. */\n async compact(invocation: AgentInvocationOptions = {}): Promise<CompactionResult | null> {\n if (this.active) throw new Error('cannot compact an agent session while a run is active')\n this.active = true\n this.activeInvocation = invocation\n try {\n await this.prepareSkills(invocation.signal)\n return await this.compactor?.compactNow(invocation.signal) ?? null\n } finally {\n this.releaseRun()\n }\n }\n\n private async compactForRuntime(invocation: AgentInvocationOptions): Promise<{\n readonly result: CompactionResult | null\n readonly report: LegacyRunReport\n readonly failure?: unknown\n }> {\n if (this.active) throw new Error('cannot compact an agent session while a run is active')\n const ledger = this.createLedger()\n this.active = true\n this.activeInvocation = invocation\n if (this.compactor !== undefined) bindCompactionAccounting(this.compactor, ledger)\n if (this.skillCatalog !== undefined) bindSkillProviderLogger(this.skillCatalog, ledger.modelInvocation.logger)\n try { return await runRuntimeCompaction({\n ...(this.compactor === undefined ? {} : { compactor: this.compactor }),\n invocation,\n accounting: ledger,\n prepare: () => this.prepareSkills(invocation.signal, ledger),\n }) } finally { this.releaseRun() }\n }\n\n /**\n * Append attributed context without starting a turn.\n *\n * A2A quiet delivery uses this primitive. The returned count includes queued\n * inputs and lets wake-up schedulers coalesce messages safely; a mid-round\n * receipt is provisional rather than the eventual persisted entry sequence.\n */\n inject(input: AgentInput): number {\n const message = userMessage(input)\n // Mid-run, hold the message until the next model request is built, so it\n // lands after every entry the model has actually answered. Bound pending\n // inputs with the same guards as history instead of an unbounded array.\n if (this.active && this.roundInFlight) {\n const pending = this.pendingInjections ??= new History(this.options.historyLimits)\n pending.append({ kind: 'user', message })\n return this.currentHistory.entries().length + pending.entries().length\n }\n this.drainInjections()\n this.currentHistory.append({ kind: 'user', message })\n return this.currentHistory.entries().length\n }\n\n /**\n * Close the in-flight window once a round's output is fully recorded: after\n * its tool results (`step-end`), or when the turn ends. The loop waits on\n * this consumer, so held messages land exactly there, never between a tool\n * call and its result.\n *\n * A round that answers without calling a tool ends the turn, and input the\n * person sent while it was being written is still owed an answer. It stays\n * held until the loop is about to end the turn; the loop then takes it (see\n * `bindQueuedInput`) and answers it in another round of the same run instead\n * of leaving it for a later `runPending()`.\n */\n private observeRoundBoundary(event: { readonly type: string; readonly kind?: string; readonly message?: { readonly content: readonly { readonly type: string }[] } }): void {\n // The chat request is now fixed. beforeStep hooks still run outside this\n // window, so their injections can be included in that request's refresh.\n if (event.type === 'span-start' && event.kind === 'chat') {\n this.roundInFlight = true\n this.roundCalledTools = false\n return\n }\n if (!this.roundInFlight) return\n if (event.type === 'tool-call' || (event.type === 'assistant-message'\n && event.message?.content.some(block => block.type === 'tool-call') === true)) {\n this.roundCalledTools = true\n }\n // A tool round's output is complete at step-end; a final answer's input\n // waits for the loop to take it at turn end, unless the turn is already over.\n if ((event.type === 'step-end' && this.roundCalledTools) || event.type === 'turn-end' || event.type === 'agent-end') {\n this.roundInFlight = false\n this.drainInjections()\n }\n }\n\n /** Deliver held injections, in arrival order, at the chronological tail. */\n private drainInjections(): void {\n if (this.pendingInjections === undefined) return\n const pending = this.pendingInjections\n // Atomic: a full history must not consume only the first queued input and\n // silently lose the rest. Keep the buffer available to snapshot/recovery.\n this.currentHistory.appendBatch(pending.entries().map(entry => ({ event: entry.event })))\n this.pendingInjections = undefined\n }\n\n /**\n * Whether the latest visible message still awaits the model: new input, a\n * tool result, or a notice. False once the model has answered everything,\n * which lets a scheduler skip a run that would only repeat that answer.\n */\n hasUnansweredInput(): boolean {\n if ((this.pendingInjections?.entries().length ?? 0) > 0) return true\n return this.currentHistory.messages().at(-1)?.role === 'user'\n }\n\n /** Resolve after the current run releases the session. */\n whenIdle(signal?: AbortSignal): Promise<void> {\n if (!this.active) return Promise.resolve()\n if (signal?.aborted) return Promise.reject(signal.reason)\n return new Promise<void>((resolve, reject) => {\n let settled = false\n const finish = (): void => {\n if (settled) return\n settled = true\n this.idleWaiters.delete(finish)\n signal?.removeEventListener('abort', abort)\n resolve()\n }\n const abort = (): void => {\n if (settled) return\n settled = true\n this.idleWaiters.delete(finish)\n reject(signal?.reason)\n }\n this.idleWaiters.add(finish)\n signal?.addEventListener('abort', abort, { once: true })\n if (!this.active) finish()\n })\n }\n\n /** Start an eager run and expose both public events and its canonical terminal report. */\n stream(input: AgentInput, invocation: AgentInvocationOptions = {}): AgentRunHandle {\n return this.createRunHandle(input, invocation)\n }\n\n /** Process context already appended with {@link inject} without duplicating it. */\n streamPending(invocation: AgentInvocationOptions = {}): AgentRunHandle {\n return this.createRunHandle(undefined, invocation)\n }\n\n /** Run one user turn and return the terminal response. */\n async run(input: AgentInput, invocation: AgentInvocationOptions = {}): Promise<AgentResponse> {\n const handle = this.stream(input, invocation)\n await consumeSessionEvents(handle, invocation.onEvent, this.runtimeLimits.observerTimeoutMs ?? 30_000)\n return await handle.result\n }\n\n /** Run one turn over already-injected context and return its terminal response. */\n async runPending(invocation: AgentInvocationOptions = {}): Promise<AgentResponse> {\n const handle = this.streamPending(invocation)\n await consumeSessionEvents(handle, invocation.onEvent, this.runtimeLimits.observerTimeoutMs ?? 30_000)\n return await handle.result\n }\n\n private createRunHandle(\n input: AgentInput | undefined,\n invocation: AgentInvocationOptions,\n additionalInstructions?: string,\n ): AgentRunHandle {\n if (this.active) throw new Error(`agent session '${this.definition.id}' is already running`)\n this.drainInjections()\n const firstTurnSeq = this.currentHistory.entries().length + 1\n const owned = new AbortController()\n let terminal = false\n const signal = invocation.signal === undefined\n ? owned.signal\n : AbortSignal.any([invocation.signal, owned.signal])\n const buffer = new RunEventBuffer<AgentRunEvent>(\n this.options.eventBufferLimits?.maxEvents,\n this.options.eventBufferLimits?.maxBytes,\n )\n const reportDeferred = deferred<RunReport>()\n const resultDeferred = deferred<AgentResponse>()\n const toolSourcesDeferred = deferred<readonly ToolSourceRunReference[]>()\n const ledger = this.createLedger()\n let toolSourceReferences: readonly ToolSourceRunReference[] = Object.freeze([])\n if (this.compactor !== undefined) bindCompactionAccounting(this.compactor, ledger)\n if (this.skillCatalog !== undefined) {\n bindSkillProviderLogger(this.skillCatalog, ledger.modelInvocation.logger)\n }\n this.active = true\n bindModelRequestBoundary(this.currentHistory, inFlight => {\n this.roundInFlight = inFlight\n if (!inFlight) this.drainInjections()\n })\n bindQueuedInput(this.currentHistory, () => {\n // By entries, not by the buffer: an input refused at admission leaves an\n // empty buffer behind, and that must not buy the run another round.\n const held = this.pendingInjections?.entries() ?? []\n if (held.length === 0) return false\n // Only the person's own messages extend the run. Team deliveries keep\n // their contract: queued behind the answer, then processed exactly once\n // by the team's wake-up through runPending().\n const fromPerson = held.some(entry => entry.event.kind === 'user' && entry.event.message.source.kind === 'user')\n if (!fromPerson) return false\n this.roundInFlight = false\n this.drainInjections()\n return true\n })\n this.activeAdditionalInstructions = additionalInstructions\n this.activeInvocation = invocation\n const spanOperations = new Map<string, string>()\n const task = (async (): Promise<void> => {\n let failure: unknown\n let outcome: AgentRunOutcome | undefined\n let memoryState: Awaited<ReturnType<typeof loadRuntimeMemory>>['state'] | undefined\n try {\n const runtime = runtimeSessionConfiguration(this)\n if (runtime?.memory !== undefined) {\n const prepared = await loadRuntimeMemory(\n runtime.memory, this.currentConversationId, this.definition.memory, signal, ledger,\n )\n memoryState = prepared.state\n if (prepared.memory !== undefined) this.currentMemory = prepared.memory\n }\n if (runtime?.prepareTools !== undefined) {\n const logger = ledger.modelInvocation.logger\n if (logger === undefined) throw new Error('runtime tool source logger is unavailable')\n const generation = runtime.prepareTools(signal, logger, [...this.catalog?.names() ?? [], ...this.definition.nativeTools.map(tool => tool.name)])\n this.activeRuntimeCatalog = toolCatalog([], this.catalog, generation.tools)\n toolSourceReferences = generation.references\n }\n toolSourcesDeferred.resolve(toolSourceReferences)\n await this.prepareSkills(signal, ledger)\n if (input !== undefined) {\n const message = userMessage(input)\n if (this.definition.memory.autoCaptureObjective) {\n const operation = ledger.startOperation('memory', { data: { action: 'capture-objective' } })\n try {\n this.currentMemory.captureOriginalObjective(message)\n ledger.endOperation(operation, 'success')\n } catch (error) {\n ledger.endOperation(operation, 'error', { error })\n throw error\n }\n }\n this.currentHistory.append({ kind: 'user', message })\n }\n // Preflight before compaction can turn a required image into a summary.\n if (invocation.imagePolicy === 'strict' && this.history.messages().some(message => contentHasImage(message.content))) {\n const config = this.callConfig(invocation)\n const model = await this.options.registry.resolveModelInfo(config.provider, config.model, signal)\n if (model.inputModalities !== undefined && !model.inputModalities.includes('image')) {\n throw new ModelError(`model ${model.id} does not support required image input`, 'UNSUPPORTED_IMAGE_INPUT')\n }\n }\n // Same preflight for documents, for the same reason.\n if (invocation.documentPolicy === 'strict' && this.history.messages().some(message => contentHasDocument(message.content))) {\n const config = this.callConfig(invocation)\n const model = await this.options.registry.resolveModelInfo(config.provider, config.model, signal)\n if (model.inputModalities !== undefined && !model.inputModalities.includes('document')) {\n throw new ModelError(`model ${model.id} does not support required document input`, 'UNSUPPORTED_DOCUMENT_INPUT')\n }\n }\n for await (const event of this.runDefinition({ ...invocation, signal }, ledger)) {\n this.observeRoundBoundary(event)\n accountTraceEvent(ledger, spanOperations, event)\n if (event.type === 'agent-end') outcome = event.outcome\n buffer.push(event)\n }\n if (outcome === undefined) {\n throw new Error(`agent session '${this.definition.id}' ended without agent-end`)\n }\n if (signal.aborted) throw signal.reason ?? new Error('agent run was aborted')\n if (outcome.reason.kind === 'error' && outcome.reason.failure.code === 'USAGE_REQUIRED') {\n const error = new Error(outcome.reason.failure.message) as Error & { code: string }\n error.code = 'USAGE_REQUIRED'\n throw error\n }\n if (runtime?.memory !== undefined && memoryState !== undefined && memoryState.status !== 'disabled') {\n await commitRuntimeMemory(\n runtime.memory, this.currentConversationId, this.currentMemory.snapshot(),\n memoryState, signal, ledger,\n )\n }\n } catch (error: unknown) {\n failure = error\n toolSourcesDeferred.resolve(toolSourceReferences)\n }\n\n try { this.drainInjections() } catch (error) { failure ??= error }\n\n let report: RunReport\n try {\n const status: OperationStatus = signal.aborted || outcome?.reason.kind === 'aborted'\n ? 'aborted'\n : failure !== undefined || outcome?.reason.kind === 'error'\n ? 'error'\n : 'success'\n const ledgerReport = await ledger.finalize(status, outcome?.completed ?? false, failure)\n report = withTerminalDelivery(createRunTerminalRecord(ledgerReport), ledgerReport.delivery)\n reportDeferred.resolve(report)\n } catch (finalizeError: unknown) {\n reportDeferred.reject(finalizeError)\n resultDeferred.reject(finalizeError)\n buffer.fail(finalizeError)\n terminal = true\n this.releaseRun()\n return\n }\n if (terminal) return\n\n if (failure === undefined && ledger.terminalAuditFailure) {\n const error = new Error('audit observation checkpoint failed after run finalization') as Error & { code: string }\n error.code = 'OBSERVABILITY_AUDIT_UNAVAILABLE'\n failure = error\n }\n if (failure !== undefined) {\n const error = new AgentRunError(\n messageOf(failure),\n errorCodeOf(failure) ?? AGENT_ACCOUNTING_ERROR_CODES.RUN_FAILED,\n report,\n { cause: failure },\n )\n resultDeferred.reject(error)\n buffer.fail(error)\n } else {\n const terminal = outcome as AgentRunOutcome\n const historyEvent = [...this.currentHistory.entries()].reverse()\n .find(entry => entry.seq >= firstTurnSeq && entry.event.kind === 'assistant')\n ?.event\n const assistantMessage = historyEvent?.kind === 'assistant' ? historyEvent.message : undefined\n const response: AgentResponse = Object.freeze({\n text: terminal.text,\n outcome: terminal,\n report,\n ...assistantMessage === undefined ? {} : { message: assistantMessage },\n })\n resultDeferred.resolve(response)\n buffer.close()\n }\n terminal = true\n this.releaseRun()\n })()\n void task.catch(error => {\n if (terminal) return\n reportDeferred.reject(error)\n resultDeferred.reject(error)\n buffer.fail(error)\n terminal = true\n this.releaseRun()\n })\n void resultDeferred.promise.catch(() => undefined)\n void reportDeferred.promise.catch(() => undefined)\n let iterated = false\n return Object.freeze({\n runId: ledger.runId,\n traceId: ledger.traceId,\n toolSourceSnapshots: toolSourcesDeferred.promise,\n eventsSettled: task.then(() => undefined, () => undefined),\n result: resultDeferred.promise,\n report: reportDeferred.promise,\n seal: () => sealRuntimeRun({ ledger, buffer, report: reportDeferred, result: resultDeferred,\n toolSources: toolSourcesDeferred, currentToolSources: () => toolSourceReferences, isTerminal: () => terminal,\n markTerminal: () => { terminal = true }, abort: () => owned.abort(new Error('Agent run was sealed')),\n release: () => this.releaseRun() }),\n abort(_reason?: unknown): void {\n if (!terminal && !owned.signal.aborted) owned.abort(new Error('Agent run was aborted'))\n },\n [Symbol.asyncIterator](): AsyncIterator<AgentRunEvent> {\n if (iterated) return (async function* () { throw new Error('an agent run handle can only be iterated once') })()\n iterated = true\n return (async function* () {\n let exhausted = false\n try {\n while (true) {\n const item = await buffer.take()\n if (item.done) { exhausted = true; break }\n yield item.value\n }\n } finally {\n if (!exhausted) {\n owned.abort(new Error('agent event consumer stopped'))\n buffer.stop()\n await waitForSettlement(task, 30_000)\n }\n }\n })()\n },\n })\n }\n\n private releaseRun(): void {\n // A message that arrived during the final model round is still delivered,\n // so the next run (or a waiting scheduler) reads it.\n try { this.drainInjections() } finally {\n bindModelRequestBoundary(this.currentHistory)\n bindQueuedInput(this.currentHistory)\n this.roundInFlight = false\n this.active = false\n this.activeAdditionalInstructions = undefined\n this.activeInvocation = undefined\n this.activeRuntimeCatalog = undefined\n if (this.skillCatalog !== undefined) bindSkillProviderLogger(this.skillCatalog, undefined)\n if (this.compactor !== undefined) bindCompactionAccounting(this.compactor, undefined)\n const waiters = [...this.idleWaiters]\n this.idleWaiters.clear()\n for (const resolve of waiters) resolve()\n }\n }\n\n private createLedger() {\n const runtime = runtimeSessionConfiguration(this)\n return createSessionLedger({\n definition: this.definition,\n options: this.options,\n runtimeLimits: this.runtimeLimits,\n conversationId: this.currentConversationId,\n ...(runtime === undefined ? {} : { runtime }),\n })\n }\n\n private runDefinition(\n invocation: AgentInvocationOptions,\n accounting?: RunAccountingPort,\n ): AsyncIterable<AgentRunEvent> {\n const definition = this.definition\n const hooks = this.combinedHooks(accounting)\n const catalog = this.effectiveCatalog()\n const outputFormat = invocation.outputFormat ?? definition.outputFormat\n const common = {\n registry: this.options.registry,\n config: this.callConfig(invocation),\n history: this.history,\n ...catalog === undefined ? {} : { tools: catalog },\n ...definition.nativeTools.length === 0 ? {} : { nativeTools: definition.nativeTools },\n ...definition.toolChoice === undefined ? {} : { toolChoice: definition.toolChoice },\n ...invocation.imagePolicy === undefined ? {} : { imagePolicy: invocation.imagePolicy },\n ...invocation.documentPolicy === undefined ? {} : { documentPolicy: invocation.documentPolicy },\n ...outputFormat === undefined ? {} : { outputFormat },\n ...(invocation.validateOutput === undefined ? {} : { validateOutput: invocation.validateOutput }),\n system: this.systemInstructions(this.activeAdditionalInstructions),\n maxTurns: definition.maxTurns,\n bounds: {\n maxToolCalls: definition.maxToolCalls,\n ...this.runtimeLimits.maxParallelToolCalls === undefined\n ? {}\n : { maxParallel: this.runtimeLimits.maxParallelToolCalls },\n ...this.runtimeLimits.maxConsecutiveToolErrors === undefined\n ? {}\n : { maxConsecutiveToolErrors: this.runtimeLimits.maxConsecutiveToolErrors },\n ...this.runtimeLimits.repeatToolWarningAt === undefined\n ? {}\n : { repeatToolWarningAt: this.runtimeLimits.repeatToolWarningAt },\n ...this.runtimeLimits.repeatToolLimit === undefined\n ? {}\n : { repeatToolLimit: this.runtimeLimits.repeatToolLimit },\n ...this.runtimeLimits.toolCycleWarningAt === undefined\n ? {}\n : { toolCycleWarningAt: this.runtimeLimits.toolCycleWarningAt },\n ...this.runtimeLimits.toolCycleLimit === undefined\n ? {}\n : { toolCycleLimit: this.runtimeLimits.toolCycleLimit },\n ...this.runtimeLimits.onExhausted === undefined\n ? {}\n : { onExhausted: this.runtimeLimits.onExhausted },\n ...this.runtimeLimits.maxToolResultTokens === undefined\n ? {}\n : { maxToolResultTokens: this.runtimeLimits.maxToolResultTokens },\n ...this.runtimeLimits.toolResultOverflow === undefined\n ? {}\n : { toolResultOverflow: this.runtimeLimits.toolResultOverflow },\n ...this.runtimeLimits.maxToolCycleLength === undefined\n ? {}\n : { maxToolCycleLength: this.runtimeLimits.maxToolCycleLength },\n ...this.runtimeLimits.finalReportReserveTokens === undefined ? {} : {\n finalReportReserveTokens: this.runtimeLimits.finalReportReserveTokens,\n },\n ...this.runtimeLimits.maxTotalTokens === undefined\n ? {}\n : { maxTotalTokens: this.runtimeLimits.maxTotalTokens },\n ...this.runtimeLimits.maxToolResultBytes === undefined\n ? {}\n : { maxToolResultBytes: this.runtimeLimits.maxToolResultBytes },\n ...this.runtimeLimits.maxToolDurationMs === undefined\n ? {}\n : { maxToolDurationMs: this.runtimeLimits.maxToolDurationMs },\n ...this.runtimeLimits.toolTeardownTimeoutMs === undefined\n ? {}\n : { toolTeardownTimeoutMs: this.runtimeLimits.toolTeardownTimeoutMs },\n },\n commentary: definition.commentary,\n ...this.runtimeLimits.teardownTimeoutMs === undefined ? {} : { teardownTimeoutMs: this.runtimeLimits.teardownTimeoutMs },\n ...this.runtimeLimits.modelTimeoutMs === undefined ? {} : { modelTimeoutMs: this.runtimeLimits.modelTimeoutMs },\n ...this.runtimeLimits.maxModelRequestBytes === undefined ? {} : { maxModelRequestBytes: this.runtimeLimits.maxModelRequestBytes },\n ...this.runtimeLimits.maxModelResponseBytes === undefined ? {} : { maxModelResponseBytes: this.runtimeLimits.maxModelResponseBytes },\n ...this.runtimeLimits.maxModelStreamEvents === undefined ? {} : { maxModelStreamEvents: this.runtimeLimits.maxModelStreamEvents },\n ...this.runtimeLimits.hookTimeoutMs === undefined ? {} : { hookTimeoutMs: this.runtimeLimits.hookTimeoutMs },\n ...this.runtimeLimits.hookTeardownTimeoutMs === undefined ? {} : { hookTeardownTimeoutMs: this.runtimeLimits.hookTeardownTimeoutMs },\n ...this.options.approvals === undefined ? {} : { approvals: this.options.approvals },\n ...this.options.spillStore === undefined ? {} : { spillStore: this.options.spillStore },\n ...this.options.experimentalPrograms === undefined ? {} : { experimentalPrograms: this.options.experimentalPrograms },\n ...this.options.interceptors === undefined ? {} : { interceptors: this.options.interceptors },\n ...this.contextSections === undefined ? {} : { contextSections: this.contextSections },\n ...hooks === undefined ? {} : { hooks },\n ...invocation.signal === undefined ? {} : { signal: invocation.signal },\n ...accounting === undefined ? {} : { accounting },\n ...accounting?.modelInvocation.logger === undefined ? {} : { logger: accounting.modelInvocation.logger },\n trace: {\n ...this.options.trace,\n conversationId: this.currentConversationId,\n agentId: definition.id,\n agentName: definition.name,\n },\n }\n if (definition.mode === 'deep-human-in-loop') {\n return runAgent({\n ...common, mode: definition.mode, userInput: this.options.userInput as UserInputBroker,\n })\n }\n if (definition.mode === 'deep') {\n return runAgent({\n ...common, mode: definition.mode,\n ...this.options.userInput === undefined ? {} : { userInput: this.options.userInput },\n })\n }\n return runAgent({ ...common, mode: 'basic' })\n }\n\n private createCompactor(): ContextCompactor | undefined {\n const configured = this.options.compaction === false\n ? false\n : this.options.compaction === undefined\n ? this.definition.compaction\n : resolveCompactionConfig(this.options.compaction)\n if (configured === false) return undefined\n return new ContextCompactor({\n registry: this.options.registry,\n config: () => this.callConfig(this.activeInvocation),\n history: () => this.currentHistory,\n system: () => this.systemInstructions(this.activeAdditionalInstructions),\n pinnedMessages: () => renderRuntimeMemory(\n this.currentMemory, this.definition.memory.maxInjectedChars,\n ),\n tools: () => [\n ...this.effectiveCatalog()?.schemas() ?? [],\n ...this.definition.nativeTools,\n ],\n policy: configured,\n })\n }\n\n private effectiveCatalog(): ToolCatalog | undefined {\n return this.activeRuntimeCatalog ?? this.catalog\n }\n\n private combinedHooks(accounting?: RunAccountingPort): TurnHooks | undefined {\n const user = this.options.hooks\n const hooks: TurnHooks = {\n ...user,\n beforeStep: async context => {\n // Before anything reads history for this request: model-round refreshes\n // its messages when entries changed, so delivered input is included.\n const generation = this.currentHistory.generation()\n const entries = this.currentHistory.entries().length\n this.drainInjections()\n const prepared = this.currentHistory.entries().length === entries\n ? context\n : { ...context, messages: normalizeToolPairing(this.currentHistory.messages()), snapshot: this.currentHistory.snapshot() }\n if (this.compactor !== undefined) bindCompactionAccounting(this.compactor, accounting)\n await this.compactor?.beforeStep(prepared)\n if (accounting?.usageStop !== undefined) return { kind: 'proceed' as const }\n const refreshed = this.currentHistory.generation() === generation && this.currentHistory.entries().length === entries\n ? context\n : {\n ...context,\n messages: normalizeToolPairing(this.currentHistory.messages()),\n snapshot: this.currentHistory.snapshot(),\n }\n const memory = renderRuntimeMemory(\n this.currentMemory, this.definition.memory.maxInjectedChars, accounting,\n )\n const current = memory.length === 0\n ? refreshed\n : { ...refreshed, messages: Object.freeze([...memory, ...refreshed.messages]) }\n const decision = await user?.beforeStep?.(current) ?? { kind: 'proceed' as const }\n if (decision.kind === 'reject') return decision\n // A projection sees injected memory already; do not inject it twice.\n const prepend = [...decision.messages === undefined ? memory : [], ...decision.prepend ?? []]\n return bindStepProjectionSources(prepend.length === 0 ? decision : { ...decision, prepend }, refreshed.messages)\n },\n onRequestError: async context => {\n if (this.compactor !== undefined) bindCompactionAccounting(this.compactor, accounting)\n const recovery = await this.compactor?.onRequestError(context)\n if (accounting?.usageStop !== undefined) return 'fail'\n if (recovery === 'retry') return 'retry'\n return await user?.onRequestError?.(context) ?? 'fail'\n },\n }\n return hooks\n }\n\n private callConfig(invocation?: AgentInvocationOptions) {\n return sessionCallConfig(this.definition, runtimeSessionConfiguration(this), invocation)\n }\n\n private systemInstructions(additionalInstructions?: string): string {\n const base = this.skillCatalog === undefined\n ? this.definition.instructions\n : renderSkillCatalog(\n this.definition.instructions,\n this.skillCatalog.summaries(),\n this.definition.skillOptions,\n )\n const team = this.options.team\n const composed = team === undefined\n ? base\n : `${base}\\n\\n${team.team.instructionsFor(team.name ?? this.definition.id)}`\n return appendRunInstructions(composed, additionalInstructions)\n }\n\n private skillLookup(signal?: AbortSignal): SkillLookupOptions {\n return {\n ...(this.options.skillCwd === undefined ? {} : { cwd: this.options.skillCwd }),\n ...(signal === undefined ? {} : { signal }),\n }\n }\n\n private activationSnapshot(): readonly AgentSessionActivatedSkillSnapshot[] {\n const activated = new Map<string, AgentSessionActivatedSkillSnapshot>()\n for (const entry of this.pendingSkillActivations) activated.set(entry.id, entry)\n for (const reference of this.skillCatalog?.activatedSkillReferences() ?? []) {\n activated.set(reference.id, reference)\n }\n for (const summary of this.skillCatalog?.activatedSummaries() ?? []) {\n if (activated.has(summary.id)) continue\n activated.set(summary.id, Object.freeze({\n id: summary.id, provider: summary.provider, source: summary.source,\n ...summary.resourceBase === undefined ? {} : {\n resourceBase: Object.freeze({ ...summary.resourceBase }),\n },\n }))\n }\n return Object.freeze([...activated.values()].sort((left, right) => left.id.localeCompare(right.id)))\n }\n\n private async prepareSkills(signal?: AbortSignal, accounting?: RunAccountingPort): Promise<void> {\n await prepareSkills(\n this.definition, this.skillCatalog, this.pendingSkillActivations,\n signal => this.skillLookup(signal),\n () => { this.pendingSkillActivations = Object.freeze([]) }, signal, accounting,\n )\n }\n}\n\nexport { configureRuntimeSessionModel, streamRuntimeSession } from './session/runtime-binding.ts'\nexport type {\n AgentInput, AgentRuntimeLimits, AgentSessionOptions, AgentTeamMemberOptions,\n AgentSessionSnapshot, AgentSessionActivatedSkillSnapshot, AgentResumeSessionOptions,\n AgentInvocationOptions, AgentResponse, AgentRunHandle,\n} from './session/types.ts'\n"],"mappings":"y3EAoDA,IAAa,EAAb,MAAa,CAAa,CACxB,WACA,QACA,QACA,qBACA,aACA,cAEA,gBACA,eACA,cACA,sBACA,UACA,wBAAiF,OAAO,OAAO,CAAC,CAAC,EACjG,OAAiB,GACjB,6BAEA,iBACA,YAA+B,IAAI,IAOnC,kBAMA,cAAwB,GAExB,iBAA2B,GAE3B,YAAY,EAA6B,EAA8B,CACrE,GAAI,EAAW,OAAS,sBAAwB,EAAQ,YAAc,IAAA,GACpE,MAAU,UAAU,UAAU,EAAW,GAAG,yDAAyD,EAEvG,KAAK,WAAa,EAClB,I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{"version":3,"file":"session.js","names":[],"sources":["../../../src/agent/define/session.ts"],"sourcesContent":["import { contentHasDocument, contentHasImage } from '../../message/projection.ts'\nimport { ModelError } from '../../errors/model-error.ts'\nimport { type ToolCatalog } from '../tool/registry.ts'\nimport { History } from '../history/history.ts'\nimport { isManagedTeamNotice } from '../history/input-work.ts'\nimport { bindModelRequestBoundary, bindQueuedInput } from '../loop/turn/model-request-boundary.ts'\nimport { bindStepProjectionSources } from '../loop/turn/step-projection.ts'\nimport { normalizeToolPairing } from '../history/normalize.ts'\nimport type { TurnHooks } from '../loop/types.ts'\nimport { ContextCompactor, type CompactionResult } from '../memory/compaction.ts'\nimport { bindCompactionAccounting } from '../memory/accounting-binding.ts'\nimport { resolveCompactionConfig } from '../memory/compaction-config.ts'\nimport { AgentMemory } from '../memory/memory.ts'\nimport { captureContextSections } from '../context/section.ts'\nimport type { ContextSection } from '../context/types.ts'\nimport { runAgent, type AgentRunEvent, type AgentRunOutcome } from '../mode/run-agent.ts'\nimport type { UserInputBroker } from '../mode/user-input.ts'\nimport { waitForSettlement } from '../../async/index.ts'\nimport type { OperationStatus } from '../../observation/index.ts'\nimport { RunEventBuffer } from '../accounting/event-buffer.ts'\nimport { AgentRunError, AGENT_ACCOUNTING_ERROR_CODES } from '../accounting/error.ts'\nimport type { RunAccountingPort } from '../accounting/contracts.ts'\nimport type { LegacyRunReport } from '../accounting/report.ts'\nimport type { RunReport } from '../accounting/delivery-types.ts'\nimport { createRunTerminalRecord, withTerminalDelivery } from '../accounting/delivery/terminal.ts'\nimport { SkillCatalog, createSkillTools, renderSkillCatalog, type SkillLookupOptions } from '../skill/index.ts'\nimport type { AgentDefinition } from './definition.ts'\nimport {\n type AgentInput, type AgentRuntimeLimits, type AgentSessionOptions, type AgentSessionSnapshot,\n type AgentSessionActivatedSkillSnapshot, type AgentResumeSessionOptions,\n type AgentInvocationOptions, type AgentResponse, type AgentRunHandle,\n} from './session/types.ts'\nimport { validateSessionSnapshot } from './session/validation.ts'\nimport { resolveRuntimeLimits } from './session/config.ts'\nimport {\n conversationId, newConversationId, userMessage, deferred, messageOf, errorCodeOf,\n toolCatalog,\n} from './session/common.ts'\nimport { captureResumedSkillActivations, prepareSkills } from './session/skills.ts'\nimport { appendRunInstructions } from './instructions.ts'\nimport type { ToolSourceRunReference } from '../tool/source-types.ts'\nimport { accountTraceEvent } from './session/trace-accounting.ts'\nimport {\n captureResumedObjective, commitRuntimeMemory, loadRuntimeMemory, renderRuntimeMemory,\n} from './session/runtime-memory.ts'\nimport { attachRuntimeSession, runtimeSessionConfiguration } from './session/runtime-binding.ts'\nimport { bindSkillProviderLogger } from '../skill/provider/context.ts'\nimport { createSessionLedger } from './session/accounting.ts'\nimport { runRuntimeCompaction } from './session/runtime-compaction.ts'\nimport { sessionCallConfig } from './session/model-config.ts'\nimport { consumeSessionEvents } from './session/observer.ts'\nimport { sealRuntimeRun } from './session/run-seal.ts'\n\nexport class AgentSession {\n readonly definition: AgentDefinition\n private readonly options: AgentSessionOptions\n private readonly catalog: ToolCatalog | undefined\n private activeRuntimeCatalog: ToolCatalog | undefined\n private readonly skillCatalog: SkillCatalog | undefined\n private readonly runtimeLimits: Readonly<AgentRuntimeLimits>\n /** Definition sections first, then session sections; duplicate ids are rejected. */\n private readonly contextSections: readonly ContextSection[] | undefined\n private currentHistory: History\n private currentMemory: AgentMemory\n private currentConversationId: string\n private compactor: ContextCompactor | undefined\n private pendingSkillActivations: readonly AgentSessionActivatedSkillSnapshot[] = Object.freeze([])\n private active = false\n private activeAdditionalInstructions: string | undefined\n /** The overlay of the run that owns the session, so maintenance follows the same model. */\n private activeInvocation: AgentInvocationOptions | undefined\n private readonly idleWaiters = new Set<() => void>()\n /**\n * Messages injected while a run is in flight, waiting for the next model\n * request. Appending them at once put them AHEAD of the assistant output of\n * the round already streaming, a round that never saw them; the next round\n * then read \"steer, then the work that ignored it\" as work that answered it.\n */\n private pendingInjections: History | undefined\n private lastRunOutcome: AgentRunOutcome | undefined\n /**\n * A model request has been built and its output is not yet fully recorded.\n * Only then is an injection held: hooks and team notices that inject between\n * rounds still append at once, as they always have.\n */\n private roundInFlight = false\n /** The round in flight called a tool, so its output ends at step-end. */\n private roundCalledTools = false\n\n constructor(definition: AgentDefinition, options: AgentSessionOptions) {\n if (definition.mode === 'deep-human-in-loop' && options.userInput === undefined) {\n throw new TypeError(`agent '${definition.id}' requires a userInput broker in deep-human-in-loop mode`)\n }\n this.definition = definition\n const historyLimits = options.historyLimits === undefined\n ? undefined\n : Object.freeze({ ...options.historyLimits })\n // Validate reset-time policy even when the initial History was supplied by\n // the host, and detach mutable option containers from the caller.\n if (options.history !== undefined && historyLimits !== undefined) void new History(historyLimits)\n const compaction = options.compaction === undefined || options.compaction === false\n ? options.compaction\n : Object.freeze({ ...options.compaction })\n const trace = options.trace === undefined ? undefined : Object.freeze({ ...options.trace })\n const team = options.team === undefined ? undefined : Object.freeze({ ...options.team })\n const ledgerLimits = options.ledgerLimits === undefined ? undefined : Object.freeze({ ...options.ledgerLimits })\n const eventBufferLimits = options.eventBufferLimits === undefined\n ? undefined\n : Object.freeze({ ...options.eventBufferLimits })\n this.options = Object.freeze({\n ...options,\n ...(historyLimits === undefined ? {} : { historyLimits }),\n ...(compaction === undefined ? {} : { compaction }),\n ...(trace === undefined ? {} : { trace }),\n ...(team === undefined ? {} : { team }),\n ...(ledgerLimits === undefined ? {} : { ledgerLimits }),\n ...(eventBufferLimits === undefined ? {} : { eventBufferLimits }),\n ...(options.skills === undefined ? {} : { skills: Object.freeze([...options.skills]) }),\n ...(Array.isArray(options.tools) ? { tools: Object.freeze([...options.tools]) } : {}),\n ...(options.interceptors === undefined ? {} : { interceptors: Object.freeze([...options.interceptors]) }),\n })\n this.runtimeLimits = resolveRuntimeLimits(options.runtimeLimits)\n // A session may replace a definition section by reusing its id: the\n // definition describes the agent, the session describes where it is\n // running, and the more specific one wins in place. Two sections with one\n // id inside the *same* list stays an error — a single live surface node\n // cannot have two owners.\n const overrides = captureContextSections(options.contextSections) ?? []\n const base = captureContextSections(definition.contextSections) ?? []\n const merged = [\n ...base.map(section => overrides.find(override => override.id === section.id) ?? section),\n ...overrides.filter(override => !base.some(section => section.id === override.id)),\n ]\n this.contextSections = merged.length === 0 ? undefined : Object.freeze(merged)\n this.currentConversationId = conversationId(options.conversationId)\n this.currentHistory = options.history ?? new History(historyLimits)\n const skillSources = [...definition.skills, ...options.skills ?? []]\n const skillRuntimeDisabled = definition.skillIds?.length === 0\n const skillRuntimeConfigured = skillSources.length > 0 || (definition.skillIds?.length ?? 0) > 0\n this.skillCatalog = skillRuntimeDisabled || !skillRuntimeConfigured\n ? undefined\n : new SkillCatalog(skillSources, {\n ...(definition.skillIds === undefined ? {} : { allowedSkillIds: definition.skillIds }),\n maxSkills: definition.skillOptions.maxSkills,\n maxCatalogBytes: definition.skillOptions.maxDiscoveryBytes,\n })\n const skillTools = this.skillCatalog === undefined ? [] : createSkillTools(\n this.skillCatalog,\n definition.skillOptions,\n () => this.skillLookup(),\n )\n const teamAccess = options.team?.tools === 'reporting' ? 'reporting' as const : 'full' as const\n const teamTools = options.team?.tools === false\n ? []\n : options.team?.team.toolsFor(options.team.name ?? definition.id, teamAccess) ?? []\n this.catalog = toolCatalog(definition.tools, options.tools, [...skillTools, ...teamTools])\n this.currentMemory = options.memory instanceof AgentMemory\n ? options.memory\n : options.memory === undefined\n ? new AgentMemory(definition.memory.seed, definition.memory)\n : AgentMemory.fromSnapshot(options.memory, definition.memory)\n captureResumedObjective(this.currentMemory, this.currentHistory, this.definition.memory.autoCaptureObjective)\n this.compactor = this.createCompactor()\n attachRuntimeSession(this, (input, invocation, additionalInstructions) =>\n this.createRunHandle(input, invocation, additionalInstructions), invocation =>\n this.createRunHandle(undefined, invocation), invocation =>\n this.compactForRuntime(invocation), () => {\n this.compactor = this.createCompactor()\n })\n options.team?.team.attach(this, {\n ...(options.team.name === undefined ? {} : { name: options.team.name }),\n ...(options.team.description === undefined ? {} : { description: options.team.description }),\n ...(options.team.instructions === undefined ? {} : { instructions: options.team.instructions }),\n ...(options.team.role === undefined ? {} : { role: options.team.role }),\n ...(options.team.tools === undefined ? {} : { tools: options.team.tools }),\n })\n }\n\n /** Restore a JSON-round-tripped session snapshot with fresh runtime dependencies. */\n static fromSnapshot(\n definition: AgentDefinition,\n options: AgentResumeSessionOptions,\n ): AgentSession {\n const { snapshot, ...runtime } = options\n validateSessionSnapshot(snapshot, definition.id, definition.skillOptions.maxSkills)\n const session = new AgentSession(definition, {\n ...runtime,\n conversationId: snapshot.conversationId,\n history: History.fromSnapshot(snapshot.history, runtime.historyLimits),\n memory: AgentMemory.fromSnapshot(snapshot.memory, definition.memory),\n })\n session.pendingSkillActivations = captureResumedSkillActivations(snapshot.skills, session.skillCatalog)\n return session\n }\n\n /** Stable identity for persistence keys, URLs, logs, and GUI trace grouping. */\n get conversationId(): string { return this.currentConversationId }\n\n /** Mutable append-only history owned by this conversation. */\n get history(): History { return this.currentHistory }\n\n /** Durable task facts injected into every request outside compactable history. */\n get memory(): AgentMemory { return this.currentMemory }\n\n /** Refreshable skill catalog for host UIs and explicit user invocation surfaces. */\n get skills(): SkillCatalog | undefined { return this.skillCatalog }\n\n /** Whether a model/tool turn currently owns this session. */\n get isRunning(): boolean { return this.active }\n\n /** Capture one JSON-safe envelope that can be passed to `agent.resumeSession()`. */\n snapshot(): AgentSessionSnapshot {\n const activated = this.activationSnapshot()\n const history = this.currentHistory.snapshot()\n const pending = this.pendingInjections?.entries() ?? []\n // An accepted input must survive a snapshot taken before its model round\n // finishes. Project pending inputs at the known tail without delivering\n // them early to the live model or changing the persisted v1 schema.\n const persistedHistory = pending.length === 0 ? history : Object.freeze({\n version: 1 as const,\n entries: Object.freeze([...history.entries, ...pending.map((entry, index) => Object.freeze({\n ...entry, seq: history.entries.length + index + 1,\n }))]),\n })\n return Object.freeze({\n version: 1 as const,\n conversationId: this.currentConversationId,\n agentId: this.definition.id,\n history: persistedHistory,\n memory: this.currentMemory.snapshot(),\n ...runtimeSessionConfiguration(this)?.memory === undefined ? {} : {\n memoryBindingId: runtimeSessionConfiguration(this)!.memory!.bindingId,\n },\n ...activated.length === 0 ? {} : {\n skills: Object.freeze({ activated }),\n },\n })\n }\n\n /** Start a fresh conversation without rebuilding provider/tool configuration. */\n reset(): void {\n if (this.active) throw new Error('cannot reset an agent session while a run is active')\n this.currentConversationId = newConversationId()\n this.currentHistory = new History(this.options.historyLimits)\n this.currentMemory = new AgentMemory(this.definition.memory.seed, this.definition.memory)\n this.pendingInjections = undefined\n this.pendingSkillActivations = Object.freeze([])\n this.lastRunOutcome = undefined\n this.skillCatalog?.clearActivations()\n this.compactor = this.createCompactor()\n }\n\n /** Create one explicit context checkpoint while the session is idle. */\n async compact(invocation: AgentInvocationOptions = {}): Promise<CompactionResult | null> {\n if (this.active) throw new Error('cannot compact an agent session while a run is active')\n this.active = true\n this.activeInvocation = invocation\n try {\n await this.prepareSkills(invocation.signal)\n return await this.compactor?.compactNow(invocation.signal) ?? null\n } finally {\n this.releaseRun()\n }\n }\n\n private async compactForRuntime(invocation: AgentInvocationOptions): Promise<{\n readonly result: CompactionResult | null\n readonly report: LegacyRunReport\n readonly failure?: unknown\n }> {\n if (this.active) throw new Error('cannot compact an agent session while a run is active')\n const ledger = this.createLedger()\n this.active = true\n this.activeInvocation = invocation\n if (this.compactor !== undefined) bindCompactionAccounting(this.compactor, ledger)\n if (this.skillCatalog !== undefined) bindSkillProviderLogger(this.skillCatalog, ledger.modelInvocation.logger)\n try { return await runRuntimeCompaction({\n ...(this.compactor === undefined ? {} : { compactor: this.compactor }),\n invocation,\n accounting: ledger,\n prepare: () => this.prepareSkills(invocation.signal, ledger),\n }) } finally { this.releaseRun() }\n }\n\n /**\n * Append attributed context without starting a turn.\n *\n * A2A quiet delivery uses this primitive. The returned count includes queued\n * inputs and lets wake-up schedulers coalesce messages safely; a mid-round\n * receipt is provisional rather than the eventual persisted entry sequence.\n */\n inject(input: AgentInput): number {\n const message = userMessage(input)\n // Mid-run, hold the message until the next model request is built, so it\n // lands after every entry the model has actually answered. Bound pending\n // inputs with the same guards as history instead of an unbounded array.\n if (this.active && this.roundInFlight) {\n // Reject over-capacity input at admission, before it can poison the\n // queued buffer used by every later run and snapshot.\n const candidate = History.fromSnapshot(this.currentHistory.snapshot(), this.options.historyLimits)\n candidate.appendBatch([\n ...(this.pendingInjections?.entries() ?? []).map(entry => ({ event: entry.event })),\n { event: { kind: 'user' as const, message } },\n ])\n const pending = this.pendingInjections ??= new History(this.options.historyLimits)\n pending.append({ kind: 'user', message })\n return this.currentHistory.entries().length + pending.entries().length\n }\n this.drainInjections()\n this.currentHistory.append({ kind: 'user', message })\n return this.currentHistory.entries().length\n }\n\n /**\n * Close the in-flight window once a round's output is fully recorded: after\n * its tool results (`step-end`), or when the turn ends. The loop waits on\n * this consumer, so held messages land exactly there, never between a tool\n * call and its result.\n *\n * A round that answers without calling a tool ends the turn, and input the\n * person sent while it was being written is still owed an answer. It stays\n * held until the loop is about to end the turn; the loop then takes it (see\n * `bindQueuedInput`) and answers it in another round of the same run instead\n * of leaving it for a later `runPending()`.\n */\n private observeRoundBoundary(event: AgentRunEvent): void {\n if (event.type === 'agent-end') this.lastRunOutcome = event.outcome\n // The chat request is now fixed. beforeStep hooks still run outside this\n // window, so their injections can be included in that request's refresh.\n if (event.type === 'span-start' && event.kind === 'chat') {\n this.roundInFlight = true\n this.roundCalledTools = false\n return\n }\n if (!this.roundInFlight) return\n if (event.type === 'tool-call' || (event.type === 'assistant-message'\n && event.message?.content.some(block => block.type === 'tool-call') === true)) {\n this.roundCalledTools = true\n }\n // A tool round's output is complete at step-end; a final answer's input\n // waits for the loop to take it at turn end, unless the turn is already over.\n if ((event.type === 'step-end' && this.roundCalledTools) || event.type === 'turn-end' || event.type === 'agent-end') {\n this.roundInFlight = false\n this.drainInjections()\n }\n }\n\n /** Deliver held injections, in arrival order, at the chronological tail. */\n private drainInjections(): void {\n if (this.pendingInjections === undefined) return\n const pending = this.pendingInjections\n // Atomic: a full history must not consume only the first queued input and\n // silently lose the rest. Keep the buffer available to snapshot/recovery.\n this.currentHistory.appendBatch(pending.entries().map(entry => ({ event: entry.event })))\n this.pendingInjections = undefined\n }\n\n /**\n * Whether attributed input or a tool result still awaits the model. App\n * notices do not create work, except managed-team coordination. False once the model has answered everything,\n * which lets a scheduler skip a run that would only repeat that answer.\n */\n hasUnansweredInput(): boolean {\n if ((this.pendingInjections?.entries().length ?? 0) > 0) return true\n for (const message of [...this.currentHistory.messages()].reverse()) {\n if (message.source.kind === 'app') {\n if (message.source.producer === 'turn-interrupted') return false\n if (message.role === 'user' && !isManagedTeamNotice(message)) continue\n }\n return message.role === 'user'\n }\n return false\n }\n\n lastOutcome(): AgentRunOutcome | undefined { return this.lastRunOutcome }\n\n /** Resolve after the current run releases the session. */\n whenIdle(signal?: AbortSignal): Promise<void> {\n if (!this.active) return Promise.resolve()\n if (signal?.aborted) return Promise.reject(signal.reason)\n return new Promise<void>((resolve, reject) => {\n let settled = false\n const finish = (): void => {\n if (settled) return\n settled = true\n this.idleWaiters.delete(finish)\n signal?.removeEventListener('abort', abort)\n resolve()\n }\n const abort = (): void => {\n if (settled) return\n settled = true\n this.idleWaiters.delete(finish)\n reject(signal?.reason)\n }\n this.idleWaiters.add(finish)\n signal?.addEventListener('abort', abort, { once: true })\n if (!this.active) finish()\n })\n }\n\n /** Start an eager run and expose both public events and its canonical terminal report. */\n stream(input: AgentInput, invocation: AgentInvocationOptions = {}): AgentRunHandle {\n return this.createRunHandle(input, invocation)\n }\n\n /** Process context already appended with {@link inject} without duplicating it. */\n streamPending(invocation: AgentInvocationOptions = {}): AgentRunHandle {\n return this.createRunHandle(undefined, invocation)\n }\n\n /** Run one user turn and return the terminal response. */\n async run(input: AgentInput, invocation: AgentInvocationOptions = {}): Promise<AgentResponse> {\n const handle = this.stream(input, invocation)\n await consumeSessionEvents(handle, invocation.onEvent, this.runtimeLimits.observerTimeoutMs ?? 30_000)\n return await handle.result\n }\n\n /** Run one turn over already-injected context and return its terminal response. */\n async runPending(invocation: AgentInvocationOptions = {}): Promise<AgentResponse> {\n const handle = this.streamPending(invocation)\n await consumeSessionEvents(handle, invocation.onEvent, this.runtimeLimits.observerTimeoutMs ?? 30_000)\n return await handle.result\n }\n\n private createRunHandle(\n input: AgentInput | undefined,\n invocation: AgentInvocationOptions,\n additionalInstructions?: string,\n ): AgentRunHandle {\n if (this.active) throw new Error(`agent session '${this.definition.id}' is already running`)\n this.drainInjections()\n const firstTurnSeq = this.currentHistory.entries().length + 1\n const owned = new AbortController()\n let terminal = false\n const signal = invocation.signal === undefined\n ? owned.signal\n : AbortSignal.any([invocation.signal, owned.signal])\n const buffer = new RunEventBuffer<AgentRunEvent>(\n this.options.eventBufferLimits?.maxEvents,\n this.options.eventBufferLimits?.maxBytes,\n )\n const reportDeferred = deferred<RunReport>()\n const resultDeferred = deferred<AgentResponse>()\n const toolSourcesDeferred = deferred<readonly ToolSourceRunReference[]>()\n const ledger = this.createLedger()\n let toolSourceReferences: readonly ToolSourceRunReference[] = Object.freeze([])\n if (this.compactor !== undefined) bindCompactionAccounting(this.compactor, ledger)\n if (this.skillCatalog !== undefined) {\n bindSkillProviderLogger(this.skillCatalog, ledger.modelInvocation.logger)\n }\n this.active = true\n bindModelRequestBoundary(this.currentHistory, inFlight => {\n this.roundInFlight = inFlight\n if (!inFlight) this.drainInjections()\n })\n bindQueuedInput(this.currentHistory, () => {\n // By entries, not by the buffer: an input refused at admission leaves an\n // empty buffer behind, and that must not buy the run another round.\n const held = this.pendingInjections?.entries() ?? []\n if (held.length === 0) return false\n // Person input and managed-team coordination extend the run. Team deliveries keep\n // their contract: queued behind the answer, then processed exactly once\n // by the team's wake-up through runPending().\n const extendsRun = held.some(entry => entry.event.kind === 'user'\n && (entry.event.message.source.kind === 'user' || isManagedTeamNotice(entry.event.message)))\n if (!extendsRun) return false\n this.roundInFlight = false\n this.drainInjections()\n return true\n })\n this.activeAdditionalInstructions = additionalInstructions\n this.activeInvocation = invocation\n const spanOperations = new Map<string, string>()\n const task = (async (): Promise<void> => {\n let failure: unknown\n let outcome: AgentRunOutcome | undefined\n let memoryState: Awaited<ReturnType<typeof loadRuntimeMemory>>['state'] | undefined\n try {\n const runtime = runtimeSessionConfiguration(this)\n if (runtime?.memory !== undefined) {\n const prepared = await loadRuntimeMemory(\n runtime.memory, this.currentConversationId, this.definition.memory, signal, ledger,\n )\n memoryState = prepared.state\n if (prepared.memory !== undefined) this.currentMemory = prepared.memory\n }\n if (runtime?.prepareTools !== undefined) {\n const logger = ledger.modelInvocation.logger\n if (logger === undefined) throw new Error('runtime tool source logger is unavailable')\n const generation = runtime.prepareTools(signal, logger, [...this.catalog?.names() ?? [], ...this.definition.nativeTools.map(tool => tool.name)])\n this.activeRuntimeCatalog = toolCatalog([], this.catalog, generation.tools)\n toolSourceReferences = generation.references\n }\n toolSourcesDeferred.resolve(toolSourceReferences)\n await this.prepareSkills(signal, ledger)\n if (input !== undefined) {\n const message = userMessage(input)\n if (this.definition.memory.autoCaptureObjective) {\n const operation = ledger.startOperation('memory', { data: { action: 'capture-objective' } })\n try {\n this.currentMemory.captureOriginalObjective(message)\n ledger.endOperation(operation, 'success')\n } catch (error) {\n ledger.endOperation(operation, 'error', { error })\n throw error\n }\n }\n this.currentHistory.append({ kind: 'user', message })\n }\n // Preflight before compaction can turn a required image into a summary.\n if (invocation.imagePolicy === 'strict' && this.history.messages().some(message => contentHasImage(message.content))) {\n const config = this.callConfig(invocation)\n const model = await this.options.registry.resolveModelInfo(config.provider, config.model, signal)\n if (model.inputModalities !== undefined && !model.inputModalities.includes('image')) {\n throw new ModelError(`model ${model.id} does not support required image input`, 'UNSUPPORTED_IMAGE_INPUT')\n }\n }\n // Same preflight for documents, for the same reason.\n if (invocation.documentPolicy === 'strict' && this.history.messages().some(message => contentHasDocument(message.content))) {\n const config = this.callConfig(invocation)\n const model = await this.options.registry.resolveModelInfo(config.provider, config.model, signal)\n if (model.inputModalities !== undefined && !model.inputModalities.includes('document')) {\n throw new ModelError(`model ${model.id} does not support required document input`, 'UNSUPPORTED_DOCUMENT_INPUT')\n }\n }\n for await (const event of this.runDefinition({ ...invocation, signal }, ledger)) {\n this.observeRoundBoundary(event)\n accountTraceEvent(ledger, spanOperations, event)\n if (event.type === 'agent-end') outcome = event.outcome\n buffer.push(event)\n }\n if (outcome === undefined) {\n throw new Error(`agent session '${this.definition.id}' ended without agent-end`)\n }\n if (signal.aborted) throw signal.reason ?? new Error('agent run was aborted')\n if (outcome.reason.kind === 'error' && outcome.reason.failure.code === 'USAGE_REQUIRED') {\n const error = new Error(outcome.reason.failure.message) as Error & { code: string }\n error.code = 'USAGE_REQUIRED'\n throw error\n }\n if (runtime?.memory !== undefined && memoryState !== undefined && memoryState.status !== 'disabled') {\n await commitRuntimeMemory(\n runtime.memory, this.currentConversationId, this.currentMemory.snapshot(),\n memoryState, signal, ledger,\n )\n }\n } catch (error: unknown) {\n failure = error\n toolSourcesDeferred.resolve(toolSourceReferences)\n }\n\n try { this.drainInjections() } catch (error) { failure ??= error }\n\n let report: RunReport\n try {\n const status: OperationStatus = signal.aborted || outcome?.reason.kind === 'aborted'\n ? 'aborted'\n : failure !== undefined || outcome?.reason.kind === 'error'\n ? 'error'\n : 'success'\n const ledgerReport = await ledger.finalize(status, outcome?.completed ?? false, failure)\n report = withTerminalDelivery(createRunTerminalRecord(ledgerReport), ledgerReport.delivery)\n reportDeferred.resolve(report)\n } catch (finalizeError: unknown) {\n reportDeferred.reject(finalizeError)\n resultDeferred.reject(finalizeError)\n buffer.fail(finalizeError)\n terminal = true\n this.releaseRun()\n return\n }\n if (terminal) return\n\n if (failure === undefined && ledger.terminalAuditFailure) {\n const error = new Error('audit observation checkpoint failed after run finalization') as Error & { code: string }\n error.code = 'OBSERVABILITY_AUDIT_UNAVAILABLE'\n failure = error\n }\n if (failure !== undefined) {\n const error = new AgentRunError(\n messageOf(failure),\n errorCodeOf(failure) ?? AGENT_ACCOUNTING_ERROR_CODES.RUN_FAILED,\n report,\n { cause: failure },\n )\n resultDeferred.reject(error)\n buffer.fail(error)\n } else {\n const terminal = outcome as AgentRunOutcome\n const historyEvent = [...this.currentHistory.entries()].reverse()\n .find(entry => entry.seq >= firstTurnSeq && entry.event.kind === 'assistant')\n ?.event\n const assistantMessage = historyEvent?.kind === 'assistant' ? historyEvent.message : undefined\n const response: AgentResponse = Object.freeze({\n text: terminal.text,\n outcome: terminal,\n report,\n ...assistantMessage === undefined ? {} : { message: assistantMessage },\n })\n resultDeferred.resolve(response)\n buffer.close()\n }\n terminal = true\n this.releaseRun()\n })()\n void task.catch(error => {\n if (terminal) return\n reportDeferred.reject(error)\n resultDeferred.reject(error)\n buffer.fail(error)\n terminal = true\n this.releaseRun()\n })\n void resultDeferred.promise.catch(() => undefined)\n void reportDeferred.promise.catch(() => undefined)\n let iterated = false\n return Object.freeze({\n runId: ledger.runId,\n traceId: ledger.traceId,\n toolSourceSnapshots: toolSourcesDeferred.promise,\n eventsSettled: task.then(() => undefined, () => undefined),\n result: resultDeferred.promise,\n report: reportDeferred.promise,\n seal: () => sealRuntimeRun({ ledger, buffer, report: reportDeferred, result: resultDeferred,\n toolSources: toolSourcesDeferred, currentToolSources: () => toolSourceReferences, isTerminal: () => terminal,\n markTerminal: () => { terminal = true }, abort: () => owned.abort(new Error('Agent run was sealed')),\n release: () => this.releaseRun() }),\n abort(_reason?: unknown): void {\n if (!terminal && !owned.signal.aborted) owned.abort(new Error('Agent run was aborted'))\n },\n [Symbol.asyncIterator](): AsyncIterator<AgentRunEvent> {\n if (iterated) return (async function* () { throw new Error('an agent run handle can only be iterated once') })()\n iterated = true\n return (async function* () {\n let exhausted = false\n try {\n while (true) {\n const item = await buffer.take()\n if (item.done) { exhausted = true; break }\n yield item.value\n }\n } finally {\n if (!exhausted) {\n owned.abort(new Error('agent event consumer stopped'))\n buffer.stop()\n await waitForSettlement(task, 30_000)\n }\n }\n })()\n },\n })\n }\n\n private releaseRun(): void {\n // A message that arrived during the final model round is still delivered,\n // so the next run (or a waiting scheduler) reads it.\n try { this.drainInjections() } finally {\n bindModelRequestBoundary(this.currentHistory)\n bindQueuedInput(this.currentHistory)\n this.roundInFlight = false\n this.active = false\n this.activeAdditionalInstructions = undefined\n this.activeInvocation = undefined\n this.activeRuntimeCatalog = undefined\n if (this.skillCatalog !== undefined) bindSkillProviderLogger(this.skillCatalog, undefined)\n if (this.compactor !== undefined) bindCompactionAccounting(this.compactor, undefined)\n const waiters = [...this.idleWaiters]\n this.idleWaiters.clear()\n for (const resolve of waiters) resolve()\n }\n }\n\n private createLedger() {\n const runtime = runtimeSessionConfiguration(this)\n return createSessionLedger({\n definition: this.definition,\n options: this.options,\n runtimeLimits: this.runtimeLimits,\n conversationId: this.currentConversationId,\n ...(runtime === undefined ? {} : { runtime }),\n })\n }\n\n private runDefinition(\n invocation: AgentInvocationOptions,\n accounting?: RunAccountingPort,\n ): AsyncIterable<AgentRunEvent> {\n const definition = this.definition\n const hooks = this.combinedHooks(accounting)\n const catalog = this.effectiveCatalog()\n const outputFormat = invocation.outputFormat ?? definition.outputFormat\n const common = {\n registry: this.options.registry,\n config: this.callConfig(invocation),\n history: this.history,\n ...catalog === undefined ? {} : { tools: catalog },\n ...definition.nativeTools.length === 0 ? {} : { nativeTools: definition.nativeTools },\n ...definition.toolChoice === undefined ? {} : { toolChoice: definition.toolChoice },\n ...invocation.imagePolicy === undefined ? {} : { imagePolicy: invocation.imagePolicy },\n ...invocation.documentPolicy === undefined ? {} : { documentPolicy: invocation.documentPolicy },\n ...outputFormat === undefined ? {} : { outputFormat },\n ...(invocation.validateOutput === undefined ? {} : { validateOutput: invocation.validateOutput }),\n system: this.systemInstructions(this.activeAdditionalInstructions),\n maxTurns: definition.maxTurns,\n bounds: {\n maxToolCalls: definition.maxToolCalls,\n ...this.runtimeLimits.maxParallelToolCalls === undefined\n ? {}\n : { maxParallel: this.runtimeLimits.maxParallelToolCalls },\n ...this.runtimeLimits.maxConsecutiveToolErrors === undefined\n ? {}\n : { maxConsecutiveToolErrors: this.runtimeLimits.maxConsecutiveToolErrors },\n ...this.runtimeLimits.repeatToolWarningAt === undefined\n ? {}\n : { repeatToolWarningAt: this.runtimeLimits.repeatToolWarningAt },\n ...this.runtimeLimits.repeatToolLimit === undefined\n ? {}\n : { repeatToolLimit: this.runtimeLimits.repeatToolLimit },\n ...this.runtimeLimits.toolCycleWarningAt === undefined\n ? {}\n : { toolCycleWarningAt: this.runtimeLimits.toolCycleWarningAt },\n ...this.runtimeLimits.toolCycleLimit === undefined\n ? {}\n : { toolCycleLimit: this.runtimeLimits.toolCycleLimit },\n ...this.runtimeLimits.onExhausted === undefined\n ? {}\n : { onExhausted: this.runtimeLimits.onExhausted },\n ...this.runtimeLimits.maxToolResultTokens === undefined\n ? {}\n : { maxToolResultTokens: this.runtimeLimits.maxToolResultTokens },\n ...this.runtimeLimits.toolResultOverflow === undefined\n ? {}\n : { toolResultOverflow: this.runtimeLimits.toolResultOverflow },\n ...this.runtimeLimits.maxToolCycleLength === undefined\n ? {}\n : { maxToolCycleLength: this.runtimeLimits.maxToolCycleLength },\n ...this.runtimeLimits.finalReportReserveTokens === undefined ? {} : {\n finalReportReserveTokens: this.runtimeLimits.finalReportReserveTokens,\n },\n ...this.runtimeLimits.maxTotalTokens === undefined\n ? {}\n : { maxTotalTokens: this.runtimeLimits.maxTotalTokens },\n ...this.runtimeLimits.maxToolResultBytes === undefined\n ? {}\n : { maxToolResultBytes: this.runtimeLimits.maxToolResultBytes },\n ...this.runtimeLimits.maxToolDurationMs === undefined\n ? {}\n : { maxToolDurationMs: this.runtimeLimits.maxToolDurationMs },\n ...this.runtimeLimits.toolTeardownTimeoutMs === undefined\n ? {}\n : { toolTeardownTimeoutMs: this.runtimeLimits.toolTeardownTimeoutMs },\n },\n commentary: definition.commentary,\n ...this.runtimeLimits.teardownTimeoutMs === undefined ? {} : { teardownTimeoutMs: this.runtimeLimits.teardownTimeoutMs },\n ...this.runtimeLimits.modelTimeoutMs === undefined ? {} : { modelTimeoutMs: this.runtimeLimits.modelTimeoutMs },\n ...this.runtimeLimits.maxModelRequestBytes === undefined ? {} : { maxModelRequestBytes: this.runtimeLimits.maxModelRequestBytes },\n ...this.runtimeLimits.maxModelResponseBytes === undefined ? {} : { maxModelResponseBytes: this.runtimeLimits.maxModelResponseBytes },\n ...this.runtimeLimits.maxModelStreamEvents === undefined ? {} : { maxModelStreamEvents: this.runtimeLimits.maxModelStreamEvents },\n ...this.runtimeLimits.hookTimeoutMs === undefined ? {} : { hookTimeoutMs: this.runtimeLimits.hookTimeoutMs },\n ...this.runtimeLimits.hookTeardownTimeoutMs === undefined ? {} : { hookTeardownTimeoutMs: this.runtimeLimits.hookTeardownTimeoutMs },\n ...this.options.approvals === undefined ? {} : { approvals: this.options.approvals },\n ...this.options.spillStore === undefined ? {} : { spillStore: this.options.spillStore },\n ...this.options.experimentalPrograms === undefined ? {} : { experimentalPrograms: this.options.experimentalPrograms },\n ...this.options.interceptors === undefined ? {} : { interceptors: this.options.interceptors },\n ...this.contextSections === undefined ? {} : { contextSections: this.contextSections },\n ...hooks === undefined ? {} : { hooks },\n ...invocation.signal === undefined ? {} : { signal: invocation.signal },\n ...accounting === undefined ? {} : { accounting },\n ...accounting?.modelInvocation.logger === undefined ? {} : { logger: accounting.modelInvocation.logger },\n trace: {\n ...this.options.trace,\n conversationId: this.currentConversationId,\n agentId: definition.id,\n agentName: definition.name,\n },\n }\n if (definition.mode === 'deep-human-in-loop') {\n return runAgent({\n ...common, mode: definition.mode, userInput: this.options.userInput as UserInputBroker,\n })\n }\n if (definition.mode === 'deep') {\n return runAgent({\n ...common, mode: definition.mode,\n ...this.options.userInput === undefined ? {} : { userInput: this.options.userInput },\n })\n }\n return runAgent({ ...common, mode: 'basic' })\n }\n\n private createCompactor(): ContextCompactor | undefined {\n const configured = this.options.compaction === false\n ? false\n : this.options.compaction === undefined\n ? this.definition.compaction\n : resolveCompactionConfig(this.options.compaction)\n if (configured === false) return undefined\n return new ContextCompactor({\n registry: this.options.registry,\n config: () => this.callConfig(this.activeInvocation),\n history: () => this.currentHistory,\n system: () => this.systemInstructions(this.activeAdditionalInstructions),\n pinnedMessages: () => renderRuntimeMemory(\n this.currentMemory, this.definition.memory.maxInjectedChars,\n ),\n tools: () => [\n ...this.effectiveCatalog()?.schemas() ?? [],\n ...this.definition.nativeTools,\n ],\n policy: configured,\n })\n }\n\n private effectiveCatalog(): ToolCatalog | undefined {\n return this.activeRuntimeCatalog ?? this.catalog\n }\n\n private combinedHooks(accounting?: RunAccountingPort): TurnHooks | undefined {\n const user = this.options.hooks\n const hooks: TurnHooks = {\n ...user,\n beforeStep: async context => {\n // Before anything reads history for this request: model-round refreshes\n // its messages when entries changed, so delivered input is included.\n const generation = this.currentHistory.generation()\n const entries = this.currentHistory.entries().length\n this.drainInjections()\n const prepared = this.currentHistory.entries().length === entries\n ? context\n : { ...context, messages: normalizeToolPairing(this.currentHistory.messages()), snapshot: this.currentHistory.snapshot() }\n if (this.compactor !== undefined) bindCompactionAccounting(this.compactor, accounting)\n await this.compactor?.beforeStep(prepared)\n if (accounting?.usageStop !== undefined) return { kind: 'proceed' as const }\n const refreshed = this.currentHistory.generation() === generation && this.currentHistory.entries().length === entries\n ? context\n : {\n ...context,\n messages: normalizeToolPairing(this.currentHistory.messages()),\n snapshot: this.currentHistory.snapshot(),\n }\n const memory = renderRuntimeMemory(\n this.currentMemory, this.definition.memory.maxInjectedChars, accounting,\n )\n const current = memory.length === 0\n ? refreshed\n : { ...refreshed, messages: Object.freeze([...memory, ...refreshed.messages]) }\n const decision = await user?.beforeStep?.(current) ?? { kind: 'proceed' as const }\n if (decision.kind === 'reject') return decision\n // A projection sees injected memory already; do not inject it twice.\n const prepend = [...decision.messages === undefined ? memory : [], ...decision.prepend ?? []]\n return bindStepProjectionSources(prepend.length === 0 ? decision : { ...decision, prepend }, refreshed.messages)\n },\n onRequestError: async context => {\n if (this.compactor !== undefined) bindCompactionAccounting(this.compactor, accounting)\n const recovery = await this.compactor?.onRequestError(context)\n if (accounting?.usageStop !== undefined) return 'fail'\n if (recovery === 'retry') return 'retry'\n return await user?.onRequestError?.(context) ?? 'fail'\n },\n }\n return hooks\n }\n\n private callConfig(invocation?: AgentInvocationOptions) {\n return sessionCallConfig(this.definition, runtimeSessionConfiguration(this), invocation)\n }\n\n private systemInstructions(additionalInstructions?: string): string {\n const base = this.skillCatalog === undefined\n ? this.definition.instructions\n : renderSkillCatalog(\n this.definition.instructions,\n this.skillCatalog.summaries(),\n this.definition.skillOptions,\n )\n const team = this.options.team\n const composed = team === undefined\n ? base\n : `${base}\\n\\n${team.team.instructionsFor(team.name ?? this.definition.id)}`\n return appendRunInstructions(composed, additionalInstructions)\n }\n\n private skillLookup(signal?: AbortSignal): SkillLookupOptions {\n return {\n ...(this.options.skillCwd === undefined ? {} : { cwd: this.options.skillCwd }),\n ...(signal === undefined ? {} : { signal }),\n }\n }\n\n private activationSnapshot(): readonly AgentSessionActivatedSkillSnapshot[] {\n const activated = new Map<string, AgentSessionActivatedSkillSnapshot>()\n for (const entry of this.pendingSkillActivations) activated.set(entry.id, entry)\n for (const reference of this.skillCatalog?.activatedSkillReferences() ?? []) {\n activated.set(reference.id, reference)\n }\n for (const summary of this.skillCatalog?.activatedSummaries() ?? []) {\n if (activated.has(summary.id)) continue\n activated.set(summary.id, Object.freeze({\n id: summary.id, provider: summary.provider, source: summary.source,\n ...summary.resourceBase === undefined ? {} : {\n resourceBase: Object.freeze({ ...summary.resourceBase }),\n },\n }))\n }\n return Object.freeze([...activated.values()].sort((left, right) => left.id.localeCompare(right.id)))\n }\n\n private async prepareSkills(signal?: AbortSignal, accounting?: RunAccountingPort): Promise<void> {\n await prepareSkills(\n this.definition, this.skillCatalog, this.pendingSkillActivations,\n signal => this.skillLookup(signal),\n () => { this.pendingSkillActivations = Object.freeze([]) }, signal, accounting,\n )\n }\n}\n\nexport { configureRuntimeSessionModel, streamRuntimeSession } from './session/runtime-binding.ts'\nexport type {\n AgentInput, AgentRuntimeLimits, AgentSessionOptions, AgentTeamMemberOptions,\n AgentSessionSnapshot, AgentSessionActivatedSkillSnapshot, AgentResumeSessionOptions,\n AgentInvocationOptions, AgentResponse, AgentRunHandle,\n} from './session/types.ts'\n"],"mappings":"w7EAqDA,IAAa,EAAb,MAAa,CAAa,CACxB,WACA,QACA,QACA,qBACA,aACA,cAEA,gBACA,eACA,cACA,sBACA,UACA,wBAAiF,OAAO,OAAO,CAAC,CAAC,EACjG,OAAiB,GACjB,6BAEA,iBACA,YAA+B,IAAI,IAOnC,kBACA,eAMA,cAAwB,GAExB,iBAA2B,GAE3B,YAAY,EAA6B,EAA8B,CACrE,GAAI,EAAW,OAAS,sBAAwB,EAAQ,YAAc,IAAA,GACpE,MAAU,UAAU,UAAU,EAAW,GAAG,yDAAyD,EAEvG,KAAK,WAAa,EAClB,IAAM,EAAgB,EAAQ,gBAAkB,IAAA,GAC5C,IAAA,GACA,OAAO,OAAO,CAAE,GAAG,EAAQ,aAAc,CAAC,EAG1C,EAAQ,UAAY,IAAA,IAAa,IAAkB,IAAA,IAAW,IAAS,EAAQ,CAAa,EAChG,IAAM,EAAa,EAAQ,aAAe,IAAA,IAAa,EAAQ,aAAe,GAC1E,EAAQ,WACR,OAAO,OAAO,CAAE,GAAG,EAAQ,UAAW,CAAC,EACrC,EAAQ,EAAQ,QAAU,IAAA,GAAY,IAAA,GAAY,OAAO,OAAO,CAAE,GAAG,EAAQ,KAAM,CAAC,EACpF,EAAO,EAAQ,OAAS,IAAA,GAAY,IAAA,GAAY,OAAO,OAAO,CAAE,GAAG,EAAQ,IAAK,CAAC,EACjF,EAAe,EAAQ,eAAiB,IAAA,GAAY,IAAA,GAAY,OAAO,OAAO,CAAE,GAAG,EAAQ,YAAa,CAAC,EACzG,EAAoB,EAAQ,oBAAsB,IAAA,GACpD,IAAA,GACA,OAAO,OAAO,CAAE,GAAG,EAAQ,iBAAkB,CAAC,EAClD,KAAK,QAAU,OAAO,OAAO,CAC3B,GAAG,EACH,GAAI,IAAkB,IAAA,GAAY,CAAC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E,OAAO,EAAsB,EAAU,CAAsB,CAC/D,CAEA,YAAoB,EAA0C,CAC5D,MAAO,CACL,GAAI,KAAK,QAAQ,WAAa,IAAA,GAAY,CAAC,EAAI,CAAE,IAAK,KAAK,QAAQ,QAAS,EAC5E,GAAI,IAAW,IAAA,GAAY,CAAC,EAAI,CAAE,QAAO,CAC3C,CACF,CAEA,oBAA4E,CAC1E,IAAM,EAAY,IAAI,IACtB,IAAK,IAAM,KAAS,KAAK,wBAAyB,EAAU,IAAI,EAAM,GAAI,CAAK,EAC/E,IAAK,IAAM,KAAa,KAAK,cAAc,yBAAyB,GAAK,CAAC,EACxE,EAAU,IAAI,EAAU,GAAI,CAAS,EAEvC,IAAK,IAAM,KAAW,KAAK,cAAc,mBAAmB,GAAK,CAAC,EAC5D,EAAU,IAAI,EAAQ,EAAE,GAC5B,EAAU,IAAI,EAAQ,GAAI,OAAO,OAAO,CACtC,GAAI,EAAQ,GAAI,SAAU,EAAQ,SAAU,OAAQ,EAAQ,OAC5D,GAAG,EAAQ,eAAiB,IAAA,GAAY,CAAC,EAAI,CAC3C,aAAc,OAAO,OAAO,CAAE,GAAG,EAAQ,YAAa,CAAC,CACzD,CACF,CAAC,CAAC,EAEJ,OAAO,OAAO,OAAO,CAAC,GAAG,EAAU,OAAO,CAAC,CAAC,CAAC,MAAM,EAAM,IAAU,EAAK,GAAG,cAAc,EAAM,EAAE,CAAC,CAAC,CACrG,CAEA,MAAc,cAAc,EAAsB,EAA+C,CAC/F,MAAM,EACJ,KAAK,WAAY,KAAK,aAAc,KAAK,wBACzC,GAAU,KAAK,YAAY,CAAM,MAC3B,CAAE,KAAK,wBAA0B,OAAO,OAAO,CAAC,CAAC,CAAE,EAAG,EAAQ,CACtE,CACF,CACF"}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
const e=new WeakSet;function t(t){return e.add(t),t}function n(t){return e.has(t)}function r(e){return e.role===`user`&&e.source.kind===`app`&&e.source.producer===`managed-team`}export{r as isManagedTeamNotice,n as isManagedTeamNoticeRequest,t as managedTeamNoticeRequest};
|
|
2
|
+
//# sourceMappingURL=input-work.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"input-work.js","names":[],"sources":["../../../src/agent/history/input-work.ts"],"sourcesContent":["import type { Message } from '../../message/index.ts'\n\nconst managedNoticeRequests = new WeakSet<object>()\n\n/** Internal attribution; ordinary team sends remain delegated input. */\nexport function managedTeamNoticeRequest<T extends object>(request: T): T {\n managedNoticeRequests.add(request)\n return request\n}\n\nexport function isManagedTeamNoticeRequest(request: object): boolean {\n return managedNoticeRequests.has(request)\n}\n\n/** Coordination must be read by the lead without changing the user's task. */\nexport function isManagedTeamNotice(message: Message): boolean {\n return message.role === 'user' && message.source.kind === 'app' && message.source.producer === 'managed-team'\n}\n"],"mappings":"AAEA,MAAM,EAAwB,IAAI,QAGlC,SAAgB,EAA2C,EAAe,CAExE,OADA,EAAsB,IAAI,CAAO,EAC1B,CACT,CAEA,SAAgB,EAA2B,EAA0B,CACnE,OAAO,EAAsB,IAAI,CAAO,CAC1C,CAGA,SAAgB,EAAoB,EAA2B,CAC7D,OAAO,EAAQ,OAAS,QAAU,EAAQ,OAAO,OAAS,OAAS,EAAQ,OAAO,WAAa,cACjG"}
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
//#region src/agent/loop/control-text.d.ts
|
|
2
|
+
/** Reserved host protocol token; never part of an application answer. */
|
|
3
|
+
declare const UNCHANGED_ANSWER_MARKER = "<<deep-mode:answer-unchanged>>";
|
|
4
|
+
//#endregion
|
|
5
|
+
export { UNCHANGED_ANSWER_MARKER };
|
|
6
|
+
//# sourceMappingURL=control-text.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"control-text.d.ts","names":[],"sources":["../../../src/agent/loop/control-text.ts"],"mappings":";;cACa"}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"control-text.js","names":[],"sources":["../../../src/agent/loop/control-text.ts"],"sourcesContent":["/** Reserved host protocol token; never part of an application answer. */\nexport const UNCHANGED_ANSWER_MARKER = '<<deep-mode:answer-unchanged>>'\n"],"mappings":"AACA,MAAa,EAA0B"}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{detachedFrozen as e}from"../../primitives/snapshot.js";import{waitForSettlement as t}from"../../async/settlement.js";import{createSpanId as n,createTraceId as r}from"../../observation/context.js";import{createUserMessage as i}from"../../message/message.js";import{authoritativeTokenUsage as a,budgetTokenTotal as o,summarizeModelCallUsage as s}from"../accounting/usage.js";import{ContextSectionRuntime as c}from"../context/section.js";import{deliverQueuedInput as l}from"./turn/model-request-boundary.js";import{AwaitedEventQueue as u}from"./queue.js";import{captureProgramGrants as d}from"../tool/nested.js";import{scheduleToolCalls as ee}from"./schedule.js";import{ProgramResultStore as f}from"../tool/program-results.js";import{positiveFinite as p,resolveBounds as m,snapshotRunTurnOptions as h}from"./turn/config.js";import{codedRuntimeError as g,errorCodeOf as _,messageOf as v,now as y}from"./turn/common.js";import{runHook as b,runOptionalHook as te}from"./turn/hooks.js";import{emitAssistantContent as x,maintenanceEmitter as S,textOf as C}from"./turn/content.js";import{repeatKey as ne,repeatedSuffixCycle as re,toolActionPattern as ie}from"./turn/repetition.js";import{accountingUsageStop as w}from"./turn/usage-stop.js";import{modelRound as T}from"./turn/model-round.js";function E(e){return e.toolChoice===`none`?!1:(e.tools?.names().length??0)>0||(e.nativeTools?.length??0)>0}function D(n){return{async*[Symbol.asyncIterator](){let r=h(n),i=new u,a=new AbortController,o=p(r.teardownTimeoutMs??3e4,`teardownTimeoutMs`),s=O(r,r.signal===void 0?a.signal:AbortSignal.any([r.signal,a.signal]),t=>i.push(e(t))).then(()=>i.close(),e=>i.fail(e));try{for(;;){let e=await i.take();if(e.done)break;yield e.value}await s}finally{if(a.abort(Error(`turn event consumer stopped`)),i.close(),!await t(s,o))throw g(`turn producer ignored cancellation for more than ${o}ms`,`TURN_TEARDOWN_TIMEOUT`,a.signal.reason)}}}}async function O(e,t,u){let p=m(e.bounds),h=p.maxTotalTokens===`auto`?1/0:p.maxTotalTokens,g=p.maxSteps===`auto`?1/0:p.maxSteps,D=e.trace?.traceId??r(),O={traceId:D,spanId:n(),parentSpanId:e.trace?.parentSpanId??null},k=Math.max(1,e.history.entries().filter(e=>e.event.kind===`user`&&e.event.message.source.kind===`user`).length),A=y(),j=0,M=0,ae=[...p.toolBudgetRemindAt].filter(e=>e>0&&e<p.maxToolCalls).sort((e,t)=>t-e),N=0,P=0,F,oe=!1,se=0,I=0,L=``,R=[],z,B,V,ce=[],H=S(u,O),le=t=>{let n=i({source:{kind:`app`,producer:`tool-loop-budget-guard`},content:[{type:`text`,text:t}]}),r=F;if(r!==void 0)try{F=e.history.append({kind:`user`,message:n},{op:`replace`,from:r,to:r,targets:[r]}).seq;return}catch{F=void 0}F=e.history.append({kind:`user`,message:n}).seq},U=e.contextSections===void 0||e.contextSections.length===0?void 0:new c({sections:e.contextSections,history:e.history,...e.logger===void 0?{}:{logger:e.logger},guard:(n,r)=>b(n,e,t,r),scope:{agentId:e.trace?.agentId,conversationId:e.trace?.conversationId}}),W=[],G=!1,K=!1,q=E(e),J=e.experimentalPrograms===void 0?void 0:d(e.experimentalPrograms),Y=J===void 0?void 0:new f,ue=e.outputFormat?.type===`json_schema`&&q,X=e.accounting?.startOperation(`turn`,{data:{turn:k,model:e.config.model}}),Z=!1,Q,$=()=>{if(t.aborted)return{kind:`aborted`};let n=w(e.accounting);if(n!==void 0)return n;if(Q!==void 0)return Q;let r=o(s(R));return r!==void 0&&r>=h?{kind:`budget-exhausted`,budget:`tokens`,forcedFinalAnswer:!1}:void 0};try{await u({type:`span-start`,trace:O,at:A,name:`invoke_agent ${e.trace?.agentId??`agent`}`,kind:`invoke_agent`,attributes:{"gen_ai.operation.name":`invoke_agent`,"gen_ai.agent.id":e.trace?.agentId??`agent`,"gen_ai.agent.name":e.trace?.agentName??e.trace?.agentId??`agent`,"gen_ai.request.model":e.config.model,...e.trace?.conversationId===void 0?{}:{"gen_ai.conversation.id":e.trace.conversationId}}}),G=!0,await u({type:`turn-start`,turn:k,trace:O});turnLifecycle:for(;;){for(;z===void 0&&j<g&&!t.aborted&&(z=$(),z===void 0);){let n=o(s(R));if(p.maxTotalTokens!==`auto`&&n!==void 0){let t=[.5,.75,.9].filter(e=>n>=h*e).length;if(t>se){se=t;let r=Math.max(0,h-n);e.history.append({kind:`user`,message:i({source:{kind:`app`,producer:`tool-loop-token-guard`},content:[{type:`text`,text:`Token budget: ${r} of ${p.maxTotalTokens} aggregate tokens remain. Each request also spends input tokens on the accumulated context. `+(t>=2?`Stop broad exploration. `:`Prioritize outstanding verification and reporting. `)+`Reserve capacity for the required self-check, honest todo reconciliation and substantive final report. State unavailable evidence and unfinished work; do not claim it is verified. No extra model call is allowed after the hard token limit.`}]})})}}!oe&&j>0&&g-j<=2&&(oe=!0,e.history.append({kind:`user`,message:i({source:{kind:`app`,producer:`tool-loop-step-guard`},content:[{type:`text`,text:`${g-j} work steps remain. Finish essential verification, update any task list honestly, and submit the result if required. Summarize findings, evidence, and unfinished work; do not start new exploration.`}]})})),U!==void 0&&(await U.reconcile(j,W,t),W=[]);let r=j+1,a=await T(e,t,u,H,O,k,r,ue?`process`:e.outputFormat?.type===`json_schema`?`final`:`standard`);if(j++,a.report!==void 0&&R.push(a.report),a.message!==void 0&&(e.history.append({kind:`assistant`,message:a.message,...a.finish.kind===`aborted`?{interrupted:!0}:{},...a.usage===void 0?{}:{usage:a.usage}}),await u({type:`assistant-message`,message:a.message,trace:a.trace}),await x(a,u),L=C(a.message.content)),Q=w(e.accounting)??(a.usageRequired?{kind:`error`,failure:{message:`provider usage is required by the configured run policy`,code:`USAGE_REQUIRED`}}:a.usageUnavailable?{kind:`usage-unavailable`,modelCallId:a.report?.modelCallId??`unknown`}:void 0),t.aborted||a.finish.kind===`aborted`){z={kind:`aborted`};break}if(a.finish.kind===`error`&&Q!==void 0){z={kind:`error`,failure:a.finish.failure};break}if(a.usageRequired&&(a.calls.length===0||e.tools===void 0)){z=Q;break}if(a.finish.kind===`error`&&!a.usageRequired){if(z=$(),z!==void 0)break;let n=await te(e.hooks?.onRequestError,[{turn:k,step:r,failure:a.finish.failure,snapshot:e.history.snapshot(),signal:t,...e.logger===void 0?{}:{logger:e.logger},emit:H}],e,t,`onRequestError`),i=w(e.accounting);if(i!==void 0){z=t.aborted?{kind:`aborted`}:i;break}if(n===`retry`&&j<g)continue;z={kind:`error`,failure:a.finish.failure};break}if(a.finish.kind===`max-tokens`&&!a.usageRequired){z={kind:`max-tokens`};break}if(a.calls.length===0&&a.usageUnavailable){z=w(e.accounting)??{kind:`usage-unavailable`,modelCallId:a.report?.modelCallId??`unknown`};break}if(a.calls.length===0&&ue){if(z=$(),z!==void 0)break;e.history.append({kind:`user`,message:i({source:{kind:`app`,producer:`structured-output-finalizer`},content:[{type:`text`,text:`The process phase is complete. Return the final answer now in the requested output format. Do not call tools.`}]})});let n=await T(e,t,u,H,O,k,j+1,`final`);j++,n.report!==void 0&&R.push(n.report),n.message!==void 0&&(e.history.append({kind:`assistant`,message:n.message,...n.usage===void 0?{}:{usage:n.usage}}),await u({type:`assistant-message`,message:n.message,trace:n.trace}),await x(n,u),L=C(n.message.content)),z=n.finish.kind===`aborted`?{kind:`aborted`}:n.finish.kind===`error`?{kind:`error`,failure:n.finish.failure}:n.finish.kind===`max-tokens`?{kind:`max-tokens`}:n.usageRequired?{kind:`error`,failure:{message:`provider usage is required by the configured run policy`,code:`USAGE_REQUIRED`}}:n.usageUnavailable?w(e.accounting)??{kind:`usage-unavailable`,modelCallId:n.report?.modelCallId??`unknown`}:{kind:`completed`};break}if(a.droppedDuplicateCalls!==void 0&&e.history.append({kind:`user`,message:i({source:{kind:`app`,producer:`tool-loop-duplicate-guard`},content:[{type:`text`,text:`You reused the tool-call id ${a.droppedDuplicateCalls.map(e=>`'${e}'`).join(`, `)}. A result pairs to exactly one call, so the repeat was not run and only the first call of that id has a result. Give every call its own id, and call again if you still need what the dropped one would have done.`}]})}),a.calls.length===0||e.tools===void 0){z={kind:`completed`};break}let c=a.calls.filter(t=>e.tools?.get(t.toolName)?.budgetExempt!==!0).length,l=Math.max(0,p.maxToolCalls-M),d=V,f=a.calls.map(e=>{let t=ne(e),n=d?.key===t?d.count+1:1;return d={key:t,count:n},n}).some(e=>e>=p.repeatToolLimit),m=ie(a.calls),_=re([...ce,m],p.maxToolCycleLength),v=_!==void 0&&_.repetitions>=p.toolCycleLimit,y=s(R),S=o(y),E=S!==void 0&&S>=h,D=f||v||E||a.usageRequired,A=E?`tokens`:v?`tool-call-cycle`:f?`repeated-tool-call`:a.usageRequired?`usage-required`:`tool-calls`,F=p.onExhausted!==`continue`,B=await ee({calls:a.calls,catalog:e.tools,history:e.history,position:{turn:k,step:r,...e.accounting===void 0?{}:{runId:e.accounting.runId},...e.trace?.conversationId===void 0?{}:{conversationId:e.trace.conversationId}},signal:t,parentTrace:O,maxParallel:p.maxParallel,dispatchLimit:D?0:F?l:a.calls.length,declineReason:A,maxResultBytes:p.maxToolResultBytes,maxResultTokens:p.maxToolResultTokens,resultOverflow:p.toolResultOverflow,...e.spillStore===void 0?{}:{spillStore:e.spillStore},maxDurationMs:p.maxToolDurationMs,teardownTimeoutMs:p.toolTeardownTimeoutMs,...e.logger===void 0?{}:{logger:e.logger},...e.interceptors===void 0?{}:{interceptors:e.interceptors},...e.approvals===void 0?{}:{approvals:e.approvals},...e.accounting===void 0?{}:{accounting:e.accounting},emit:u,...e.hooks?.checkpoint===void 0?{}:{checkpoint:n=>b(Promise.resolve(e.hooks?.checkpoint?.(n)),e,t,`checkpoint`)}},{admissionLimit:D?0:F?l:`unbounded`,...J===void 0?{}:{programs:J},...Y===void 0?{}:{programResults:Y}});U!==void 0&&B.results.length===a.calls.length&&W.push(...a.calls.map((e,t)=>({toolName:e.toolName,rawArguments:e.rawArguments,failed:B.results[t]?.isError??!0}))),M+=B.budgeted;let G=Math.max(0,p.maxToolCalls-M),K=ae.filter(e=>G<=e).length;if(K>N&&G>0&&(N=K,le(`Tool budget: ${G} of ${p.maxToolCalls} calls remain in this turn. Stop broad exploration, make the necessary edits, and reserve calls for`+(F?` verification. When the budget runs out no further work call will run, so finish with what you can still verify.`:` verification. Past the budget you are expected to be wrapping up, not opening new lines of work.`))),!F&&G===0){let e=Math.floor(M/p.maxToolCalls);e>P&&(P=e,le(`Tool budget spent: ${M} calls made against a budget of ${p.maxToolCalls}. Do not start new substantive work. Finish what is in flight, verify what you can, and answer — stating plainly what is unverified or unfinished.`))}await u({type:`step-end`,turn:k,step:r,trace:a.trace}),ce.push(m);let q=f;for(let t=0;t<a.calls.length;t++){let n=a.calls[t],r=B.results[t];if(n===void 0||r===void 0)continue;I=r.isError?I+1:0;let o=ne(n),s=V?.key===o?V.count+1:1;V={key:o,count:s},s===p.repeatToolWarningAt&&e.history.append({kind:`user`,message:i({source:{kind:`app`,producer:`tool-loop-repeat-guard`},content:[{type:`text`,text:`You have called ${n.toolName} with the same arguments ${s} consecutive times. Reassess before repeating it.`}]})}),s>=p.repeatToolLimit&&(q=!0)}if(_?.repetitions===p.toolCycleWarningAt&&e.history.append({kind:`user`,message:i({source:{kind:`app`,producer:`tool-loop-cycle-guard`},content:[{type:`text`,text:`Tool-use pattern repeated ${_.repetitions} times across ${_.period} step(s). Reassess the approach and identify concrete new evidence before continuing.`}]})}),B.concluded){z={kind:`concluded-by-tool`,toolName:B.concludedBy??`unknown`};break}if(t.aborted){z={kind:`aborted`};break}if(a.usageRequired){z=Q;break}if(a.usageUnavailable){z=w(e.accounting)??{kind:`usage-unavailable`,modelCallId:a.report?.modelCallId??`unknown`};break}let X,Z=p.maxTotalTokens!==`auto`&&p.finalReportReserveTokens>0&&S!==void 0&&S>=h-p.finalReportReserveTokens;if(E||Z?X=`tokens`:v?X=`tool-call-cycle`:F&&c>l?X=`tool-calls`:I>=p.maxConsecutiveToolErrors?X=`consecutive-tool-errors`:q?X=`repeated-tool-call`:j>=g&&(X=`steps`),X!==void 0){let n=(X!==`tokens`||Z&&!E)&&p.onExhausted!==`stop`&&$()===void 0;if(n){let n=await T(e,t,u,H,O,k,j+1,`forced-final`);if(j++,n.report!==void 0&&R.push(n.report),n.message!==void 0&&(e.history.append({kind:`assistant`,message:n.message,...n.usage===void 0?{}:{usage:n.usage}}),await u({type:`assistant-message`,message:n.message,trace:n.trace}),await x(n,u),L=C(n.message.content)),n.finish.kind===`aborted`){z={kind:`aborted`};break}if(n.finish.kind===`error`){z={kind:`error`,failure:n.finish.failure};break}if(n.finish.kind===`max-tokens`){z={kind:`max-tokens`};break}if(n.usageRequired){z={kind:`error`,failure:{message:`provider usage is required by the configured run policy`,code:`USAGE_REQUIRED`}};break}if(n.usageUnavailable){z=w(e.accounting)??{kind:`usage-unavailable`,modelCallId:n.report?.modelCallId??`unknown`};break}}z={kind:`budget-exhausted`,budget:X,forcedFinalAnswer:n,...X===`tokens`&&Z&&!E?{trigger:`report-reserve`}:{}}}}z===void 0&&(z=t.aborted?{kind:`aborted`}:{kind:`budget-exhausted`,budget:`steps`,forcedFinalAnswer:!1});let n=s(R),r=a(n),c={reason:z,text:L,steps:j,usageReport:n,toolCalls:M,traceId:D,...r===void 0?{}:{usage:r}},d=e.history.entries().length,f=z.kind===`completed`&&j<g&&$()===void 0;if(await te(e.hooks?.onTurnEnd,[{outcome:c,snapshot:e.history.snapshot(),canContinue:f}],e,t,`onTurnEnd`),f&&!t.aborted&&(e.history.entries().length>d||l(e.history))){z=void 0;continue turnLifecycle}B=c;break}B.reason.kind===`aborted`&&e.history.append({kind:`user`,message:i({source:{kind:`app`,producer:`turn-interrupted`},content:[{type:`text`,text:`The previous request was interrupted before it finished. Use the next message to determine what to do next.`}]})}),await u({type:`span-end`,trace:O,at:y(),status:B.reason.kind===`error`?`error`:B.reason.kind===`aborted`?`aborted`:`success`,output:{reason:B.reason,text:L},...B.usage===void 0?{}:{usage:B.usage},...B.reason.kind===`error`?{error:{type:`ModelError`,message:B.reason.failure.message,code:B.reason.failure.code}}:{}}),K=!0,X!==void 0&&(e.accounting?.endOperation(X,B.reason.kind===`error`?`error`:B.reason.kind===`aborted`?`aborted`:`success`,{data:{reason:B.reason.kind,steps:j,toolCalls:M}}),Z=!0),await u({type:`turn-end`,outcome:B,trace:O})}catch(n){let r=_(n);throw G&&!K&&await u({type:`span-end`,trace:O,at:y(),status:t.aborted?`aborted`:`error`,error:{type:n instanceof Error?n.name:`RuntimeError`,message:v(n),...r===void 0?{}:{code:r}}}).catch(()=>void 0),X!==void 0&&!Z&&(e.accounting?.endOperation(X,t.aborted?`aborted`:`error`,{error:n}),Z=!0),n}finally{Y?.close()}}export{D as runTurn};
|
|
1
|
+
import{detachedFrozen as e}from"../../primitives/snapshot.js";import{waitForSettlement as t}from"../../async/settlement.js";import{createSpanId as n,createTraceId as r}from"../../observation/context.js";import{createUserMessage as i}from"../../message/message.js";import{authoritativeTokenUsage as a,budgetTokenTotal as o,summarizeModelCallUsage as s}from"../accounting/usage.js";import{ContextSectionRuntime as c}from"../context/section.js";import{deliverQueuedInput as l}from"./turn/model-request-boundary.js";import{AwaitedEventQueue as u}from"./queue.js";import{captureProgramGrants as d}from"../tool/nested.js";import{scheduleToolCalls as ee}from"./schedule.js";import{ProgramResultStore as f}from"../tool/program-results.js";import{positiveFinite as p,resolveBounds as m,snapshotRunTurnOptions as h}from"./turn/config.js";import{codedRuntimeError as g,errorCodeOf as _,messageOf as v,now as y}from"./turn/common.js";import{runHook as te,runOptionalHook as b}from"./turn/hooks.js";import{emitAssistantContent as x,maintenanceEmitter as S,textOf as C}from"./turn/content.js";import{repeatKey as ne,repeatedSuffixCycle as re,toolActionPattern as ie}from"./turn/repetition.js";import{accountingUsageStop as w}from"./turn/usage-stop.js";import{modelRound as T}from"./turn/model-round.js";function E(e){return e.toolChoice===`none`?!1:(e.tools?.names().length??0)>0||(e.nativeTools?.length??0)>0}function D(n){return{async*[Symbol.asyncIterator](){let r=h(n),i=new u,a=new AbortController,o=p(r.teardownTimeoutMs??3e4,`teardownTimeoutMs`),s=O(r,r.signal===void 0?a.signal:AbortSignal.any([r.signal,a.signal]),t=>i.push(e(t))).then(()=>i.close(),e=>i.fail(e));try{for(;;){let e=await i.take();if(e.done)break;yield e.value}await s}finally{if(a.abort(Error(`turn event consumer stopped`)),i.close(),!await t(s,o))throw g(`turn producer ignored cancellation for more than ${o}ms`,`TURN_TEARDOWN_TIMEOUT`,a.signal.reason)}}}}async function O(e,t,u){let p=m(e.bounds),h=p.maxTotalTokens===`auto`?1/0:p.maxTotalTokens,g=p.maxSteps===`auto`?1/0:p.maxSteps,D=e.trace?.traceId??r(),O={traceId:D,spanId:n(),parentSpanId:e.trace?.parentSpanId??null},k=Math.max(1,e.history.entries().filter(e=>e.event.kind===`user`&&e.event.message.source.kind===`user`).length),A=y(),j=0,M=0,ae=[...p.toolBudgetRemindAt].filter(e=>e>0&&e<p.maxToolCalls).sort((e,t)=>t-e),oe=0,se=0,N,P=!1,F=0,I=0,L=``,R=[],z,B,V,ce=[],H=S(u,O),le=t=>{let n=i({source:{kind:`app`,producer:`tool-loop-budget-guard`},content:[{type:`text`,text:t}]}),r=N;if(r!==void 0)try{N=e.history.append({kind:`user`,message:n},{op:`replace`,from:r,to:r,targets:[r]}).seq;return}catch{N=void 0}N=e.history.append({kind:`user`,message:n}).seq},U=e.contextSections===void 0||e.contextSections.length===0?void 0:new c({sections:e.contextSections,history:e.history,...e.logger===void 0?{}:{logger:e.logger},guard:(n,r)=>te(n,e,t,r),scope:{agentId:e.trace?.agentId,conversationId:e.trace?.conversationId}}),W=[],G=!1,K=!1,q=E(e),J=e.experimentalPrograms===void 0?void 0:d(e.experimentalPrograms),Y=J===void 0?void 0:new f,ue=e.outputFormat?.type===`json_schema`&&q,X=e.accounting?.startOperation(`turn`,{data:{turn:k,model:e.config.model}}),Z=!1,Q,$=()=>{if(t.aborted)return{kind:`aborted`};let n=w(e.accounting);if(n!==void 0)return n;if(Q!==void 0)return Q;let r=o(s(R));return r!==void 0&&r>=h?{kind:`budget-exhausted`,budget:`tokens`,forcedFinalAnswer:!1}:void 0};try{await u({type:`span-start`,trace:O,at:A,name:`invoke_agent ${e.trace?.agentId??`agent`}`,kind:`invoke_agent`,attributes:{"gen_ai.operation.name":`invoke_agent`,"gen_ai.agent.id":e.trace?.agentId??`agent`,"gen_ai.agent.name":e.trace?.agentName??e.trace?.agentId??`agent`,"gen_ai.request.model":e.config.model,...e.trace?.conversationId===void 0?{}:{"gen_ai.conversation.id":e.trace.conversationId}}}),G=!0,await u({type:`turn-start`,turn:k,trace:O});turnLifecycle:for(;;){for(;z===void 0&&j<g&&!t.aborted&&(z=$(),z===void 0);){let n=o(s(R));if(p.maxTotalTokens!==`auto`&&n!==void 0){let t=[.5,.75,.9].filter(e=>n>=h*e).length;if(t>F){F=t;let r=Math.max(0,h-n);e.history.append({kind:`user`,message:i({source:{kind:`app`,producer:`tool-loop-token-guard`},content:[{type:`text`,text:`Token budget: ${r} of ${p.maxTotalTokens} aggregate tokens remain. Each request also spends input tokens on the accumulated context. `+(t>=2?`Stop broad exploration. `:`Prioritize outstanding verification and reporting. `)+`Reserve capacity for the required self-check, honest todo reconciliation and substantive final report. State unavailable evidence and unfinished work; do not claim it is verified. No extra model call is allowed after the hard token limit.`}]})})}}!P&&j>0&&g-j<=2&&(P=!0,e.history.append({kind:`user`,message:i({source:{kind:`app`,producer:`tool-loop-step-guard`},content:[{type:`text`,text:`${g-j} work steps remain. Finish essential verification, update any task list honestly, and submit the result if required. Summarize findings, evidence, and unfinished work; do not start new exploration.`}]})})),U!==void 0&&(await U.reconcile(j,W,t),W=[]);let r=j+1,a=await T(e,t,u,H,O,k,r,ue?`process`:e.outputFormat?.type===`json_schema`?`final`:`standard`);if(j++,a.report!==void 0&&R.push(a.report),a.message===void 0?a.finish.kind===`stop`&&(L=``):(e.history.append({kind:`assistant`,message:a.message,...a.finish.kind===`aborted`?{interrupted:!0}:{},...a.usage===void 0?{}:{usage:a.usage}}),await u({type:`assistant-message`,message:a.message,trace:a.trace}),await x(a,u),L=C(a.message.content)),Q=w(e.accounting)??(a.usageRequired?{kind:`error`,failure:{message:`provider usage is required by the configured run policy`,code:`USAGE_REQUIRED`}}:a.usageUnavailable?{kind:`usage-unavailable`,modelCallId:a.report?.modelCallId??`unknown`}:void 0),t.aborted||a.finish.kind===`aborted`){z={kind:`aborted`};break}if(a.finish.kind===`error`&&Q!==void 0){z={kind:`error`,failure:a.finish.failure};break}if(a.usageRequired&&(a.calls.length===0||e.tools===void 0)){z=Q;break}if(a.finish.kind===`error`&&!a.usageRequired){if(z=$(),z!==void 0)break;let n=await b(e.hooks?.onRequestError,[{turn:k,step:r,failure:a.finish.failure,snapshot:e.history.snapshot(),signal:t,...e.logger===void 0?{}:{logger:e.logger},emit:H}],e,t,`onRequestError`),i=w(e.accounting);if(i!==void 0){z=t.aborted?{kind:`aborted`}:i;break}if(n===`retry`&&j<g)continue;z={kind:`error`,failure:a.finish.failure};break}if(a.finish.kind===`max-tokens`&&!a.usageRequired){z={kind:`max-tokens`};break}if(a.calls.length===0&&a.usageUnavailable){z=w(e.accounting)??{kind:`usage-unavailable`,modelCallId:a.report?.modelCallId??`unknown`};break}if(a.calls.length===0&&ue){if(z=$(),z!==void 0)break;e.history.append({kind:`user`,message:i({source:{kind:`app`,producer:`structured-output-finalizer`},content:[{type:`text`,text:`The process phase is complete. Return the final answer now in the requested output format. Do not call tools.`}]})});let n=await T(e,t,u,H,O,k,j+1,`final`);j++,n.report!==void 0&&R.push(n.report),n.message!==void 0&&(e.history.append({kind:`assistant`,message:n.message,...n.usage===void 0?{}:{usage:n.usage}}),await u({type:`assistant-message`,message:n.message,trace:n.trace}),await x(n,u),L=C(n.message.content)),z=n.finish.kind===`aborted`?{kind:`aborted`}:n.finish.kind===`error`?{kind:`error`,failure:n.finish.failure}:n.finish.kind===`max-tokens`?{kind:`max-tokens`}:n.usageRequired?{kind:`error`,failure:{message:`provider usage is required by the configured run policy`,code:`USAGE_REQUIRED`}}:n.usageUnavailable?w(e.accounting)??{kind:`usage-unavailable`,modelCallId:n.report?.modelCallId??`unknown`}:{kind:`completed`};break}if(a.droppedDuplicateCalls!==void 0&&e.history.append({kind:`user`,message:i({source:{kind:`app`,producer:`tool-loop-duplicate-guard`},content:[{type:`text`,text:`You reused the tool-call id ${a.droppedDuplicateCalls.map(e=>`'${e}'`).join(`, `)}. A result pairs to exactly one call, so the repeat was not run and only the first call of that id has a result. Give every call its own id, and call again if you still need what the dropped one would have done.`}]})}),a.calls.length===0||e.tools===void 0){z={kind:`completed`};break}let c=a.calls.filter(t=>e.tools?.get(t.toolName)?.budgetExempt!==!0).length,l=Math.max(0,p.maxToolCalls-M),d=V,f=a.calls.map(e=>{let t=ne(e),n=d?.key===t?d.count+1:1;return d={key:t,count:n},n}).some(e=>e>=p.repeatToolLimit),m=ie(a.calls),_=re([...ce,m],p.maxToolCycleLength),v=_!==void 0&&_.repetitions>=p.toolCycleLimit,y=s(R),S=o(y),E=S!==void 0&&S>=h,D=f||v||E||a.usageRequired,A=E?`tokens`:v?`tool-call-cycle`:f?`repeated-tool-call`:a.usageRequired?`usage-required`:`tool-calls`,N=p.onExhausted!==`continue`,B=await ee({calls:a.calls,catalog:e.tools,history:e.history,position:{turn:k,step:r,...e.accounting===void 0?{}:{runId:e.accounting.runId},...e.trace?.conversationId===void 0?{}:{conversationId:e.trace.conversationId}},signal:t,parentTrace:O,maxParallel:p.maxParallel,dispatchLimit:D?0:N?l:a.calls.length,declineReason:A,maxResultBytes:p.maxToolResultBytes,maxResultTokens:p.maxToolResultTokens,resultOverflow:p.toolResultOverflow,...e.spillStore===void 0?{}:{spillStore:e.spillStore},maxDurationMs:p.maxToolDurationMs,teardownTimeoutMs:p.toolTeardownTimeoutMs,...e.logger===void 0?{}:{logger:e.logger},...e.interceptors===void 0?{}:{interceptors:e.interceptors},...e.approvals===void 0?{}:{approvals:e.approvals},...e.accounting===void 0?{}:{accounting:e.accounting},emit:u,...e.hooks?.checkpoint===void 0?{}:{checkpoint:n=>te(Promise.resolve(e.hooks?.checkpoint?.(n)),e,t,`checkpoint`)}},{admissionLimit:D?0:N?l:`unbounded`,...J===void 0?{}:{programs:J},...Y===void 0?{}:{programResults:Y}});U!==void 0&&B.results.length===a.calls.length&&W.push(...a.calls.map((e,t)=>({toolName:e.toolName,rawArguments:e.rawArguments,failed:B.results[t]?.isError??!0}))),M+=B.budgeted;let G=Math.max(0,p.maxToolCalls-M),K=ae.filter(e=>G<=e).length;if(K>oe&&G>0&&(oe=K,le(`Tool budget: ${G} of ${p.maxToolCalls} calls remain in this turn. Stop broad exploration, make the necessary edits, and reserve calls for`+(N?` verification. When the budget runs out no further work call will run, so finish with what you can still verify.`:` verification. Past the budget you are expected to be wrapping up, not opening new lines of work.`))),!N&&G===0){let e=Math.floor(M/p.maxToolCalls);e>se&&(se=e,le(`Tool budget spent: ${M} calls made against a budget of ${p.maxToolCalls}. Do not start new substantive work. Finish what is in flight, verify what you can, and answer — stating plainly what is unverified or unfinished.`))}await u({type:`step-end`,turn:k,step:r,trace:a.trace}),ce.push(m);let q=f;for(let t=0;t<a.calls.length;t++){let n=a.calls[t],r=B.results[t];if(n===void 0||r===void 0)continue;I=r.isError?I+1:0;let o=ne(n),s=V?.key===o?V.count+1:1;V={key:o,count:s},s===p.repeatToolWarningAt&&e.history.append({kind:`user`,message:i({source:{kind:`app`,producer:`tool-loop-repeat-guard`},content:[{type:`text`,text:`You have called ${n.toolName} with the same arguments ${s} consecutive times. Reassess before repeating it.`}]})}),s>=p.repeatToolLimit&&(q=!0)}if(_?.repetitions===p.toolCycleWarningAt&&e.history.append({kind:`user`,message:i({source:{kind:`app`,producer:`tool-loop-cycle-guard`},content:[{type:`text`,text:`Tool-use pattern repeated ${_.repetitions} times across ${_.period} step(s). Reassess the approach and identify concrete new evidence before continuing.`}]})}),B.concluded){z={kind:`concluded-by-tool`,toolName:B.concludedBy??`unknown`};break}if(t.aborted){z={kind:`aborted`};break}if(a.usageRequired){z=Q;break}if(a.usageUnavailable){z=w(e.accounting)??{kind:`usage-unavailable`,modelCallId:a.report?.modelCallId??`unknown`};break}let X,Z=p.maxTotalTokens!==`auto`&&p.finalReportReserveTokens>0&&S!==void 0&&S>=h-p.finalReportReserveTokens;if(E||Z?X=`tokens`:v?X=`tool-call-cycle`:N&&c>l?X=`tool-calls`:I>=p.maxConsecutiveToolErrors?X=`consecutive-tool-errors`:q?X=`repeated-tool-call`:j>=g&&(X=`steps`),X!==void 0){let n=(X!==`tokens`||Z&&!E)&&p.onExhausted!==`stop`&&$()===void 0;if(n){let n=await T(e,t,u,H,O,k,j+1,`forced-final`);if(j++,n.report!==void 0&&R.push(n.report),n.message!==void 0&&(e.history.append({kind:`assistant`,message:n.message,...n.usage===void 0?{}:{usage:n.usage}}),await u({type:`assistant-message`,message:n.message,trace:n.trace}),await x(n,u),L=C(n.message.content)),n.finish.kind===`aborted`){z={kind:`aborted`};break}if(n.finish.kind===`error`){z={kind:`error`,failure:n.finish.failure};break}if(n.finish.kind===`max-tokens`){z={kind:`max-tokens`};break}if(n.usageRequired){z={kind:`error`,failure:{message:`provider usage is required by the configured run policy`,code:`USAGE_REQUIRED`}};break}if(n.usageUnavailable){z=w(e.accounting)??{kind:`usage-unavailable`,modelCallId:n.report?.modelCallId??`unknown`};break}}z={kind:`budget-exhausted`,budget:X,forcedFinalAnswer:n,...X===`tokens`&&Z&&!E?{trigger:`report-reserve`}:{}}}}z===void 0&&(z=t.aborted?{kind:`aborted`}:{kind:`budget-exhausted`,budget:`steps`,forcedFinalAnswer:!1});let n=s(R),r=a(n),c={reason:z,text:L,steps:j,usageReport:n,toolCalls:M,traceId:D,...r===void 0?{}:{usage:r}},d=e.history.entries().length,f=z.kind===`completed`&&j<g&&$()===void 0;if(await b(e.hooks?.onTurnEnd,[{outcome:c,snapshot:e.history.snapshot(),canContinue:f}],e,t.aborted?new AbortController().signal:t,`onTurnEnd`),f&&!t.aborted&&(e.history.entries().length>d||l(e.history))){z=void 0;continue turnLifecycle}B=c;break}B.reason.kind===`aborted`&&e.history.append({kind:`user`,message:i({source:{kind:`app`,producer:`turn-interrupted`},content:[{type:`text`,text:`The previous request was interrupted before it finished. Use the next message to determine what to do next.`}]})}),await u({type:`span-end`,trace:O,at:y(),status:B.reason.kind===`error`?`error`:B.reason.kind===`aborted`?`aborted`:`success`,output:{reason:B.reason,text:L},...B.usage===void 0?{}:{usage:B.usage},...B.reason.kind===`error`?{error:{type:`ModelError`,message:B.reason.failure.message,code:B.reason.failure.code}}:{}}),K=!0,X!==void 0&&(e.accounting?.endOperation(X,B.reason.kind===`error`?`error`:B.reason.kind===`aborted`?`aborted`:`success`,{data:{reason:B.reason.kind,steps:j,toolCalls:M}}),Z=!0),await u({type:`turn-end`,outcome:B,trace:O})}catch(n){let r=_(n);throw G&&!K&&await u({type:`span-end`,trace:O,at:y(),status:t.aborted?`aborted`:`error`,error:{type:n instanceof Error?n.name:`RuntimeError`,message:v(n),...r===void 0?{}:{code:r}}}).catch(()=>void 0),X!==void 0&&!Z&&(e.accounting?.endOperation(X,t.aborted?`aborted`:`error`,{error:n}),Z=!0),n}finally{Y?.close()}}export{D as runTurn};
|
|
2
2
|
//# sourceMappingURL=run-turn.js.map
|