@alvin0/ai-agent-sdk-core 0.1.7 → 0.1.9
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +6 -0
- package/dist/agent/define/session/config.js +1 -1
- package/dist/agent/define/session/config.js.map +1 -1
- package/dist/agent/define/session/types.d.ts +14 -0
- package/dist/agent/define/session/types.d.ts.map +1 -1
- 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/events.d.ts +24 -1
- package/dist/agent/loop/events.d.ts.map +1 -1
- 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 +5 -0
- package/dist/agent/loop/schedule.d.ts.map +1 -1
- package/dist/agent/loop/schedule.js +1 -1
- package/dist/agent/loop/schedule.js.map +1 -1
- package/dist/agent/loop/turn/config.js +1 -1
- package/dist/agent/loop/turn/config.js.map +1 -1
- package/dist/agent/loop/turn/model-request-boundary.js +1 -1
- package/dist/agent/loop/turn/model-request-boundary.js.map +1 -1
- package/dist/agent/loop/turn/model-round.js +1 -1
- package/dist/agent/loop/turn/model-round.js.map +1 -1
- package/dist/agent/loop/turn/types.d.ts +35 -2
- package/dist/agent/loop/turn/types.d.ts.map +1 -1
- package/dist/agent/loop/types.d.ts +16 -0
- package/dist/agent/loop/types.d.ts.map +1 -1
- package/dist/agent/mode/run-agent.d.ts +9 -0
- 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/mode/user-input.d.ts.map +1 -1
- package/dist/agent/mode/user-input.js +1 -1
- package/dist/agent/mode/user-input.js.map +1 -1
- package/dist/agent/team/managed.d.ts.map +1 -1
- package/dist/agent/team/managed.js +1 -1
- package/dist/agent/team/managed.js.map +1 -1
- package/dist/agent/tool/capture.js +1 -1
- package/dist/agent/tool/capture.js.map +1 -1
- package/dist/agent/tool/definition.d.ts +7 -0
- package/dist/agent/tool/definition.d.ts.map +1 -1
- package/dist/agent/tool/definition.js.map +1 -1
- package/dist/agent.js +1 -1
- package/dist/composition/agent/public-event.d.ts +19 -0
- package/dist/composition/agent/public-event.d.ts.map +1 -0
- package/dist/composition/agent/public-event.js +2 -0
- package/dist/composition/agent/public-event.js.map +1 -0
- package/dist/composition/agent/session.js +1 -1
- package/dist/composition/agent/session.js.map +1 -1
- package/dist/composition/agent/types.d.ts +11 -1
- package/dist/composition/agent/types.d.ts.map +1 -1
- package/dist/composition/embedding/retry.js +1 -1
- package/dist/composition/embedding/retry.js.map +1 -1
- package/dist/embedding/errors.d.ts +5 -1
- package/dist/embedding/errors.d.ts.map +1 -1
- package/dist/embedding/errors.js +1 -1
- package/dist/embedding/errors.js.map +1 -1
- package/dist/index.d.ts +2 -1
- package/dist/index.js +1 -1
- package/dist/observability/bus.js +1 -1
- package/dist/primitives/version.d.ts +1 -1
- package/dist/primitives/version.js +1 -1
- package/dist/primitives/version.js.map +1 -1
- package/dist/runtime/registry.js +1 -1
- package/dist/runtime/with-retry.d.ts +15 -0
- package/dist/runtime/with-retry.d.ts.map +1 -1
- package/dist/runtime/with-retry.js +1 -1
- package/dist/runtime/with-retry.js.map +1 -1
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -67,3 +67,9 @@ For 0.1.7 completion, pending input, stream replacement and Stop behavior, see
|
|
|
67
67
|
the [upgrade guide](https://github.com/alvin0/ai-agent-sdk/blob/main/docs/upgrading-from-0.1.6.md).
|
|
68
68
|
`RuntimeAgentSession.hasUnansweredInput()` and `runPending()` expose work left
|
|
69
69
|
after a terminal round. Use `response.completed` for objective completion.
|
|
70
|
+
|
|
71
|
+
In 0.1.8, the exact-repeat guard can reuse the immediately preceding successful
|
|
72
|
+
tool result and allow one bounded model replan. `EmbeddingError.failure` preserves
|
|
73
|
+
available provider HTTP status, retry delay and request id through normalization.
|
|
74
|
+
See [upgrading from 0.1.7](https://github.com/alvin0/ai-agent-sdk/blob/main/docs/upgrading-from-0.1.7.md)
|
|
75
|
+
for exclusions, cancellation and budget behavior.
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{timeoutValue as e}from"../../../platform/config.js";function t(t){if(t===void 0)return Object.freeze({});let n={...t};if(n.maxTotalTokens!==void 0&&n.maxTotalTokens!==`auto`&&(!Number.isSafeInteger(n.maxTotalTokens)||n.maxTotalTokens<1))throw RangeError(`agent runtimeLimits.maxTotalTokens must be a positive safe integer or 'auto'`);if(n.finalReportReserveTokens!==void 0&&(!Number.isSafeInteger(n.finalReportReserveTokens)||n.finalReportReserveTokens<0||typeof n.maxTotalTokens==`number`&&n.finalReportReserveTokens>=n.maxTotalTokens))throw RangeError(`agent runtimeLimits.finalReportReserveTokens must be a non-negative safe integer below maxTotalTokens`);for(let t of[`teardownTimeoutMs`,`modelTimeoutMs`,`maxModelRequestBytes`,`maxModelResponseBytes`,`maxModelStreamEvents`,`maxToolResultBytes`,`maxToolDurationMs`,`toolTeardownTimeoutMs`,`maxParallelToolCalls`,`maxConsecutiveToolErrors`,`repeatToolWarningAt`,`repeatToolLimit`,`toolCycleWarningAt`,`toolCycleLimit`,`maxToolCycleLength`,`maxToolResultTokens`,`hookTimeoutMs`,`hookTeardownTimeoutMs`,`memoryOperationTimeoutMs`,`observerTimeoutMs`]){let r=n[t];if(r!==void 0&&t.endsWith(`Ms`)&&e(r),r!==void 0&&(!Number.isSafeInteger(r)||r<1))throw RangeError(`agent runtimeLimits.${t} must be a positive safe integer`)}if(n.toolResultOverflow!==void 0&&![`auto`,`truncate`,`spill`].includes(n.toolResultOverflow))throw RangeError(`agent runtimeLimits.toolResultOverflow must be 'auto', 'truncate', or 'spill'`);if(n.onExhausted!==void 0&&![`force-final-answer`,`stop`,`continue`].includes(n.onExhausted))throw RangeError(`agent runtimeLimits.onExhausted must be 'force-final-answer', 'stop', or 'continue'`);if((n.repeatToolLimit??6)<(n.repeatToolWarningAt??3))throw RangeError(`agent runtimeLimits.repeatToolLimit must be >= repeatToolWarningAt`);if((n.toolCycleLimit??3)<(n.toolCycleWarningAt??2))throw RangeError(`agent runtimeLimits.toolCycleLimit must be >= toolCycleWarningAt`);return Object.freeze(n)}export{t as resolveRuntimeLimits};
|
|
1
|
+
import{timeoutValue as e}from"../../../platform/config.js";function t(t){if(t===void 0)return Object.freeze({});let n={...t};if(n.maxTotalTokens!==void 0&&n.maxTotalTokens!==`auto`&&(!Number.isSafeInteger(n.maxTotalTokens)||n.maxTotalTokens<1))throw RangeError(`agent runtimeLimits.maxTotalTokens must be a positive safe integer or 'auto'`);if(n.finalReportReserveTokens!==void 0&&(!Number.isSafeInteger(n.finalReportReserveTokens)||n.finalReportReserveTokens<0||typeof n.maxTotalTokens==`number`&&n.finalReportReserveTokens>=n.maxTotalTokens))throw RangeError(`agent runtimeLimits.finalReportReserveTokens must be a non-negative safe integer below maxTotalTokens`);if(n.finalizeSteps!==void 0&&(!Number.isSafeInteger(n.finalizeSteps)||n.finalizeSteps<0||n.finalizeSteps>8))throw RangeError(`agent runtimeLimits.finalizeSteps must be a safe integer from 0 to 8`);if(n.maxTurnDurationMs!==void 0&&n.maxTurnDurationMs!==`auto`&&(!Number.isSafeInteger(n.maxTurnDurationMs)||n.maxTurnDurationMs<1))throw RangeError(`agent runtimeLimits.maxTurnDurationMs must be a positive safe integer or 'auto'`);if(n.userInputTimeoutMs!==void 0&&(!Number.isSafeInteger(n.userInputTimeoutMs)||n.userInputTimeoutMs<1))throw RangeError(`agent runtimeLimits.userInputTimeoutMs must be a positive safe integer`);for(let t of[`teardownTimeoutMs`,`modelTimeoutMs`,`maxModelRequestBytes`,`maxModelResponseBytes`,`maxModelStreamEvents`,`maxToolResultBytes`,`maxToolDurationMs`,`toolTeardownTimeoutMs`,`maxParallelToolCalls`,`maxConsecutiveToolErrors`,`repeatToolWarningAt`,`repeatToolLimit`,`toolCycleWarningAt`,`toolCycleLimit`,`maxToolCycleLength`,`maxToolResultTokens`,`hookTimeoutMs`,`hookTeardownTimeoutMs`,`memoryOperationTimeoutMs`,`observerTimeoutMs`]){let r=n[t];if(r!==void 0&&t.endsWith(`Ms`)&&e(r),r!==void 0&&(!Number.isSafeInteger(r)||r<1))throw RangeError(`agent runtimeLimits.${t} must be a positive safe integer`)}if(n.toolResultOverflow!==void 0&&![`auto`,`truncate`,`spill`].includes(n.toolResultOverflow))throw RangeError(`agent runtimeLimits.toolResultOverflow must be 'auto', 'truncate', or 'spill'`);if(n.onExhausted!==void 0&&![`force-final-answer`,`stop`,`continue`].includes(n.onExhausted))throw RangeError(`agent runtimeLimits.onExhausted must be 'force-final-answer', 'stop', or 'continue'`);if((n.repeatToolLimit??6)<(n.repeatToolWarningAt??3))throw RangeError(`agent runtimeLimits.repeatToolLimit must be >= repeatToolWarningAt`);if((n.toolCycleLimit??3)<(n.toolCycleWarningAt??2))throw RangeError(`agent runtimeLimits.toolCycleLimit must be >= toolCycleWarningAt`);return Object.freeze(n)}export{t as resolveRuntimeLimits};
|
|
2
2
|
//# sourceMappingURL=config.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"config.js","names":[],"sources":["../../../../src/agent/define/session/config.ts"],"sourcesContent":["import { type AgentRuntimeLimits } from './types.ts'\nimport { timeoutValue } from '../../../platform/config.ts'\n\nexport function resolveRuntimeLimits(input: AgentRuntimeLimits | undefined): Readonly<AgentRuntimeLimits> {\n if (input === undefined) return Object.freeze({})\n const values = { ...input }\n if (values.maxTotalTokens !== undefined && values.maxTotalTokens !== 'auto'\n && (!Number.isSafeInteger(values.maxTotalTokens) || values.maxTotalTokens < 1)) {\n throw new RangeError(\"agent runtimeLimits.maxTotalTokens must be a positive safe integer or 'auto'\")\n }\n if (values.finalReportReserveTokens !== undefined\n && (!Number.isSafeInteger(values.finalReportReserveTokens) || values.finalReportReserveTokens < 0\n || (typeof values.maxTotalTokens === 'number' && values.finalReportReserveTokens >= values.maxTotalTokens))) {\n throw new RangeError('agent runtimeLimits.finalReportReserveTokens must be a non-negative safe integer below maxTotalTokens')\n }\n for (const key of [\n 'teardownTimeoutMs', 'modelTimeoutMs', 'maxModelRequestBytes',\n 'maxModelResponseBytes', 'maxModelStreamEvents', 'maxToolResultBytes',\n 'maxToolDurationMs', 'toolTeardownTimeoutMs', 'maxParallelToolCalls',\n 'maxConsecutiveToolErrors', 'repeatToolWarningAt', 'repeatToolLimit',\n 'toolCycleWarningAt', 'toolCycleLimit', 'maxToolCycleLength', 'maxToolResultTokens',\n 'hookTimeoutMs', 'hookTeardownTimeoutMs', 'memoryOperationTimeoutMs',\n 'observerTimeoutMs',\n ] as const) {\n const value = values[key]\n if (value !== undefined && key.endsWith('Ms')) timeoutValue(value)\n if (value !== undefined && (!Number.isSafeInteger(value) || value < 1)) {\n throw new RangeError(`agent runtimeLimits.${key} must be a positive safe integer`)\n }\n }\n if (values.toolResultOverflow !== undefined\n && !['auto', 'truncate', 'spill'].includes(values.toolResultOverflow)) {\n throw new RangeError(\n \"agent runtimeLimits.toolResultOverflow must be 'auto', 'truncate', or 'spill'\",\n )\n }\n if (values.onExhausted !== undefined\n && !['force-final-answer', 'stop', 'continue'].includes(values.onExhausted)) {\n throw new RangeError(\n \"agent runtimeLimits.onExhausted must be 'force-final-answer', 'stop', or 'continue'\",\n )\n }\n if ((values.repeatToolLimit ?? 6) < (values.repeatToolWarningAt ?? 3)) {\n throw new RangeError('agent runtimeLimits.repeatToolLimit must be >= repeatToolWarningAt')\n }\n if ((values.toolCycleLimit ?? 3) < (values.toolCycleWarningAt ?? 2)) {\n throw new RangeError('agent runtimeLimits.toolCycleLimit must be >= toolCycleWarningAt')\n }\n return Object.freeze(values)\n}\n"],"mappings":"2DAGA,SAAgB,EAAqB,EAAqE,CACxG,GAAI,IAAU,IAAA,GAAW,OAAO,OAAO,OAAO,CAAC,CAAC,EAChD,IAAM,EAAS,CAAE,GAAG,CAAM,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RuntimeLimits } from './types.ts'\nimport { timeoutValue } from '../../../platform/config.ts'\n\nexport function resolveRuntimeLimits(input: AgentRuntimeLimits | undefined): Readonly<AgentRuntimeLimits> {\n if (input === undefined) return Object.freeze({})\n const values = { ...input }\n if (values.maxTotalTokens !== undefined && values.maxTotalTokens !== 'auto'\n && (!Number.isSafeInteger(values.maxTotalTokens) || values.maxTotalTokens < 1)) {\n throw new RangeError(\"agent runtimeLimits.maxTotalTokens must be a positive safe integer or 'auto'\")\n }\n if (values.finalReportReserveTokens !== undefined\n && (!Number.isSafeInteger(values.finalReportReserveTokens) || values.finalReportReserveTokens < 0\n || (typeof values.maxTotalTokens === 'number' && values.finalReportReserveTokens >= values.maxTotalTokens))) {\n throw new RangeError('agent runtimeLimits.finalReportReserveTokens must be a non-negative safe integer below maxTotalTokens')\n }\n if (values.finalizeSteps !== undefined\n && (!Number.isSafeInteger(values.finalizeSteps) || values.finalizeSteps < 0 || values.finalizeSteps > 8)) {\n throw new RangeError('agent runtimeLimits.finalizeSteps must be a safe integer from 0 to 8')\n }\n if (values.maxTurnDurationMs !== undefined && values.maxTurnDurationMs !== 'auto'\n && (!Number.isSafeInteger(values.maxTurnDurationMs) || values.maxTurnDurationMs < 1)) {\n throw new RangeError(\"agent runtimeLimits.maxTurnDurationMs must be a positive safe integer or 'auto'\")\n }\n if (values.userInputTimeoutMs !== undefined\n && (!Number.isSafeInteger(values.userInputTimeoutMs) || values.userInputTimeoutMs < 1)) {\n throw new RangeError('agent runtimeLimits.userInputTimeoutMs must be a positive safe integer')\n }\n for (const key of [\n 'teardownTimeoutMs', 'modelTimeoutMs', 'maxModelRequestBytes',\n 'maxModelResponseBytes', 'maxModelStreamEvents', 'maxToolResultBytes',\n 'maxToolDurationMs', 'toolTeardownTimeoutMs', 'maxParallelToolCalls',\n 'maxConsecutiveToolErrors', 'repeatToolWarningAt', 'repeatToolLimit',\n 'toolCycleWarningAt', 'toolCycleLimit', 'maxToolCycleLength', 'maxToolResultTokens',\n 'hookTimeoutMs', 'hookTeardownTimeoutMs', 'memoryOperationTimeoutMs',\n 'observerTimeoutMs',\n ] as const) {\n const value = values[key]\n if (value !== undefined && key.endsWith('Ms')) timeoutValue(value)\n if (value !== undefined && (!Number.isSafeInteger(value) || value < 1)) {\n throw new RangeError(`agent runtimeLimits.${key} must be a positive safe integer`)\n }\n }\n if (values.toolResultOverflow !== undefined\n && !['auto', 'truncate', 'spill'].includes(values.toolResultOverflow)) {\n throw new RangeError(\n \"agent runtimeLimits.toolResultOverflow must be 'auto', 'truncate', or 'spill'\",\n )\n }\n if (values.onExhausted !== undefined\n && !['force-final-answer', 'stop', 'continue'].includes(values.onExhausted)) {\n throw new RangeError(\n \"agent runtimeLimits.onExhausted must be 'force-final-answer', 'stop', or 'continue'\",\n )\n }\n if ((values.repeatToolLimit ?? 6) < (values.repeatToolWarningAt ?? 3)) {\n throw new RangeError('agent runtimeLimits.repeatToolLimit must be >= repeatToolWarningAt')\n }\n if ((values.toolCycleLimit ?? 3) < (values.toolCycleWarningAt ?? 2)) {\n throw new RangeError('agent runtimeLimits.toolCycleLimit must be >= toolCycleWarningAt')\n }\n return Object.freeze(values)\n}\n"],"mappings":"2DAGA,SAAgB,EAAqB,EAAqE,CACxG,GAAI,IAAU,IAAA,GAAW,OAAO,OAAO,OAAO,CAAC,CAAC,EAChD,IAAM,EAAS,CAAE,GAAG,CAAM,EAC1B,GAAI,EAAO,iBAAmB,IAAA,IAAa,EAAO,iBAAmB,SAC/D,CAAC,OAAO,cAAc,EAAO,cAAc,GAAK,EAAO,eAAiB,GAC5E,MAAU,WAAW,8EAA8E,EAErG,GAAI,EAAO,2BAA6B,IAAA,KAClC,CAAC,OAAO,cAAc,EAAO,wBAAwB,GAAK,EAAO,yBAA2B,GAC1F,OAAO,EAAO,gBAAmB,UAAY,EAAO,0BAA4B,EAAO,gBAC7F,MAAU,WAAW,uGAAuG,EAE9H,GAAI,EAAO,gBAAkB,IAAA,KACvB,CAAC,OAAO,cAAc,EAA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xTotalTokens?: number | 'auto';
|
|
74
74
|
/** Token headroom for one tools-disabled final report; ignored with auto total tokens. Default zero. */
|
|
75
75
|
readonly finalReportReserveTokens?: number;
|
|
76
|
+
/** Exempt-only steps to confirm an answer a budget forced; deep mode defaults to 2, basic to 0. */
|
|
77
|
+
readonly finalizeSteps?: number;
|
|
78
|
+
/**
|
|
79
|
+
* How long `request_user_input` waits for an answer. Defaults to
|
|
80
|
+
* `maxToolDurationMs`, which no longer bounds the wait itself, so a host can
|
|
81
|
+
* give people longer than it gives tools.
|
|
82
|
+
*/
|
|
83
|
+
readonly userInputTimeoutMs?: number;
|
|
84
|
+
/**
|
|
85
|
+
* Wall-clock budget for one turn's work, excluding waits for a person. When
|
|
86
|
+
* it passes the turn answers from the evidence it has (reason
|
|
87
|
+
* `budget-exhausted` / `time`) instead of being cancelled. Default 'auto'.
|
|
88
|
+
*/
|
|
89
|
+
readonly maxTurnDurationMs?: number | 'auto';
|
|
76
90
|
readonly hookTimeoutMs?: number;
|
|
77
91
|
readonly hookTeardownTimeoutMs?: number;
|
|
78
92
|
/** Maximum settlement time for each host memory-store load or commit callback. */
|
|
@@ -1 +1 @@
|
|
|
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"}
|
|
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;;WAEA;;;;;;WAMA;;;;;;WAMA;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;;;;;;;;W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d,OAAO,OAAO;;;;;;;;;;;;;UAkCN;;UAuBA;;;;;;EAcR;EAYA,eAAe;;EAGf,SAAS,SAAS,cAAc;;EAyBhC,OAAO,OAAO,YAAY,aAAY,yBAA8B;;EAKpE,cAAc,aAAY,yBAA8B;;EAKlD,IAAI,OAAO,YAAY,aAAY,yBAA8B,QAAQ;;EAOzE,WAAW,aAAY,yBAA8B,QAAQ;UAM3D;
|
|
1
|
+
{"version":3,"file":"session.d.ts","names":[],"sources":["../../../src/agent/define/session.ts"],"mappings":";;;;;;;;cAqDa;WACF,YAAY;mBACJ;mBACA;UACT;mBACS;mBACA;;mBAEA;UACT;UACA;UACA;UACA;UACA;UACA;UACA;;UAEA;mBACS;;;;;;;UAOT;UACA;;;;;;UAMA;;UAEA;EAER,YAAY,YAAY,iBAAiB,SAAS;;SA0F3C,aACL,YAAY,iBACZ,SAAS,4BACR;;MAcC;;MAGA,WAAW;;MAGX,UAAU;;MAGV,UAAU;;MAGV;;EAGJ,YAAY;;EA6BZ;;EAaM,QAAQ,aAAY,yBAA8B,QAAQ;UAYlD;;;;;;;;EA0Bd,OAAO,OAAO;;;;;;;;;;;;;UAkCN;;UAuBA;;;;;;EAcR;EAYA,eAAe;;EAGf,SAAS,SAAS,cAAc;;EAyBhC,OAAO,OAAO,YAAY,aAAY,yBAA8B;;EAKpE,cAAc,aAAY,yBAA8B;;EAKlD,IAAI,OAAO,YAAY,aAAY,yBAA8B,QAAQ;;EAOzE,WAAW,aAAY,yBAA8B,QAAQ;UAM3D;UAsOA;UAmBA;UAWA;UA+GA;UAuBA;UAIA;UA8CA;UAIA;UAeA;UAOA;UAkBM"}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{waitForSettlement as e}from"../../async/settlement.js";import{ModelError as t}from"../../errors/model-error.js";import{contentHasDocument as n,contentHasImage as r}from"../../message/projection.js";import{AgentMemory as i}from"../memory/memory.js";import{normalizeToolPairing as a}from"../history/normalize.js";import{bindCompactionAccounting as o}from"../memory/accounting-binding.js";import{ContextCompactor as s}from"../memory/compaction.js";import{resolveCompactionConfig as c}from"../memory/compaction-config.js";import{bindSkillProviderLogger as l}from"../skill/provider/context.js";import{SkillCatalog as u}from"../skill/catalog.js";import{createSkillTools as d,renderSkillCatalog as f}from"../skill/tools.js";import{createRunTerminalRecord as p,withTerminalDelivery as m}from"../accounting/delivery/terminal.js";import{captureContextSections as h}from"../context/section.js";import{History as g}from"../history/history.js";import{isManagedTeamNotice as _}from"../history/input-work.js";import{bindModelRequestBoundary as v,bindQueuedInput as y}from"../loop/turn/model-request-boundary.js";import{bindStepProjectionSources as b}from"../loop/turn/step-projection.js";import{AGENT_ACCOUNTING_ERROR_CODES as x,AgentRunError as S}from"../accounting/error.js";import{runAgent as C}from"../mode/run-agent.js";import{RunEventBuffer as w}from"../accounting/event-buffer.js";import{validateSessionSnapshot as T}from"./session/validation.js";import{resolveRuntimeLimits as E}from"./session/config.js";import{conversationId as D,deferred as O,errorCodeOf as k,messageOf as A,newConversationId as j,toolCatalog as M,userMessage as N}from"./session/common.js";import{captureResumedSkillActivations as P,prepareSkills as F}from"./session/skills.js";import{appendRunInstructions as I}from"./instructions.js";import{accountTraceEvent as L}from"./session/trace-accounting.js";import{captureResumedObjective as R,commitRuntimeMemory as z,loadRuntimeMemory as B,renderRuntimeMemory as V}from"./session/runtime-memory.js";import{attachRuntimeSession as H,configureRuntimeSessionModel as U,runtimeSessionConfiguration as W,streamRuntimeSession as G}from"./session/runtime-binding.js";import{createSessionLedger as K}from"./session/accounting.js";import{runRuntimeCompaction as q}from"./session/runtime-compaction.js";import{sessionCallConfig as J}from"./session/model-config.js";import{consumeSessionEvents as Y}from"./session/observer.js";import{sealRuntimeRun as X}from"./session/run-seal.js";var Z=class U{definition;options;catalog;activeRuntimeCatalog;skillCatalog;runtimeLimits;contextSections;currentHistory;currentMemory;currentConversationId;compactor;pendingSkillActivations=Object.freeze([]);active=!1;activeAdditionalInstructions;activeInvocation;idleWaiters=new Set;pendingInjections;lastRunOutcome;roundInFlight=!1;roundCalledTools=!1;constructor(e,t){if(e.mode===`deep-human-in-loop`&&t.userInput===void 0)throw TypeError(`agent '${e.id}' requires a userInput broker in deep-human-in-loop mode`);this.definition=e;let n=t.historyLimits===void 0?void 0:Object.freeze({...t.historyLimits});t.history!==void 0&&n!==void 0&&new g(n);let r=t.compaction===void 0||t.compaction===!1?t.compaction:Object.freeze({...t.compaction}),a=t.trace===void 0?void 0:Object.freeze({...t.trace}),o=t.team===void 0?void 0:Object.freeze({...t.team}),s=t.ledgerLimits===void 0?void 0:Object.freeze({...t.ledgerLimits}),c=t.eventBufferLimits===void 0?void 0:Object.freeze({...t.eventBufferLimits});this.options=Object.freeze({...t,...n===void 0?{}:{historyLimits:n},...r===void 0?{}:{compaction:r},...a===void 0?{}:{trace:a},...o===void 0?{}:{team:o},...s===void 0?{}:{ledgerLimits:s},...c===void 0?{}:{eventBufferLimits:c},...t.skills===void 0?{}:{skills:Object.freeze([...t.skills])},...Array.isArray(t.tools)?{tools:Object.freeze([...t.tools])}:{},...t.interceptors===void 0?{}:{interceptors:Object.freeze([...t.interceptors])}}),this.runtimeLimits=E(t.runtimeLimits);let l=h(t.contextSections)??[],f=h(e.contextSections)??[],p=[...f.map(e=>l.find(t=>t.id===e.id)??e),...l.filter(e=>!f.some(t=>t.id===e.id))];this.contextSections=p.length===0?void 0:Object.freeze(p),this.currentConversationId=D(t.conversationId),this.currentHistory=t.history??new g(n);let m=[...e.skills,...t.skills??[]],_=e.skillIds?.length===0,v=m.length>0||(e.skillIds?.length??0)>0;this.skillCatalog=_||!v?void 0:new u(m,{...e.skillIds===void 0?{}:{allowedSkillIds:e.skillIds},maxSkills:e.skillOptions.maxSkills,maxCatalogBytes:e.skillOptions.maxDiscoveryBytes});let y=this.skillCatalog===void 0?[]:d(this.skillCatalog,e.skillOptions,()=>this.skillLookup()),b=t.team?.tools===`reporting`?`reporting`:`full`,x=t.team?.tools===!1?[]:t.team?.team.toolsFor(t.team.name??e.id,b)??[];this.catalog=M(e.tools,t.tools,[...y,...x]),this.currentMemory=t.memory instanceof i?t.memory:t.memory===void 0?new i(e.memory.seed,e.memory):i.fromSnapshot(t.memory,e.memory),R(this.currentMemory,this.currentHistory,this.definition.memory.autoCaptureObjective),this.compactor=this.createCompactor(),H(this,(e,t,n)=>this.createRunHandle(e,t,n),e=>this.createRunHandle(void 0,e),e=>this.compactForRuntime(e),()=>{this.compactor=this.createCompactor()}),t.team?.team.attach(this,{...t.team.name===void 0?{}:{name:t.team.name},...t.team.description===void 0?{}:{description:t.team.description},...t.team.instructions===void 0?{}:{instructions:t.team.instructions},...t.team.role===void 0?{}:{role:t.team.role},...t.team.tools===void 0?{}:{tools:t.team.tools}})}static fromSnapshot(e,t){let{snapshot:n,...r}=t;T(n,e.id,e.skillOptions.maxSkills);let a=new U(e,{...r,conversationId:n.conversationId,history:g.fromSnapshot(n.history,r.historyLimits),memory:i.fromSnapshot(n.memory,e.memory)});return a.pendingSkillActivations=P(n.skills,a.skillCatalog),a}get conversationId(){return this.currentConversationId}get history(){return this.currentHistory}get memory(){return this.currentMemory}get skills(){return this.skillCatalog}get isRunning(){return this.active}snapshot(){let e=this.activationSnapshot(),t=this.currentHistory.snapshot(),n=this.pendingInjections?.entries()??[],r=n.length===0?t:Object.freeze({version:1,entries:Object.freeze([...t.entries,...n.map((e,n)=>Object.freeze({...e,seq:t.entries.length+n+1}))])});return Object.freeze({version:1,conversationId:this.currentConversationId,agentId:this.definition.id,history:r,memory:this.currentMemory.snapshot(),...W(this)?.memory===void 0?{}:{memoryBindingId:W(this).memory.bindingId},...e.length===0?{}:{skills:Object.freeze({activated:e})}})}reset(){if(this.active)throw Error(`cannot reset an agent session while a run is active`);this.currentConversationId=j(),this.currentHistory=new g(this.options.historyLimits),this.currentMemory=new i(this.definition.memory.seed,this.definition.memory),this.pendingInjections=void 0,this.pendingSkillActivations=Object.freeze([]),this.lastRunOutcome=void 0,this.skillCatalog?.clearActivations(),this.compactor=this.createCompactor()}async compact(e={}){if(this.active)throw Error(`cannot compact an agent session while a run is active`);this.active=!0,this.activeInvocation=e;try{return await this.prepareSkills(e.signal),await this.compactor?.compactNow(e.signal)??null}finally{this.releaseRun()}}async compactForRuntime(e){if(this.active)throw Error(`cannot compact an agent session while a run is active`);let t=this.createLedger();this.active=!0,this.activeInvocation=e,this.compactor!==void 0&&o(this.compactor,t),this.skillCatalog!==void 0&&l(this.skillCatalog,t.modelInvocation.logger);try{return await q({...this.compactor===void 0?{}:{compactor:this.compactor},invocation:e,accounting:t,prepare:()=>this.prepareSkills(e.signal,t)})}finally{this.releaseRun()}}inject(e){let t=N(e);if(this.active&&this.roundInFlight){g.fromSnapshot(this.currentHistory.snapshot(),this.options.historyLimits).appendBatch([...(this.pendingInjections?.entries()??[]).map(e=>({event:e.event})),{event:{kind:`user`,message:t}}]);let e=this.pendingInjections??=new g(this.options.historyLimits);return e.append({kind:`user`,message:t}),this.currentHistory.entries().length+e.entries().length}return this.drainInjections(),this.currentHistory.append({kind:`user`,message:t}),this.currentHistory.entries().length}observeRoundBoundary(e){if(e.type===`agent-end`&&(this.lastRunOutcome=e.outcome),e.type===`span-start`&&e.kind===`chat`){this.roundInFlight=!0,this.roundCalledTools=!1;return}this.roundInFlight&&((e.type===`tool-call`||e.type===`assistant-message`&&e.message?.content.some(e=>e.type===`tool-call`)===!0)&&(this.roundCalledTools=!0),(e.type===`step-end`&&this.roundCalledTools||e.type===`turn-end`||e.type===`agent-end`)&&(this.roundInFlight=!1,this.drainInjections()))}drainInjections(){if(this.pendingInjections===void 0)return;let e=this.pendingInjections;this.currentHistory.appendBatch(e.entries().map(e=>({event:e.event}))),this.pendingInjections=void 0}hasUnansweredInput(){if((this.pendingInjections?.entries().length??0)>0)return!0;for(let e of[...this.currentHistory.messages()].reverse()){if(e.source.kind===`app`){if(e.source.producer===`turn-interrupted`)return!1;if(e.role===`user`&&!_(e))continue}return e.role===`user`}return!1}lastOutcome(){return this.lastRunOutcome}whenIdle(e){return this.active?e?.aborted?Promise.reject(e.reason):new Promise((t,n)=>{let r=!1,i=()=>{r||(r=!0,this.idleWaiters.delete(i),e?.removeEventListener(`abort`,a),t())},a=()=>{r||(r=!0,this.idleWaiters.delete(i),n(e?.reason))};this.idleWaiters.add(i),e?.addEventListener(`abort`,a,{once:!0}),this.active||i()}):Promise.resolve()}stream(e,t={}){return this.createRunHandle(e,t)}streamPending(e={}){return this.createRunHandle(void 0,e)}async run(e,t={}){let n=this.stream(e,t);return await Y(n,t.onEvent,this.runtimeLimits.observerTimeoutMs??3e4),await n.result}async runPending(e={}){let t=this.streamPending(e);return await Y(t,e.onEvent,this.runtimeLimits.observerTimeoutMs??3e4),await t.result}createRunHandle(i,a,s){if(this.active)throw Error(`agent session '${this.definition.id}' is already running`);this.drainInjections();let c=this.currentHistory.entries().length+1,u=new AbortController,d=!1,f=a.signal===void 0?u.signal:AbortSignal.any([a.signal,u.signal]),h=new w(this.options.eventBufferLimits?.maxEvents,this.options.eventBufferLimits?.maxBytes),g=O(),b=O(),C=O(),T=this.createLedger(),E=Object.freeze([]);this.compactor!==void 0&&o(this.compactor,T),this.skillCatalog!==void 0&&l(this.skillCatalog,T.modelInvocation.logger),this.active=!0,v(this.currentHistory,e=>{this.roundInFlight=e,e||this.drainInjections()}),y(this.currentHistory,()=>{let e=this.pendingInjections?.entries()??[];return e.length===0||!e.some(e=>e.event.kind===`user`&&(e.event.message.source.kind===`user`||_(e.event.message)))?!1:(this.roundInFlight=!1,this.drainInjections(),!0)}),this.activeAdditionalInstructions=s,this.activeInvocation=a;let D=new Map,j=(async()=>{let e,o,s;try{let e=W(this);if(e?.memory!==void 0){let t=await B(e.memory,this.currentConversationId,this.definition.memory,f,T);s=t.state,t.memory!==void 0&&(this.currentMemory=t.memory)}if(e?.prepareTools!==void 0){let t=T.modelInvocation.logger;if(t===void 0)throw Error(`runtime tool source logger is unavailable`);let n=e.prepareTools(f,t,[...this.catalog?.names()??[],...this.definition.nativeTools.map(e=>e.name)]);this.activeRuntimeCatalog=M([],this.catalog,n.tools),E=n.references}if(C.resolve(E),await this.prepareSkills(f,T),i!==void 0){let e=N(i);if(this.definition.memory.autoCaptureObjective){let t=T.startOperation(`memory`,{data:{action:`capture-objective`}});try{this.currentMemory.captureOriginalObjective(e),T.endOperation(t,`success`)}catch(e){throw T.endOperation(t,`error`,{error:e}),e}}this.currentHistory.append({kind:`user`,message:e})}if(a.imagePolicy===`strict`&&this.history.messages().some(e=>r(e.content))){let e=this.callConfig(a),n=await this.options.registry.resolveModelInfo(e.provider,e.model,f);if(n.inputModalities!==void 0&&!n.inputModalities.includes(`image`))throw new t(`model ${n.id} does not support required image input`,`UNSUPPORTED_IMAGE_INPUT`)}if(a.documentPolicy===`strict`&&this.history.messages().some(e=>n(e.content))){let e=this.callConfig(a),n=await this.options.registry.resolveModelInfo(e.provider,e.model,f);if(n.inputModalities!==void 0&&!n.inputModalities.includes(`document`))throw new t(`model ${n.id} does not support required document input`,`UNSUPPORTED_DOCUMENT_INPUT`)}for await(let e of this.runDefinition({...a,signal:f},T))this.observeRoundBoundary(e),L(T,D,e),e.type===`agent-end`&&(o=e.outcome),h.push(e);if(o===void 0)throw Error(`agent session '${this.definition.id}' ended without agent-end`);if(f.aborted)throw f.reason??Error(`agent run was aborted`);if(o.reason.kind===`error`&&o.reason.failure.code===`USAGE_REQUIRED`){let e=Error(o.reason.failure.message);throw e.code=`USAGE_REQUIRED`,e}e?.memory!==void 0&&s!==void 0&&s.status!==`disabled`&&await z(e.memory,this.currentConversationId,this.currentMemory.snapshot(),s,f,T)}catch(t){e=t,C.resolve(E)}try{this.drainInjections()}catch(t){e??=t}let l;try{let t=f.aborted||o?.reason.kind===`aborted`?`aborted`:e!==void 0||o?.reason.kind===`error`?`error`:`success`,n=await T.finalize(t,o?.completed??!1,e);l=m(p(n),n.delivery),g.resolve(l)}catch(e){g.reject(e),b.reject(e),h.fail(e),d=!0,this.releaseRun();return}if(!d){if(e===void 0&&T.terminalAuditFailure){let t=Error(`audit observation checkpoint failed after run finalization`);t.code=`OBSERVABILITY_AUDIT_UNAVAILABLE`,e=t}if(e!==void 0){let t=new S(A(e),k(e)??x.RUN_FAILED,l,{cause:e});b.reject(t),h.fail(t)}else{let e=o,t=[...this.currentHistory.entries()].reverse().find(e=>e.seq>=c&&e.event.kind===`assistant`)?.event,n=t?.kind===`assistant`?t.message:void 0,r=Object.freeze({text:e.text,outcome:e,report:l,...n===void 0?{}:{message:n}});b.resolve(r),h.close()}d=!0,this.releaseRun()}})();j.catch(e=>{d||(g.reject(e),b.reject(e),h.fail(e),d=!0,this.releaseRun())}),b.promise.catch(()=>void 0),g.promise.catch(()=>void 0);let P=!1;return Object.freeze({runId:T.runId,traceId:T.traceId,toolSourceSnapshots:C.promise,eventsSettled:j.then(()=>void 0,()=>void 0),result:b.promise,report:g.promise,seal:()=>X({ledger:T,buffer:h,report:g,result:b,toolSources:C,currentToolSources:()=>E,isTerminal:()=>d,markTerminal:()=>{d=!0},abort:()=>u.abort(Error(`Agent run was sealed`)),release:()=>this.releaseRun()}),abort(e){!d&&!u.signal.aborted&&u.abort(Error(`Agent run was aborted`))},[Symbol.asyncIterator](){return P?(async function*(){throw Error(`an agent run handle can only be iterated once`)})():(P=!0,(async function*(){let t=!1;try{for(;;){let e=await h.take();if(e.done){t=!0;break}yield e.value}}finally{t||(u.abort(Error(`agent event consumer stopped`)),h.stop(),await e(j,3e4))}})())}})}releaseRun(){try{this.drainInjections()}finally{v(this.currentHistory),y(this.currentHistory),this.roundInFlight=!1,this.active=!1,this.activeAdditionalInstructions=void 0,this.activeInvocation=void 0,this.activeRuntimeCatalog=void 0,this.skillCatalog!==void 0&&l(this.skillCatalog,void 0),this.compactor!==void 0&&o(this.compactor,void 0);let e=[...this.idleWaiters];this.idleWaiters.clear();for(let t of e)t()}}createLedger(){let e=W(this);return K({definition:this.definition,options:this.options,runtimeLimits:this.runtimeLimits,conversationId:this.currentConversationId,...e===void 0?{}:{runtime:e}})}runDefinition(e,t){let n=this.definition,r=this.combinedHooks(t),i=this.effectiveCatalog(),a=e.outputFormat??n.outputFormat,o={registry:this.options.registry,config:this.callConfig(e),history:this.history,...i===void 0?{}:{tools:i},...n.nativeTools.length===0?{}:{nativeTools:n.nativeTools},...n.toolChoice===void 0?{}:{toolChoice:n.toolChoice},...e.imagePolicy===void 0?{}:{imagePolicy:e.imagePolicy},...e.documentPolicy===void 0?{}:{documentPolicy:e.documentPolicy},...a===void 0?{}:{outputFormat:a},...e.validateOutput===void 0?{}:{validateOutput:e.validateOutput},system:this.systemInstructions(this.activeAdditionalInstructions),maxTurns:n.maxTurns,bounds:{maxToolCalls:n.maxToolCalls,...this.runtimeLimits.maxParallelToolCalls===void 0?{}:{maxParallel:this.runtimeLimits.maxParallelToolCalls},...this.runtimeLimits.maxConsecutiveToolErrors===void 0?{}:{maxConsecutiveToolErrors:this.runtimeLimits.maxConsecutiveToolErrors},...this.runtimeLimits.repeatToolWarningAt===void 0?{}:{repeatToolWarningAt:this.runtimeLimits.repeatToolWarningAt},...this.runtimeLimits.repeatToolLimit===void 0?{}:{repeatToolLimit:this.runtimeLimits.repeatToolLimit},...this.runtimeLimits.toolCycleWarningAt===void 0?{}:{toolCycleWarningAt:this.runtimeLimits.toolCycleWarningAt},...this.runtimeLimits.toolCycleLimit===void 0?{}:{toolCycleLimit:this.runtimeLimits.toolCycleLimit},...this.runtimeLimits.onExhausted===void 0?{}:{onExhausted:this.runtimeLimits.onExhausted},...this.runtimeLimits.maxToolResultTokens===void 0?{}:{maxToolResultTokens:this.runtimeLimits.maxToolResultTokens},...this.runtimeLimits.toolResultOverflow===void 0?{}:{toolResultOverflow:this.runtimeLimits.toolResultOverflow},...this.runtimeLimits.maxToolCycleLength===void 0?{}:{maxToolCycleLength:this.runtimeLimits.maxToolCycleLength},...this.runtimeLimits.finalReportReserveTokens===void 0?{}:{finalReportReserveTokens:this.runtimeLimits.finalReportReserveTokens},...this.runtimeLimits.maxTotalTokens===void 0?{}:{maxTotalTokens:this.runtimeLimits.maxTotalTokens},...this.runtimeLimits.maxToolResultBytes===void 0?{}:{maxToolResultBytes:this.runtimeLimits.maxToolResultBytes},...this.runtimeLimits.maxToolDurationMs===void 0?{}:{maxToolDurationMs:this.runtimeLimits.maxToolDurationMs},...this.runtimeLimits.toolTeardownTimeoutMs===void 0?{}:{toolTeardownTimeoutMs:this.runtimeLimits.toolTeardownTimeoutMs}},commentary:n.commentary,...this.runtimeLimits.teardownTimeoutMs===void 0?{}:{teardownTimeoutMs:this.runtimeLimits.teardownTimeoutMs},...this.runtimeLimits.modelTimeoutMs===void 0?{}:{modelTimeoutMs:this.runtimeLimits.modelTimeoutMs},...this.runtimeLimits.maxModelRequestBytes===void 0?{}:{maxModelRequestBytes:this.runtimeLimits.maxModelRequestBytes},...this.runtimeLimits.maxModelResponseBytes===void 0?{}:{maxModelResponseBytes:this.runtimeLimits.maxModelResponseBytes},...this.runtimeLimits.maxModelStreamEvents===void 0?{}:{maxModelStreamEvents:this.runtimeLimits.maxModelStreamEvents},...this.runtimeLimits.hookTimeoutMs===void 0?{}:{hookTimeoutMs:this.runtimeLimits.hookTimeoutMs},...this.runtimeLimits.hookTeardownTimeoutMs===void 0?{}:{hookTeardownTimeoutMs:this.runtimeLimits.hookTeardownTimeoutMs},...this.options.approvals===void 0?{}:{approvals:this.options.approvals},...this.options.spillStore===void 0?{}:{spillStore:this.options.spillStore},...this.options.experimentalPrograms===void 0?{}:{experimentalPrograms:this.options.experimentalPrograms},...this.options.interceptors===void 0?{}:{interceptors:this.options.interceptors},...this.contextSections===void 0?{}:{contextSections:this.contextSections},...r===void 0?{}:{hooks:r},...e.signal===void 0?{}:{signal:e.signal},...t===void 0?{}:{accounting:t},...t?.modelInvocation.logger===void 0?{}:{logger:t.modelInvocation.logger},trace:{...this.options.trace,conversationId:this.currentConversationId,agentId:n.id,agentName:n.name}};return n.mode===`deep-human-in-loop`?C({...o,mode:n.mode,userInput:this.options.userInput}):n.mode===`deep`?C({...o,mode:n.mode,...this.options.userInput===void 0?{}:{userInput:this.options.userInput}}):C({...o,mode:`basic`})}createCompactor(){let e=this.options.compaction===!1?!1:this.options.compaction===void 0?this.definition.compaction:c(this.options.compaction);if(e!==!1)return new s({registry:this.options.registry,config:()=>this.callConfig(this.activeInvocation),history:()=>this.currentHistory,system:()=>this.systemInstructions(this.activeAdditionalInstructions),pinnedMessages:()=>V(this.currentMemory,this.definition.memory.maxInjectedChars),tools:()=>[...this.effectiveCatalog()?.schemas()??[],...this.definition.nativeTools],policy:e})}effectiveCatalog(){return this.activeRuntimeCatalog??this.catalog}combinedHooks(e){let t=this.options.hooks;return{...t,beforeStep:async n=>{let r=this.currentHistory.generation(),i=this.currentHistory.entries().length;this.drainInjections();let s=this.currentHistory.entries().length===i?n:{...n,messages:a(this.currentHistory.messages()),snapshot:this.currentHistory.snapshot()};if(this.compactor!==void 0&&o(this.compactor,e),await this.compactor?.beforeStep(s),e?.usageStop!==void 0)return{kind:`proceed`};let c=this.currentHistory.generation()===r&&this.currentHistory.entries().length===i?n:{...n,messages:a(this.currentHistory.messages()),snapshot:this.currentHistory.snapshot()},l=V(this.currentMemory,this.definition.memory.maxInjectedChars,e),u=l.length===0?c:{...c,messages:Object.freeze([...l,...c.messages])},d=await t?.beforeStep?.(u)??{kind:`proceed`};if(d.kind===`reject`)return d;let f=[...d.messages===void 0?l:[],...d.prepend??[]];return b(f.length===0?d:{...d,prepend:f},c.messages)},onRequestError:async n=>{this.compactor!==void 0&&o(this.compactor,e);let r=await this.compactor?.onRequestError(n);return e?.usageStop===void 0?r===`retry`?`retry`:await t?.onRequestError?.(n)??`fail`:`fail`}}}callConfig(e){return J(this.definition,W(this),e)}systemInstructions(e){let t=this.skillCatalog===void 0?this.definition.instructions:f(this.definition.instructions,this.skillCatalog.summaries(),this.definition.skillOptions),n=this.options.team,r=n===void 0?t:`${t}\n\n${n.team.instructionsFor(n.name??this.definition.id)}`;return I(r,e)}skillLookup(e){return{...this.options.skillCwd===void 0?{}:{cwd:this.options.skillCwd},...e===void 0?{}:{signal:e}}}activationSnapshot(){let e=new Map;for(let t of this.pendingSkillActivations)e.set(t.id,t);for(let t of this.skillCatalog?.activatedSkillReferences()??[])e.set(t.id,t);for(let t of this.skillCatalog?.activatedSummaries()??[])e.has(t.id)||e.set(t.id,Object.freeze({id:t.id,provider:t.provider,source:t.source,...t.resourceBase===void 0?{}:{resourceBase:Object.freeze({...t.resourceBase})}}));return Object.freeze([...e.values()].sort((e,t)=>e.id.localeCompare(t.id)))}async prepareSkills(e,t){await F(this.definition,this.skillCatalog,this.pendingSkillActivations,e=>this.skillLookup(e),()=>{this.pendingSkillActivations=Object.freeze([])},e,t)}};export{Z as AgentSession,U as configureRuntimeSessionModel,G as streamRuntimeSession};
|
|
1
|
+
import{waitForSettlement as e}from"../../async/settlement.js";import{ModelError as t}from"../../errors/model-error.js";import{contentHasDocument as n,contentHasImage as r}from"../../message/projection.js";import{AgentMemory as i}from"../memory/memory.js";import{normalizeToolPairing as a}from"../history/normalize.js";import{bindCompactionAccounting as o}from"../memory/accounting-binding.js";import{ContextCompactor as s}from"../memory/compaction.js";import{resolveCompactionConfig as c}from"../memory/compaction-config.js";import{bindSkillProviderLogger as l}from"../skill/provider/context.js";import{SkillCatalog as u}from"../skill/catalog.js";import{createSkillTools as d,renderSkillCatalog as f}from"../skill/tools.js";import{createRunTerminalRecord as p,withTerminalDelivery as m}from"../accounting/delivery/terminal.js";import{captureContextSections as h}from"../context/section.js";import{History as g}from"../history/history.js";import{isManagedTeamNotice as _}from"../history/input-work.js";import{bindModelRequestBoundary as v,bindQueuedInput as y}from"../loop/turn/model-request-boundary.js";import{bindStepProjectionSources as b}from"../loop/turn/step-projection.js";import{AGENT_ACCOUNTING_ERROR_CODES as x,AgentRunError as S}from"../accounting/error.js";import{runAgent as C}from"../mode/run-agent.js";import{RunEventBuffer as w}from"../accounting/event-buffer.js";import{validateSessionSnapshot as T}from"./session/validation.js";import{resolveRuntimeLimits as E}from"./session/config.js";import{conversationId as D,deferred as O,errorCodeOf as k,messageOf as A,newConversationId as j,toolCatalog as M,userMessage as N}from"./session/common.js";import{captureResumedSkillActivations as P,prepareSkills as F}from"./session/skills.js";import{appendRunInstructions as I}from"./instructions.js";import{accountTraceEvent as L}from"./session/trace-accounting.js";import{captureResumedObjective as R,commitRuntimeMemory as z,loadRuntimeMemory as B,renderRuntimeMemory as V}from"./session/runtime-memory.js";import{attachRuntimeSession as H,configureRuntimeSessionModel as U,runtimeSessionConfiguration as W,streamRuntimeSession as G}from"./session/runtime-binding.js";import{createSessionLedger as K}from"./session/accounting.js";import{runRuntimeCompaction as q}from"./session/runtime-compaction.js";import{sessionCallConfig as J}from"./session/model-config.js";import{consumeSessionEvents as Y}from"./session/observer.js";import{sealRuntimeRun as X}from"./session/run-seal.js";var Z=class U{definition;options;catalog;activeRuntimeCatalog;skillCatalog;runtimeLimits;contextSections;currentHistory;currentMemory;currentConversationId;compactor;pendingSkillActivations=Object.freeze([]);active=!1;activeAdditionalInstructions;activeInvocation;idleWaiters=new Set;pendingInjections;lastRunOutcome;roundInFlight=!1;roundCalledTools=!1;constructor(e,t){if(e.mode===`deep-human-in-loop`&&t.userInput===void 0)throw TypeError(`agent '${e.id}' requires a userInput broker in deep-human-in-loop mode`);this.definition=e;let n=t.historyLimits===void 0?void 0:Object.freeze({...t.historyLimits});t.history!==void 0&&n!==void 0&&new g(n);let r=t.compaction===void 0||t.compaction===!1?t.compaction:Object.freeze({...t.compaction}),a=t.trace===void 0?void 0:Object.freeze({...t.trace}),o=t.team===void 0?void 0:Object.freeze({...t.team}),s=t.ledgerLimits===void 0?void 0:Object.freeze({...t.ledgerLimits}),c=t.eventBufferLimits===void 0?void 0:Object.freeze({...t.eventBufferLimits});this.options=Object.freeze({...t,...n===void 0?{}:{historyLimits:n},...r===void 0?{}:{compaction:r},...a===void 0?{}:{trace:a},...o===void 0?{}:{team:o},...s===void 0?{}:{ledgerLimits:s},...c===void 0?{}:{eventBufferLimits:c},...t.skills===void 0?{}:{skills:Object.freeze([...t.skills])},...Array.isArray(t.tools)?{tools:Object.freeze([...t.tools])}:{},...t.interceptors===void 0?{}:{interceptors:Object.freeze([...t.interceptors])}}),this.runtimeLimits=E(t.runtimeLimits);let l=h(t.contextSections)??[],f=h(e.contextSections)??[],p=[...f.map(e=>l.find(t=>t.id===e.id)??e),...l.filter(e=>!f.some(t=>t.id===e.id))];this.contextSections=p.length===0?void 0:Object.freeze(p),this.currentConversationId=D(t.conversationId),this.currentHistory=t.history??new g(n);let m=[...e.skills,...t.skills??[]],_=e.skillIds?.length===0,v=m.length>0||(e.skillIds?.length??0)>0;this.skillCatalog=_||!v?void 0:new u(m,{...e.skillIds===void 0?{}:{allowedSkillIds:e.skillIds},maxSkills:e.skillOptions.maxSkills,maxCatalogBytes:e.skillOptions.maxDiscoveryBytes});let y=this.skillCatalog===void 0?[]:d(this.skillCatalog,e.skillOptions,()=>this.skillLookup()),b=t.team?.tools===`reporting`?`reporting`:`full`,x=t.team?.tools===!1?[]:t.team?.team.toolsFor(t.team.name??e.id,b)??[];this.catalog=M(e.tools,t.tools,[...y,...x]),this.currentMemory=t.memory instanceof i?t.memory:t.memory===void 0?new i(e.memory.seed,e.memory):i.fromSnapshot(t.memory,e.memory),R(this.currentMemory,this.currentHistory,this.definition.memory.autoCaptureObjective),this.compactor=this.createCompactor(),H(this,(e,t,n)=>this.createRunHandle(e,t,n),e=>this.createRunHandle(void 0,e),e=>this.compactForRuntime(e),()=>{this.compactor=this.createCompactor()}),t.team?.team.attach(this,{...t.team.name===void 0?{}:{name:t.team.name},...t.team.description===void 0?{}:{description:t.team.description},...t.team.instructions===void 0?{}:{instructions:t.team.instructions},...t.team.role===void 0?{}:{role:t.team.role},...t.team.tools===void 0?{}:{tools:t.team.tools}})}static fromSnapshot(e,t){let{snapshot:n,...r}=t;T(n,e.id,e.skillOptions.maxSkills);let a=new U(e,{...r,conversationId:n.conversationId,history:g.fromSnapshot(n.history,r.historyLimits),memory:i.fromSnapshot(n.memory,e.memory)});return a.pendingSkillActivations=P(n.skills,a.skillCatalog),a}get conversationId(){return this.currentConversationId}get history(){return this.currentHistory}get memory(){return this.currentMemory}get skills(){return this.skillCatalog}get isRunning(){return this.active}snapshot(){let e=this.activationSnapshot(),t=this.currentHistory.snapshot(),n=this.pendingInjections?.entries()??[],r=n.length===0?t:Object.freeze({version:1,entries:Object.freeze([...t.entries,...n.map((e,n)=>Object.freeze({...e,seq:t.entries.length+n+1}))])});return Object.freeze({version:1,conversationId:this.currentConversationId,agentId:this.definition.id,history:r,memory:this.currentMemory.snapshot(),...W(this)?.memory===void 0?{}:{memoryBindingId:W(this).memory.bindingId},...e.length===0?{}:{skills:Object.freeze({activated:e})}})}reset(){if(this.active)throw Error(`cannot reset an agent session while a run is active`);this.currentConversationId=j(),this.currentHistory=new g(this.options.historyLimits),this.currentMemory=new i(this.definition.memory.seed,this.definition.memory),this.pendingInjections=void 0,this.pendingSkillActivations=Object.freeze([]),this.lastRunOutcome=void 0,this.skillCatalog?.clearActivations(),this.compactor=this.createCompactor()}async compact(e={}){if(this.active)throw Error(`cannot compact an agent session while a run is active`);this.active=!0,this.activeInvocation=e;try{return await this.prepareSkills(e.signal),await this.compactor?.compactNow(e.signal)??null}finally{this.releaseRun()}}async compactForRuntime(e){if(this.active)throw Error(`cannot compact an agent session while a run is active`);let t=this.createLedger();this.active=!0,this.activeInvocation=e,this.compactor!==void 0&&o(this.compactor,t),this.skillCatalog!==void 0&&l(this.skillCatalog,t.modelInvocation.logger);try{return await q({...this.compactor===void 0?{}:{compactor:this.compactor},invocation:e,accounting:t,prepare:()=>this.prepareSkills(e.signal,t)})}finally{this.releaseRun()}}inject(e){let t=N(e);if(this.active&&this.roundInFlight){g.fromSnapshot(this.currentHistory.snapshot(),this.options.historyLimits).appendBatch([...(this.pendingInjections?.entries()??[]).map(e=>({event:e.event})),{event:{kind:`user`,message:t}}]);let e=this.pendingInjections??=new g(this.options.historyLimits);return e.append({kind:`user`,message:t}),this.currentHistory.entries().length+e.entries().length}return this.drainInjections(),this.currentHistory.append({kind:`user`,message:t}),this.currentHistory.entries().length}observeRoundBoundary(e){if(e.type===`agent-end`&&(this.lastRunOutcome=e.outcome),e.type===`span-start`&&e.kind===`chat`){this.roundInFlight=!0,this.roundCalledTools=!1;return}this.roundInFlight&&((e.type===`tool-call`||e.type===`assistant-message`&&e.message?.content.some(e=>e.type===`tool-call`)===!0)&&(this.roundCalledTools=!0),(e.type===`step-end`&&this.roundCalledTools||e.type===`turn-end`||e.type===`agent-end`)&&(this.roundInFlight=!1,this.drainInjections()))}drainInjections(){if(this.pendingInjections===void 0)return;let e=this.pendingInjections;this.currentHistory.appendBatch(e.entries().map(e=>({event:e.event}))),this.pendingInjections=void 0}hasUnansweredInput(){if((this.pendingInjections?.entries().length??0)>0)return!0;for(let e of[...this.currentHistory.messages()].reverse()){if(e.source.kind===`app`){if(e.source.producer===`turn-interrupted`)return!1;if(e.role===`user`&&!_(e))continue}return e.role===`user`}return!1}lastOutcome(){return this.lastRunOutcome}whenIdle(e){return this.active?e?.aborted?Promise.reject(e.reason):new Promise((t,n)=>{let r=!1,i=()=>{r||(r=!0,this.idleWaiters.delete(i),e?.removeEventListener(`abort`,a),t())},a=()=>{r||(r=!0,this.idleWaiters.delete(i),n(e?.reason))};this.idleWaiters.add(i),e?.addEventListener(`abort`,a,{once:!0}),this.active||i()}):Promise.resolve()}stream(e,t={}){return this.createRunHandle(e,t)}streamPending(e={}){return this.createRunHandle(void 0,e)}async run(e,t={}){let n=this.stream(e,t);return await Y(n,t.onEvent,this.runtimeLimits.observerTimeoutMs??3e4),await n.result}async runPending(e={}){let t=this.streamPending(e);return await Y(t,e.onEvent,this.runtimeLimits.observerTimeoutMs??3e4),await t.result}createRunHandle(i,a,s){if(this.active)throw Error(`agent session '${this.definition.id}' is already running`);this.drainInjections();let c=this.currentHistory.entries().length+1,u=new AbortController,d=!1,f=a.signal===void 0?u.signal:AbortSignal.any([a.signal,u.signal]),h=new w(this.options.eventBufferLimits?.maxEvents,this.options.eventBufferLimits?.maxBytes),g=O(),b=O(),C=O(),T=this.createLedger(),E=Object.freeze([]);this.compactor!==void 0&&o(this.compactor,T),this.skillCatalog!==void 0&&l(this.skillCatalog,T.modelInvocation.logger),this.active=!0,v(this.currentHistory,e=>{this.roundInFlight=e,e||this.drainInjections()}),y(this.currentHistory,()=>{let e=this.pendingInjections?.entries()??[];return e.length===0||!e.some(e=>e.event.kind===`user`&&(e.event.message.source.kind===`user`||_(e.event.message)))?!1:(this.roundInFlight=!1,this.drainInjections(),!0)},()=>(this.pendingInjections?.entries()??[]).some(e=>e.event.kind===`user`&&(e.event.message.source.kind===`user`||_(e.event.message)))),this.activeAdditionalInstructions=s,this.activeInvocation=a;let D=new Map,j=(async()=>{let e,o,s;try{let e=W(this);if(e?.memory!==void 0){let t=await B(e.memory,this.currentConversationId,this.definition.memory,f,T);s=t.state,t.memory!==void 0&&(this.currentMemory=t.memory)}if(e?.prepareTools!==void 0){let t=T.modelInvocation.logger;if(t===void 0)throw Error(`runtime tool source logger is unavailable`);let n=e.prepareTools(f,t,[...this.catalog?.names()??[],...this.definition.nativeTools.map(e=>e.name)]);this.activeRuntimeCatalog=M([],this.catalog,n.tools),E=n.references}if(C.resolve(E),await this.prepareSkills(f,T),i!==void 0){let e=N(i);if(this.definition.memory.autoCaptureObjective){let t=T.startOperation(`memory`,{data:{action:`capture-objective`}});try{this.currentMemory.captureOriginalObjective(e),T.endOperation(t,`success`)}catch(e){throw T.endOperation(t,`error`,{error:e}),e}}this.currentHistory.append({kind:`user`,message:e})}if(a.imagePolicy===`strict`&&this.history.messages().some(e=>r(e.content))){let e=this.callConfig(a),n=await this.options.registry.resolveModelInfo(e.provider,e.model,f);if(n.inputModalities!==void 0&&!n.inputModalities.includes(`image`))throw new t(`model ${n.id} does not support required image input`,`UNSUPPORTED_IMAGE_INPUT`)}if(a.documentPolicy===`strict`&&this.history.messages().some(e=>n(e.content))){let e=this.callConfig(a),n=await this.options.registry.resolveModelInfo(e.provider,e.model,f);if(n.inputModalities!==void 0&&!n.inputModalities.includes(`document`))throw new t(`model ${n.id} does not support required document input`,`UNSUPPORTED_DOCUMENT_INPUT`)}for await(let e of this.runDefinition({...a,signal:f},T))this.observeRoundBoundary(e),L(T,D,e),e.type===`agent-end`&&(o=e.outcome),h.push(e);if(o===void 0)throw Error(`agent session '${this.definition.id}' ended without agent-end`);if(f.aborted)throw f.reason??Error(`agent run was aborted`);if(o.reason.kind===`error`&&o.reason.failure.code===`USAGE_REQUIRED`){let e=Error(o.reason.failure.message);throw e.code=`USAGE_REQUIRED`,e}e?.memory!==void 0&&s!==void 0&&s.status!==`disabled`&&await z(e.memory,this.currentConversationId,this.currentMemory.snapshot(),s,f,T)}catch(t){e=t,C.resolve(E)}try{this.drainInjections()}catch(t){e??=t}let l;try{let t=f.aborted||o?.reason.kind===`aborted`?`aborted`:e!==void 0||o?.reason.kind===`error`?`error`:`success`,n=await T.finalize(t,o?.completed??!1,e);l=m(p(n),n.delivery),g.resolve(l)}catch(e){g.reject(e),b.reject(e),h.fail(e),d=!0,this.releaseRun();return}if(!d){if(e===void 0&&T.terminalAuditFailure){let t=Error(`audit observation checkpoint failed after run finalization`);t.code=`OBSERVABILITY_AUDIT_UNAVAILABLE`,e=t}if(e!==void 0){let t=new S(A(e),k(e)??x.RUN_FAILED,l,{cause:e});b.reject(t),h.fail(t)}else{let e=o,t=[...this.currentHistory.entries()].reverse().find(e=>e.seq>=c&&e.event.kind===`assistant`)?.event,n=t?.kind===`assistant`?t.message:void 0,r=Object.freeze({text:e.text,outcome:e,report:l,...n===void 0?{}:{message:n}});b.resolve(r),h.close()}d=!0,this.releaseRun()}})();j.catch(e=>{d||(g.reject(e),b.reject(e),h.fail(e),d=!0,this.releaseRun())}),b.promise.catch(()=>void 0),g.promise.catch(()=>void 0);let P=!1;return Object.freeze({runId:T.runId,traceId:T.traceId,toolSourceSnapshots:C.promise,eventsSettled:j.then(()=>void 0,()=>void 0),result:b.promise,report:g.promise,seal:()=>X({ledger:T,buffer:h,report:g,result:b,toolSources:C,currentToolSources:()=>E,isTerminal:()=>d,markTerminal:()=>{d=!0},abort:()=>u.abort(Error(`Agent run was sealed`)),release:()=>this.releaseRun()}),abort(e){!d&&!u.signal.aborted&&u.abort(Error(`Agent run was aborted`))},[Symbol.asyncIterator](){return P?(async function*(){throw Error(`an agent run handle can only be iterated once`)})():(P=!0,(async function*(){let t=!1;try{for(;;){let e=await h.take();if(e.done){t=!0;break}yield e.value}}finally{t||(u.abort(Error(`agent event consumer stopped`)),h.stop(),await e(j,3e4))}})())}})}releaseRun(){try{this.drainInjections()}finally{v(this.currentHistory),y(this.currentHistory),this.roundInFlight=!1,this.active=!1,this.activeAdditionalInstructions=void 0,this.activeInvocation=void 0,this.activeRuntimeCatalog=void 0,this.skillCatalog!==void 0&&l(this.skillCatalog,void 0),this.compactor!==void 0&&o(this.compactor,void 0);let e=[...this.idleWaiters];this.idleWaiters.clear();for(let t of e)t()}}createLedger(){let e=W(this);return K({definition:this.definition,options:this.options,runtimeLimits:this.runtimeLimits,conversationId:this.currentConversationId,...e===void 0?{}:{runtime:e}})}runDefinition(e,t){let n=this.definition,r=this.combinedHooks(t),i=this.effectiveCatalog(),a=e.outputFormat??n.outputFormat,o={registry:this.options.registry,config:this.callConfig(e),history:this.history,...i===void 0?{}:{tools:i},...n.nativeTools.length===0?{}:{nativeTools:n.nativeTools},...n.toolChoice===void 0?{}:{toolChoice:n.toolChoice},...e.imagePolicy===void 0?{}:{imagePolicy:e.imagePolicy},...e.documentPolicy===void 0?{}:{documentPolicy:e.documentPolicy},...a===void 0?{}:{outputFormat:a},...e.validateOutput===void 0?{}:{validateOutput:e.validateOutput},system:this.systemInstructions(this.activeAdditionalInstructions),maxTurns:n.maxTurns,bounds:{maxToolCalls:n.maxToolCalls,...this.runtimeLimits.maxParallelToolCalls===void 0?{}:{maxParallel:this.runtimeLimits.maxParallelToolCalls},...this.runtimeLimits.maxConsecutiveToolErrors===void 0?{}:{maxConsecutiveToolErrors:this.runtimeLimits.maxConsecutiveToolErrors},...this.runtimeLimits.repeatToolWarningAt===void 0?{}:{repeatToolWarningAt:this.runtimeLimits.repeatToolWarningAt},...this.runtimeLimits.repeatToolLimit===void 0?{}:{repeatToolLimit:this.runtimeLimits.repeatToolLimit},...this.runtimeLimits.toolCycleWarningAt===void 0?{}:{toolCycleWarningAt:this.runtimeLimits.toolCycleWarningAt},...this.runtimeLimits.toolCycleLimit===void 0?{}:{toolCycleLimit:this.runtimeLimits.toolCycleLimit},...this.runtimeLimits.onExhausted===void 0?{}:{onExhausted:this.runtimeLimits.onExhausted},...this.runtimeLimits.maxToolResultTokens===void 0?{}:{maxToolResultTokens:this.runtimeLimits.maxToolResultTokens},...this.runtimeLimits.toolResultOverflow===void 0?{}:{toolResultOverflow:this.runtimeLimits.toolResultOverflow},...this.runtimeLimits.maxToolCycleLength===void 0?{}:{maxToolCycleLength:this.runtimeLimits.maxToolCycleLength},...this.runtimeLimits.finalReportReserveTokens===void 0?{}:{finalReportReserveTokens:this.runtimeLimits.finalReportReserveTokens},...this.runtimeLimits.finalizeSteps===void 0?{}:{finalizeSteps:this.runtimeLimits.finalizeSteps},...this.runtimeLimits.maxTurnDurationMs===void 0?{}:{maxTurnDurationMs:this.runtimeLimits.maxTurnDurationMs},...this.runtimeLimits.maxTotalTokens===void 0?{}:{maxTotalTokens:this.runtimeLimits.maxTotalTokens},...this.runtimeLimits.maxToolResultBytes===void 0?{}:{maxToolResultBytes:this.runtimeLimits.maxToolResultBytes},...this.runtimeLimits.maxToolDurationMs===void 0?{}:{maxToolDurationMs:this.runtimeLimits.maxToolDurationMs},...this.runtimeLimits.toolTeardownTimeoutMs===void 0?{}:{toolTeardownTimeoutMs:this.runtimeLimits.toolTeardownTimeoutMs}},commentary:n.commentary,...this.runtimeLimits.teardownTimeoutMs===void 0?{}:{teardownTimeoutMs:this.runtimeLimits.teardownTimeoutMs},...this.runtimeLimits.modelTimeoutMs===void 0?{}:{modelTimeoutMs:this.runtimeLimits.modelTimeoutMs},...this.runtimeLimits.maxModelRequestBytes===void 0?{}:{maxModelRequestBytes:this.runtimeLimits.maxModelRequestBytes},...this.runtimeLimits.maxModelResponseBytes===void 0?{}:{maxModelResponseBytes:this.runtimeLimits.maxModelResponseBytes},...this.runtimeLimits.maxModelStreamEvents===void 0?{}:{maxModelStreamEvents:this.runtimeLimits.maxModelStreamEvents},...this.runtimeLimits.hookTimeoutMs===void 0?{}:{hookTimeoutMs:this.runtimeLimits.hookTimeoutMs},...this.runtimeLimits.hookTeardownTimeoutMs===void 0?{}:{hookTeardownTimeoutMs:this.runtimeLimits.hookTeardownTimeoutMs},...this.options.approvals===void 0?{}:{approvals:this.options.approvals},...this.options.spillStore===void 0?{}:{spillStore:this.options.spillStore},...this.options.experimentalPrograms===void 0?{}:{experimentalPrograms:this.options.experimentalPrograms},...this.options.interceptors===void 0?{}:{interceptors:this.options.interceptors},...this.contextSections===void 0?{}:{contextSections:this.contextSections},...r===void 0?{}:{hooks:r},...e.signal===void 0?{}:{signal:e.signal},...t===void 0?{}:{accounting:t},...t?.modelInvocation.logger===void 0?{}:{logger:t.modelInvocation.logger},trace:{...this.options.trace,conversationId:this.currentConversationId,agentId:n.id,agentName:n.name}};return n.mode===`deep-human-in-loop`?C({...o,mode:n.mode,userInput:this.options.userInput,...this.runtimeLimits.userInputTimeoutMs===void 0?{}:{userInputTimeoutMs:this.runtimeLimits.userInputTimeoutMs}}):n.mode===`deep`?C({...o,mode:n.mode,...this.options.userInput===void 0?{}:{userInput:this.options.userInput},...this.runtimeLimits.userInputTimeoutMs===void 0?{}:{userInputTimeoutMs:this.runtimeLimits.userInputTimeoutMs}}):C({...o,mode:`basic`})}createCompactor(){let e=this.options.compaction===!1?!1:this.options.compaction===void 0?this.definition.compaction:c(this.options.compaction);if(e!==!1)return new s({registry:this.options.registry,config:()=>this.callConfig(this.activeInvocation),history:()=>this.currentHistory,system:()=>this.systemInstructions(this.activeAdditionalInstructions),pinnedMessages:()=>V(this.currentMemory,this.definition.memory.maxInjectedChars),tools:()=>[...this.effectiveCatalog()?.schemas()??[],...this.definition.nativeTools],policy:e})}effectiveCatalog(){return this.activeRuntimeCatalog??this.catalog}combinedHooks(e){let t=this.options.hooks;return{...t,beforeStep:async n=>{let r=this.currentHistory.generation(),i=this.currentHistory.entries().length;this.drainInjections();let s=this.currentHistory.entries().length===i?n:{...n,messages:a(this.currentHistory.messages()),snapshot:this.currentHistory.snapshot()};if(this.compactor!==void 0&&o(this.compactor,e),await this.compactor?.beforeStep(s),e?.usageStop!==void 0)return{kind:`proceed`};let c=this.currentHistory.generation()===r&&this.currentHistory.entries().length===i?n:{...n,messages:a(this.currentHistory.messages()),snapshot:this.currentHistory.snapshot()},l=V(this.currentMemory,this.definition.memory.maxInjectedChars,e),u=l.length===0?c:{...c,messages:Object.freeze([...l,...c.messages])},d=await t?.beforeStep?.(u)??{kind:`proceed`};if(d.kind===`reject`)return d;let f=[...d.messages===void 0?l:[],...d.prepend??[]];return b(f.length===0?d:{...d,prepend:f},c.messages)},onRequestError:async n=>{this.compactor!==void 0&&o(this.compactor,e);let r=await this.compactor?.onRequestError(n);return e?.usageStop===void 0?r===`retry`?`retry`:await t?.onRequestError?.(n)??`fail`:`fail`}}}callConfig(e){return J(this.definition,W(this),e)}systemInstructions(e){let t=this.skillCatalog===void 0?this.definition.instructions:f(this.definition.instructions,this.skillCatalog.summaries(),this.definition.skillOptions),n=this.options.team,r=n===void 0?t:`${t}\n\n${n.team.instructionsFor(n.name??this.definition.id)}`;return I(r,e)}skillLookup(e){return{...this.options.skillCwd===void 0?{}:{cwd:this.options.skillCwd},...e===void 0?{}:{signal:e}}}activationSnapshot(){let e=new Map;for(let t of this.pendingSkillActivations)e.set(t.id,t);for(let t of this.skillCatalog?.activatedSkillReferences()??[])e.set(t.id,t);for(let t of this.skillCatalog?.activatedSummaries()??[])e.has(t.id)||e.set(t.id,Object.freeze({id:t.id,provider:t.provider,source:t.source,...t.resourceBase===void 0?{}:{resourceBase:Object.freeze({...t.resourceBase})}}));return Object.freeze([...e.values()].sort((e,t)=>e.id.localeCompare(t.id)))}async prepareSkills(e,t){await F(this.definition,this.skillCatalog,this.pendingSkillActivations,e=>this.skillLookup(e),()=>{this.pendingSkillActivations=Object.freeze([])},e,t)}};export{Z as AgentSession,U as configureRuntimeSessionModel,G as streamRuntimeSession};
|
|
2
2
|
//# sourceMappingURL=session.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"session.js","names":[],"sources":["../../../src/agent/define/session.ts"],"sourcesContent":["import { contentHasDocument, contentHasImage } from '../../message/projection.ts'\nimport { ModelError } from '../../errors/model-error.ts'\nimport { type ToolCatalog } from '../tool/registry.ts'\nimport { History } from '../history/history.ts'\nimport { isManagedTeamNotice } from '../history/input-work.ts'\nimport { bindModelRequestBoundary, bindQueuedInput } from '../loop/turn/model-request-boundary.ts'\nimport { bindStepProjectionSources } from '../loop/turn/step-projection.ts'\nimport { normalizeToolPairing } from '../history/normalize.ts'\nimport type { TurnHooks } from '../loop/types.ts'\nimport { ContextCompactor, type CompactionResult } from '../memory/compaction.ts'\nimport { bindCompactionAccounting } from '../memory/accounting-binding.ts'\nimport { resolveCompactionConfig } from '../memory/compaction-config.ts'\nimport { AgentMemory } from '../memory/memory.ts'\nimport { captureContextSections } from '../context/section.ts'\nimport type { ContextSection } from '../context/types.ts'\nimport { runAgent, type AgentRunEvent, type AgentRunOutcome } from '../mode/run-agent.ts'\nimport type { UserInputBroker } from '../mode/user-input.ts'\nimport { waitForSettlement } from '../../async/index.ts'\nimport type { OperationStatus } from '../../observation/index.ts'\nimport { RunEventBuffer } from '../accounting/event-buffer.ts'\nimport { AgentRunError, AGENT_ACCOUNTING_ERROR_CODES } from '../accounting/error.ts'\nimport type { RunAccountingPort } from '../accounting/contracts.ts'\nimport type { LegacyRunReport } from '../accounting/report.ts'\nimport type { RunReport } from '../accounting/delivery-types.ts'\nimport { createRunTerminalRecord, withTerminalDelivery } from '../accounting/delivery/terminal.ts'\nimport { SkillCatalog, createSkillTools, renderSkillCatalog, type SkillLookupOptions } from '../skill/index.ts'\nimport type { AgentDefinition } from './definition.ts'\nimport {\n type AgentInput, type AgentRuntimeLimits, type AgentSessionOptions, type AgentSessionSnapshot,\n type AgentSessionActivatedSkillSnapshot, type AgentResumeSessionOptions,\n type AgentInvocationOptions, type AgentResponse, type AgentRunHandle,\n} from './session/types.ts'\nimport { validateSessionSnapshot } from './session/validation.ts'\nimport { resolveRuntimeLimits } from './session/config.ts'\nimport {\n conversationId, newConversationId, userMessage, deferred, messageOf, errorCodeOf,\n toolCatalog,\n} from './session/common.ts'\nimport { captureResumedSkillActivations, prepareSkills } from './session/skills.ts'\nimport { appendRunInstructions } from './instructions.ts'\nimport type { ToolSourceRunReference } from '../tool/source-types.ts'\nimport { accountTraceEvent } from './session/trace-accounting.ts'\nimport {\n captureResumedObjective, commitRuntimeMemory, loadRuntimeMemory, renderRuntimeMemory,\n} from './session/runtime-memory.ts'\nimport { attachRuntimeSession, runtimeSessionConfiguration } from './session/runtime-binding.ts'\nimport { bindSkillProviderLogger } from '../skill/provider/context.ts'\nimport { createSessionLedger } from './session/accounting.ts'\nimport { runRuntimeCompaction } from './session/runtime-compaction.ts'\nimport { sessionCallConfig } from './session/model-config.ts'\nimport { consumeSessionEvents } from './session/observer.ts'\nimport { sealRuntimeRun } from './session/run-seal.ts'\n\nexport class AgentSession {\n readonly definition: AgentDefinition\n private readonly options: AgentSessionOptions\n private readonly catalog: ToolCatalog | undefined\n private activeRuntimeCatalog: ToolCatalog | undefined\n private readonly skillCatalog: SkillCatalog | undefined\n private readonly runtimeLimits: Readonly<AgentRuntimeLimits>\n /** Definition sections first, then session sections; duplicate ids are rejected. */\n private readonly contextSections: readonly ContextSection[] | undefined\n private currentHistory: History\n private currentMemory: AgentMemory\n private currentConversationId: string\n private compactor: ContextCompactor | undefined\n private pendingSkillActivations: readonly AgentSessionActivatedSkillSnapshot[] = Object.freeze([])\n private active = false\n private activeAdditionalInstructions: string | undefined\n /** The overlay of the run that owns the session, so maintenance follows the same model. */\n private activeInvocation: AgentInvocationOptions | undefined\n private readonly idleWaiters = new Set<() => void>()\n /**\n * Messages injected while a run is in flight, waiting for the next model\n * request. Appending them at once put them AHEAD of the assistant output of\n * the round already streaming, a round that never saw them; the next round\n * then read \"steer, then the work that ignored it\" as work that answered it.\n */\n private pendingInjections: History | undefined\n private lastRunOutcome: AgentRunOutcome | undefined\n /**\n * A model request has been built and its output is not yet fully recorded.\n * Only then is an injection held: hooks and team notices that inject between\n * rounds still append at once, as they always have.\n */\n private roundInFlight = false\n /** The round in flight called a tool, so its output ends at step-end. */\n private roundCalledTools = false\n\n constructor(definition: AgentDefinition, options: AgentSessionOptions) {\n if (definition.mode === 'deep-human-in-loop' && options.userInput === undefined) {\n throw new TypeError(`agent '${definition.id}' requires a userInput broker in deep-human-in-loop mode`)\n }\n this.definition = definition\n const historyLimits = options.historyLimits === undefined\n ? undefined\n : Object.freeze({ ...options.historyLimits })\n // Validate reset-time policy even when the initial History was supplied by\n // the host, and detach mutable option containers from the caller.\n if (options.history !== undefined && historyLimits !== undefined) void new History(historyLimits)\n const compaction = options.compaction === undefined || options.compaction === false\n ? options.compaction\n : Object.freeze({ ...options.compaction })\n const trace = options.trace === undefined ? undefined : Object.freeze({ ...options.trace })\n const team = options.team === undefined ? undefined : Object.freeze({ ...options.team })\n const ledgerLimits = options.ledgerLimits === undefined ? undefined : Object.freeze({ ...options.ledgerLimits })\n const eventBufferLimits = options.eventBufferLimits === undefined\n ? undefined\n : Object.freeze({ ...options.eventBufferLimits })\n this.options = Object.freeze({\n ...options,\n ...(historyLimits === undefined ? {} : { historyLimits }),\n ...(compaction === undefined ? {} : { compaction }),\n ...(trace === undefined ? {} : { trace }),\n ...(team === undefined ? {} : { team }),\n ...(ledgerLimits === undefined ? {} : { ledgerLimits }),\n ...(eventBufferLimits === undefined ? {} : { eventBufferLimits }),\n ...(options.skills === undefined ? {} : { skills: Object.freeze([...options.skills]) }),\n ...(Array.isArray(options.tools) ? { tools: Object.freeze([...options.tools]) } : {}),\n ...(options.interceptors === undefined ? {} : { interceptors: Object.freeze([...options.interceptors]) }),\n })\n this.runtimeLimits = resolveRuntimeLimits(options.runtimeLimits)\n // A session may replace a definition section by reusing its id: the\n // definition describes the agent, the session describes where it is\n // running, and the more specific one wins in place. Two sections with one\n // id inside the *same* list stays an error — a single live surface node\n // cannot have two owners.\n const overrides = captureContextSections(options.contextSections) ?? []\n const base = captureContextSections(definition.contextSections) ?? []\n const merged = [\n ...base.map(section => overrides.find(override => override.id === section.id) ?? section),\n ...overrides.filter(override => !base.some(section => section.id === override.id)),\n ]\n this.contextSections = merged.length === 0 ? undefined : Object.freeze(merged)\n this.currentConversationId = conversationId(options.conversationId)\n this.currentHistory = options.history ?? new History(historyLimits)\n const skillSources = [...definition.skills, ...options.skills ?? []]\n const skillRuntimeDisabled = definition.skillIds?.length === 0\n const skillRuntimeConfigured = skillSources.length > 0 || (definition.skillIds?.length ?? 0) > 0\n this.skillCatalog = skillRuntimeDisabled || !skillRuntimeConfigured\n ? undefined\n : new SkillCatalog(skillSources, {\n ...(definition.skillIds === undefined ? {} : { allowedSkillIds: definition.skillIds }),\n maxSkills: definition.skillOptions.maxSkills,\n maxCatalogBytes: definition.skillOptions.maxDiscoveryBytes,\n })\n const skillTools = this.skillCatalog === undefined ? [] : createSkillTools(\n this.skillCatalog,\n definition.skillOptions,\n () => this.skillLookup(),\n )\n const teamAccess = options.team?.tools === 'reporting' ? 'reporting' as const : 'full' as const\n const teamTools = options.team?.tools === false\n ? []\n : options.team?.team.toolsFor(options.team.name ?? definition.id, teamAccess) ?? []\n this.catalog = toolCatalog(definition.tools, options.tools, [...skillTools, ...teamTools])\n this.currentMemory = options.memory instanceof AgentMemory\n ? options.memory\n : options.memory === undefined\n ? new AgentMemory(definition.memory.seed, definition.memory)\n : AgentMemory.fromSnapshot(options.memory, definition.memory)\n captureResumedObjective(this.currentMemory, this.currentHistory, this.definition.memory.autoCaptureObjective)\n this.compactor = this.createCompactor()\n attachRuntimeSession(this, (input, invocation, additionalInstructions) =>\n this.createRunHandle(input, invocation, additionalInstructions), invocation =>\n this.createRunHandle(undefined, invocation), invocation =>\n this.compactForRuntime(invocation), () => {\n this.compactor = this.createCompactor()\n })\n options.team?.team.attach(this, {\n ...(options.team.name === undefined ? {} : { name: options.team.name }),\n ...(options.team.description === undefined ? {} : { description: options.team.description }),\n ...(options.team.instructions === undefined ? {} : { instructions: options.team.instructions }),\n ...(options.team.role === undefined ? {} : { role: options.team.role }),\n ...(options.team.tools === undefined ? {} : { tools: options.team.tools }),\n })\n }\n\n /** Restore a JSON-round-tripped session snapshot with fresh runtime dependencies. */\n static fromSnapshot(\n definition: AgentDefinition,\n options: AgentResumeSessionOptions,\n ): AgentSession {\n const { snapshot, ...runtime } = options\n validateSessionSnapshot(snapshot, definition.id, definition.skillOptions.maxSkills)\n const session = new AgentSession(definition, {\n ...runtime,\n conversationId: snapshot.conversationId,\n history: History.fromSnapshot(snapshot.history, runtime.historyLimits),\n memory: AgentMemory.fromSnapshot(snapshot.memory, definition.memory),\n })\n session.pendingSkillActivations = captureResumedSkillActivations(snapshot.skills, session.skillCatalog)\n return session\n }\n\n /** Stable identity for persistence keys, URLs, logs, and GUI trace grouping. */\n get conversationId(): string { return this.currentConversationId }\n\n /** Mutable append-only history owned by this conversation. */\n get history(): History { return this.currentHistory }\n\n /** Durable task facts injected into every request outside compactable history. */\n get memory(): AgentMemory { return this.currentMemory }\n\n /** Refreshable skill catalog for host UIs and explicit user invocation surfaces. */\n get skills(): SkillCatalog | undefined { return this.skillCatalog }\n\n /** Whether a model/tool turn currently owns this session. */\n get isRunning(): boolean { return this.active }\n\n /** Capture one JSON-safe envelope that can be passed to `agent.resumeSession()`. */\n snapshot(): AgentSessionSnapshot {\n const activated = this.activationSnapshot()\n const history = this.currentHistory.snapshot()\n const pending = this.pendingInjections?.entries() ?? []\n // An accepted input must survive a snapshot taken before its model round\n // finishes. Project pending inputs at the known tail without delivering\n // them early to the live model or changing the persisted v1 schema.\n const persistedHistory = pending.length === 0 ? history : Object.freeze({\n version: 1 as const,\n entries: Object.freeze([...history.entries, ...pending.map((entry, index) => Object.freeze({\n ...entry, seq: history.entries.length + index + 1,\n }))]),\n })\n return Object.freeze({\n version: 1 as const,\n conversationId: this.currentConversationId,\n agentId: this.definition.id,\n history: persistedHistory,\n memory: this.currentMemory.snapshot(),\n ...runtimeSessionConfiguration(this)?.memory === undefined ? {} : {\n memoryBindingId: runtimeSessionConfiguration(this)!.memory!.bindingId,\n },\n ...activated.length === 0 ? {} : {\n skills: Object.freeze({ activated }),\n },\n })\n }\n\n /** Start a fresh conversation without rebuilding provider/tool configuration. */\n reset(): void {\n if (this.active) throw new Error('cannot reset an agent session while a run is active')\n this.currentConversationId = newConversationId()\n this.currentHistory = new History(this.options.historyLimits)\n this.currentMemory = new AgentMemory(this.definition.memory.seed, this.definition.memory)\n this.pendingInjections = undefined\n this.pendingSkillActivations = Object.freeze([])\n this.lastRunOutcome = undefined\n this.skillCatalog?.clearActivations()\n this.compactor = this.createCompactor()\n }\n\n /** Create one explicit context checkpoint while the session is idle. */\n async compact(invocation: AgentInvocationOptions = {}): Promise<CompactionResult | null> {\n if (this.active) throw new Error('cannot compact an agent session while a run is active')\n this.active = true\n this.activeInvocation = invocation\n try {\n await this.prepareSkills(invocation.signal)\n return await this.compactor?.compactNow(invocation.signal) ?? null\n } finally {\n this.releaseRun()\n }\n }\n\n private async compactForRuntime(invocation: AgentInvocationOptions): Promise<{\n readonly result: CompactionResult | null\n readonly report: LegacyRunReport\n readonly failure?: unknown\n }> {\n if (this.active) throw new Error('cannot compact an agent session while a run is active')\n const ledger = this.createLedger()\n this.active = true\n this.activeInvocation = invocation\n if (this.compactor !== undefined) bindCompactionAccounting(this.compactor, ledger)\n if (this.skillCatalog !== undefined) bindSkillProviderLogger(this.skillCatalog, ledger.modelInvocation.logger)\n try { return await runRuntimeCompaction({\n ...(this.compactor === undefined ? {} : { compactor: this.compactor }),\n invocation,\n accounting: ledger,\n prepare: () => this.prepareSkills(invocation.signal, ledger),\n }) } finally { this.releaseRun() }\n }\n\n /**\n * Append attributed context without starting a turn.\n *\n * A2A quiet delivery uses this primitive. The returned count includes queued\n * inputs and lets wake-up schedulers coalesce messages safely; a mid-round\n * receipt is provisional rather than the eventual persisted entry sequence.\n */\n inject(input: AgentInput): number {\n const message = userMessage(input)\n // Mid-run, hold the message until the next model request is built, so it\n // lands after every entry the model has actually answered. Bound pending\n // inputs with the same guards as history instead of an unbounded array.\n if (this.active && this.roundInFlight) {\n // Reject over-capacity input at admission, before it can poison the\n // queued buffer used by every later run and snapshot.\n const candidate = History.fromSnapshot(this.currentHistory.snapshot(), this.options.historyLimits)\n candidate.appendBatch([\n ...(this.pendingInjections?.entries() ?? []).map(entry => ({ event: entry.event })),\n { event: { kind: 'user' as const, message } },\n ])\n const pending = this.pendingInjections ??= new History(this.options.historyLimits)\n pending.append({ kind: 'user', message })\n return this.currentHistory.entries().length + pending.entries().length\n }\n this.drainInjections()\n this.currentHistory.append({ kind: 'user', message })\n return this.currentHistory.entries().length\n }\n\n /**\n * Close the in-flight window once a round's output is fully recorded: after\n * its tool results (`step-end`), or when the turn ends. The loop waits on\n * this consumer, so held messages land exactly there, never between a tool\n * call and its result.\n *\n * A round that answers without calling a tool ends the turn, and input the\n * person sent while it was being written is still owed an answer. It stays\n * held until the loop is about to end the turn; the loop then takes it (see\n * `bindQueuedInput`) and answers it in another round of the same run instead\n * of leaving it for a later `runPending()`.\n */\n private observeRoundBoundary(event: AgentRunEvent): void {\n if (event.type === 'agent-end') this.lastRunOutcome = event.outcome\n // The chat request is now fixed. beforeStep hooks still run outside this\n // window, so their injections can be included in that request's refresh.\n if (event.type === 'span-start' && event.kind === 'chat') {\n this.roundInFlight = true\n this.roundCalledTools = false\n return\n }\n if (!this.roundInFlight) return\n if (event.type === 'tool-call' || (event.type === 'assistant-message'\n && event.message?.content.some(block => block.type === 'tool-call') === true)) {\n this.roundCalledTools = true\n }\n // A tool round's output is complete at step-end; a final answer's input\n // waits for the loop to take it at turn end, unless the turn is already over.\n if ((event.type === 'step-end' && this.roundCalledTools) || event.type === 'turn-end' || event.type === 'agent-end') {\n this.roundInFlight = false\n this.drainInjections()\n }\n }\n\n /** Deliver held injections, in arrival order, at the chronological tail. */\n private drainInjections(): void {\n if (this.pendingInjections === undefined) return\n const pending = this.pendingInjections\n // Atomic: a full history must not consume only the first queued input and\n // silently lose the rest. Keep the buffer available to snapshot/recovery.\n this.currentHistory.appendBatch(pending.entries().map(entry => ({ event: entry.event })))\n this.pendingInjections = undefined\n }\n\n /**\n * Whether attributed input or a tool result still awaits the model. App\n * notices do not create work, except managed-team coordination. False once the model has answered everything,\n * which lets a scheduler skip a run that would only repeat that answer.\n */\n hasUnansweredInput(): boolean {\n if ((this.pendingInjections?.entries().length ?? 0) > 0) return true\n for (const message of [...this.currentHistory.messages()].reverse()) {\n if (message.source.kind === 'app') {\n if (message.source.producer === 'turn-interrupted') return false\n if (message.role === 'user' && !isManagedTeamNotice(message)) continue\n }\n return message.role === 'user'\n }\n return false\n }\n\n lastOutcome(): AgentRunOutcome | undefined { return this.lastRunOutcome }\n\n /** Resolve after the current run releases the session. */\n whenIdle(signal?: AbortSignal): Promise<void> {\n if (!this.active) return Promise.resolve()\n if (signal?.aborted) return Promise.reject(signal.reason)\n return new Promise<void>((resolve, reject) => {\n let settled = false\n const finish = (): void => {\n if (settled) return\n settled = true\n this.idleWaiters.delete(finish)\n signal?.removeEventListener('abort', abort)\n resolve()\n }\n const abort = (): void => {\n if (settled) return\n settled = true\n this.idleWaiters.delete(finish)\n reject(signal?.reason)\n }\n this.idleWaiters.add(finish)\n signal?.addEventListener('abort', abort, { once: true })\n if (!this.active) finish()\n })\n }\n\n /** Start an eager run and expose both public events and its canonical terminal report. */\n stream(input: AgentInput, invocation: AgentInvocationOptions = {}): AgentRunHandle {\n return this.createRunHandle(input, invocation)\n }\n\n /** Process context already appended with {@link inject} without duplicating it. */\n streamPending(invocation: AgentInvocationOptions = {}): AgentRunHandle {\n return this.createRunHandle(undefined, invocation)\n }\n\n /** Run one user turn and return the terminal response. */\n async run(input: AgentInput, invocation: AgentInvocationOptions = {}): Promise<AgentResponse> {\n const handle = this.stream(input, invocation)\n await consumeSessionEvents(handle, invocation.onEvent, this.runtimeLimits.observerTimeoutMs ?? 30_000)\n return await handle.result\n }\n\n /** Run one turn over already-injected context and return its terminal response. */\n async runPending(invocation: AgentInvocationOptions = {}): Promise<AgentResponse> {\n const handle = this.streamPending(invocation)\n await consumeSessionEvents(handle, invocation.onEvent, this.runtimeLimits.observerTimeoutMs ?? 30_000)\n return await handle.result\n }\n\n private createRunHandle(\n input: AgentInput | undefined,\n invocation: AgentInvocationOptions,\n additionalInstructions?: string,\n ): AgentRunHandle {\n if (this.active) throw new Error(`agent session '${this.definition.id}' is already running`)\n this.drainInjections()\n const firstTurnSeq = this.currentHistory.entries().length + 1\n const owned = new AbortController()\n let terminal = false\n const signal = invocation.signal === undefined\n ? owned.signal\n : AbortSignal.any([invocation.signal, owned.signal])\n const buffer = new RunEventBuffer<AgentRunEvent>(\n this.options.eventBufferLimits?.maxEvents,\n this.options.eventBufferLimits?.maxBytes,\n )\n const reportDeferred = deferred<RunReport>()\n const resultDeferred = deferred<AgentResponse>()\n const toolSourcesDeferred = deferred<readonly ToolSourceRunReference[]>()\n const ledger = this.createLedger()\n let toolSourceReferences: readonly ToolSourceRunReference[] = Object.freeze([])\n if (this.compactor !== undefined) bindCompactionAccounting(this.compactor, ledger)\n if (this.skillCatalog !== undefined) {\n bindSkillProviderLogger(this.skillCatalog, ledger.modelInvocation.logger)\n }\n this.active = true\n bindModelRequestBoundary(this.currentHistory, inFlight => {\n this.roundInFlight = inFlight\n if (!inFlight) this.drainInjections()\n })\n bindQueuedInput(this.currentHistory, () => {\n // By entries, not by the buffer: an input refused at admission leaves an\n // empty buffer behind, and that must not buy the run another round.\n const held = this.pendingInjections?.entries() ?? []\n if (held.length === 0) return false\n // Person input and managed-team coordination extend the run. Team deliveries keep\n // their contract: queued behind the answer, then processed exactly once\n // by the team's wake-up through runPending().\n const extendsRun = held.some(entry => entry.event.kind === 'user'\n && (entry.event.message.source.kind === 'user' || isManagedTeamNotice(entry.event.message)))\n if (!extendsRun) return false\n this.roundInFlight = false\n this.drainInjections()\n return true\n })\n this.activeAdditionalInstructions = additionalInstructions\n this.activeInvocation = invocation\n const spanOperations = new Map<string, string>()\n const task = (async (): Promise<void> => {\n let failure: unknown\n let outcome: AgentRunOutcome | undefined\n let memoryState: Awaited<ReturnType<typeof loadRuntimeMemory>>['state'] | undefined\n try {\n const runtime = runtimeSessionConfiguration(this)\n if (runtime?.memory !== undefined) {\n const prepared = await loadRuntimeMemory(\n runtime.memory, this.currentConversationId, this.definition.memory, signal, ledger,\n )\n memoryState = prepared.state\n if (prepared.memory !== undefined) this.currentMemory = prepared.memory\n }\n if (runtime?.prepareTools !== undefined) {\n const logger = ledger.modelInvocation.logger\n if (logger === undefined) throw new Error('runtime tool source logger is unavailable')\n const generation = runtime.prepareTools(signal, logger, [...this.catalog?.names() ?? [], ...this.definition.nativeTools.map(tool => tool.name)])\n this.activeRuntimeCatalog = toolCatalog([], this.catalog, generation.tools)\n toolSourceReferences = generation.references\n }\n toolSourcesDeferred.resolve(toolSourceReferences)\n await this.prepareSkills(signal, ledger)\n if (input !== undefined) {\n const message = userMessage(input)\n if (this.definition.memory.autoCaptureObjective) {\n const operation = ledger.startOperation('memory', { data: { action: 'capture-objective' } })\n try {\n this.currentMemory.captureOriginalObjective(message)\n ledger.endOperation(operation, 'success')\n } catch (error) {\n ledger.endOperation(operation, 'error', { error })\n throw error\n }\n }\n this.currentHistory.append({ kind: 'user', message })\n }\n // Preflight before compaction can turn a required image into a summary.\n if (invocation.imagePolicy === 'strict' && this.history.messages().some(message => contentHasImage(message.content))) {\n const config = this.callConfig(invocation)\n const model = await this.options.registry.resolveModelInfo(config.provider, config.model, signal)\n if (model.inputModalities !== undefined && !model.inputModalities.includes('image')) {\n throw new ModelError(`model ${model.id} does not support required image input`, 'UNSUPPORTED_IMAGE_INPUT')\n }\n }\n // Same preflight for documents, for the same reason.\n if (invocation.documentPolicy === 'strict' && this.history.messages().some(message => contentHasDocument(message.content))) {\n const config = this.callConfig(invocation)\n const model = await this.options.registry.resolveModelInfo(config.provider, config.model, signal)\n if (model.inputModalities !== undefined && !model.inputModalities.includes('document')) {\n throw new ModelError(`model ${model.id} does not support required document input`, 'UNSUPPORTED_DOCUMENT_INPUT')\n }\n }\n for await (const event of this.runDefinition({ ...invocation, signal }, ledger)) {\n this.observeRoundBoundary(event)\n accountTraceEvent(ledger, spanOperations, event)\n if (event.type === 'agent-end') outcome = event.outcome\n buffer.push(event)\n }\n if (outcome === undefined) {\n throw new Error(`agent session '${this.definition.id}' ended without agent-end`)\n }\n if (signal.aborted) throw signal.reason ?? new Error('agent run was aborted')\n if (outcome.reason.kind === 'error' && outcome.reason.failure.code === 'USAGE_REQUIRED') {\n const error = new Error(outcome.reason.failure.message) as Error & { code: string }\n error.code = 'USAGE_REQUIRED'\n throw error\n }\n if (runtime?.memory !== undefined && memoryState !== undefined && memoryState.status !== 'disabled') {\n await commitRuntimeMemory(\n runtime.memory, this.currentConversationId, this.currentMemory.snapshot(),\n memoryState, signal, ledger,\n )\n }\n } catch (error: unknown) {\n failure = error\n toolSourcesDeferred.resolve(toolSourceReferences)\n }\n\n try { this.drainInjections() } catch (error) { failure ??= error }\n\n let report: RunReport\n try {\n const status: OperationStatus = signal.aborted || outcome?.reason.kind === 'aborted'\n ? 'aborted'\n : failure !== undefined || outcome?.reason.kind === 'error'\n ? 'error'\n : 'success'\n const ledgerReport = await ledger.finalize(status, outcome?.completed ?? false, failure)\n report = withTerminalDelivery(createRunTerminalRecord(ledgerReport), ledgerReport.delivery)\n reportDeferred.resolve(report)\n } catch (finalizeError: unknown) {\n reportDeferred.reject(finalizeError)\n resultDeferred.reject(finalizeError)\n buffer.fail(finalizeError)\n terminal = true\n this.releaseRun()\n return\n }\n if (terminal) return\n\n if (failure === undefined && ledger.terminalAuditFailure) {\n const error = new Error('audit observation checkpoint failed after run finalization') as Error & { code: string }\n error.code = 'OBSERVABILITY_AUDIT_UNAVAILABLE'\n failure = error\n }\n if (failure !== undefined) {\n const error = new AgentRunError(\n messageOf(failure),\n errorCodeOf(failure) ?? AGENT_ACCOUNTING_ERROR_CODES.RUN_FAILED,\n report,\n { cause: failure },\n )\n resultDeferred.reject(error)\n buffer.fail(error)\n } else {\n const terminal = outcome as AgentRunOutcome\n const historyEvent = [...this.currentHistory.entries()].reverse()\n .find(entry => entry.seq >= firstTurnSeq && entry.event.kind === 'assistant')\n ?.event\n const assistantMessage = historyEvent?.kind === 'assistant' ? historyEvent.message : undefined\n const response: AgentResponse = Object.freeze({\n text: terminal.text,\n outcome: terminal,\n report,\n ...assistantMessage === undefined ? {} : { message: assistantMessage },\n })\n resultDeferred.resolve(response)\n buffer.close()\n }\n terminal = true\n this.releaseRun()\n })()\n void task.catch(error => {\n if (terminal) return\n reportDeferred.reject(error)\n resultDeferred.reject(error)\n buffer.fail(error)\n terminal = true\n this.releaseRun()\n })\n void resultDeferred.promise.catch(() => undefined)\n void reportDeferred.promise.catch(() => undefined)\n let iterated = false\n return Object.freeze({\n runId: ledger.runId,\n traceId: ledger.traceId,\n toolSourceSnapshots: toolSourcesDeferred.promise,\n eventsSettled: task.then(() => undefined, () => undefined),\n result: resultDeferred.promise,\n report: reportDeferred.promise,\n seal: () => sealRuntimeRun({ ledger, buffer, report: reportDeferred, result: resultDeferred,\n toolSources: toolSourcesDeferred, currentToolSources: () => toolSourceReferences, isTerminal: () => terminal,\n markTerminal: () => { terminal = true }, abort: () => owned.abort(new Error('Agent run was sealed')),\n release: () => this.releaseRun() }),\n abort(_reason?: unknown): void {\n if (!terminal && !owned.signal.aborted) owned.abort(new Error('Agent run was aborted'))\n },\n [Symbol.asyncIterator](): AsyncIterator<AgentRunEvent> {\n if (iterated) return (async function* () { throw new Error('an agent run handle can only be iterated once') })()\n iterated = true\n return (async function* () {\n let exhausted = false\n try {\n while (true) {\n const item = await buffer.take()\n if (item.done) { exhausted = true; break }\n yield item.value\n }\n } finally {\n if (!exhausted) {\n owned.abort(new Error('agent event consumer stopped'))\n buffer.stop()\n await waitForSettlement(task, 30_000)\n }\n }\n })()\n },\n })\n }\n\n private releaseRun(): void {\n // A message that arrived during the final model round is still delivered,\n // so the next run (or a waiting scheduler) reads it.\n try { this.drainInjections() } finally {\n bindModelRequestBoundary(this.currentHistory)\n bindQueuedInput(this.currentHistory)\n this.roundInFlight = false\n this.active = false\n this.activeAdditionalInstructions = undefined\n this.activeInvocation = undefined\n this.activeRuntimeCatalog = undefined\n if (this.skillCatalog !== undefined) bindSkillProviderLogger(this.skillCatalog, undefined)\n if (this.compactor !== undefined) bindCompactionAccounting(this.compactor, undefined)\n const waiters = [...this.idleWaiters]\n this.idleWaiters.clear()\n for (const resolve of waiters) resolve()\n }\n }\n\n private createLedger() {\n const runtime = runtimeSessionConfiguration(this)\n return createSessionLedger({\n definition: this.definition,\n options: this.options,\n runtimeLimits: this.runtimeLimits,\n conversationId: this.currentConversationId,\n ...(runtime === undefined ? {} : { runtime }),\n })\n }\n\n private runDefinition(\n invocation: AgentInvocationOptions,\n accounting?: RunAccountingPort,\n ): AsyncIterable<AgentRunEvent> {\n const definition = this.definition\n const hooks = this.combinedHooks(accounting)\n const catalog = this.effectiveCatalog()\n const outputFormat = invocation.outputFormat ?? definition.outputFormat\n const common = {\n registry: this.options.registry,\n config: this.callConfig(invocation),\n history: this.history,\n ...catalog === undefined ? {} : { tools: catalog },\n ...definition.nativeTools.length === 0 ? {} : { nativeTools: definition.nativeTools },\n ...definition.toolChoice === undefined ? {} : { toolChoice: definition.toolChoice },\n ...invocation.imagePolicy === undefined ? {} : { imagePolicy: invocation.imagePolicy },\n ...invocation.documentPolicy === undefined ? {} : { documentPolicy: invocation.documentPolicy },\n ...outputFormat === undefined ? {} : { outputFormat },\n ...(invocation.validateOutput === undefined ? {} : { validateOutput: invocation.validateOutput }),\n system: this.systemInstructions(this.activeAdditionalInstructions),\n maxTurns: definition.maxTurns,\n bounds: {\n maxToolCalls: definition.maxToolCalls,\n ...this.runtimeLimits.maxParallelToolCalls === undefined\n ? {}\n : { maxParallel: this.runtimeLimits.maxParallelToolCalls },\n ...this.runtimeLimits.maxConsecutiveToolErrors === undefined\n ? {}\n : { maxConsecutiveToolErrors: this.runtimeLimits.maxConsecutiveToolErrors },\n ...this.runtimeLimits.repeatToolWarningAt === undefined\n ? {}\n : { repeatToolWarningAt: this.runtimeLimits.repeatToolWarningAt },\n ...this.runtimeLimits.repeatToolLimit === undefined\n ? {}\n : { repeatToolLimit: this.runtimeLimits.repeatToolLimit },\n ...this.runtimeLimits.toolCycleWarningAt === undefined\n ? {}\n : { toolCycleWarningAt: this.runtimeLimits.toolCycleWarningAt },\n ...this.runtimeLimits.toolCycleLimit === undefined\n ? {}\n : { toolCycleLimit: this.runtimeLimits.toolCycleLimit },\n ...this.runtimeLimits.onExhausted === undefined\n ? {}\n : { onExhausted: this.runtimeLimits.onExhausted },\n ...this.runtimeLimits.maxToolResultTokens === undefined\n ? {}\n : { maxToolResultTokens: this.runtimeLimits.maxToolResultTokens },\n ...this.runtimeLimits.toolResultOverflow === undefined\n ? {}\n : { toolResultOverflow: this.runtimeLimits.toolResultOverflow },\n ...this.runtimeLimits.maxToolCycleLength === undefined\n ? {}\n : { maxToolCycleLength: this.runtimeLimits.maxToolCycleLength },\n ...this.runtimeLimits.finalReportReserveTokens === undefined ? {} : {\n finalReportReserveTokens: this.runtimeLimits.finalReportReserveTokens,\n },\n ...this.runtimeLimits.maxTotalTokens === undefined\n ? {}\n : { maxTotalTokens: this.runtimeLimits.maxTotalTokens },\n ...this.runtimeLimits.maxToolResultBytes === undefined\n ? {}\n : { maxToolResultBytes: this.runtimeLimits.maxToolResultBytes },\n ...this.runtimeLimits.maxToolDurationMs === undefined\n ? {}\n : { maxToolDurationMs: this.runtimeLimits.maxToolDurationMs },\n ...this.runtimeLimits.toolTeardownTimeoutMs === undefined\n ? {}\n : { toolTeardownTimeoutMs: this.runtimeLimits.toolTeardownTimeoutMs },\n },\n commentary: definition.commentary,\n ...this.runtimeLimits.teardownTimeoutMs === undefined ? {} : { teardownTimeoutMs: this.runtimeLimits.teardownTimeoutMs },\n ...this.runtimeLimits.modelTimeoutMs === undefined ? {} : { modelTimeoutMs: this.runtimeLimits.modelTimeoutMs },\n ...this.runtimeLimits.maxModelRequestBytes === undefined ? {} : { maxModelRequestBytes: this.runtimeLimits.maxModelRequestBytes },\n ...this.runtimeLimits.maxModelResponseBytes === undefined ? {} : { maxModelResponseBytes: this.runtimeLimits.maxModelResponseBytes },\n ...this.runtimeLimits.maxModelStreamEvents === undefined ? {} : { maxModelStreamEvents: this.runtimeLimits.maxModelStreamEvents },\n ...this.runtimeLimits.hookTimeoutMs === undefined ? {} : { hookTimeoutMs: this.runtimeLimits.hookTimeoutMs },\n ...this.runtimeLimits.hookTeardownTimeoutMs === undefined ? {} : { hookTeardownTimeoutMs: this.runtimeLimits.hookTeardownTimeoutMs },\n ...this.options.approvals === undefined ? {} : { approvals: this.options.approvals },\n ...this.options.spillStore === undefined ? {} : { spillStore: this.options.spillStore },\n ...this.options.experimentalPrograms === undefined ? {} : { experimentalPrograms: this.options.experimentalPrograms },\n ...this.options.interceptors === undefined ? {} : { interceptors: this.options.interceptors },\n ...this.contextSections === undefined ? {} : { contextSections: this.contextSections },\n ...hooks === undefined ? {} : { hooks },\n ...invocation.signal === undefined ? {} : { signal: invocation.signal },\n ...accounting === undefined ? {} : { accounting },\n ...accounting?.modelInvocation.logger === undefined ? {} : { logger: accounting.modelInvocation.logger },\n trace: {\n ...this.options.trace,\n conversationId: this.currentConversationId,\n agentId: definition.id,\n agentName: definition.name,\n },\n }\n if (definition.mode === 'deep-human-in-loop') {\n return runAgent({\n ...common, mode: definition.mode, userInput: this.options.userInput as UserInputBroker,\n })\n }\n if (definition.mode === 'deep') {\n return runAgent({\n ...common, mode: definition.mode,\n ...this.options.userInput === undefined ? {} : { userInput: this.options.userInput },\n })\n }\n return runAgent({ ...common, mode: 'basic' })\n }\n\n private createCompactor(): ContextCompactor | undefined {\n const configured = this.options.compaction === false\n ? false\n : this.options.compaction === undefined\n ? this.definition.compaction\n : resolveCompactionConfig(this.options.compaction)\n if (configured === false) return undefined\n return new ContextCompactor({\n registry: this.options.registry,\n config: () => this.callConfig(this.activeInvocation),\n history: () => this.currentHistory,\n system: () => this.systemInstructions(this.activeAdditionalInstructions),\n pinnedMessages: () => renderRuntimeMemory(\n this.currentMemory, this.definition.memory.maxInjectedChars,\n ),\n tools: () => [\n ...this.effectiveCatalog()?.schemas() ?? [],\n ...this.definition.nativeTools,\n ],\n policy: configured,\n })\n }\n\n private effectiveCatalog(): ToolCatalog | undefined {\n return this.activeRuntimeCatalog ?? this.catalog\n }\n\n private combinedHooks(accounting?: RunAccountingPort): TurnHooks | undefined {\n const user = this.options.hooks\n const hooks: TurnHooks = {\n ...user,\n beforeStep: async context => {\n // Before anything reads history for this request: model-round refreshes\n // its messages when entries changed, so delivered input is included.\n const generation = this.currentHistory.generation()\n const entries = this.currentHistory.entries().length\n this.drainInjections()\n const prepared = this.currentHistory.entries().length === entries\n ? context\n : { ...context, messages: normalizeToolPairing(this.currentHistory.messages()), snapshot: this.currentHistory.snapshot() }\n if (this.compactor !== undefined) bindCompactionAccounting(this.compactor, accounting)\n await this.compactor?.beforeStep(prepared)\n if (accounting?.usageStop !== undefined) return { kind: 'proceed' as const }\n const refreshed = this.currentHistory.generation() === generation && this.currentHistory.entries().length === entries\n ? context\n : {\n ...context,\n messages: normalizeToolPairing(this.currentHistory.messages()),\n snapshot: this.currentHistory.snapshot(),\n }\n const memory = renderRuntimeMemory(\n this.currentMemory, this.definition.memory.maxInjectedChars, accounting,\n )\n const current = memory.length === 0\n ? refreshed\n : { ...refreshed, messages: Object.freeze([...memory, ...refreshed.messages]) }\n const decision = await user?.beforeStep?.(current) ?? { kind: 'proceed' as const }\n if (decision.kind === 'reject') return decision\n // A projection sees injected memory already; do not inject it twice.\n const prepend = [...decision.messages === undefined ? memory : [], ...decision.prepend ?? []]\n return bindStepProjectionSources(prepend.length === 0 ? decision : { ...decision, prepend }, refreshed.messages)\n },\n onRequestError: async context => {\n if (this.compactor !== undefined) bindCompactionAccounting(this.compactor, accounting)\n const recovery = await this.compactor?.onRequestError(context)\n if (accounting?.usageStop !== undefined) return 'fail'\n if (recovery === 'retry') return 'retry'\n return await user?.onRequestError?.(context) ?? 'fail'\n },\n }\n return hooks\n }\n\n private callConfig(invocation?: AgentInvocationOptions) {\n return sessionCallConfig(this.definition, runtimeSessionConfiguration(this), invocation)\n }\n\n private systemInstructions(additionalInstructions?: string): string {\n const base = this.skillCatalog === undefined\n ? this.definition.instructions\n : renderSkillCatalog(\n this.definition.instructions,\n this.skillCatalog.summaries(),\n this.definition.skillOptions,\n )\n const team = this.options.team\n const composed = team === undefined\n ? base\n : `${base}\\n\\n${team.team.instructionsFor(team.name ?? this.definition.id)}`\n return appendRunInstructions(composed, additionalInstructions)\n }\n\n private skillLookup(signal?: AbortSignal): SkillLookupOptions {\n return {\n ...(this.options.skillCwd === undefined ? {} : { cwd: this.options.skillCwd }),\n ...(signal === undefined ? {} : { signal }),\n }\n }\n\n private activationSnapshot(): readonly AgentSessionActivatedSkillSnapshot[] {\n const activated = new Map<string, AgentSessionActivatedSkillSnapshot>()\n for (const entry of this.pendingSkillActivations) activated.set(entry.id, entry)\n for (const reference of this.skillCatalog?.activatedSkillReferences() ?? []) {\n activated.set(reference.id, reference)\n }\n for (const summary of this.skillCatalog?.activatedSummaries() ?? []) {\n if (activated.has(summary.id)) continue\n activated.set(summary.id, Object.freeze({\n id: summary.id, provider: summary.provider, source: summary.source,\n ...summary.resourceBase === undefined ? {} : {\n resourceBase: Object.freeze({ ...summary.resourceBase }),\n },\n }))\n }\n return Object.freeze([...activated.values()].sort((left, right) => left.id.localeCompare(right.id)))\n }\n\n private async prepareSkills(signal?: AbortSignal, accounting?: RunAccountingPort): Promise<void> {\n await prepareSkills(\n this.definition, this.skillCatalog, this.pendingSkillActivations,\n signal => this.skillLookup(signal),\n () => { this.pendingSkillActivations = Object.freeze([]) }, signal, accounting,\n )\n }\n}\n\nexport { configureRuntimeSessionModel, streamRuntimeSession } from './session/runtime-binding.ts'\nexport type {\n AgentInput, AgentRuntimeLimits, AgentSessionOptions, AgentTeamMemberOptions,\n AgentSessionSnapshot, AgentSessionActivatedSkillSnapshot, AgentResumeSessionOptions,\n AgentInvocationOptions, AgentResponse, AgentRunHandle,\n} from './session/types.ts'\n"],"mappings":"w7EAqDA,IAAa,EAAb,MAAa,CAAa,CACxB,WACA,QACA,QACA,qBACA,aACA,cAEA,gBACA,eACA,cACA,sBACA,UACA,wBAAiF,OAAO,OAAO,CAAC,CAAC,EACjG,OAAiB,GACjB,6BAEA,iBACA,YAA+B,IAAI,IAOnC,kBACA,eAMA,cAAwB,GAExB,iBAA2B,GAE3B,YAAY,EAA6B,EAA8B,CACrE,GAAI,EAAW,OAAS,sBAAwB,EAAQ,YAAc,IAAA,GACpE,MAAU,UAAU,UAAU,EAAW,GAAG,yDAAyD,EAEvG,KAAK,WAAa,EAClB,IAAM,EAAgB,EAAQ,gBAAkB,IAAA,GAC5C,IAAA,GACA,OAAO,OAAO,CAAE,GAAG,EAAQ,aAAc,CAAC,EAG1C,EAAQ,UAAY,IAAA,IAAa,IAAkB,IAAA,IAAW,IAAS,EAAQ,CAAa,EAChG,IAAM,EAAa,EAAQ,aAAe,IAAA,IAAa,EAAQ,aAAe,GAC1E,EAAQ,WACR,OAAO,OAAO,CAAE,GAAG,EAAQ,UAAW,CAAC,EACrC,EAAQ,EAAQ,QAAU,IAAA,GAAY,IAAA,GAAY,OAAO,OAAO,CAAE,GAAG,EAAQ,KAAM,CAAC,EACpF,EAAO,EAAQ,OAAS,IAAA,GAAY,IAAA,GAAY,OAAO,OAAO,CAAE,GAAG,EAAQ,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K,aAAc,KAAK,wBACzC,GAAU,KAAK,YAAY,CAAM,MAC3B,CAAE,KAAK,wBAA0B,OAAO,OAAO,CAAC,CAAC,CAAE,EAAG,EAAQ,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 { isManagedTeamNotice } from '../history/input-work.ts'\nimport { bindModelRequestBoundary, bindQueuedInput } from '../loop/turn/model-request-boundary.ts'\nimport { bindStepProjectionSources } from '../loop/turn/step-projection.ts'\nimport { normalizeToolPairing } from '../history/normalize.ts'\nimport type { TurnHooks } from '../loop/types.ts'\nimport { ContextCompactor, type CompactionResult } from '../memory/compaction.ts'\nimport { bindCompactionAccounting } from '../memory/accounting-binding.ts'\nimport { resolveCompactionConfig } from '../memory/compaction-config.ts'\nimport { AgentMemory } from '../memory/memory.ts'\nimport { captureContextSections } from '../context/section.ts'\nimport type { ContextSection } from '../context/types.ts'\nimport { runAgent, type AgentRunEvent, type AgentRunOutcome } from '../mode/run-agent.ts'\nimport type { UserInputBroker } from '../mode/user-input.ts'\nimport { waitForSettlement } from '../../async/index.ts'\nimport type { OperationStatus } from '../../observation/index.ts'\nimport { RunEventBuffer } from '../accounting/event-buffer.ts'\nimport { AgentRunError, AGENT_ACCOUNTING_ERROR_CODES } from '../accounting/error.ts'\nimport type { RunAccountingPort } from '../accounting/contracts.ts'\nimport type { LegacyRunReport } from '../accounting/report.ts'\nimport type { RunReport } from '../accounting/delivery-types.ts'\nimport { createRunTerminalRecord, withTerminalDelivery } from '../accounting/delivery/terminal.ts'\nimport { SkillCatalog, createSkillTools, renderSkillCatalog, type SkillLookupOptions } from '../skill/index.ts'\nimport type { AgentDefinition } from './definition.ts'\nimport {\n type AgentInput, type AgentRuntimeLimits, type AgentSessionOptions, type AgentSessionSnapshot,\n type AgentSessionActivatedSkillSnapshot, type AgentResumeSessionOptions,\n type AgentInvocationOptions, type AgentResponse, type AgentRunHandle,\n} from './session/types.ts'\nimport { validateSessionSnapshot } from './session/validation.ts'\nimport { resolveRuntimeLimits } from './session/config.ts'\nimport {\n conversationId, newConversationId, userMessage, deferred, messageOf, errorCodeOf,\n toolCatalog,\n} from './session/common.ts'\nimport { captureResumedSkillActivations, prepareSkills } from './session/skills.ts'\nimport { appendRunInstructions } from './instructions.ts'\nimport type { ToolSourceRunReference } from '../tool/source-types.ts'\nimport { accountTraceEvent } from './session/trace-accounting.ts'\nimport {\n captureResumedObjective, commitRuntimeMemory, loadRuntimeMemory, renderRuntimeMemory,\n} from './session/runtime-memory.ts'\nimport { attachRuntimeSession, runtimeSessionConfiguration } from './session/runtime-binding.ts'\nimport { bindSkillProviderLogger } from '../skill/provider/context.ts'\nimport { createSessionLedger } from './session/accounting.ts'\nimport { runRuntimeCompaction } from './session/runtime-compaction.ts'\nimport { sessionCallConfig } from './session/model-config.ts'\nimport { consumeSessionEvents } from './session/observer.ts'\nimport { sealRuntimeRun } from './session/run-seal.ts'\n\nexport class AgentSession {\n readonly definition: AgentDefinition\n private readonly options: AgentSessionOptions\n private readonly catalog: ToolCatalog | undefined\n private activeRuntimeCatalog: ToolCatalog | undefined\n private readonly skillCatalog: SkillCatalog | undefined\n private readonly runtimeLimits: Readonly<AgentRuntimeLimits>\n /** Definition sections first, then session sections; duplicate ids are rejected. */\n private readonly contextSections: readonly ContextSection[] | undefined\n private currentHistory: History\n private currentMemory: AgentMemory\n private currentConversationId: string\n private compactor: ContextCompactor | undefined\n private pendingSkillActivations: readonly AgentSessionActivatedSkillSnapshot[] = Object.freeze([])\n private active = false\n private activeAdditionalInstructions: string | undefined\n /** The overlay of the run that owns the session, so maintenance follows the same model. */\n private activeInvocation: AgentInvocationOptions | undefined\n private readonly idleWaiters = new Set<() => void>()\n /**\n * Messages injected while a run is in flight, waiting for the next model\n * request. Appending them at once put them AHEAD of the assistant output of\n * the round already streaming, a round that never saw them; the next round\n * then read \"steer, then the work that ignored it\" as work that answered it.\n */\n private pendingInjections: History | undefined\n private lastRunOutcome: AgentRunOutcome | undefined\n /**\n * A model request has been built and its output is not yet fully recorded.\n * Only then is an injection held: hooks and team notices that inject between\n * rounds still append at once, as they always have.\n */\n private roundInFlight = false\n /** The round in flight called a tool, so its output ends at step-end. */\n private roundCalledTools = false\n\n constructor(definition: AgentDefinition, options: AgentSessionOptions) {\n if (definition.mode === 'deep-human-in-loop' && options.userInput === undefined) {\n throw new TypeError(`agent '${definition.id}' requires a userInput broker in deep-human-in-loop mode`)\n }\n this.definition = definition\n const historyLimits = options.historyLimits === undefined\n ? undefined\n : Object.freeze({ ...options.historyLimits })\n // Validate reset-time policy even when the initial History was supplied by\n // the host, and detach mutable option containers from the caller.\n if (options.history !== undefined && historyLimits !== undefined) void new History(historyLimits)\n const compaction = options.compaction === undefined || options.compaction === false\n ? options.compaction\n : Object.freeze({ ...options.compaction })\n const trace = options.trace === undefined ? undefined : Object.freeze({ ...options.trace })\n const team = options.team === undefined ? undefined : Object.freeze({ ...options.team })\n const ledgerLimits = options.ledgerLimits === undefined ? undefined : Object.freeze({ ...options.ledgerLimits })\n const eventBufferLimits = options.eventBufferLimits === undefined\n ? undefined\n : Object.freeze({ ...options.eventBufferLimits })\n this.options = Object.freeze({\n ...options,\n ...(historyLimits === undefined ? {} : { historyLimits }),\n ...(compaction === undefined ? {} : { compaction }),\n ...(trace === undefined ? {} : { trace }),\n ...(team === undefined ? {} : { team }),\n ...(ledgerLimits === undefined ? {} : { ledgerLimits }),\n ...(eventBufferLimits === undefined ? {} : { eventBufferLimits }),\n ...(options.skills === undefined ? {} : { skills: Object.freeze([...options.skills]) }),\n ...(Array.isArray(options.tools) ? { tools: Object.freeze([...options.tools]) } : {}),\n ...(options.interceptors === undefined ? {} : { interceptors: Object.freeze([...options.interceptors]) }),\n })\n this.runtimeLimits = resolveRuntimeLimits(options.runtimeLimits)\n // A session may replace a definition section by reusing its id: the\n // definition describes the agent, the session describes where it is\n // running, and the more specific one wins in place. Two sections with one\n // id inside the *same* list stays an error — a single live surface node\n // cannot have two owners.\n const overrides = captureContextSections(options.contextSections) ?? []\n const base = captureContextSections(definition.contextSections) ?? []\n const merged = [\n ...base.map(section => overrides.find(override => override.id === section.id) ?? section),\n ...overrides.filter(override => !base.some(section => section.id === override.id)),\n ]\n this.contextSections = merged.length === 0 ? undefined : Object.freeze(merged)\n this.currentConversationId = conversationId(options.conversationId)\n this.currentHistory = options.history ?? new History(historyLimits)\n const skillSources = [...definition.skills, ...options.skills ?? []]\n const skillRuntimeDisabled = definition.skillIds?.length === 0\n const skillRuntimeConfigured = skillSources.length > 0 || (definition.skillIds?.length ?? 0) > 0\n this.skillCatalog = skillRuntimeDisabled || !skillRuntimeConfigured\n ? undefined\n : new SkillCatalog(skillSources, {\n ...(definition.skillIds === undefined ? {} : { allowedSkillIds: definition.skillIds }),\n maxSkills: definition.skillOptions.maxSkills,\n maxCatalogBytes: definition.skillOptions.maxDiscoveryBytes,\n })\n const skillTools = this.skillCatalog === undefined ? [] : createSkillTools(\n this.skillCatalog,\n definition.skillOptions,\n () => this.skillLookup(),\n )\n const teamAccess = options.team?.tools === 'reporting' ? 'reporting' as const : 'full' as const\n const teamTools = options.team?.tools === false\n ? []\n : options.team?.team.toolsFor(options.team.name ?? definition.id, teamAccess) ?? []\n this.catalog = toolCatalog(definition.tools, options.tools, [...skillTools, ...teamTools])\n this.currentMemory = options.memory instanceof AgentMemory\n ? options.memory\n : options.memory === undefined\n ? new AgentMemory(definition.memory.seed, definition.memory)\n : AgentMemory.fromSnapshot(options.memory, definition.memory)\n captureResumedObjective(this.currentMemory, this.currentHistory, this.definition.memory.autoCaptureObjective)\n this.compactor = this.createCompactor()\n attachRuntimeSession(this, (input, invocation, additionalInstructions) =>\n this.createRunHandle(input, invocation, additionalInstructions), invocation =>\n this.createRunHandle(undefined, invocation), invocation =>\n this.compactForRuntime(invocation), () => {\n this.compactor = this.createCompactor()\n })\n options.team?.team.attach(this, {\n ...(options.team.name === undefined ? {} : { name: options.team.name }),\n ...(options.team.description === undefined ? {} : { description: options.team.description }),\n ...(options.team.instructions === undefined ? {} : { instructions: options.team.instructions }),\n ...(options.team.role === undefined ? {} : { role: options.team.role }),\n ...(options.team.tools === undefined ? {} : { tools: options.team.tools }),\n })\n }\n\n /** Restore a JSON-round-tripped session snapshot with fresh runtime dependencies. */\n static fromSnapshot(\n definition: AgentDefinition,\n options: AgentResumeSessionOptions,\n ): AgentSession {\n const { snapshot, ...runtime } = options\n validateSessionSnapshot(snapshot, definition.id, definition.skillOptions.maxSkills)\n const session = new AgentSession(definition, {\n ...runtime,\n conversationId: snapshot.conversationId,\n history: History.fromSnapshot(snapshot.history, runtime.historyLimits),\n memory: AgentMemory.fromSnapshot(snapshot.memory, definition.memory),\n })\n session.pendingSkillActivations = captureResumedSkillActivations(snapshot.skills, session.skillCatalog)\n return session\n }\n\n /** Stable identity for persistence keys, URLs, logs, and GUI trace grouping. */\n get conversationId(): string { return this.currentConversationId }\n\n /** Mutable append-only history owned by this conversation. */\n get history(): History { return this.currentHistory }\n\n /** Durable task facts injected into every request outside compactable history. */\n get memory(): AgentMemory { return this.currentMemory }\n\n /** Refreshable skill catalog for host UIs and explicit user invocation surfaces. */\n get skills(): SkillCatalog | undefined { return this.skillCatalog }\n\n /** Whether a model/tool turn currently owns this session. */\n get isRunning(): boolean { return this.active }\n\n /** Capture one JSON-safe envelope that can be passed to `agent.resumeSession()`. */\n snapshot(): AgentSessionSnapshot {\n const activated = this.activationSnapshot()\n const history = this.currentHistory.snapshot()\n const pending = this.pendingInjections?.entries() ?? []\n // An accepted input must survive a snapshot taken before its model round\n // finishes. Project pending inputs at the known tail without delivering\n // them early to the live model or changing the persisted v1 schema.\n const persistedHistory = pending.length === 0 ? history : Object.freeze({\n version: 1 as const,\n entries: Object.freeze([...history.entries, ...pending.map((entry, index) => Object.freeze({\n ...entry, seq: history.entries.length + index + 1,\n }))]),\n })\n return Object.freeze({\n version: 1 as const,\n conversationId: this.currentConversationId,\n agentId: this.definition.id,\n history: persistedHistory,\n memory: this.currentMemory.snapshot(),\n ...runtimeSessionConfiguration(this)?.memory === undefined ? {} : {\n memoryBindingId: runtimeSessionConfiguration(this)!.memory!.bindingId,\n },\n ...activated.length === 0 ? {} : {\n skills: Object.freeze({ activated }),\n },\n })\n }\n\n /** Start a fresh conversation without rebuilding provider/tool configuration. */\n reset(): void {\n if (this.active) throw new Error('cannot reset an agent session while a run is active')\n this.currentConversationId = newConversationId()\n this.currentHistory = new History(this.options.historyLimits)\n this.currentMemory = new AgentMemory(this.definition.memory.seed, this.definition.memory)\n this.pendingInjections = undefined\n this.pendingSkillActivations = Object.freeze([])\n this.lastRunOutcome = undefined\n this.skillCatalog?.clearActivations()\n this.compactor = this.createCompactor()\n }\n\n /** Create one explicit context checkpoint while the session is idle. */\n async compact(invocation: AgentInvocationOptions = {}): Promise<CompactionResult | null> {\n if (this.active) throw new Error('cannot compact an agent session while a run is active')\n this.active = true\n this.activeInvocation = invocation\n try {\n await this.prepareSkills(invocation.signal)\n return await this.compactor?.compactNow(invocation.signal) ?? null\n } finally {\n this.releaseRun()\n }\n }\n\n private async compactForRuntime(invocation: AgentInvocationOptions): Promise<{\n readonly result: CompactionResult | null\n readonly report: LegacyRunReport\n readonly failure?: unknown\n }> {\n if (this.active) throw new Error('cannot compact an agent session while a run is active')\n const ledger = this.createLedger()\n this.active = true\n this.activeInvocation = invocation\n if (this.compactor !== undefined) bindCompactionAccounting(this.compactor, ledger)\n if (this.skillCatalog !== undefined) bindSkillProviderLogger(this.skillCatalog, ledger.modelInvocation.logger)\n try { return await runRuntimeCompaction({\n ...(this.compactor === undefined ? {} : { compactor: this.compactor }),\n invocation,\n accounting: ledger,\n prepare: () => this.prepareSkills(invocation.signal, ledger),\n }) } finally { this.releaseRun() }\n }\n\n /**\n * Append attributed context without starting a turn.\n *\n * A2A quiet delivery uses this primitive. The returned count includes queued\n * inputs and lets wake-up schedulers coalesce messages safely; a mid-round\n * receipt is provisional rather than the eventual persisted entry sequence.\n */\n inject(input: AgentInput): number {\n const message = userMessage(input)\n // Mid-run, hold the message until the next model request is built, so it\n // lands after every entry the model has actually answered. Bound pending\n // inputs with the same guards as history instead of an unbounded array.\n if (this.active && this.roundInFlight) {\n // Reject over-capacity input at admission, before it can poison the\n // queued buffer used by every later run and snapshot.\n const candidate = History.fromSnapshot(this.currentHistory.snapshot(), this.options.historyLimits)\n candidate.appendBatch([\n ...(this.pendingInjections?.entries() ?? []).map(entry => ({ event: entry.event })),\n { event: { kind: 'user' as const, message } },\n ])\n const pending = this.pendingInjections ??= new History(this.options.historyLimits)\n pending.append({ kind: 'user', message })\n return this.currentHistory.entries().length + pending.entries().length\n }\n this.drainInjections()\n this.currentHistory.append({ kind: 'user', message })\n return this.currentHistory.entries().length\n }\n\n /**\n * Close the in-flight window once a round's output is fully recorded: after\n * its tool results (`step-end`), or when the turn ends. The loop waits on\n * this consumer, so held messages land exactly there, never between a tool\n * call and its result.\n *\n * A round that answers without calling a tool ends the turn, and input the\n * person sent while it was being written is still owed an answer. It stays\n * held until the loop is about to end the turn; the loop then takes it (see\n * `bindQueuedInput`) and answers it in another round of the same run instead\n * of leaving it for a later `runPending()`.\n */\n private observeRoundBoundary(event: AgentRunEvent): void {\n if (event.type === 'agent-end') this.lastRunOutcome = event.outcome\n // The chat request is now fixed. beforeStep hooks still run outside this\n // window, so their injections can be included in that request's refresh.\n if (event.type === 'span-start' && event.kind === 'chat') {\n this.roundInFlight = true\n this.roundCalledTools = false\n return\n }\n if (!this.roundInFlight) return\n if (event.type === 'tool-call' || (event.type === 'assistant-message'\n && event.message?.content.some(block => block.type === 'tool-call') === true)) {\n this.roundCalledTools = true\n }\n // A tool round's output is complete at step-end; a final answer's input\n // waits for the loop to take it at turn end, unless the turn is already over.\n if ((event.type === 'step-end' && this.roundCalledTools) || event.type === 'turn-end' || event.type === 'agent-end') {\n this.roundInFlight = false\n this.drainInjections()\n }\n }\n\n /** Deliver held injections, in arrival order, at the chronological tail. */\n private drainInjections(): void {\n if (this.pendingInjections === undefined) return\n const pending = this.pendingInjections\n // Atomic: a full history must not consume only the first queued input and\n // silently lose the rest. Keep the buffer available to snapshot/recovery.\n this.currentHistory.appendBatch(pending.entries().map(entry => ({ event: entry.event })))\n this.pendingInjections = undefined\n }\n\n /**\n * Whether attributed input or a tool result still awaits the model. App\n * notices do not create work, except managed-team coordination. False once the model has answered everything,\n * which lets a scheduler skip a run that would only repeat that answer.\n */\n hasUnansweredInput(): boolean {\n if ((this.pendingInjections?.entries().length ?? 0) > 0) return true\n for (const message of [...this.currentHistory.messages()].reverse()) {\n if (message.source.kind === 'app') {\n if (message.source.producer === 'turn-interrupted') return false\n if (message.role === 'user' && !isManagedTeamNotice(message)) continue\n }\n return message.role === 'user'\n }\n return false\n }\n\n lastOutcome(): AgentRunOutcome | undefined { return this.lastRunOutcome }\n\n /** Resolve after the current run releases the session. */\n whenIdle(signal?: AbortSignal): Promise<void> {\n if (!this.active) return Promise.resolve()\n if (signal?.aborted) return Promise.reject(signal.reason)\n return new Promise<void>((resolve, reject) => {\n let settled = false\n const finish = (): void => {\n if (settled) return\n settled = true\n this.idleWaiters.delete(finish)\n signal?.removeEventListener('abort', abort)\n resolve()\n }\n const abort = (): void => {\n if (settled) return\n settled = true\n this.idleWaiters.delete(finish)\n reject(signal?.reason)\n }\n this.idleWaiters.add(finish)\n signal?.addEventListener('abort', abort, { once: true })\n if (!this.active) finish()\n })\n }\n\n /** Start an eager run and expose both public events and its canonical terminal report. */\n stream(input: AgentInput, invocation: AgentInvocationOptions = {}): AgentRunHandle {\n return this.createRunHandle(input, invocation)\n }\n\n /** Process context already appended with {@link inject} without duplicating it. */\n streamPending(invocation: AgentInvocationOptions = {}): AgentRunHandle {\n return this.createRunHandle(undefined, invocation)\n }\n\n /** Run one user turn and return the terminal response. */\n async run(input: AgentInput, invocation: AgentInvocationOptions = {}): Promise<AgentResponse> {\n const handle = this.stream(input, invocation)\n await consumeSessionEvents(handle, invocation.onEvent, this.runtimeLimits.observerTimeoutMs ?? 30_000)\n return await handle.result\n }\n\n /** Run one turn over already-injected context and return its terminal response. */\n async runPending(invocation: AgentInvocationOptions = {}): Promise<AgentResponse> {\n const handle = this.streamPending(invocation)\n await consumeSessionEvents(handle, invocation.onEvent, this.runtimeLimits.observerTimeoutMs ?? 30_000)\n return await handle.result\n }\n\n private createRunHandle(\n input: AgentInput | undefined,\n invocation: AgentInvocationOptions,\n additionalInstructions?: string,\n ): AgentRunHandle {\n if (this.active) throw new Error(`agent session '${this.definition.id}' is already running`)\n this.drainInjections()\n const firstTurnSeq = this.currentHistory.entries().length + 1\n const owned = new AbortController()\n let terminal = false\n const signal = invocation.signal === undefined\n ? owned.signal\n : AbortSignal.any([invocation.signal, owned.signal])\n const buffer = new RunEventBuffer<AgentRunEvent>(\n this.options.eventBufferLimits?.maxEvents,\n this.options.eventBufferLimits?.maxBytes,\n )\n const reportDeferred = deferred<RunReport>()\n const resultDeferred = deferred<AgentResponse>()\n const toolSourcesDeferred = deferred<readonly ToolSourceRunReference[]>()\n const ledger = this.createLedger()\n let toolSourceReferences: readonly ToolSourceRunReference[] = Object.freeze([])\n if (this.compactor !== undefined) bindCompactionAccounting(this.compactor, ledger)\n if (this.skillCatalog !== undefined) {\n bindSkillProviderLogger(this.skillCatalog, ledger.modelInvocation.logger)\n }\n this.active = true\n bindModelRequestBoundary(this.currentHistory, inFlight => {\n this.roundInFlight = inFlight\n if (!inFlight) this.drainInjections()\n })\n bindQueuedInput(this.currentHistory, () => {\n // By entries, not by the buffer: an input refused at admission leaves an\n // empty buffer behind, and that must not buy the run another round.\n const held = this.pendingInjections?.entries() ?? []\n if (held.length === 0) return false\n // Person input and managed-team coordination extend the run. Team deliveries keep\n // their contract: queued behind the answer, then processed exactly once\n // by the team's wake-up through runPending().\n const extendsRun = held.some(entry => entry.event.kind === 'user'\n && (entry.event.message.source.kind === 'user' || isManagedTeamNotice(entry.event.message)))\n if (!extendsRun) return false\n this.roundInFlight = false\n this.drainInjections()\n return true\n }, () => (this.pendingInjections?.entries() ?? []).some(entry => entry.event.kind === 'user'\n && (entry.event.message.source.kind === 'user' || isManagedTeamNotice(entry.event.message))))\n this.activeAdditionalInstructions = additionalInstructions\n this.activeInvocation = invocation\n const spanOperations = new Map<string, string>()\n const task = (async (): Promise<void> => {\n let failure: unknown\n let outcome: AgentRunOutcome | undefined\n let memoryState: Awaited<ReturnType<typeof loadRuntimeMemory>>['state'] | undefined\n try {\n const runtime = runtimeSessionConfiguration(this)\n if (runtime?.memory !== undefined) {\n const prepared = await loadRuntimeMemory(\n runtime.memory, this.currentConversationId, this.definition.memory, signal, ledger,\n )\n memoryState = prepared.state\n if (prepared.memory !== undefined) this.currentMemory = prepared.memory\n }\n if (runtime?.prepareTools !== undefined) {\n const logger = ledger.modelInvocation.logger\n if (logger === undefined) throw new Error('runtime tool source logger is unavailable')\n const generation = runtime.prepareTools(signal, logger, [...this.catalog?.names() ?? [], ...this.definition.nativeTools.map(tool => tool.name)])\n this.activeRuntimeCatalog = toolCatalog([], this.catalog, generation.tools)\n toolSourceReferences = generation.references\n }\n toolSourcesDeferred.resolve(toolSourceReferences)\n await this.prepareSkills(signal, ledger)\n if (input !== undefined) {\n const message = userMessage(input)\n if (this.definition.memory.autoCaptureObjective) {\n const operation = ledger.startOperation('memory', { data: { action: 'capture-objective' } })\n try {\n this.currentMemory.captureOriginalObjective(message)\n ledger.endOperation(operation, 'success')\n } catch (error) {\n ledger.endOperation(operation, 'error', { error })\n throw error\n }\n }\n this.currentHistory.append({ kind: 'user', message })\n }\n // Preflight before compaction can turn a required image into a summary.\n if (invocation.imagePolicy === 'strict' && this.history.messages().some(message => contentHasImage(message.content))) {\n const config = this.callConfig(invocation)\n const model = await this.options.registry.resolveModelInfo(config.provider, config.model, signal)\n if (model.inputModalities !== undefined && !model.inputModalities.includes('image')) {\n throw new ModelError(`model ${model.id} does not support required image input`, 'UNSUPPORTED_IMAGE_INPUT')\n }\n }\n // Same preflight for documents, for the same reason.\n if (invocation.documentPolicy === 'strict' && this.history.messages().some(message => contentHasDocument(message.content))) {\n const config = this.callConfig(invocation)\n const model = await this.options.registry.resolveModelInfo(config.provider, config.model, signal)\n if (model.inputModalities !== undefined && !model.inputModalities.includes('document')) {\n throw new ModelError(`model ${model.id} does not support required document input`, 'UNSUPPORTED_DOCUMENT_INPUT')\n }\n }\n for await (const event of this.runDefinition({ ...invocation, signal }, ledger)) {\n this.observeRoundBoundary(event)\n accountTraceEvent(ledger, spanOperations, event)\n if (event.type === 'agent-end') outcome = event.outcome\n buffer.push(event)\n }\n if (outcome === undefined) {\n throw new Error(`agent session '${this.definition.id}' ended without agent-end`)\n }\n if (signal.aborted) throw signal.reason ?? new Error('agent run was aborted')\n if (outcome.reason.kind === 'error' && outcome.reason.failure.code === 'USAGE_REQUIRED') {\n const error = new Error(outcome.reason.failure.message) as Error & { code: string }\n error.code = 'USAGE_REQUIRED'\n throw error\n }\n if (runtime?.memory !== undefined && memoryState !== undefined && memoryState.status !== 'disabled') {\n await commitRuntimeMemory(\n runtime.memory, this.currentConversationId, this.currentMemory.snapshot(),\n memoryState, signal, ledger,\n )\n }\n } catch (error: unknown) {\n failure = error\n toolSourcesDeferred.resolve(toolSourceReferences)\n }\n\n try { this.drainInjections() } catch (error) { failure ??= error }\n\n let report: RunReport\n try {\n const status: OperationStatus = signal.aborted || outcome?.reason.kind === 'aborted'\n ? 'aborted'\n : failure !== undefined || outcome?.reason.kind === 'error'\n ? 'error'\n : 'success'\n const ledgerReport = await ledger.finalize(status, outcome?.completed ?? false, failure)\n report = withTerminalDelivery(createRunTerminalRecord(ledgerReport), ledgerReport.delivery)\n reportDeferred.resolve(report)\n } catch (finalizeError: unknown) {\n reportDeferred.reject(finalizeError)\n resultDeferred.reject(finalizeError)\n buffer.fail(finalizeError)\n terminal = true\n this.releaseRun()\n return\n }\n if (terminal) return\n\n if (failure === undefined && ledger.terminalAuditFailure) {\n const error = new Error('audit observation checkpoint failed after run finalization') as Error & { code: string }\n error.code = 'OBSERVABILITY_AUDIT_UNAVAILABLE'\n failure = error\n }\n if (failure !== undefined) {\n const error = new AgentRunError(\n messageOf(failure),\n errorCodeOf(failure) ?? AGENT_ACCOUNTING_ERROR_CODES.RUN_FAILED,\n report,\n { cause: failure },\n )\n resultDeferred.reject(error)\n buffer.fail(error)\n } else {\n const terminal = outcome as AgentRunOutcome\n const historyEvent = [...this.currentHistory.entries()].reverse()\n .find(entry => entry.seq >= firstTurnSeq && entry.event.kind === 'assistant')\n ?.event\n const assistantMessage = historyEvent?.kind === 'assistant' ? historyEvent.message : undefined\n const response: AgentResponse = Object.freeze({\n text: terminal.text,\n outcome: terminal,\n report,\n ...assistantMessage === undefined ? {} : { message: assistantMessage },\n })\n resultDeferred.resolve(response)\n buffer.close()\n }\n terminal = true\n this.releaseRun()\n })()\n void task.catch(error => {\n if (terminal) return\n reportDeferred.reject(error)\n resultDeferred.reject(error)\n buffer.fail(error)\n terminal = true\n this.releaseRun()\n })\n void resultDeferred.promise.catch(() => undefined)\n void reportDeferred.promise.catch(() => undefined)\n let iterated = false\n return Object.freeze({\n runId: ledger.runId,\n traceId: ledger.traceId,\n toolSourceSnapshots: toolSourcesDeferred.promise,\n eventsSettled: task.then(() => undefined, () => undefined),\n result: resultDeferred.promise,\n report: reportDeferred.promise,\n seal: () => sealRuntimeRun({ ledger, buffer, report: reportDeferred, result: resultDeferred,\n toolSources: toolSourcesDeferred, currentToolSources: () => toolSourceReferences, isTerminal: () => terminal,\n markTerminal: () => { terminal = true }, abort: () => owned.abort(new Error('Agent run was sealed')),\n release: () => this.releaseRun() }),\n abort(_reason?: unknown): void {\n if (!terminal && !owned.signal.aborted) owned.abort(new Error('Agent run was aborted'))\n },\n [Symbol.asyncIterator](): AsyncIterator<AgentRunEvent> {\n if (iterated) return (async function* () { throw new Error('an agent run handle can only be iterated once') })()\n iterated = true\n return (async function* () {\n let exhausted = false\n try {\n while (true) {\n const item = await buffer.take()\n if (item.done) { exhausted = true; break }\n yield item.value\n }\n } finally {\n if (!exhausted) {\n owned.abort(new Error('agent event consumer stopped'))\n buffer.stop()\n await waitForSettlement(task, 30_000)\n }\n }\n })()\n },\n })\n }\n\n private releaseRun(): void {\n // A message that arrived during the final model round is still delivered,\n // so the next run (or a waiting scheduler) reads it.\n try { this.drainInjections() } finally {\n bindModelRequestBoundary(this.currentHistory)\n bindQueuedInput(this.currentHistory)\n this.roundInFlight = false\n this.active = false\n this.activeAdditionalInstructions = undefined\n this.activeInvocation = undefined\n this.activeRuntimeCatalog = undefined\n if (this.skillCatalog !== undefined) bindSkillProviderLogger(this.skillCatalog, undefined)\n if (this.compactor !== undefined) bindCompactionAccounting(this.compactor, undefined)\n const waiters = [...this.idleWaiters]\n this.idleWaiters.clear()\n for (const resolve of waiters) resolve()\n }\n }\n\n private createLedger() {\n const runtime = runtimeSessionConfiguration(this)\n return createSessionLedger({\n definition: this.definition,\n options: this.options,\n runtimeLimits: this.runtimeLimits,\n conversationId: this.currentConversationId,\n ...(runtime === undefined ? {} : { runtime }),\n })\n }\n\n private runDefinition(\n invocation: AgentInvocationOptions,\n accounting?: RunAccountingPort,\n ): AsyncIterable<AgentRunEvent> {\n const definition = this.definition\n const hooks = this.combinedHooks(accounting)\n const catalog = this.effectiveCatalog()\n const outputFormat = invocation.outputFormat ?? definition.outputFormat\n const common = {\n registry: this.options.registry,\n config: this.callConfig(invocation),\n history: this.history,\n ...catalog === undefined ? {} : { tools: catalog },\n ...definition.nativeTools.length === 0 ? {} : { nativeTools: definition.nativeTools },\n ...definition.toolChoice === undefined ? {} : { toolChoice: definition.toolChoice },\n ...invocation.imagePolicy === undefined ? {} : { imagePolicy: invocation.imagePolicy },\n ...invocation.documentPolicy === undefined ? {} : { documentPolicy: invocation.documentPolicy },\n ...outputFormat === undefined ? {} : { outputFormat },\n ...(invocation.validateOutput === undefined ? {} : { validateOutput: invocation.validateOutput }),\n system: this.systemInstructions(this.activeAdditionalInstructions),\n maxTurns: definition.maxTurns,\n bounds: {\n maxToolCalls: definition.maxToolCalls,\n ...this.runtimeLimits.maxParallelToolCalls === undefined\n ? {}\n : { maxParallel: this.runtimeLimits.maxParallelToolCalls },\n ...this.runtimeLimits.maxConsecutiveToolErrors === undefined\n ? {}\n : { maxConsecutiveToolErrors: this.runtimeLimits.maxConsecutiveToolErrors },\n ...this.runtimeLimits.repeatToolWarningAt === undefined\n ? {}\n : { repeatToolWarningAt: this.runtimeLimits.repeatToolWarningAt },\n ...this.runtimeLimits.repeatToolLimit === undefined\n ? {}\n : { repeatToolLimit: this.runtimeLimits.repeatToolLimit },\n ...this.runtimeLimits.toolCycleWarningAt === undefined\n ? {}\n : { toolCycleWarningAt: this.runtimeLimits.toolCycleWarningAt },\n ...this.runtimeLimits.toolCycleLimit === undefined\n ? {}\n : { toolCycleLimit: this.runtimeLimits.toolCycleLimit },\n ...this.runtimeLimits.onExhausted === undefined\n ? {}\n : { onExhausted: this.runtimeLimits.onExhausted },\n ...this.runtimeLimits.maxToolResultTokens === undefined\n ? {}\n : { maxToolResultTokens: this.runtimeLimits.maxToolResultTokens },\n ...this.runtimeLimits.toolResultOverflow === undefined\n ? {}\n : { toolResultOverflow: this.runtimeLimits.toolResultOverflow },\n ...this.runtimeLimits.maxToolCycleLength === undefined\n ? {}\n : { maxToolCycleLength: this.runtimeLimits.maxToolCycleLength },\n ...this.runtimeLimits.finalReportReserveTokens === undefined ? {} : {\n finalReportReserveTokens: this.runtimeLimits.finalReportReserveTokens,\n },\n ...this.runtimeLimits.finalizeSteps === undefined ? {} : { finalizeSteps: this.runtimeLimits.finalizeSteps },\n ...this.runtimeLimits.maxTurnDurationMs === undefined ? {} : { maxTurnDurationMs: this.runtimeLimits.maxTurnDurationMs },\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 ...this.runtimeLimits.userInputTimeoutMs === undefined ? {} : { userInputTimeoutMs: this.runtimeLimits.userInputTimeoutMs },\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 ...this.runtimeLimits.userInputTimeoutMs === undefined ? {} : { userInputTimeoutMs: this.runtimeLimits.userInputTimeoutMs },\n })\n }\n return runAgent({ ...common, mode: 'basic' })\n }\n\n private createCompactor(): ContextCompactor | undefined {\n const configured = this.options.compaction === false\n ? false\n : this.options.compaction === undefined\n ? this.definition.compaction\n : resolveCompactionConfig(this.options.compaction)\n if (configured === false) return undefined\n return new ContextCompactor({\n registry: this.options.registry,\n config: () => this.callConfig(this.activeInvocation),\n history: () => this.currentHistory,\n system: () => this.systemInstructions(this.activeAdditionalInstructions),\n pinnedMessages: () => renderRuntimeMemory(\n this.currentMemory, this.definition.memory.maxInjectedChars,\n ),\n tools: () => [\n ...this.effectiveCatalog()?.schemas() ?? [],\n ...this.definition.nativeTools,\n ],\n policy: configured,\n })\n }\n\n private effectiveCatalog(): ToolCatalog | undefined {\n return this.activeRuntimeCatalog ?? this.catalog\n }\n\n private combinedHooks(accounting?: RunAccountingPort): TurnHooks | undefined {\n const user = this.options.hooks\n const hooks: TurnHooks = {\n ...user,\n beforeStep: async context => {\n // Before anything reads history for this request: model-round refreshes\n // its messages when entries changed, so delivered input is included.\n const generation = this.currentHistory.generation()\n const entries = this.currentHistory.entries().length\n this.drainInjections()\n const prepared = this.currentHistory.entries().length === entries\n ? context\n : { ...context, messages: normalizeToolPairing(this.currentHistory.messages()), snapshot: this.currentHistory.snapshot() }\n if (this.compactor !== undefined) bindCompactionAccounting(this.compactor, accounting)\n await this.compactor?.beforeStep(prepared)\n if (accounting?.usageStop !== undefined) return { kind: 'proceed' as const }\n const refreshed = this.currentHistory.generation() === generation && this.currentHistory.entries().length === entries\n ? context\n : {\n ...context,\n messages: normalizeToolPairing(this.currentHistory.messages()),\n snapshot: this.currentHistory.snapshot(),\n }\n const memory = renderRuntimeMemory(\n this.currentMemory, this.definition.memory.maxInjectedChars, accounting,\n )\n const current = memory.length === 0\n ? refreshed\n : { ...refreshed, messages: Object.freeze([...memory, ...refreshed.messages]) }\n const decision = await user?.beforeStep?.(current) ?? { kind: 'proceed' as const }\n if (decision.kind === 'reject') return decision\n // A projection sees injected memory already; do not inject it twice.\n const prepend = [...decision.messages === undefined ? memory : [], ...decision.prepend ?? []]\n return bindStepProjectionSources(prepend.length === 0 ? decision : { ...decision, prepend }, refreshed.messages)\n },\n onRequestError: async context => {\n if (this.compactor !== undefined) bindCompactionAccounting(this.compactor, accounting)\n const recovery = await this.compactor?.onRequestError(context)\n if (accounting?.usageStop !== undefined) return 'fail'\n if (recovery === 'retry') return 'retry'\n return await user?.onRequestError?.(context) ?? 'fail'\n },\n }\n return hooks\n }\n\n private callConfig(invocation?: AgentInvocationOptions) {\n return sessionCallConfig(this.definition, runtimeSessionConfiguration(this), invocation)\n }\n\n private systemInstructions(additionalInstructions?: string): string {\n const base = this.skillCatalog === undefined\n ? this.definition.instructions\n : renderSkillCatalog(\n this.definition.instructions,\n this.skillCatalog.summaries(),\n this.definition.skillOptions,\n )\n const team = this.options.team\n const composed = team === undefined\n ? base\n : `${base}\\n\\n${team.team.instructionsFor(team.name ?? this.definition.id)}`\n return appendRunInstructions(composed, additionalInstructions)\n }\n\n private skillLookup(signal?: AbortSignal): SkillLookupOptions {\n return {\n ...(this.options.skillCwd === undefined ? {} : { cwd: this.options.skillCwd }),\n ...(signal === undefined ? {} : { signal }),\n }\n }\n\n private activationSnapshot(): readonly AgentSessionActivatedSkillSnapshot[] {\n const activated = new Map<string, AgentSessionActivatedSkillSnapshot>()\n for (const entry of this.pendingSkillActivations) activated.set(entry.id, entry)\n for (const reference of this.skillCatalog?.activatedSkillReferences() ?? []) {\n activated.set(reference.id, reference)\n }\n for (const summary of this.skillCatalog?.activatedSummaries() ?? []) {\n if (activated.has(summary.id)) continue\n activated.set(summary.id, Object.freeze({\n id: summary.id, provider: summary.provider, source: summary.source,\n ...summary.resourceBase === undefined ? {} : {\n resourceBase: Object.freeze({ ...summary.resourceBase }),\n },\n }))\n }\n return Object.freeze([...activated.values()].sort((left, right) => left.id.localeCompare(right.id)))\n }\n\n private async prepareSkills(signal?: AbortSignal, accounting?: RunAccountingPort): Promise<void> {\n await prepareSkills(\n this.definition, this.skillCatalog, this.pendingSkillActivations,\n signal => this.skillLookup(signal),\n () => { this.pendingSkillActivations = Object.freeze([]) }, signal, accounting,\n )\n }\n}\n\nexport { configureRuntimeSessionModel, streamRuntimeSession } from './session/runtime-binding.ts'\nexport type {\n AgentInput, AgentRuntimeLimits, AgentSessionOptions, AgentTeamMemberOptions,\n AgentSessionSnapshot, AgentSessionActivatedSkillSnapshot, AgentResumeSessionOptions,\n AgentInvocationOptions, AgentResponse, AgentRunHandle,\n} from './session/types.ts'\n"],"mappings":"w7EAqDA,IAAa,EAAb,MAAa,CAAa,CACxB,WACA,QACA,QACA,qBACA,aACA,cAEA,gBACA,eACA,cACA,sBACA,UACA,wBAAiF,OAAO,OAAO,CAAC,CAAC,EACjG,OAAiB,GACjB,6BAEA,iBACA,YAA+B,IAAI,IAOnC,kBACA,eAMA,cAAwB,GAExB,iBAA2B,GAE3B,YAAY,EAA6B,EAA8B,CACrE,GAAI,EAAW,OAAS,sBAAwB,EAAQ,YAAc,IAAA,GACpE,MAAU,UAAU,UAAU,EAAW,GAAG,yDAAyD,EAEvG,KAAK,WAAa,EAClB,IAAM,EAAgB,EAAQ,gBAAkB,IAAA,GAC5C,IAAA,GACA,OAAO,OAAO,CAAE,GAAG,EAAQ,aAAc,CAAC,EAG1C,EAAQ,UAAY,IAAA,IAAa,IAAkB,IAAA,IAAW,IAAS,EAAQ,CAAa,EAChG,IAAM,EAAa,EAAQ,a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E,GAAI,IAAW,IAAA,GAAY,CAAC,EAAI,CAAE,QAAO,CAC3C,CACF,CAEA,oBAA4E,CAC1E,IAAM,EAAY,IAAI,IACtB,IAAK,IAAM,KAAS,KAAK,wBAAyB,EAAU,IAAI,EAAM,GAAI,CAAK,EAC/E,IAAK,IAAM,KAAa,KAAK,cAAc,yBAAyB,GAAK,CAAC,EACxE,EAAU,IAAI,EAAU,GAAI,CAAS,EAEvC,IAAK,IAAM,KAAW,KAAK,cAAc,mBAAmB,GAAK,CAAC,EAC5D,EAAU,IAAI,EAAQ,EAAE,GAC5B,EAAU,IAAI,EAAQ,GAAI,OAAO,OAAO,CACtC,GAAI,EAAQ,GAAI,SAAU,EAAQ,SAAU,OAAQ,EAAQ,OAC5D,GAAG,EAAQ,eAAiB,IAAA,GAAY,CAAC,EAAI,CAC3C,aAAc,OAAO,OAAO,CAAE,GAAG,EAAQ,YAAa,CAAC,CACzD,CACF,CAAC,CAAC,EAEJ,OAAO,OAAO,OAAO,CAAC,GAAG,EAAU,OAAO,CAAC,CAAC,CAAC,MAAM,EAAM,IAAU,EAAK,GAAG,cAAc,EAAM,EAAE,CAAC,CAAC,CACrG,CAEA,MAAc,cAAc,EAAsB,EAA+C,CAC/F,MAAM,EACJ,KAAK,WAAY,KAAK,aAAc,KAAK,wBACzC,GAAU,KAAK,YAAY,CAAM,MAC3B,CAAE,KAAK,wBAA0B,OAAO,OAAO,CAAC,CAAC,CAAE,EAAG,EAAQ,CACtE,CACF,CACF"}
|
|
@@ -13,7 +13,9 @@ import { ToolCallRequest } from "../tool/pipeline.js";
|
|
|
13
13
|
import { TraceEvent, TraceRef } from "../trace/trace.js";
|
|
14
14
|
import { RunUsageReport } from "../accounting/report.js";
|
|
15
15
|
//#region src/agent/loop/events.d.ts
|
|
16
|
-
type ExhaustedBudget = 'steps' | 'tool-calls' | 'consecutive-tool-errors' | 'repeated-tool-call' | 'tool-call-cycle' | 'tokens'
|
|
16
|
+
type ExhaustedBudget = 'steps' | 'tool-calls' | 'consecutive-tool-errors' | 'repeated-tool-call' | 'tool-call-cycle' | 'tokens' |
|
|
17
|
+
/** `TurnBounds.maxTurnDurationMs` passed; the answer was forced from the evidence so far. */
|
|
18
|
+
'time';
|
|
17
19
|
/**
|
|
18
20
|
* Why a call the model asked for was not run.
|
|
19
21
|
*
|
|
@@ -145,6 +147,15 @@ type AgentEvent = TraceEvent | (AgentMaintenanceEvent & Traced) | ({
|
|
|
145
147
|
readonly type: 'tool-result';
|
|
146
148
|
readonly call: ToolCallRequest;
|
|
147
149
|
readonly result: ToolExecutionResult;
|
|
150
|
+
/** The loop refused the call; no tool body ran. Set by the scheduler, never by a tool. */
|
|
151
|
+
readonly declined?: true;
|
|
152
|
+
/** Answered from this turn's earlier identical result; no tool body ran. */
|
|
153
|
+
readonly recovered?: true;
|
|
154
|
+
/**
|
|
155
|
+
* False when the tool body never ran: declined, recovered, denied by an
|
|
156
|
+
* interceptor or approval, or cancelled before it started.
|
|
157
|
+
*/
|
|
158
|
+
readonly dispatched?: false;
|
|
148
159
|
} & Traced) | ({
|
|
149
160
|
readonly type: 'approval-request';
|
|
150
161
|
readonly request: ApprovalRequest;
|
|
@@ -165,7 +176,19 @@ type AgentEvent = TraceEvent | (AgentMaintenanceEvent & Traced) | ({
|
|
|
165
176
|
} & Traced);
|
|
166
177
|
interface BeforeStepContext {
|
|
167
178
|
readonly turn: number;
|
|
179
|
+
/** Request number in the turn; retried requests take numbers too. */
|
|
168
180
|
readonly step: number;
|
|
181
|
+
/**
|
|
182
|
+
* The work step this request is for, which is what `maxSteps` limits:
|
|
183
|
+
* retried requests do not advance it. Past `maxSteps` the request is the
|
|
184
|
+
* forced answer or the finalize window, where tools are not available for
|
|
185
|
+
* work, so cues tied to a step budget should not be sent there.
|
|
186
|
+
*/
|
|
187
|
+
readonly workStep?: number;
|
|
188
|
+
/** `forced-final`: the tools-off answer a budget forced; `final`: a structured-output finalizer. */
|
|
189
|
+
readonly phase?: 'standard' | 'process' | 'final' | 'forced-final';
|
|
190
|
+
/** Set in the finalize window, where only the mode's confirmation tool runs. */
|
|
191
|
+
readonly finalizing?: true;
|
|
169
192
|
readonly messages: readonly Message[];
|
|
170
193
|
readonly snapshot: HistorySnapshot;
|
|
171
194
|
readonly signal: AbortSignal;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"events.d.ts","names":[],"sources":["../../../src/agent/loop/events.ts"],"mappings":";;;;;;;;;;;;;;;KAgBY
|
|
1
|
+
{"version":3,"file":"events.d.ts","names":[],"sources":["../../../src/agent/loop/events.ts"],"mappings":";;;;;;;;;;;;;;;KAgBY;;;;;;;;;;KAgBA,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;WAEzD;WAA8B,MAAM;WAA0B,QAAQ;;WAEtE;;WAEA;;;;;WAKA;IACP;WACU;WAAmC,SAAS;IAAoB;WAChE;WAAwB,OAAO;IAAe;WAC9C;WAAiC,OADa;WACuD;IAAuB;WAC5H;WAA2B;WAAuB;IAAiB;WACnE;WAA2B,SAAS;IAAgB;UAEnD;WACN;;WAEA;;;;;;;WAOA;;WAEA;;WAEA;WACA,mBAAmB;WACnB,UAAU;WACV,QAAQ;WACR,SAAS;EAClB,KAAK,OAAO,wBAAwB;;KAE1B;WACG;WAA0B,mBAAmB;;WAE7C,oBAAoB;;WACpB;WAAyB;;UACvB;WACN;WACA;WACA,SAAS;WACT,UAAU;WACV,QAAQ;WACR,SAAS;EAClB,KAAK,OAAO,wBAAwB;;KAE1B;WACG;WAAuC,SAAS;WAA0B,UAAU;WACpF,SAAS;WAAsB,SAAS;;WACxC;WAAuC,MAAM;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"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"run-turn.d.ts","names":[],"sources":["../../../src/agent/loop/run-turn.ts"],"mappings":";;;;
|
|
1
|
+
{"version":3,"file":"run-turn.d.ts","names":[],"sources":["../../../src/agent/loop/run-turn.ts"],"mappings":";;;;iBA8BgB,QAAQ,SAAS,iBAAiB,cAAc"}
|