@alvin0/ai-agent-sdk-core 0.1.3 → 0.1.5
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 +13 -1
- package/dist/agent/accounting/ledger.js +1 -1
- package/dist/agent/accounting/ledger.js.map +1 -1
- package/dist/agent/accounting/report.d.ts +1 -1
- package/dist/agent/define/definition.d.ts +27 -6
- package/dist/agent/define/definition.d.ts.map +1 -1
- package/dist/agent/define/definition.js +1 -1
- package/dist/agent/define/definition.js.map +1 -1
- package/dist/agent/define/session/accounting.js +1 -1
- package/dist/agent/define/session/accounting.js.map +1 -1
- package/dist/agent/define/session/model-config.js +1 -1
- package/dist/agent/define/session/model-config.js.map +1 -1
- package/dist/agent/define/session/types.d.ts +6 -3
- package/dist/agent/define/session/types.d.ts.map +1 -1
- package/dist/agent/define/session.d.ts +25 -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/loop/admission.js +2 -0
- package/dist/agent/loop/admission.js.map +1 -0
- package/dist/agent/loop/events.d.ts +4 -0
- package/dist/agent/loop/events.d.ts.map +1 -1
- package/dist/agent/loop/program.js +2 -0
- package/dist/agent/loop/program.js.map +1 -0
- package/dist/agent/loop/run-turn.d.ts.map +1 -1
- package/dist/agent/loop/run-turn.js +1 -1
- package/dist/agent/loop/run-turn.js.map +1 -1
- package/dist/agent/loop/schedule.d.ts.map +1 -1
- package/dist/agent/loop/schedule.js +2 -2
- package/dist/agent/loop/schedule.js.map +1 -1
- package/dist/agent/loop/tool-call-support.js +2 -0
- package/dist/agent/loop/tool-call-support.js.map +1 -0
- package/dist/agent/loop/turn/config.js +1 -1
- package/dist/agent/loop/turn/config.js.map +1 -1
- package/dist/agent/loop/turn/hooks.js +1 -1
- package/dist/agent/loop/turn/hooks.js.map +1 -1
- package/dist/agent/loop/turn/model-request-boundary.js +2 -0
- package/dist/agent/loop/turn/model-request-boundary.js.map +1 -0
- package/dist/agent/loop/turn/model-round.js +1 -1
- package/dist/agent/loop/turn/model-round.js.map +1 -1
- package/dist/agent/loop/turn/step-projection.js +2 -0
- package/dist/agent/loop/turn/step-projection.js.map +1 -0
- package/dist/agent/loop/turn/types.d.ts +6 -0
- package/dist/agent/loop/turn/types.d.ts.map +1 -1
- package/dist/agent/memory/compaction.d.ts.map +1 -1
- package/dist/agent/memory/compaction.js +1 -1
- package/dist/agent/memory/compaction.js.map +1 -1
- package/dist/agent/memory/context-optimizer.d.ts +61 -0
- package/dist/agent/memory/context-optimizer.d.ts.map +1 -0
- package/dist/agent/memory/context-optimizer.js +4 -0
- package/dist/agent/memory/context-optimizer.js.map +1 -0
- package/dist/agent/memory/memory.js +1 -1
- package/dist/agent/memory/memory.js.map +1 -1
- package/dist/agent/mode/run-agent.d.ts +15 -1
- 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/skill/provider/snapshot.js +1 -1
- package/dist/agent/team/managed.d.ts +33 -64
- package/dist/agent/team/managed.d.ts.map +1 -1
- package/dist/agent/team/managed.js +6 -3
- package/dist/agent/team/managed.js.map +1 -1
- package/dist/agent/team/team.d.ts +2 -0
- 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/team/types.d.ts +1 -0
- package/dist/agent/team/types.d.ts.map +1 -1
- package/dist/agent/tool/action-fusion.d.ts +30 -0
- package/dist/agent/tool/action-fusion.d.ts.map +1 -0
- package/dist/agent/tool/action-fusion.js +2 -0
- package/dist/agent/tool/action-fusion.js.map +1 -0
- package/dist/agent/tool/capture.js +1 -1
- package/dist/agent/tool/capture.js.map +1 -1
- package/dist/agent/tool/definition.d.ts +8 -0
- package/dist/agent/tool/definition.d.ts.map +1 -1
- package/dist/agent/tool/definition.js.map +1 -1
- package/dist/agent/tool/evidence-reducer.d.ts +41 -0
- package/dist/agent/tool/evidence-reducer.d.ts.map +1 -0
- package/dist/agent/tool/evidence-reducer.js +7 -0
- package/dist/agent/tool/evidence-reducer.js.map +1 -0
- package/dist/agent/tool/nested.d.ts +117 -0
- package/dist/agent/tool/nested.d.ts.map +1 -0
- package/dist/agent/tool/nested.js +2 -0
- package/dist/agent/tool/nested.js.map +1 -0
- package/dist/agent/tool/output-budget.d.ts.map +1 -1
- package/dist/agent/tool/output-budget.js +2 -2
- package/dist/agent/tool/output-budget.js.map +1 -1
- package/dist/agent/tool/output-schema.js +2 -0
- package/dist/agent/tool/output-schema.js.map +1 -0
- package/dist/agent/tool/pipeline.d.ts +7 -0
- package/dist/agent/tool/pipeline.d.ts.map +1 -1
- package/dist/agent/tool/pipeline.js +2 -2
- package/dist/agent/tool/pipeline.js.map +1 -1
- package/dist/agent/tool/program-results.js +2 -0
- package/dist/agent/tool/program-results.js.map +1 -0
- package/dist/agent.d.ts +6 -2
- package/dist/agent.js +1 -1
- package/dist/composition/agent/definition.js +1 -1
- package/dist/composition/agent/definition.js.map +1 -1
- package/dist/composition/agent/options.js +1 -1
- package/dist/composition/agent/options.js.map +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 +17 -10
- package/dist/composition/agent/types.d.ts.map +1 -1
- package/dist/composition/runtime/owner.js +1 -1
- package/dist/composition/runtime/owner.js.map +1 -1
- package/dist/composition/runtime/types.d.ts +7 -1
- package/dist/composition/runtime/types.d.ts.map +1 -1
- package/dist/composition/tool-source/snapshot.js +1 -1
- package/dist/contract/adapter.d.ts +1 -1
- package/dist/contract/call-config.d.ts +8 -1
- package/dist/contract/call-config.d.ts.map +1 -1
- package/dist/contract/call-config.js +1 -1
- package/dist/contract/call-config.js.map +1 -1
- package/dist/contract/generate-options.d.ts +5 -0
- package/dist/contract/generate-options.d.ts.map +1 -1
- package/dist/contract/model-info.d.ts +26 -7
- package/dist/contract/model-info.d.ts.map +1 -1
- package/dist/errors/model-error.d.ts +0 -1
- package/dist/errors/model-error.d.ts.map +1 -1
- package/dist/errors/model-error.js +1 -1
- package/dist/errors/model-error.js.map +1 -1
- package/dist/index.d.ts +4 -3
- package/dist/index.js +1 -1
- package/dist/memory.d.ts +2 -1
- package/dist/memory.js +1 -1
- package/dist/observability/bus.js +1 -1
- package/dist/observation/report.d.ts +11 -0
- package/dist/observation/report.d.ts.map +1 -1
- package/dist/observation/report.js.map +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/provider.d.ts +1 -1
- package/dist/runtime/model-call-handle.js +1 -1
- package/dist/runtime/model-call-handle.js.map +1 -1
- package/dist/runtime/model-metadata.js +1 -1
- package/dist/runtime/model-metadata.js.map +1 -1
- package/dist/runtime/model-stream.js +1 -1
- package/dist/runtime/model-stream.js.map +1 -1
- package/dist/runtime/registry.d.ts +7 -1
- package/dist/runtime/registry.d.ts.map +1 -1
- package/dist/runtime/registry.js +1 -1
- package/dist/runtime/registry.js.map +1 -1
- package/dist/tools.d.ts +4 -1
- package/dist/tools.js +1 -1
- package/package.json +1 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"model-config.js","names":[],"sources":["../../../../src/agent/define/session/model-config.ts"],"sourcesContent":["import type { AgentDefinition } from '../definition.ts'\nimport type { CallConfig } from '../../../contract/index.ts'\nimport type { RuntimeSessionConfiguration } from './runtime-binding.ts'\nimport type { AgentInvocationOptions } from './types.ts'\n\nexport type SessionCallConfig = Pick<CallConfig
|
|
1
|
+
{"version":3,"file":"model-config.js","names":[],"sources":["../../../../src/agent/define/session/model-config.ts"],"sourcesContent":["import type { AgentDefinition } from '../definition.ts'\nimport type { CallConfig } from '../../../contract/index.ts'\nimport type { RuntimeSessionConfiguration } from './runtime-binding.ts'\nimport type { AgentInvocationOptions } from './types.ts'\n\nexport type SessionCallConfig = Pick<CallConfig,\n 'provider' | 'model' | 'reasoningEffort' | 'maxTokens' | 'contextWindow' | 'inputModalities'>\n\n/**\n * The model binding for ONE run: the session's binding, then the invocation's\n * overlay on top of it.\n *\n * Effort belongs to the agent, not to a single run: there is no per-invocation\n * effort override, so the only way effort changes is by defining a different\n * agent. Switching model on one invocation still drops the inherited effort —\n * an effort belongs to the model that offers it, and carrying it onto a\n * different model would be a guess this package has no way to validate, now\n * that effort is pure pass-through. maxTokens follows the same drop-on-switch\n * rule, but stays overridable per invocation like today.\n *\n * contextWindow/inputModalities are a fact about the agent's own\n * configuration, not about a specific model's ladder, so they always come\n * from `definition` (never `runtime`) and survive a model switch instead of\n * being dropped like effort/maxTokens.\n */\nexport function sessionCallConfig(\n definition: AgentDefinition,\n runtime: RuntimeSessionConfiguration | undefined,\n invocation?: Pick<AgentInvocationOptions, 'model' | 'maxTokens'>,\n): SessionCallConfig {\n const agentTier = {\n ...(definition.contextWindow === undefined ? {} : { contextWindow: definition.contextWindow }),\n ...(definition.inputModalities === undefined ? {} : { inputModalities: definition.inputModalities }),\n }\n const base: SessionCallConfig = runtime !== undefined\n ? {\n provider: runtime.provider,\n model: runtime.model,\n ...(runtime.reasoningEffort === undefined ? {} : { reasoningEffort: runtime.reasoningEffort }),\n ...(runtime.maxTokens === undefined ? {} : { maxTokens: runtime.maxTokens }),\n ...agentTier,\n }\n : {\n provider: definition.provider,\n model: definition.model,\n ...(definition.effort === undefined ? {} : { reasoningEffort: definition.effort }),\n ...(definition.maxTokens === undefined ? {} : { maxTokens: definition.maxTokens }),\n ...agentTier,\n }\n const target = invocation?.model\n if (target === undefined && invocation?.maxTokens === undefined) {\n return base\n }\n const switched = target !== undefined\n && (target.provider !== base.provider || target.model !== base.model)\n const reasoningEffort = switched ? undefined : base.reasoningEffort\n const maxTokens = invocation?.maxTokens ?? (switched ? undefined : base.maxTokens)\n return {\n provider: target?.provider ?? base.provider,\n model: target?.model ?? base.model,\n ...(reasoningEffort === undefined ? {} : { reasoningEffort }),\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from "../../../primitives/brand.js";
|
|
2
1
|
import { JsonValue } from "../../../primitives/json.js";
|
|
3
2
|
import { SpanId, TraceId } from "../../../observation/context.js";
|
|
4
3
|
import { ObservationResource } from "../../../observation/event.js";
|
|
@@ -14,6 +13,7 @@ import { ToolCatalog } from "../../tool/registry.js";
|
|
|
14
13
|
import { ToolInterceptor } from "../../tool/pipeline.js";
|
|
15
14
|
import { RunLedgerLimits, UsagePolicy } from "../../accounting/report.js";
|
|
16
15
|
import { TurnHooks } from "../../loop/events.js";
|
|
16
|
+
import { ExperimentalProgramGrant } from "../../tool/nested.js";
|
|
17
17
|
import { ModelRegistry } from "../../../runtime/registry.js";
|
|
18
18
|
import { ContextSection } from "../../context/types.js";
|
|
19
19
|
import { UserInputBroker } from "../../mode/user-input.js";
|
|
@@ -110,6 +110,11 @@ interface AgentSessionOptions {
|
|
|
110
110
|
* back what was taken out of its context.
|
|
111
111
|
*/
|
|
112
112
|
readonly spillStore?: SpillStore;
|
|
113
|
+
/**
|
|
114
|
+
* Experimental: program tools and the tools each may call. Off by default.
|
|
115
|
+
* Child calls spend this turn's tool budget and never enter model history.
|
|
116
|
+
*/
|
|
117
|
+
readonly experimentalPrograms?: readonly ExperimentalProgramGrant[];
|
|
113
118
|
readonly interceptors?: readonly ToolInterceptor[];
|
|
114
119
|
/**
|
|
115
120
|
* Model-visible context recomputed before every model round.
|
|
@@ -207,8 +212,6 @@ interface AgentInvocationOptions {
|
|
|
207
212
|
readonly provider: string;
|
|
208
213
|
readonly model: string;
|
|
209
214
|
};
|
|
210
|
-
/** Reasoning effort for this run only. Alone, it keeps the session's model. */
|
|
211
|
-
readonly reasoningEffort?: ReasoningEffortId;
|
|
212
215
|
/** Output ceiling for this run only. */
|
|
213
216
|
readonly maxTokens?: number;
|
|
214
217
|
readonly outputFormat?: ModelOutputFormat;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"types.d.ts","names":[],"sources":["../../../../src/agent/define/session/types.ts"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;
|
|
1
|
+
{"version":3,"file":"types.d.ts","names":[],"sources":["../../../../src/agent/define/session/types.ts"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;KAuBY,sBAAsB;;UAGjB;WACN;WACA;WACA;WACA;WACA;WACA;WACA;WACA;WACA;WACA;WACA;WACA;WACA;WACA;WACA;;;;;WAKA;;;;;;;;WAQA,qBAAqB;;;;;;;;;;;WAWrB;;;;;WAKA;;WAEA;WACA;WACA;;WAEA;;WAEA;;UAGM;WACN;WACA;;UAGM;WACN,UAAU;;WAEV;;WAEA,UAAU;;WAEV,gBAAgB;;WAEhB,gBAAgB;;WAEhB,QAAQ,uBAAuB;;WAE/B,kBAAkB;;WAElB;WACA,YAAY;WACZ,YAAY;;;;;;;;WAQZ,aAAa;;;;;WAKb,gCAAgC;WAChC,wBAAwB;;;;;;;;WAQxB,2BAA2B;WAC3B,QAAQ;;WAER,cAAc;;WAEd,sBAAsB;;WAEtB,cAAc;;WAEd,eAAe;;WAEf,oBAAoB;;WAEpB,SAAS,cAAc;;WAEvB,aAAa;WACb;aACE,UAAU;aACV,eAAe;;;WAGjB,OAAO;;UAGD;EACf,OAAO,SAAS,cAAc,UAAU;EACxC,SAAS,gBAAgB,yCAAyC;EAClE,gBAAgB;;UAGD;WACN;WACA;WACA;WACA;;;;;;;;;;WAUA;;;UAIM,+BAA+B;WACrC,MAAM;;;UAIA;WACN;WACA;WACA;WACA,SAAS;WACT,QAAQ;;WAER;;aAEE,oBAAoB;;;UAIhB;WACN;WACA;WACA;WACA;WACA,UAAU;;WAEV,eAAe;;;UAIT,kCACP,KAAK;WACJ,UAAU;;UAGJ;;;;;;;;;;;WAWN;aAAmB;aAA2B;;;WAE9C;WACA,eAdM;WAeN,kBAAkB;;WAElB;;WAEA;WACA,SAAS;;WAET,WAAW,OAAO,yBAAyB;;UAGrC;WACN;WACA,SAAS;WACT,QAAQ;WACR,UAAU;;;UAIJ,uBAAuB,cAAc;WAC3C;WACA,QAAQ,QAAQ;WAChB,QAAQ,QAAQ"}
|
|
@@ -24,6 +24,19 @@ declare class AgentSession {
|
|
|
24
24
|
/** The overlay of the run that owns the session, so maintenance follows the same model. */
|
|
25
25
|
private activeInvocation;
|
|
26
26
|
private readonly idleWaiters;
|
|
27
|
+
/**
|
|
28
|
+
* Messages injected while a run is in flight, waiting for the next model
|
|
29
|
+
* request. Appending them at once put them AHEAD of the assistant output of
|
|
30
|
+
* the round already streaming, a round that never saw them; the next round
|
|
31
|
+
* then read "steer, then the work that ignored it" as work that answered it.
|
|
32
|
+
*/
|
|
33
|
+
private pendingInjections;
|
|
34
|
+
/**
|
|
35
|
+
* A model request has been built and its output is not yet fully recorded.
|
|
36
|
+
* Only then is an injection held: hooks and team notices that inject between
|
|
37
|
+
* rounds still append at once, as they always have.
|
|
38
|
+
*/
|
|
39
|
+
private roundInFlight;
|
|
27
40
|
constructor(definition: AgentDefinition, options: AgentSessionOptions);
|
|
28
41
|
/** Restore a JSON-round-tripped session snapshot with fresh runtime dependencies. */
|
|
29
42
|
static fromSnapshot(definition: AgentDefinition, options: AgentResumeSessionOptions): AgentSession;
|
|
@@ -47,10 +60,20 @@ declare class AgentSession {
|
|
|
47
60
|
/**
|
|
48
61
|
* Append attributed context without starting a turn.
|
|
49
62
|
*
|
|
50
|
-
* A2A quiet delivery uses this primitive. The returned
|
|
51
|
-
*
|
|
63
|
+
* A2A quiet delivery uses this primitive. The returned count includes queued
|
|
64
|
+
* inputs and lets wake-up schedulers coalesce messages safely; a mid-round
|
|
65
|
+
* receipt is provisional rather than the eventual persisted entry sequence.
|
|
52
66
|
*/
|
|
53
67
|
inject(input: AgentInput): number;
|
|
68
|
+
/**
|
|
69
|
+
* Close the in-flight window once a round's output is fully recorded: after
|
|
70
|
+
* its tool results (`step-end`), after a final answer with no tool calls, or
|
|
71
|
+
* when the turn ends. The loop waits on this consumer, so held messages land
|
|
72
|
+
* exactly there, never between a tool call and its result.
|
|
73
|
+
*/
|
|
74
|
+
private observeRoundBoundary;
|
|
75
|
+
/** Deliver held injections, in arrival order, at the chronological tail. */
|
|
76
|
+
private drainInjections;
|
|
54
77
|
/** Resolve after the current run releases the session. */
|
|
55
78
|
whenIdle(signal?: AbortSignal): Promise<void>;
|
|
56
79
|
/** 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":";;;;;;;cAoDa;WACF,YAAY;mBACJ;mBACA;UACT;mBACS;mBACA;;mBAEA;UACT;UACA;UACA;UACA;UACA;UACA;UACA;;UAEA;mBACS;;;;;;;UAOT;;;;;;UAMA;EAER,YAAY,YAAY,iBAAiB,SAAS;;SA0F3C,aACL,YAAY,iBACZ,SAAS,4BACR;;MAcC;;MAGA,WAAW;;MAGX,UAAU;;MAGV,UAAU;;MAGV;;EAGJ,YAAY;;EA6BZ;;EAYM,QAAQ,aAAY,yBAA8B,QAAQ;UAYlD;;;;;;;;EA0Bd,OAAO,OAAO;;;;;;;UAqBN;;UAiBA;;EAUR,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;UAsNA;UAkBA;UAWA;UA2GA;UAuBA;UAIA;UA6CA;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{AGENT_ACCOUNTING_ERROR_CODES as _,AgentRunError as v}from"../accounting/error.js";import{runAgent as y}from"../mode/run-agent.js";import{RunEventBuffer as b}from"../accounting/event-buffer.js";import{validateSessionSnapshot as x}from"./session/validation.js";import{resolveRuntimeLimits as S}from"./session/config.js";import{conversationId as C,deferred as w,errorCodeOf as T,messageOf as E,newConversationId as D,toolCatalog as O,userMessage as k}from"./session/common.js";import{captureResumedSkillActivations as A,prepareSkills as j}from"./session/skills.js";import{appendRunInstructions as M}from"./instructions.js";import{accountTraceEvent as N}from"./session/trace-accounting.js";import{captureResumedObjective as P,commitRuntimeMemory as F,loadRuntimeMemory as I,renderRuntimeMemory as L}from"./session/runtime-memory.js";import{attachRuntimeSession as R,configureRuntimeSessionModel as z,runtimeSessionConfiguration as B,streamRuntimeSession as V}from"./session/runtime-binding.js";import{createSessionLedger as H}from"./session/accounting.js";import{runRuntimeCompaction as U}from"./session/runtime-compaction.js";import{sessionCallConfig as W}from"./session/model-config.js";import{consumeSessionEvents as G}from"./session/observer.js";import{sealRuntimeRun as K}from"./session/run-seal.js";var q=class z{definition;options;catalog;activeRuntimeCatalog;skillCatalog;runtimeLimits;contextSections;currentHistory;currentMemory;currentConversationId;compactor;pendingSkillActivations=Object.freeze([]);active=!1;activeAdditionalInstructions;activeInvocation;idleWaiters=new Set;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=S(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=C(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=O(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),P(this.currentMemory,this.currentHistory,this.definition.memory.autoCaptureObjective),this.compactor=this.createCompactor(),R(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;x(n,e.id,e.skillOptions.maxSkills);let a=new z(e,{...r,conversationId:n.conversationId,history:g.fromSnapshot(n.history,r.historyLimits),memory:i.fromSnapshot(n.memory,e.memory)});return a.pendingSkillActivations=A(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();return Object.freeze({version:1,conversationId:this.currentConversationId,agentId:this.definition.id,history:this.currentHistory.snapshot(),memory:this.currentMemory.snapshot(),...B(this)?.memory===void 0?{}:{memoryBindingId:B(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=D(),this.currentHistory=new g(this.options.historyLimits),this.currentMemory=new i(this.definition.memory.seed,this.definition.memory),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 U({...this.compactor===void 0?{}:{compactor:this.compactor},invocation:e,accounting:t,prepare:()=>this.prepareSkills(e.signal,t)})}finally{this.releaseRun()}}inject(e){let t=k(e);return this.currentHistory.append({kind:`user`,message:t}),this.currentHistory.entries().length}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 G(n,t.onEvent,this.runtimeLimits.observerTimeoutMs??3e4),await n.result}async runPending(e={}){let t=this.streamPending(e);return await G(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`);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 b(this.options.eventBufferLimits?.maxEvents,this.options.eventBufferLimits?.maxBytes),g=w(),y=w(),x=w(),S=this.createLedger(),C=Object.freeze([]);this.compactor!==void 0&&o(this.compactor,S),this.skillCatalog!==void 0&&l(this.skillCatalog,S.modelInvocation.logger),this.active=!0,this.activeAdditionalInstructions=s,this.activeInvocation=a;let D=new Map,A=(async()=>{let e,o,s;try{let e=B(this);if(e?.memory!==void 0){let t=await I(e.memory,this.currentConversationId,this.definition.memory,f,S);s=t.state,t.memory!==void 0&&(this.currentMemory=t.memory)}if(e?.prepareTools!==void 0){let t=S.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=O([],this.catalog,n.tools),C=n.references}if(x.resolve(C),await this.prepareSkills(f,S),i!==void 0){let e=k(i);if(this.definition.memory.autoCaptureObjective){let t=S.startOperation(`memory`,{data:{action:`capture-objective`}});try{this.currentMemory.captureOriginalObjective(e),S.endOperation(t,`success`)}catch(e){throw S.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},S))N(S,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 F(e.memory,this.currentConversationId,this.currentMemory.snapshot(),s,f,S)}catch(t){e=t,x.resolve(C)}let l;try{let t=f.aborted||o?.reason.kind===`aborted`?`aborted`:e!==void 0||o?.reason.kind===`error`?`error`:`success`,n=await S.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&&S.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 v(E(e),T(e)??_.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 j=!1;return Object.freeze({runId:S.runId,traceId:S.traceId,toolSourceSnapshots:x.promise,eventsSettled:A.then(()=>void 0,()=>void 0),result:y.promise,report:g.promise,seal:()=>K({ledger:S,buffer:h,report:g,result:y,toolSources:x,currentToolSources:()=>C,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 j?(async function*(){throw Error(`an agent run handle can only be iterated once`)})():(j=!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(){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=B(this);return H({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.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`?y({...o,mode:n.mode,userInput:this.options.userInput}):n.mode===`deep`?y({...o,mode:n.mode,...this.options.userInput===void 0?{}:{userInput:this.options.userInput}}):y({...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:()=>L(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;if(this.compactor!==void 0||t!==void 0||this.currentMemory.items().length!==0)return{...t,beforeStep:async n=>{let r=this.currentHistory.generation();if(this.compactor!==void 0&&o(this.compactor,e),await this.compactor?.beforeStep(n),e?.usageStop!==void 0)return{kind:`proceed`};let i=this.currentHistory.generation()===r?n:{...n,messages:a(this.currentHistory.messages()),snapshot:this.currentHistory.snapshot()},s=L(this.currentMemory,this.definition.memory.maxInjectedChars,e),c=s.length===0?i:{...i,messages:Object.freeze([...s,...i.messages])},l=await t?.beforeStep?.(c)??{kind:`proceed`};if(l.kind===`reject`)return l;let u=[...s,...l.prepend??[]];return u.length===0?l:{kind:`proceed`,prepend:u}},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 W(this.definition,B(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 M(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 j(this.definition,this.skillCatalog,this.pendingSkillActivations,e=>this.skillLookup(e),()=>{this.pendingSkillActivations=Object.freeze([])},e,t)}};export{q as AgentSession,z as configureRuntimeSessionModel,V 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{bindModelRequestBoundary as _}from"../loop/turn/model-request-boundary.js";import{bindStepProjectionSources as v}from"../loop/turn/step-projection.js";import{AGENT_ACCOUNTING_ERROR_CODES as y,AgentRunError as b}from"../accounting/error.js";import{runAgent as x}from"../mode/run-agent.js";import{RunEventBuffer as S}from"../accounting/event-buffer.js";import{validateSessionSnapshot as C}from"./session/validation.js";import{resolveRuntimeLimits as w}from"./session/config.js";import{conversationId as T,deferred as E,errorCodeOf as D,messageOf as O,newConversationId as k,toolCatalog as A,userMessage as j}from"./session/common.js";import{captureResumedSkillActivations as M,prepareSkills as N}from"./session/skills.js";import{appendRunInstructions as P}from"./instructions.js";import{accountTraceEvent as F}from"./session/trace-accounting.js";import{captureResumedObjective as I,commitRuntimeMemory as L,loadRuntimeMemory as R,renderRuntimeMemory as z}from"./session/runtime-memory.js";import{attachRuntimeSession as B,configureRuntimeSessionModel as V,runtimeSessionConfiguration as H,streamRuntimeSession as U}from"./session/runtime-binding.js";import{createSessionLedger as W}from"./session/accounting.js";import{runRuntimeCompaction as G}from"./session/runtime-compaction.js";import{sessionCallConfig as K}from"./session/model-config.js";import{consumeSessionEvents as q}from"./session/observer.js";import{sealRuntimeRun as J}from"./session/run-seal.js";var Y=class V{definition;options;catalog;activeRuntimeCatalog;skillCatalog;runtimeLimits;contextSections;currentHistory;currentMemory;currentConversationId;compactor;pendingSkillActivations=Object.freeze([]);active=!1;activeAdditionalInstructions;activeInvocation;idleWaiters=new Set;pendingInjections;roundInFlight=!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=w(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=T(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=A(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),I(this.currentMemory,this.currentHistory,this.definition.memory.autoCaptureObjective),this.compactor=this.createCompactor(),B(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;C(n,e.id,e.skillOptions.maxSkills);let a=new V(e,{...r,conversationId:n.conversationId,history:g.fromSnapshot(n.history,r.historyLimits),memory:i.fromSnapshot(n.memory,e.memory)});return a.pendingSkillActivations=M(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(),...H(this)?.memory===void 0?{}:{memoryBindingId:H(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=k(),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 G({...this.compactor===void 0?{}:{compactor:this.compactor},invocation:e,accounting:t,prepare:()=>this.prepareSkills(e.signal,t)})}finally{this.releaseRun()}}inject(e){let t=j(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;return}if(!this.roundInFlight)return;let t=e.type===`assistant-message`&&e.message?.content.every(e=>e.type!==`tool-call`)===!0;(e.type===`step-end`||e.type===`turn-end`||e.type===`agent-end`||t)&&(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}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 q(n,t.onEvent,this.runtimeLimits.observerTimeoutMs??3e4),await n.result}async runPending(e={}){let t=this.streamPending(e);return await q(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 S(this.options.eventBufferLimits?.maxEvents,this.options.eventBufferLimits?.maxBytes),g=E(),v=E(),x=E(),C=this.createLedger(),w=Object.freeze([]);this.compactor!==void 0&&o(this.compactor,C),this.skillCatalog!==void 0&&l(this.skillCatalog,C.modelInvocation.logger),this.active=!0,_(this.currentHistory,e=>{this.roundInFlight=e,e||this.drainInjections()}),this.activeAdditionalInstructions=s,this.activeInvocation=a;let T=new Map,k=(async()=>{let e,o,s;try{let e=H(this);if(e?.memory!==void 0){let t=await R(e.memory,this.currentConversationId,this.definition.memory,f,C);s=t.state,t.memory!==void 0&&(this.currentMemory=t.memory)}if(e?.prepareTools!==void 0){let t=C.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=A([],this.catalog,n.tools),w=n.references}if(x.resolve(w),await this.prepareSkills(f,C),i!==void 0){let e=j(i);if(this.definition.memory.autoCaptureObjective){let t=C.startOperation(`memory`,{data:{action:`capture-objective`}});try{this.currentMemory.captureOriginalObjective(e),C.endOperation(t,`success`)}catch(e){throw C.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},C))this.observeRoundBoundary(e),F(C,T,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 L(e.memory,this.currentConversationId,this.currentMemory.snapshot(),s,f,C)}catch(t){e=t,x.resolve(w)}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 C.finalize(t,o?.completed??!1,e);l=m(p(n),n.delivery),g.resolve(l)}catch(e){g.reject(e),v.reject(e),h.fail(e),d=!0,this.releaseRun();return}if(!d){if(e===void 0&&C.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 b(O(e),D(e)??y.RUN_FAILED,l,{cause:e});v.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}});v.resolve(r),h.close()}d=!0,this.releaseRun()}})();k.catch(e=>{d||(g.reject(e),v.reject(e),h.fail(e),d=!0,this.releaseRun())}),v.promise.catch(()=>void 0),g.promise.catch(()=>void 0);let M=!1;return Object.freeze({runId:C.runId,traceId:C.traceId,toolSourceSnapshots:x.promise,eventsSettled:k.then(()=>void 0,()=>void 0),result:v.promise,report:g.promise,seal:()=>J({ledger:C,buffer:h,report:g,result:v,toolSources:x,currentToolSources:()=>w,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 M?(async function*(){throw Error(`an agent run handle can only be iterated once`)})():(M=!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(k,3e4))}})())}})}releaseRun(){try{this.drainInjections()}finally{_(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=H(this);return W({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`?x({...o,mode:n.mode,userInput:this.options.userInput}):n.mode===`deep`?x({...o,mode:n.mode,...this.options.userInput===void 0?{}:{userInput:this.options.userInput}}):x({...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:()=>z(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=z(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 v(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 K(this.definition,H(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 P(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 N(this.definition,this.skillCatalog,this.pendingSkillActivations,e=>this.skillLookup(e),()=>{this.pendingSkillActivations=Object.freeze([])},e,t)}};export{Y as AgentSession,V as configureRuntimeSessionModel,U 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 { 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 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 return Object.freeze({\n version: 1 as const,\n conversationId: this.currentConversationId,\n agentId: this.definition.id,\n history: this.currentHistory.snapshot(),\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.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 history sequence is a\n * delivery receipt and lets wake-up schedulers coalesce messages safely.\n */\n inject(input: AgentInput): number {\n const message = userMessage(input)\n this.currentHistory.append({ kind: 'user', message })\n return this.currentHistory.entries().length\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 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 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 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 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 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 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.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 if (this.compactor === undefined\n && user === undefined\n && this.currentMemory.items().length === 0) return undefined\n return {\n ...user,\n beforeStep: async context => {\n const generation = this.currentHistory.generation()\n if (this.compactor !== undefined) bindCompactionAccounting(this.compactor, accounting)\n await this.compactor?.beforeStep(context)\n if (accounting?.usageStop !== undefined) return { kind: 'proceed' as const }\n const refreshed = this.currentHistory.generation() === generation\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 const prepend = [...memory, ...decision.prepend ?? []]\n return prepend.length === 0 ? decision : { kind: 'proceed' as const, prepend }\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 }\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":"ssEAkDA,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,IAEnC,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,EAA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CACtE,CACF,CACF"}
|
|
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 } 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\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`), after a final answer with no tool calls, or\n * when the turn ends. The loop waits on this consumer, so held messages land\n * exactly there, never between a tool call and its result.\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 return\n }\n if (!this.roundInFlight) return\n const finalAnswer = event.type === 'assistant-message'\n && event.message?.content.every(block => block.type !== 'tool-call') === true\n if (event.type === 'step-end' || event.type === 'turn-end' || event.type === 'agent-end' || finalAnswer) {\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 /** 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 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 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 return {\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 }\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, A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+
function e(e){let t=e===`unbounded`?1/0:Math.max(0,e),n=0,r=0;return{reserve(e){if(!e&&n+r>=t)return;e||r++;let i=!1;return{budgeted:!e,confirm(){i||(i=!0,e||(r--,n++))},release(){i||(i=!0,e||r--)}}},get budgeted(){return n}}}export{e as createToolAdmission};
|
|
2
|
+
//# sourceMappingURL=admission.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"admission.js","names":[],"sources":["../../../src/agent/loop/admission.ts"],"sourcesContent":["/**\n * The one owner of a step's tool-call budget.\n *\n * Every dispatch in a step — a model-issued call or a call a program makes on\n * the model's behalf — reserves here before authorization and confirms only\n * when its body actually starts. A second counter anywhere else is how a nested\n * caller ends up running ten bodies against a budget of three.\n */\nexport interface ToolAdmission {\n /**\n * Reserve room for one call about to be authorized.\n * @param exempt - Whether the tool is `budgetExempt`; exempt calls never spend budget.\n * @returns A ticket, or `undefined` when the budget declines the call.\n */\n reserve(exempt: boolean): AdmissionTicket | undefined\n /** Dispatched calls that spent budget; exempt tools are excluded. */\n readonly budgeted: number\n}\n\n/** One reservation. Exactly one of `confirm` or `release` takes effect. */\nexport interface AdmissionTicket {\n /** Whether confirming this ticket spends budget. */\n readonly budgeted: boolean\n /** The body is starting: the reservation becomes spent budget. */\n confirm(): void\n /** The call will not run: return the reservation. */\n release(): void\n}\n\n/**\n * @param limit - Budgeted dispatches this step may still make, or `unbounded`\n * when the budget is a notice rather than a wall.\n * @returns A fresh admission for one step.\n */\nexport function createToolAdmission(limit: number | 'unbounded'): ToolAdmission {\n const ceiling = limit === 'unbounded' ? Number.POSITIVE_INFINITY : Math.max(0, limit)\n let spent = 0\n let reserved = 0\n return {\n reserve(exempt) {\n if (!exempt && spent + reserved >= ceiling) return undefined\n if (!exempt) reserved++\n let settled = false\n return {\n budgeted: !exempt,\n confirm() {\n if (settled) return\n settled = true\n if (!exempt) { reserved--; spent++ }\n },\n release() {\n if (settled) return\n settled = true\n if (!exempt) reserved--\n },\n }\n },\n get budgeted() { return spent },\n }\n}\n"],"mappings":"AAkCA,SAAgB,EAAoB,EAA4C,CAC9E,IAAM,EAAU,IAAU,YAAc,IAA2B,KAAK,IAAI,EAAG,CAAK,EAChF,EAAQ,EACR,EAAW,EACf,MAAO,CACL,QAAQ,EAAQ,CACd,GAAI,CAAC,GAAU,EAAQ,GAAY,EAAS,OACvC,GAAQ,IACb,IAAI,EAAU,GACd,MAAO,CACL,SAAU,CAAC,EACX,SAAU,CACJ,IACJ,EAAU,GACL,IAAU,IAAY,KAC7B,EACA,SAAU,CACJ,IACJ,EAAU,GACL,GAAQ,IACf,CACF,CACF,EACA,IAAI,UAAW,CAAE,OAAO,CAAM,CAChC,CACF"}
|
|
@@ -175,6 +175,8 @@ interface BeforeStepContext {
|
|
|
175
175
|
type StepDecision = {
|
|
176
176
|
readonly kind: 'proceed';
|
|
177
177
|
readonly prepend?: readonly Message[];
|
|
178
|
+
/** Model-only projection. Raw history and checkpoint snapshots remain unchanged. */
|
|
179
|
+
readonly messages?: readonly Message[];
|
|
178
180
|
} | {
|
|
179
181
|
readonly kind: 'reject';
|
|
180
182
|
readonly reason: string;
|
|
@@ -198,6 +200,8 @@ type CheckpointContext = {
|
|
|
198
200
|
readonly kind: 'before-tool-dispatch';
|
|
199
201
|
readonly call: ToolCallRequest;
|
|
200
202
|
readonly snapshot: HistorySnapshot;
|
|
203
|
+
/** Set when a program tool made this call; the id of that outer call. */
|
|
204
|
+
readonly parentCallId?: ToolCallRequest['callId'];
|
|
201
205
|
readonly signal?: AbortSignal;
|
|
202
206
|
readonly logger?: SdkLogger;
|
|
203
207
|
};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"events.d.ts","names":[],"sources":["../../../src/agent/loop/events.ts"],"mappings":";;;;;;;;;;;;;;;KAgBY;;;;;;;;KAcA,oBAAoB;KAEpB;WACG;;WACA;WAAoC;;WACpC;WAAmC,QAAQ;WAA0B;;WAErE;;WACA;;WACA;WAAoC;;WACpC;;WACA;WAAwB,SAAS;;UAE/B;WACN,QAAQ;WACR;WACA;;WAEA,QAAQ;;WAER,aAAa;WACb;WACA;;UAGD;WAAkB,OAAO;;KACvB;KACA,6BAA6B;KAC7B;KACA;WAEC;WACA;WACA,SAAS;WACT;;WAGA;WACA;WACA,SAAS;WACT;WACA;WACA;WACA;WACA;WACA;WACA,gBAAgB;WAChB;WACA;WACA;WACA,QAAQ;;KAET,aAAa,cACpB,wBAAwB;WACb;WAA6B;IAAiB;WAC9C;WAA6B;WAAuB;WAAuB;IAAuB;WAClG;WAA6B;WAAwB;WAAuB,OAAO;IAA+B;;;;;WAIlH;WAA2B;WAAwB;WAAuB,OAAO;WAA6B;IAAsB;WACpI;WAAkC;WAAwB;IAAiB;WAE9E;WACA;WACA;WACA,WAAW;WACX;IACP;WACU;WAAoC,SAAS;IAAY;WAE5D;WACA,WAAW;WACX;WACA,OAAO;WACP,QAAQ;WACR,sBAAsB;WACtB,2BAA2B;IAClC;WAEO;WACA,WAAW;WACX,MAAM;IACb;;WAGO;WACA,WAAW;WACX;WACA,QAAQ;WACR,sBAAsB;WACtB,2BAA2B;IAClC;WACU;WAA4B,MAAM;IAAoB;WACtD;WAA8B,MAAM;WAA0B,QAAQ;IAAwB;WAC9F;WAAmC,SAAS;IAAoB;WAChE;WAAwB,OAAO;IAAe;WAC9C;WAAiC,OADa;WACuD;IAAuB;WAC5H;WAA2B;WAAuB;IAAiB;WACnE;WAA2B,SAAS;IAAgB;UAEnD;WACN;WACA;WACA,mBAAmB;WACnB,UAAU;WACV,QAAQ;WACR,SAAS;EAClB,KAAK,OAAO,wBAAwB;;KAE1B;WACG;WAA0B,mBAAmB;;
|
|
1
|
+
{"version":3,"file":"events.d.ts","names":[],"sources":["../../../src/agent/loop/events.ts"],"mappings":";;;;;;;;;;;;;;;KAgBY;;;;;;;;KAcA,oBAAoB;KAEpB;WACG;;WACA;WAAoC;;WACpC;WAAmC,QAAQ;WAA0B;;WAErE;;WACA;;WACA;WAAoC;;WACpC;;W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;WAA0B,UAAU;;WAEjF,eAAe;WACf,SAAS;WAAsB,SAAS;;UACtC;WACN,SAAS;WACT,UAAU;;WAEV;;UAEM;WACN,cAAc,KAAK,sBAAsB,QAAQ,gBAAgB;WACjE,kBAAkB,KAAK,wBAAwB;WAC/C,cAAc,KAAK,sBAAsB;WACzC,aAAa,KAAK,mBAAmB"}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{ToolCallId as e}from"../../primitives/brand.js";import{waitForSettlement as t}from"../../async/settlement.js";import{createSpanId as n}from"../../observation/context.js";import{snapshotJsonValue as r}from"../../primitives/json-snapshot.js";import{TOOL_ERROR_CODES as i,ToolError as a}from"../tool/errors.js";import{NESTED_TOOL_ERROR_CODES as o}from"../tool/nested.js";import{authorizeToolCall as s,dispatchAuthorizedToolCall as c,finalizeToolCall as l,prepareToolCall as u,toolFailure as d}from"../tool/pipeline.js";import{emitEvent as f,errorCode as p,immutableResult as m,messageOf as h,now as g,raceWithSignal as _,teardownFailure as v,withApprovalEvents as y}from"./tool-call-support.js";import{checkOutputSchema as b,outputSchemaSupported as x}from"../tool/output-schema.js";const S=65536,C=Object.freeze({maxBytes:S,maxDepth:64,maxNodes:32768,maxArrayItems:16384,maxObjectFields:16384,maxKeyBytes:S});function w(e){let t=new Map;for(let[n,r]of e??[]){if(!Number.isSafeInteger(r.maxCalls)||r.maxCalls<1)throw RangeError(`program "${n}" maxCalls must be a positive safe integer`);let i=Object.freeze([...new Set(r.allow)]);for(let t of i){if(typeof t!=`string`||t.length===0)throw TypeError(`program "${n}" grants an invalid tool name`);if(e?.has(t)===!0)throw RangeError(`program "${n}" may not call program "${t}"`)}t.set(n,Object.freeze({allow:i,maxCalls:r.maxCalls}))}return t}var T=class{options;step;grant;outer;port;fatal;closedCode;closedMessage=``;shutdown=new AbortController;inFlight;requests=0;sequence=0;unbindExecutionSignal;captured;constructor(e,t,n,r){this.options=e,this.step=t,this.grant=n,this.outer=r,this.captured=new Map(n.allow.map(t=>[t,e.catalog.get(t)]));let i=Object.freeze(n.allow.flatMap(e=>{let t=this.captured.get(e);return t===void 0?[]:[E(t)]}));this.port=Object.freeze({call:(e,t,n)=>this.request(e,t,n?.retain===!0),catalog:()=>i,load:e=>this.load(e),release:e=>this.step.programResults?.release(e,this.outer.call.toolName)===!0})}async close(e){this.unbindExecutionSignal?.(),this.latch(o.CLOSED,`the program has ended`),this.shutdown.abort(Error(`program closed`));let n=this.inFlight;return n===void 0||await t(n,e)}abort(e){this.unbindExecutionSignal?.(),this.latch(o.CLOSED,`the program was cancelled`),this.shutdown.abort(e)}bindExecutionSignal(e){this.unbindExecutionSignal?.();let t=()=>this.abort(e.reason);this.unbindExecutionSignal=()=>{e.removeEventListener(`abort`,t),this.unbindExecutionSignal=void 0},e.aborted?t():e.addEventListener(`abort`,t,{once:!0})}load(e){let t=this.step.programResults;if(typeof e!=`string`||t===void 0||this.fatal!==void 0||this.closedCode!==void 0)return D(o.RESULT_UNAVAILABLE,`no retained result is available`);let n;try{n=t.load(e,this.outer.call.toolName,e=>this.options.catalog.get(e))}catch(e){throw this.fatal??=a.fatal(h(e),p(e),{cause:e}),this.latch(o.CLOSED,`retained-result authority could not be checked`),this.fatal}return n.kind===`unavailable`?D(o.RESULT_UNAVAILABLE,`the retained result is ${n.reason===`unknown`?`not available to this program`:n.reason}`):Object.freeze({ok:!0,value:n.value,schema:n.schema,provenance:n.provenance})}async request(e,t,n=!1){if(this.fatal!==void 0||this.closedCode!==void 0)return this.refusal();if(this.inFlight!==void 0)return D(o.CALL_IN_FLIGHT,`a program may run one tool call at a time`);if(this.requests++,this.requests>this.grant.maxCalls)return this.latch(o.CALL_CAP,`the program reached its limit of ${this.grant.maxCalls} tool calls`),this.refusal();let r,i,s=new Promise((e,t)=>{r=e,i=t});this.inFlight=s,this.run(e,t,n).then(r,e=>{this.fatal??=a.fatal(h(e),p(e),{cause:e}),this.latch(o.CLOSED,`an earlier tool call failed fatally`),i(e)});try{return await s}finally{this.inFlight=void 0}}async run(t,s,c){if(!this.captured.has(t))return D(o.NOT_ALLOWED,`the program may not call "${t}"`);if(!this.current(t))return this.stale(t);let l=this.captured.get(t);if(l===void 0)return D(i.UNKNOWN_TOOL,`no tool named "${t}" is available`);let u;try{u=JSON.stringify(r(s,C))}catch{u=void 0}if(u===void 0||new TextEncoder().encode(u).byteLength>65536)return D(o.INVALID_ARGUMENTS,`tool arguments must be JSON within the size limit`);let _=Object.freeze({callId:e(`${this.outer.call.callId}:${String(++this.sequence)}`),toolName:t,rawArguments:u}),v={traceId:this.outer.trace.traceId,spanId:n(),parentSpanId:this.outer.trace.spanId},y=AbortSignal.any([this.outer.signal,this.shutdown.signal]);await f(this.options,{type:`span-start`,trace:v,at:g(),name:`execute_tool ${t}`,kind:`execute_tool`,attributes:{"gen_ai.operation.name":`execute_tool`,"gen_ai.tool.name":t,"gen_ai.tool.call.id":_.callId,"sdk.tool.parent_call_id":this.outer.call.callId},input:u});let x;try{x=m(await this.execute(_,l,v,y),this.step.maxResultBytes)}catch(e){this.fatal??=a.fatal(h(e),p(e),{cause:e}),this.latch(o.CLOSED,`an earlier tool call failed fatally`),x=d(h(e),p(e))}let S=this.current(t)&&!y.aborted;if(this.current(t)||this.latch(o.STALE_CATALOG,`"${t}" changed while the program was running`),await f(this.options,{type:`span-end`,trace:v,at:g(),status:y.aborted?`aborted`:x.isError?`error`:`success`,...x.isError?{error:{type:`ToolError`,message:x.error.message,code:x.error.code}}:{}}),!S)return this.refusal();if(x.isError)return D(x.error.code,x.error.message);if(x.value===void 0)return D(o.STRUCTURED_OUTPUT_UNAVAILABLE,`"${t}" returned no structured value the program may read`);let w=l.experimentalOutputSchema,T=w===void 0?`unsupported`:b(w,x.value);if(T===`invalid`)return D(o.OUTPUT_SCHEMA_MISMATCH,`"${t}" returned a value outside its declared output schema`);let E=T===`valid`?`validated`:`unchecked`;if(!c)return Object.freeze({ok:!0,value:x.value,schema:E});let O=this.step.programResults?.save({owner:this.outer.call.toolName,value:x.value,definition:l,schema:E,provenance:{toolName:t,callId:String(_.callId),parentCallId:String(this.outer.call.callId)}})??{refused:`closed`};return Object.freeze({ok:!0,value:x.value,schema:E,...`handle`in O?{handle:O.handle}:{retainRefused:O.refused}})}async execute(e,n,r,f){let{teardownTimeoutMs:p}=this.step,m=u({catalog:this.options.catalog,call:e,position:this.options.position,signal:f,teardownTimeoutMs:p,parentCallId:this.outer.call.callId,...this.options.logger===void 0?{}:{logger:this.options.logger},...this.options.interceptors===void 0?{}:{interceptors:this.options.interceptors},...this.options.approvals===void 0?{}:{approvals:this.options.approvals}}),g=this.step.admission.reserve(n.budgetExempt===!0);if(g===void 0){let e=`the turn has spent its tool-call budget`;return this.latch(o.BUDGET_EXHAUSTED,e),d(e,o.BUDGET_EXHAUSTED)}try{let n=s(y(this.options,m,r)),u;try{u=await _(n,f)}catch(r){if(!f.aborted)throw r;if(!await t(n,p))throw v(e.toolName,`authorization`,p,r);return d(`the call was cancelled`,i.ABORTED)}if(u.kind===`final`)return u.result;try{let n=Promise.resolve(this.options.checkpoint?.({kind:`before-tool-dispatch`,call:e,parentCallId:this.outer.call.callId,snapshot:this.options.history.snapshot(),signal:f,...this.options.logger===void 0?{}:{logger:this.options.logger}}));try{await _(n,f)}catch(r){if(!f.aborted)throw r;if(!await t(n,p))throw v(e.toolName,`checkpoint`,p,r)}}catch(e){if(e instanceof a&&e.code===i.TEARDOWN_TIMEOUT)throw e;return d(`history checkpoint failed: ${h(e)}`,i.CHECKPOINT_FAILED)}if(!this.current(e.toolName)){let t=`"${e.toolName}" changed while the program was running`;return this.latch(o.STALE_CATALOG,t),d(t,o.STALE_CATALOG)}if(this.fatal!==void 0||f.aborted)return d(`the program was cancelled`,i.ABORTED);g.confirm();let b=c(u.call);b.catch(()=>void 0);let x=await O(b,f,p,e.toolName,`execution`);return await O(l(u.call,x),f,p,e.toolName,`finalization`)}finally{g.release()}}current(e){return this.options.catalog.get(e)===this.captured.get(e)}stale(e){return this.latch(o.STALE_CATALOG,`"${e}" changed after the program started`),this.refusal()}latch(e,t){this.closedCode===void 0&&(this.closedCode=e,this.closedMessage=t)}refusal(){return D(this.closedCode??o.CLOSED,this.closedMessage||`the program is closed`)}};function E(e){let t=e.experimentalOutputSchema;return Object.freeze({name:e.name,description:e.description,parameters:e.parameters,output:t===void 0?`unknown`:x(t)?`declared`:`unsupported`,...t===void 0?{}:{outputSchema:t}})}function D(e,t){return Object.freeze({ok:!1,code:e,message:t})}async function O(e,n,r,a,o){try{return await _(e,n)}catch(s){if(!n.aborted)throw s;if(!await t(e,r))throw v(a,o,r,s);return d(`the call was cancelled`,i.ABORTED)}}export{S as MAX_NESTED_ARGUMENT_BYTES,T as ProgramRun,E as describe,D as refuse,O as settleWithin,w as validPrograms};
|
|
2
|
+
//# sourceMappingURL=program.js.map
|