@arnilo/prism 0.3.2 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (208) hide show
  1. package/CHANGELOG.md +50 -1
  2. package/README.md +42 -62
  3. package/dist/agent-run-lifecycle.js +4 -0
  4. package/dist/agent-run-state.d.ts +5 -2
  5. package/dist/agent-run-state.js +18 -8
  6. package/dist/agent-session/session/assemble.d.ts +6 -0
  7. package/dist/agent-session/session/assemble.js +391 -0
  8. package/dist/agent-session/session/persist.d.ts +28 -0
  9. package/dist/agent-session/session/persist.js +166 -0
  10. package/dist/agent-session/session/provider-round.d.ts +6 -0
  11. package/dist/agent-session/session/provider-round.js +231 -0
  12. package/dist/agent-session/session/tool-round.d.ts +31 -0
  13. package/dist/agent-session/session/tool-round.js +473 -0
  14. package/dist/agent-session/session/types.d.ts +115 -0
  15. package/dist/agent-session/session/types.js +5 -0
  16. package/dist/agent-session/session.d.ts +54 -41
  17. package/dist/agent-session/session.js +23 -1132
  18. package/dist/capture.d.ts +63 -0
  19. package/dist/capture.js +67 -0
  20. package/dist/cli-dev.d.ts +29 -0
  21. package/dist/cli-dev.js +52 -0
  22. package/dist/cli-init.d.ts +34 -3
  23. package/dist/cli-init.js +192 -24
  24. package/dist/cli-runner.d.ts +6 -2
  25. package/dist/cli-runner.js +57 -10
  26. package/dist/content.d.ts +3 -3
  27. package/dist/content.js +3 -1
  28. package/dist/contracts-core/agent.d.ts +8 -0
  29. package/dist/contracts-core/batch.d.ts +97 -0
  30. package/dist/contracts-core/batch.js +65 -0
  31. package/dist/contracts-core/content.d.ts +72 -1
  32. package/dist/contracts-core/embeddings.d.ts +30 -0
  33. package/dist/contracts-core/embeddings.js +17 -0
  34. package/dist/contracts-core/images.d.ts +60 -0
  35. package/dist/contracts-core/images.js +17 -0
  36. package/dist/contracts-core/moderation.d.ts +46 -0
  37. package/dist/contracts-core/moderation.js +34 -0
  38. package/dist/contracts-core/speech.d.ts +39 -0
  39. package/dist/contracts-core/speech.js +17 -0
  40. package/dist/contracts-core/transcription.d.ts +48 -0
  41. package/dist/contracts-core/transcription.js +17 -0
  42. package/dist/contracts-core/video.d.ts +61 -0
  43. package/dist/contracts-core/video.js +17 -0
  44. package/dist/contracts-core.d.ts +7 -0
  45. package/dist/contracts-core.js +7 -0
  46. package/dist/contracts-protocol.d.ts +18 -0
  47. package/dist/contracts-run-state.d.ts +1 -2
  48. package/dist/index.d.ts +7 -3
  49. package/dist/index.js +5 -3
  50. package/dist/input.d.ts +8 -0
  51. package/dist/input.js +4 -0
  52. package/dist/node/agent-definitions.d.ts +1 -8
  53. package/dist/node/agent-definitions.js +0 -34
  54. package/dist/node/settings.d.ts +0 -1
  55. package/dist/node/settings.js +0 -5
  56. package/dist/pinned-fetch.js +29 -3
  57. package/dist/provider-events.js +3 -4
  58. package/dist/providers/media.d.ts +1 -2
  59. package/dist/providers/media.js +1 -4
  60. package/dist/rpc.d.ts +1 -1
  61. package/dist/rpc.js +4 -4
  62. package/dist/testing/persistence-schema.d.ts +1 -1
  63. package/dist/testing/persistence-schema.js +32 -28
  64. package/dist/testing/provider-conformance.d.ts +114 -5
  65. package/dist/testing/provider-conformance.js +342 -0
  66. package/dist/testing/tool-conformance.d.ts +25 -0
  67. package/dist/testing/tool-conformance.js +128 -1
  68. package/dist/testing/tool-effect-store-conformance.d.ts +0 -1
  69. package/dist/testing/tool-effect-store-conformance.js +0 -3
  70. package/dist/thinking.d.ts +48 -9
  71. package/dist/thinking.js +134 -8
  72. package/dist/tool-search.d.ts +76 -0
  73. package/dist/tool-search.js +199 -0
  74. package/docs/0.1.0-readiness.md +3 -3
  75. package/docs/a2a.md +2 -2
  76. package/docs/acp-agent.md +1 -1
  77. package/docs/acp.md +3 -3
  78. package/docs/ag-ui-adoption.md +1 -1
  79. package/docs/ag-ui.md +1 -2
  80. package/docs/agent-definitions.md +1 -1
  81. package/docs/agent-events.md +5 -5
  82. package/docs/agent-identity.md +13 -2
  83. package/docs/audit-export.md +3 -3
  84. package/docs/batch-jobs.md +120 -0
  85. package/docs/browser-automation.md +5 -5
  86. package/docs/caveman.md +2 -2
  87. package/docs/cli-rpc.md +43 -9
  88. package/docs/coding-agent-tools.md +19 -19
  89. package/docs/coding-review-and-diagnostics.md +2 -2
  90. package/docs/coding-security.md +5 -5
  91. package/docs/coding-tools.md +82 -0
  92. package/docs/coding-workspaces.md +2 -2
  93. package/docs/compaction-and-retry.md +2 -2
  94. package/docs/compaction-llm.md +4 -4
  95. package/docs/compaction-observational-memory.md +3 -3
  96. package/docs/computer-use-linux.md +13 -2
  97. package/docs/context-and-skills.md +3 -1
  98. package/docs/conversations.md +4 -4
  99. package/docs/core.md +85 -0
  100. package/docs/credential-storage.md +12 -8
  101. package/docs/credentials-and-redaction.md +1 -1
  102. package/docs/data-classification.md +1 -1
  103. package/docs/database-persistence.md +7 -3
  104. package/docs/dev-inspector.md +103 -0
  105. package/docs/device-adapters.md +2 -2
  106. package/docs/diagrams.md +247 -0
  107. package/docs/document-reader.md +6 -6
  108. package/docs/documents.md +214 -0
  109. package/docs/embeddings.md +112 -0
  110. package/docs/enterprise-postgres-state.md +7 -7
  111. package/docs/evaluations.md +41 -7
  112. package/docs/extensions.md +3 -3
  113. package/docs/forge-integration.md +3 -3
  114. package/docs/graft.md +5 -5
  115. package/docs/guardrails.md +2 -2
  116. package/docs/host-security.md +16 -15
  117. package/docs/image-generation.md +129 -0
  118. package/docs/impeccable.md +7 -5
  119. package/docs/index.md +84 -46
  120. package/docs/indexed-code-search.md +2 -2
  121. package/docs/language-intelligence.md +4 -4
  122. package/docs/live-testing.md +126 -0
  123. package/docs/mcp-tools.md +44 -13
  124. package/docs/middleware-hooks.md +1 -1
  125. package/docs/migrate-to-0.4.md +312 -0
  126. package/docs/migrate-to-0.5.md +122 -0
  127. package/docs/migration.md +51 -1
  128. package/docs/model-registry.md +38 -0
  129. package/docs/model-routing.md +6 -6
  130. package/docs/moderation.md +117 -0
  131. package/docs/multi-agent-patterns.md +177 -0
  132. package/docs/multimodal-content.md +27 -3
  133. package/docs/obscura.md +12 -12
  134. package/docs/observability.md +32 -7
  135. package/docs/openapi-tools.md +14 -4
  136. package/docs/operations.md +11 -0
  137. package/docs/performance.md +30 -10
  138. package/docs/persistence-credentials-multimodality-primitives.md +7 -7
  139. package/docs/policy-and-audit.md +18 -8
  140. package/docs/ponytail.md +3 -3
  141. package/docs/postgres-persistence.md +5 -5
  142. package/docs/process-sessions.md +2 -2
  143. package/docs/prompt-registry.md +106 -0
  144. package/docs/provider-caching.md +36 -32
  145. package/docs/provider-conformance.md +24 -2
  146. package/docs/provider-packages.md +58 -22
  147. package/docs/provider-primitives.md +5 -5
  148. package/docs/provider-request-policies.md +1 -1
  149. package/docs/providers/ai-sdk.md +18 -6
  150. package/docs/providers/alibaba.md +10 -6
  151. package/docs/providers/anthropic.md +10 -6
  152. package/docs/providers/azure.md +20 -4
  153. package/docs/providers/bedrock.md +18 -3
  154. package/docs/providers/clinepass.md +7 -3
  155. package/docs/providers/commandcode.md +253 -0
  156. package/docs/providers/deepseek.md +7 -3
  157. package/docs/providers/google.md +8 -4
  158. package/docs/providers/hyper.md +284 -0
  159. package/docs/providers/kimi.md +7 -3
  160. package/docs/providers/neuralwatt.md +12 -8
  161. package/docs/providers/ollama.md +18 -3
  162. package/docs/providers/openai-compatible.md +5 -1
  163. package/docs/providers/openai.md +9 -5
  164. package/docs/providers/opencode-go.md +8 -4
  165. package/docs/providers/openrouter.md +8 -4
  166. package/docs/providers/vertex.md +21 -5
  167. package/docs/providers/xai.md +7 -3
  168. package/docs/providers/zai.md +7 -3
  169. package/docs/rag.md +31 -9
  170. package/docs/release-and-install.md +181 -76
  171. package/docs/resource-loading.md +1 -1
  172. package/docs/runs-and-usage.md +28 -3
  173. package/docs/server.md +94 -5
  174. package/docs/settings-auth-trust-security.md +7 -5
  175. package/docs/sheets.md +229 -0
  176. package/docs/speech.md +126 -0
  177. package/docs/sqlite-persistence.md +4 -4
  178. package/docs/supervisors.md +4 -3
  179. package/docs/thinking-and-reasoning.md +93 -60
  180. package/docs/tool-conformance.md +28 -3
  181. package/docs/tool-execution-primitives.md +8 -8
  182. package/docs/tools.md +32 -5
  183. package/docs/web-tools.md +3 -3
  184. package/docs/wiki.md +7 -7
  185. package/docs/work-artifacts-and-review.md +17 -6
  186. package/docs/work-connectors.md +4 -4
  187. package/docs/work-tools.md +5 -5
  188. package/docs/workflow-orchestration-primitives.md +35 -11
  189. package/docs/workflows.md +74 -13
  190. package/docs/working-and-semantic-memory.md +53 -5
  191. package/package.json +14 -31
  192. package/templates/README.md +23 -0
  193. package/templates/deep-research/README.md.tmpl +47 -0
  194. package/templates/deep-research/env.example.tmpl +12 -0
  195. package/templates/deep-research/gitignore.tmpl +7 -0
  196. package/templates/deep-research/manifest.json +12 -0
  197. package/templates/deep-research/package.json.tmpl +23 -0
  198. package/templates/deep-research/src/agent.ts.tmpl +81 -0
  199. package/templates/deep-research/src/index.ts.tmpl +53 -0
  200. package/templates/deep-research/src/tests/research.test.ts.tmpl +114 -0
  201. package/templates/deep-research/src/tools.ts.tmpl +86 -0
  202. package/templates/deep-research/src/types.ts.tmpl +45 -0
  203. package/templates/deep-research/src/workflow.ts.tmpl +156 -0
  204. package/templates/deep-research/tsconfig.json.tmpl +15 -0
  205. package/templates/init/manifest.json +5 -0
  206. package/templates/init/package.json.tmpl +2 -1
  207. package/templates/init/providers.json +40 -24
  208. package/docs/antigravity-agent.md +0 -207
@@ -1,32 +1,20 @@
1
1
  /** session (0.2.5 plan 025 Task 1 split). Moved verbatim from agent-session.ts; public surface unchanged behind the barrel. */
2
- import { AgentRunSuspended, decisionIdentityRef, decisionScopesEqual, nestedApprovalId, nestedOutcomeToolResult, pathsEqual, } from "../agent-approval.js";
3
- import { resolveLoop, resolveToolConcurrency } from "../agent-loops.js";
4
- import { boundedLoopSnapshot, initialAgentRunState, publicState, saveAgentRunState, validateRunStateOptions } from "../agent-run-state.js";
5
- import { activeTools, policyList, toolElicitationRequest } from "../agent-tool-dispatch.js";
2
+ import { policyList } from "../agent-tool-dispatch.js";
6
3
  import { createDefaultCompactionStrategy, isCompactionEntryData } from "../compaction.js";
7
- import { AgentDecisionError, AgentDelegationSuspendedError, AgentLoopStateError, AgentRunError, AgentRunStateError, DEFAULT_MAX_PENDING_DECISIONS, DEFAULT_MAX_PENDING_STEER_BYTES, DEFAULT_MAX_PENDING_STEERS, HARD_MAX_PENDING_DECISIONS, MAX_ATTRIBUTION_DEPTH, } from "../contracts.js";
8
- import { assertGuardrailsAllowed, GuardrailError, runGuardrails } from "../guardrails.js";
9
- import { identityTelemetryAttributes, ownershipFromIdentity, resolveRunIdentity } from "../identity.js";
10
- import { assembleProviderInput } from "../input.js";
11
- import { createProviderTurnMetadata, readProviderHttpStatus } from "../observability.js";
12
- import { providerToolCallDeltaContent } from "../provider-events.js";
4
+ import { DEFAULT_MAX_PENDING_STEER_BYTES, DEFAULT_MAX_PENDING_STEERS } from "../contracts.js";
5
+ import { GuardrailError, runGuardrails } from "../guardrails.js";
13
6
  import { createProviderRequestPolicyChain, normalizeProviderRequestPolicyResult } from "../provider-request-policy.js";
14
- import { errorToErrorInfo, redactAgentEvent, redactProviderRequest, redactRunLedgerRecord, redactSecrets, redactSessionEntry, } from "../redaction.js";
15
- import { createDefaultRetryPolicy, waitForRetry } from "../retry.js";
16
- import { isFlushableRunLedger } from "../run-ledger.js";
17
- import { RunLimitError, RunLimitTracker, resolveRunLimits } from "../run-limits.js";
7
+ import { redactAgentEvent, redactProviderRequest, redactRunLedgerRecord, redactSecrets, redactSessionEntry } from "../redaction.js";
18
8
  import { createMemorySessionStore, createSessionEntry, getSessionBranchEntries, rebuildSessionContext } from "../session-stores.js";
19
- import { createLoadedSkillSet, resolveSkillsDisclosure } from "../skill-disclosure.js";
20
- import { applyRestoredSkillBodies, snapshotLoadedSkillBodies, validateLoadedSkillBodies } from "../skill-load.js";
9
+ import { createLoadedSkillSet } from "../skill-disclosure.js";
10
+ import { validateLoadedSkillBodies } from "../skill-load.js";
21
11
  import { resolveActiveSkills } from "../skills.js";
22
- import { assertStructuredOutputRequestSupported, resolveRunProviderOptions } from "../structured-output.js";
23
- import { composeSystemPrompt, mergeSystemPromptConfig } from "../system-prompts.js";
24
- import { canonicalToolEffectJson, toolEffectArgumentsHash } from "../tool-effects.js";
25
- import { resolveToolResultFold } from "../tool-result-fold.js";
26
- import { dispatchToolCall, resolveToolEffectDeclaration } from "../tools.js";
12
+ import { createActiveToolSet } from "../tool-search.js";
27
13
  import { createAgentSession } from "./create-agent.js";
28
14
  import { EventSubscriber } from "./event-subscriber.js";
29
- import { bridgeAbort, createUsageAccumulator, errorFromInfo, finalAssistantMessage, inputToMessages, isDurableLoop, isSteerSoftInterrupt, jsonBytes, mergeCompaction, mergeGuardrails, mergeRetry, messageTextBytes, ProviderTurnFailure, providerContent, randomId, reconstructMissingToolCalls, SteerSoftInterrupt, throwIfAborted, throwIfAbortedSignal, withoutTrailingInput, } from "./helpers.js";
15
+ import { finalAssistantMessage, inputToMessages, mergeCompaction, messageTextBytes, randomId, SteerSoftInterrupt, throwIfAborted, throwIfAbortedSignal, withoutTrailingInput, } from "./helpers.js";
16
+ import { executeRun } from "./session/assemble.js";
17
+ import { asSessionHost } from "./session/types.js";
30
18
  export class RuntimeAgentSession {
31
19
  id;
32
20
  agent;
@@ -50,6 +38,7 @@ export class RuntimeAgentSession {
50
38
  activeIdempotencyKey;
51
39
  activeGuardrails;
52
40
  activeMetadata;
41
+ activePromptVersion;
53
42
  activeLimits;
54
43
  activeLimitOutputBuffer = false;
55
44
  activeDurable;
@@ -58,6 +47,8 @@ export class RuntimeAgentSession {
58
47
  activeGatedRound;
59
48
  activeLoopTurn = 1;
60
49
  loadedSkills = createLoadedSkillSet();
50
+ /** Tools activated via `search_tools` this session (plan 041); names-only in persistence. */
51
+ activatedTools = createActiveToolSet();
61
52
  /** Plan 018 Task 6 (closeout `checkpoint-bodies`): persisted exact instructions, registry-independent. */
62
53
  restoredSkillBodies = [];
63
54
  /** Skills of the current run (for the bodies snapshot); replaced at each run start. */
@@ -67,6 +58,15 @@ export class RuntimeAgentSession {
67
58
  for (const name of names)
68
59
  this.loadedSkills.add(name);
69
60
  }
61
+ /** Plan 041: re-add persisted activated-tool names (names only; inert for absent tools). */
62
+ restoreActivatedTools(names) {
63
+ for (const name of names)
64
+ this.activatedTools.add(name);
65
+ }
66
+ /** Plan 041: host reset of search-activated tools. */
67
+ clearActivatedTools() {
68
+ this.activatedTools.clear();
69
+ }
70
70
  /** Plan 018 Task 6: restore persisted loaded-skill bodies (already validated fail-closed at load). */
71
71
  restoreLoadedSkillBodies(bodies) {
72
72
  validateLoadedSkillBodies(bodies);
@@ -160,790 +160,7 @@ export class RuntimeAgentSession {
160
160
  }
161
161
  }
162
162
  async runInternal(input, options, runId, resumed) {
163
- // 0.1.5 breaking cut: the deprecated RunOptions.maxToolRounds alias was removed. Reject
164
- // untyped/legacy input fail-closed before any session mutation, provider call, or tool
165
- // execution; silently honoring it would widen or mis-apply the intended tool-round cap.
166
- const legacyMaxToolRounds = options.maxToolRounds;
167
- if (legacyMaxToolRounds !== undefined) {
168
- throw new TypeError("RunOptions.maxToolRounds was removed in 0.1.5; use RunOptions.limits.maxToolRounds instead");
169
- }
170
- if (this.agent.config.secure &&
171
- (options.redactor !== undefined ||
172
- options.ownership !== undefined ||
173
- options.validate !== undefined ||
174
- options.effectStore !== undefined ||
175
- options.runState !== undefined)) {
176
- throw new AgentRunStateError("Secure agent defaults cannot be replaced per run");
177
- }
178
- const requestedLimits = options.limits;
179
- const resolvedLimits = resolveRunLimits(this.agent.config.limits, requestedLimits);
180
- const durableOptions = options.runState ?? this.agent.config.runState;
181
- if (this.agent.config.runState && options.runState && this.agent.config.runState !== options.runState) {
182
- throw new AgentRunStateError("RunOptions cannot replace agent durable run-state configuration");
183
- }
184
- if (durableOptions) {
185
- validateRunStateOptions(durableOptions);
186
- if (options.model || options.guardrails || options.loop || options.effectStore)
187
- throw new AgentRunStateError("Durable runs require model, guardrails, loop, and effect store on AgentConfig for fingerprinting");
188
- const configuredLoop = this.agent.config.loop;
189
- if (configuredLoop && !isDurableLoop(configuredLoop)) {
190
- throw new AgentLoopStateError("ERR_PRISM_LOOP_NOT_DURABLE", "Custom AgentLoopStrategy on a durable run requires snapshot and restore hooks");
191
- }
192
- }
193
- if (this.activeRun) {
194
- const error = new Error("Agent session already has an active run");
195
- this.emit({ type: "error", sessionId: this.id, runId, error: errorToErrorInfo(error) });
196
- throw error;
197
- }
198
- const controller = new AbortController();
199
- const cleanupSignal = bridgeAbort(options.signal, controller);
200
- this.activeRun = controller;
201
- this.activeRunId = runId;
202
- this.pendingSteers = [];
203
- this.pendingSteerBytes = 0;
204
- this.pendingSoftInterrupt = false;
205
- this.activeRedactor = options.redactor ?? this.agent.config.redactor;
206
- this.activeLedger = options.runLedger ?? this.agent.config.runLedger;
207
- this.activeEffectStore = options.effectStore ?? this.agent.config.effectStore;
208
- this.activeOwnership = options.ownership ?? this.agent.config.ownership;
209
- this.activeIdentity = resolveRunIdentity(options.identity, this.agent.config.identity, this.activeOwnership);
210
- if (this.activeIdentity && !this.activeOwnership)
211
- this.activeOwnership = ownershipFromIdentity(this.activeIdentity);
212
- this.activeIdempotencyKey = options.idempotencyKey ?? this.agent.config.idempotencyKey;
213
- this.activeGuardrails = mergeGuardrails(this.agent.config.guardrails, options.guardrails);
214
- this.activeDurable = resumed ?? (durableOptions ? { options: durableOptions, version: 0 } : undefined);
215
- this.activeGatedRound = undefined;
216
- if (resumed)
217
- this.invalidateSnapshot();
218
- const model = options.model ?? this.agent.config.model;
219
- const startedAt = new Date().toISOString();
220
- let runError;
221
- let runStatus = "succeeded";
222
- const runUsage = createUsageAccumulator();
223
- let usage;
224
- const metadata = {
225
- ...this.agent.config.metadata,
226
- ...this.metadata,
227
- ...options.metadata,
228
- ...(this.activeIdentity ? identityTelemetryAttributes(this.activeIdentity) : {}),
229
- };
230
- this.activeMetadata = metadata;
231
- const limits = new RunLimitTracker(resolvedLimits, {
232
- onExceeded: (breach) => {
233
- this.emit({ type: "run_limit_exceeded", sessionId: this.id, runId, breach });
234
- controller.abort(new RunLimitError(breach));
235
- },
236
- snapshot: resumed?.state?.counters,
237
- deadlineAt: resumed?.state?.deadlineAt,
238
- });
239
- this.activeLimits = limits;
240
- this.activeLimitOutputBuffer = [this.agent.config.limits, requestedLimits].some((value) => value?.maxOutputTokens !== undefined || value?.maxTotalTokens !== undefined || value?.maxCost !== undefined);
241
- try {
242
- this.resolveRunProvider(options);
243
- throwIfAborted(controller.signal);
244
- this.emit({ type: "agent_started", sessionId: this.id, runId });
245
- if (resumed)
246
- this.emit({ type: "agent_resumed", sessionId: this.id, runId, version: resumed.version });
247
- const startRecord = {
248
- id: runId,
249
- sessionId: this.id,
250
- branchId: this.currentLeafId,
251
- model,
252
- provider: model.provider,
253
- idempotencyKey: this.activeIdempotencyKey,
254
- status: "running",
255
- startedAt,
256
- ...this.activeOwnership,
257
- };
258
- await this.activeLedger?.appendRun(redactRunLedgerRecord(startRecord, this.activeRedactor));
259
- await this.rebuildHistory();
260
- const { registry, tools } = activeTools(this.agent.config.tools);
261
- const activeSkills = this.resolveRunSkills(options, tools);
262
- this.activeRunSkills = activeSkills; // for the durable bodies snapshot (plan 018 Task 6)
263
- if (options.model && JSON.stringify(options.model) !== JSON.stringify(this.agent.config.model)) {
264
- await this.appendEntry(createSessionEntry({
265
- sessionId: this.id,
266
- parentId: this.currentLeafId,
267
- runId,
268
- kind: "model_change",
269
- previousModel: this.agent.config.model,
270
- model: options.model,
271
- }));
272
- }
273
- const inputMessages = inputToMessages(input).map((message) => this.redact(message));
274
- const inputGuardrails = await runGuardrails({
275
- stage: "input",
276
- guardrails: this.activeGuardrails,
277
- value: inputMessages,
278
- context: { sessionId: this.id, runId, metadata, signal: controller.signal },
279
- redactor: this.activeRedactor,
280
- emit: (event) => this.emit(event),
281
- });
282
- // Input-guardrail decision table:
283
- // - interrupt + durable + fresh run → suspend for approval.
284
- // - interrupt + durable + resumed run → proceed: resuming IS the operator approval.
285
- // - interrupt without durable, or block/tripwire → fail via assertGuardrailsAllowed.
286
- const approvedByResume = resumed !== undefined && inputGuardrails.terminal?.action === "interrupt" && this.activeDurable !== undefined;
287
- if (inputGuardrails.terminal?.action === "interrupt" && this.activeDurable && !approvedByResume) {
288
- const interruption = { kind: "input_guardrail", reason: inputGuardrails.terminal.reason ?? "Input requires approval" };
289
- throw new AgentRunSuspended(await this.suspendDurable({ runId, model, limits, interruption, messages: inputMessages }), interruption);
290
- }
291
- if (inputGuardrails.terminal && !approvedByResume)
292
- assertGuardrailsAllowed(inputGuardrails);
293
- for (const message of inputMessages)
294
- await this.appendMessage(message, runId);
295
- await this.autoCompact(runId, options, controller.signal, inputMessages);
296
- const maxToolRounds = resolvedLimits.maxToolRounds;
297
- const systemInstructions = composeSystemPrompt(mergeSystemPromptConfig(this.agent.config.systemPrompt, options.systemPrompt), {
298
- base: this.agent.config.instructions,
299
- });
300
- const contextProviders = [
301
- ...(this.agent.config.context ?? []),
302
- // ponytail: skill context after host context; no per-skill token budget yet.
303
- ...activeSkills.flatMap((skill) => skill.context ?? []),
304
- ];
305
- const providerOptions = resolveRunProviderOptions(options, this.agent.config);
306
- assertStructuredOutputRequestSupported(options.model ?? this.agent.config.model, providerOptions);
307
- const validate = options.validate ?? this.agent.config.validator;
308
- // ponytail: RunOptions.instructionInjectors overrides AgentConfig.instructionInjectors (mirrors validate/loop).
309
- const instructionInjectors = options.instructionInjectors ?? this.agent.config.instructionInjectors ?? [];
310
- const inputLayout = options.inputLayout ?? this.agent.config.inputLayout;
311
- const loop = resolveLoop(options, this.agent.config);
312
- this.activeLoop = loop;
313
- const toolConcurrency = resolveToolConcurrency(options, this.agent.config);
314
- this.activeLoopTurn = 1;
315
- const recordProviderUsage = async (turnUsage, turn, attempt) => {
316
- limits.recordUsage(turnUsage);
317
- if (!turnUsage)
318
- return;
319
- runUsage.add(turnUsage);
320
- if (!this.activeLedger)
321
- return;
322
- const usageRecord = {
323
- id: randomId("usage"),
324
- sessionId: this.id,
325
- runId,
326
- scope: "provider_turn",
327
- turn,
328
- attempt,
329
- usage: turnUsage,
330
- recordedAt: new Date().toISOString(),
331
- ...this.activeOwnership,
332
- };
333
- await this.activeLedger.appendUsage(redactRunLedgerRecord(usageRecord, this.activeRedactor));
334
- };
335
- // Suspends the run when a round recorded gated calls. Fires at the next provider turn
336
- // (generate) or after the loop ends, so ungated round siblings dispatch first.
337
- const suspendGatedRound = async () => {
338
- const gated = this.activeGatedRound;
339
- if (!gated?.size)
340
- return;
341
- const entries = [...gated.values()];
342
- const decisions = entries.map((gatedCall) => gatedCall.decision);
343
- const single = decisions.length === 1 ? decisions[0] : undefined;
344
- const interruption = {
345
- kind: single?.kind === "elicitation" ? "elicitation" : "tool_approval",
346
- reason: single ? single.reason : `${decisions.length} tool side effects require approval`,
347
- ...(single?.toolCallId ? { toolCallId: single.toolCallId } : {}),
348
- ...(single?.scope.toolName ? { toolName: single.scope.toolName } : {}),
349
- pendingDecisions: decisions,
350
- };
351
- throw new AgentRunSuspended(await this.suspendDurable({ runId, model, limits, interruption, pendingCalls: entries.map((gatedCall) => gatedCall.entry) }), interruption);
352
- };
353
- // Suspends on a nested run's pending decisions, merging any still-ready round entries
354
- // (with their decisions attached) so a nested signal mid-replay never drops own work.
355
- const suspendNested = async (nested) => {
356
- const state = this.activeDurable?.state;
357
- const kept = (state?.pendingCalls ?? [])
358
- .filter((entry) => entry.status === "ready")
359
- .map((entry) => {
360
- const decision = entry.decision ?? resumed?.decisions?.get(entry.approvalId);
361
- return decision ? { ...entry, decision } : entry;
362
- });
363
- const gated = [...(this.activeGatedRound?.values() ?? [])];
364
- const pendingCalls = [
365
- ...kept,
366
- ...gated.map((gatedCall) => gatedCall.entry),
367
- { call: nested.toolCall, status: "ready", approvalId: `nr_${nested.entry.runId}` },
368
- ];
369
- const keptIds = new Set(kept.map((entry) => entry.approvalId));
370
- const decisions = [
371
- ...(state?.interruption?.pendingDecisions ?? []).filter((pending) => keptIds.has(pending.approvalId)),
372
- ...gated.map((gatedCall) => gatedCall.decision),
373
- ...nested.pending,
374
- ];
375
- if (decisions.length > HARD_MAX_PENDING_DECISIONS) {
376
- throw new AgentDecisionError("ERR_PRISM_DECISION_LIMIT", `Pending decisions exceed ${HARD_MAX_PENDING_DECISIONS} per run`);
377
- }
378
- const single = decisions.length === 1 ? decisions[0] : undefined;
379
- const interruption = {
380
- kind: single?.kind ?? "tool_approval",
381
- reason: single ? single.reason : `${decisions.length} approval request(s) need a decision`,
382
- ...(single?.toolCallId ? { toolCallId: single.toolCallId } : {}),
383
- ...(single?.scope.toolName ? { toolName: single.scope.toolName } : {}),
384
- pendingDecisions: decisions,
385
- };
386
- throw new AgentRunSuspended(await this.suspendDurable({
387
- runId,
388
- model,
389
- limits,
390
- interruption,
391
- pendingCalls,
392
- nestedRuns: [...(state?.nestedRuns ?? []), nested.entry],
393
- }), interruption);
394
- };
395
- // Converts a nested-run suspension into either root-visible pending decisions (hashed,
396
- // attributed approval ids) or — when a root sticky covers every surfaced decision and a
397
- // hook is available — an immediate child resume loop ending in a synthesized tool result.
398
- const applyNestedRun = async (input) => {
399
- let current = input.pending;
400
- // ponytail: sticky auto-apply only when the whole surfaced set is covered; mixed sets
401
- // surface to the host. Hook round-trips capped at 4 per suspension event.
402
- for (let depth = 0;; depth += 1) {
403
- const attributed = current.map((decision) => {
404
- const id = nestedApprovalId(input.ref.runId, decision.approvalId);
405
- return {
406
- id,
407
- childApprovalId: decision.approvalId,
408
- decision: { ...decision, approvalId: id, attribution: decision.attribution ?? { path: input.path } },
409
- };
410
- });
411
- if (attributed.some(({ decision }) => (decision.attribution?.path.length ?? 0) > MAX_ATTRIBUTION_DEPTH)) {
412
- throw new AgentDecisionError("ERR_PRISM_DECISION_LIMIT", `Attribution path exceeds ${MAX_ATTRIBUTION_DEPTH} entries`);
413
- }
414
- const allSticky = attributed.length > 0 && attributed.every(({ decision }) => this.matchNestedSticky(decision) !== undefined);
415
- if (!input.hook || !allSticky || depth >= 4) {
416
- return {
417
- entry: {
418
- runId: input.ref.runId,
419
- ...(input.ref.sessionId ? { sessionId: input.ref.sessionId } : {}),
420
- toolCallId: input.toolCall.id,
421
- path: attributed[0]?.decision.attribution?.path ?? input.path,
422
- approvals: attributed.map(({ id, childApprovalId }) => ({ id, childApprovalId })),
423
- },
424
- pending: attributed.map(({ decision }) => decision),
425
- };
426
- }
427
- const outcome = await input.hook({ ref: input.ref, toolCallId: input.toolCall.id, path: input.path }, attributed.map(({ childApprovalId, decision }) => {
428
- const sticky = this.matchNestedSticky(decision);
429
- return {
430
- approvalId: childApprovalId,
431
- outcome: sticky.outcome,
432
- ...(sticky.reason !== undefined ? { reason: sticky.reason } : {}),
433
- };
434
- }));
435
- if (outcome.status === "suspended") {
436
- current = outcome.pendingDecisions;
437
- continue;
438
- }
439
- return { toolResult: nestedOutcomeToolResult(outcome, input.toolCall.id, input.toolCall.name) };
440
- }
441
- };
442
- // ponytail: LoopContext binds existing private helpers; loop orchestrates only.
443
- let assembledTurn = false;
444
- let artifactFinished = false;
445
- let artifactFailedInfo;
446
- const ctx = {
447
- sessionId: this.id,
448
- runId,
449
- metadata,
450
- signal: controller.signal,
451
- history: this.history,
452
- input,
453
- inputMessages,
454
- maxToolRounds,
455
- toolConcurrency,
456
- restoredLoopState: resumed?.state?.loopState?.snapshot,
457
- assemble: async (nextInput, toolResults, turn) => {
458
- limits.charge("maxTurns");
459
- const request = await assembleProviderInput({
460
- model: options.model ?? this.agent.config.model,
461
- input: nextInput,
462
- history: this.history,
463
- summaries: (await this.snapshot()).summaries,
464
- toolResults: toolResults ?? [],
465
- turn,
466
- instructionInjectors,
467
- inputLayout,
468
- systemInstructions,
469
- inputBuilder: this.agent.config.inputBuilder,
470
- promptBuilder: this.agent.config.promptBuilder,
471
- contextProviders,
472
- skills: this.restoredSkillBodies.length ? applyRestoredSkillBodies(activeSkills, this.restoredSkillBodies) : activeSkills,
473
- skillsDisclosure: resolveSkillsDisclosure(options.skillsDisclosure, this.agent.config.skillsDisclosure),
474
- toolResultFold: resolveToolResultFold(options.toolResultFold, this.agent.config.toolResultFold),
475
- loadedSkills: this.loadedSkills,
476
- tools,
477
- resourceLoader: this.agent.config.resourceLoader,
478
- permission: this.agent.config.permission,
479
- trust: this.agent.config.trust,
480
- providerOptions,
481
- redactor: this.activeRedactor,
482
- middleware: this.agent.config.middleware,
483
- sessionId: this.id,
484
- runId,
485
- metadata,
486
- signal: controller.signal,
487
- });
488
- assembledTurn = true;
489
- return request;
490
- },
491
- chargeToolRound: (calls) => {
492
- if (calls.length > 0)
493
- limits.charge("maxToolRounds");
494
- const durable = this.activeDurable;
495
- if (!durable?.options.interruptBeforeTool || calls.length === 0)
496
- return;
497
- // Round-level gate: record one pending decision per uncovered gated call. Ungated
498
- // and sticky-allowed calls still dispatch; the suspension fires at the next provider
499
- // turn (or run end) via suspendGatedRound. Per-call beforeExecute is the backstop
500
- // for loops that dispatch without charging a round.
501
- for (const call of calls) {
502
- if (this.matchStickyDecision(call, registry))
503
- continue;
504
- const approvalId = randomId("approval");
505
- this.activeGatedRound ??= new Map();
506
- this.activeGatedRound.set(call.id, {
507
- entry: { call, status: "ready", approvalId },
508
- decision: this.buildPendingDecision(call, approvalId, registry, runId, metadata, controller.signal),
509
- });
510
- }
511
- if (this.activeGatedRound && this.activeGatedRound.size > DEFAULT_MAX_PENDING_DECISIONS) {
512
- throw new AgentDecisionError("ERR_PRISM_DECISION_LIMIT", `Pending decisions exceed ${DEFAULT_MAX_PENDING_DECISIONS} per run`);
513
- }
514
- },
515
- generate: async (request) => {
516
- await suspendGatedRound();
517
- if (!assembledTurn)
518
- limits.charge("maxTurns");
519
- assembledTurn = false;
520
- const policyResult = await this.applyProviderRequestPolicies(request, runId, options, metadata, controller.signal);
521
- const middlewareRequest = (await this.agent.config.middleware?.run("provider_request", policyResult.request)) ?? policyResult.request;
522
- try {
523
- return await this.generateWithRetry(this.redactProviderRequest(middlewareRequest), runId, options, controller.signal, policyResult.secrets, this.activeLoopTurn, recordProviderUsage);
524
- }
525
- catch (error) {
526
- if (isSteerSoftInterrupt(error)) {
527
- return { content: [], calls: [], started: false, usage: undefined };
528
- }
529
- throw error;
530
- }
531
- },
532
- isToolCallExclusive: (call) => registry.get(call.name)?.exclusive === true,
533
- dispatchToolCall: async (call) => {
534
- const sticky = this.matchStickyDecision(call, registry);
535
- if (sticky?.outcome === "reject_for_run") {
536
- return {
537
- toolCallId: call.id,
538
- name: call.name,
539
- error: { code: "approval_rejected", message: sticky.reason ?? "Rejected for this run" },
540
- };
541
- }
542
- if (this.activeGatedRound?.has(call.id)) {
543
- // Gated this round: never dispatched. The marker is skipped by
544
- // dispatchToolCallsInOrder so the transcript stays free of phantom results.
545
- return { toolCallId: call.id, name: call.name, metadata: { approvalPending: true } };
546
- }
547
- try {
548
- return await dispatchToolCall({
549
- call,
550
- registry,
551
- context: {
552
- sessionId: this.id,
553
- runId,
554
- toolCallId: call.id,
555
- signal: controller.signal,
556
- metadata: {
557
- ...metadata,
558
- loadedSkills: this.loadedSkills,
559
- activeTools: tools,
560
- activeSkillNames: activeSkills.map((skill) => skill.name),
561
- },
562
- identity: this.activeIdentity,
563
- },
564
- middleware: this.agent.config.middleware,
565
- emit: (event) => this.emit(event),
566
- permission: this.agent.config.permission,
567
- trust: this.agent.config.trust,
568
- redactor: this.activeRedactor,
569
- ledger: this.activeLedger,
570
- effectStore: this.activeEffectStore,
571
- ownership: this.activeOwnership,
572
- identity: this.activeIdentity,
573
- guardrails: this.activeGuardrails,
574
- limitTracker: limits,
575
- beforeExecute: async (mediatedCall) => {
576
- const durable = this.activeDurable;
577
- if (!durable)
578
- return;
579
- const pendingCalls = durable.state?.pendingCalls;
580
- const matched = pendingCalls?.find((entry) => entry.call.id === mediatedCall.id && entry.status === "ready");
581
- if (matched) {
582
- await this.persistDurable({
583
- ...durable.state,
584
- status: "running",
585
- pendingCalls: pendingCalls.map((entry) => (entry === matched ? { ...entry, status: "dispatched" } : entry)),
586
- interruption: undefined,
587
- });
588
- return;
589
- }
590
- const pending = durable.state?.pending;
591
- if (pending?.call.id === mediatedCall.id && pending.status === "ready") {
592
- await this.persistDurable({
593
- ...durable.state,
594
- status: "running",
595
- pending: { ...pending, status: "dispatched" },
596
- interruption: undefined,
597
- });
598
- return;
599
- }
600
- if (!durable.options.interruptBeforeTool)
601
- return;
602
- if (this.matchStickyDecision(mediatedCall, registry)?.outcome === "allow_for_run")
603
- return;
604
- // Backstop for loops that dispatch without awaiting chargeToolRound: suspend on
605
- // the first uncovered gated call with a single pending decision.
606
- const approvalId = randomId("approval");
607
- const decision = this.buildPendingDecision(mediatedCall, approvalId, registry, runId, metadata, controller.signal);
608
- const interruption = {
609
- kind: "tool_approval",
610
- reason: decision.reason,
611
- toolCallId: mediatedCall.id,
612
- toolName: mediatedCall.name,
613
- pendingDecisions: [decision],
614
- };
615
- throw new AgentRunSuspended(await this.suspendDurable({
616
- runId,
617
- model,
618
- limits,
619
- interruption,
620
- pending: { call: mediatedCall, status: "ready" },
621
- pendingCalls: [{ call: mediatedCall, status: "ready", approvalId }],
622
- }), interruption);
623
- },
624
- // ponytail: RunOptions wins; array-compose deferred (roadmap: compose-later).
625
- validate,
626
- });
627
- }
628
- catch (error) {
629
- // Link the suspension signal to the hosting call so the root suspension can
630
- // synthesize this call's tool_result when the nested run later terminates.
631
- if (error instanceof AgentDelegationSuspendedError && !error.toolCall)
632
- error.toolCall = call;
633
- throw error;
634
- }
635
- },
636
- appendMessage: (message) => this.appendMessage(message, runId),
637
- hasPendingSteers: () => this.pendingSteers.length > 0,
638
- applyPendingSteers: () => this.applyPendingSteers(runId, metadata, controller.signal),
639
- emit: (event) => {
640
- if (event.type === "turn_started")
641
- this.activeLoopTurn = event.turn;
642
- if (event.type === "artifact_finished")
643
- artifactFinished = true;
644
- if (event.type === "artifact_failed") {
645
- const first = event.result.errors?.[0];
646
- const reason = event.result.metadata?.reason;
647
- artifactFailedInfo = {
648
- message: first?.message ?? "artifact failed",
649
- code: typeof reason === "string" || typeof reason === "number" ? reason : "artifact_failed",
650
- };
651
- }
652
- this.emit(event);
653
- },
654
- };
655
- const replayToolResult = async (result) => {
656
- await ctx.appendMessage({
657
- role: "tool",
658
- content: [
659
- { type: "tool_result", toolCallId: result.toolCallId, name: result.name, result: result.value, error: result.error },
660
- ...(result.content ?? []),
661
- ],
662
- metadata: result.metadata,
663
- });
664
- };
665
- // Handles a nested-run suspension signal: sticky auto-apply appends a synthesized
666
- // tool_result and returns; anything else re-suspends the root (throws AgentRunSuspended).
667
- const handleNestedSignal = async (error) => {
668
- const durableOptions = this.activeDurable?.options;
669
- if (!durableOptions || !error.toolCall) {
670
- throw new AgentDecisionError("ERR_PRISM_DECISION_INVALID", "Nested-run suspension requires durable run state and a hosting tool call");
671
- }
672
- if (error.pendingDecisions.length === 0) {
673
- throw new AgentDecisionError("ERR_PRISM_DECISION_INVALID", "Nested-run suspension carried no pending decisions");
674
- }
675
- const applied = await applyNestedRun({
676
- ref: error.ref,
677
- toolCall: error.toolCall,
678
- path: error.path ?? [],
679
- pending: error.pendingDecisions,
680
- hook: durableOptions.resumeNestedRun,
681
- });
682
- if ("toolResult" in applied) {
683
- await replayToolResult(applied.toolResult);
684
- return;
685
- }
686
- await suspendNested({ entry: applied.entry, toolCall: error.toolCall, pending: applied.pending });
687
- };
688
- // Route decided nested-run approvals back to their children before replaying own calls.
689
- // Undecided or re-suspended children re-suspend the root with the surfaced remainder.
690
- let resumePendingCalls = resumed?.state?.pendingCalls;
691
- if (resumed?.state?.nestedRuns?.length) {
692
- const nestedRuns = resumed.state.nestedRuns;
693
- const hook = this.activeDurable?.options.resumeNestedRun;
694
- const oldPending = resumed.state.interruption?.pendingDecisions ?? [];
695
- const nestedApprovalIds = new Set(nestedRuns.flatMap((entry) => entry.approvals.map((approval) => approval.id)));
696
- const remainingNested = [];
697
- const surfacedPending = [];
698
- const resolvedToolCallIds = new Set();
699
- for (const entry of nestedRuns) {
700
- const grouped = [];
701
- for (const approval of entry.approvals) {
702
- const decision = entry.decisions?.[approval.id] ?? resumed.decisions?.get(approval.id);
703
- if (decision)
704
- grouped.push({ ...decision, approvalId: approval.childApprovalId });
705
- }
706
- if (grouped.length === 0) {
707
- remainingNested.push(entry);
708
- surfacedPending.push(...oldPending.filter((pending) => entry.approvals.some((approval) => approval.id === pending.approvalId)));
709
- continue;
710
- }
711
- if (!hook) {
712
- throw new AgentDecisionError("ERR_PRISM_DECISION_INVALID", "Nested-run decisions require a resumeNestedRun hook");
713
- }
714
- const toolCall = resumePendingCalls?.find((pending) => pending.call.id === entry.toolCallId)?.call;
715
- if (!toolCall)
716
- throw new AgentRunStateError("Nested run link is missing its tool call");
717
- const ref = { runId: entry.runId, ...(entry.sessionId ? { sessionId: entry.sessionId } : {}) };
718
- const outcome = await hook({ ref, toolCallId: entry.toolCallId, path: entry.path }, grouped);
719
- if (outcome.status !== "suspended") {
720
- await replayToolResult(nestedOutcomeToolResult(outcome, entry.toolCallId, toolCall.name));
721
- resolvedToolCallIds.add(entry.toolCallId);
722
- continue;
723
- }
724
- const applied = await applyNestedRun({ ref, toolCall, path: entry.path, pending: outcome.pendingDecisions, hook });
725
- if ("toolResult" in applied) {
726
- await replayToolResult(applied.toolResult);
727
- resolvedToolCallIds.add(entry.toolCallId);
728
- }
729
- else {
730
- remainingNested.push(applied.entry);
731
- surfacedPending.push(...applied.pending);
732
- }
733
- }
734
- resumePendingCalls = resumePendingCalls
735
- ?.filter((entry) => !resolvedToolCallIds.has(entry.call.id))
736
- .map((entry) => {
737
- const decision = resumed.decisions?.get(entry.approvalId);
738
- return decision && !entry.decision ? { ...entry, decision } : entry;
739
- });
740
- if (this.activeDurable?.state) {
741
- this.activeDurable.state = {
742
- ...this.activeDurable.state,
743
- pendingCalls: resumePendingCalls?.length ? resumePendingCalls : undefined,
744
- nestedRuns: remainingNested.length ? remainingNested : undefined,
745
- };
746
- }
747
- const remainingOwn = oldPending.filter((pending) => !nestedApprovalIds.has(pending.approvalId) &&
748
- !resumed.decisions?.has(pending.approvalId) &&
749
- !resumePendingCalls?.some((entry) => entry.approvalId === pending.approvalId && entry.decision !== undefined));
750
- if (remainingOwn.length > 0 || surfacedPending.length > 0) {
751
- const pendingDecisions = [...remainingOwn, ...surfacedPending];
752
- const single = pendingDecisions.length === 1 ? pendingDecisions[0] : undefined;
753
- const interruption = {
754
- kind: single?.kind ?? "tool_approval",
755
- reason: `${pendingDecisions.length} approval request(s) remain`,
756
- ...(single?.toolCallId ? { toolCallId: single.toolCallId } : {}),
757
- ...(single?.scope.toolName ? { toolName: single.scope.toolName } : {}),
758
- pendingDecisions,
759
- };
760
- throw new AgentRunSuspended(await this.suspendDurable({
761
- runId,
762
- model,
763
- limits,
764
- interruption,
765
- pendingCalls: resumePendingCalls,
766
- nestedRuns: remainingNested,
767
- }), interruption);
768
- }
769
- }
770
- if (resumePendingCalls?.length) {
771
- for (const entry of resumePendingCalls) {
772
- if (entry.status !== "ready")
773
- continue;
774
- const decision = entry.decision ?? resumed?.decisions?.get(entry.approvalId);
775
- if (decision && (decision.outcome === "reject_once" || decision.outcome === "reject_for_run")) {
776
- await replayToolResult({
777
- toolCallId: entry.call.id,
778
- name: entry.call.name,
779
- error: { code: "approval_rejected", message: decision.reason ?? "Approval rejected" },
780
- });
781
- continue;
782
- }
783
- if (decision?.elicitation !== undefined) {
784
- // Elicitation acceptance resolves the suspended call with the validated payload.
785
- await replayToolResult({ toolCallId: entry.call.id, name: entry.call.name, value: decision.elicitation });
786
- continue;
787
- }
788
- const call = decision?.modifiedArguments ? { ...entry.call, arguments: decision.modifiedArguments } : entry.call;
789
- try {
790
- await replayToolResult(await ctx.dispatchToolCall(call));
791
- }
792
- catch (error) {
793
- if (!(error instanceof AgentDelegationSuspendedError))
794
- throw error;
795
- await handleNestedSignal(error);
796
- }
797
- }
798
- }
799
- else if (resumed?.state?.pending?.status === "ready") {
800
- await replayToolResult(await ctx.dispatchToolCall(resumed.state.pending.call));
801
- }
802
- const resumedLoopState = resumed?.state?.loopState;
803
- if (resumedLoopState) {
804
- if (loop.name !== resumedLoopState.name || (loop.revision ?? "1") !== resumedLoopState.revision) {
805
- throw new AgentLoopStateError("ERR_PRISM_LOOP_REVISION", `Loop ${resumedLoopState.name} revision ${resumedLoopState.revision} does not match the resumed durable run`);
806
- }
807
- loop.restore?.(resumedLoopState.snapshot);
808
- }
809
- let loopUsage;
810
- while (true) {
811
- try {
812
- loopUsage = await loop.run(ctx);
813
- await suspendGatedRound();
814
- break;
815
- }
816
- catch (error) {
817
- if (!(error instanceof AgentDelegationSuspendedError))
818
- throw error;
819
- await handleNestedSignal(error);
820
- }
821
- }
822
- if (loop.name === "generate-validate-revise" && !artifactFinished) {
823
- throw Object.assign(new Error(artifactFailedInfo?.message ?? "artifact loop ended without a validated artifact"), {
824
- name: "ArtifactFailed",
825
- code: artifactFailedInfo?.code ?? "artifact_failed",
826
- });
827
- }
828
- usage = runUsage.value() ?? loopUsage;
829
- if (usage && this.activeLedger) {
830
- const usageRecord = {
831
- id: randomId("usage"),
832
- sessionId: this.id,
833
- runId,
834
- scope: "run_total",
835
- usage,
836
- recordedAt: new Date().toISOString(),
837
- ...this.activeOwnership,
838
- };
839
- await this.activeLedger.appendUsage(redactRunLedgerRecord(usageRecord, this.activeRedactor));
840
- }
841
- await this.drainLedger();
842
- const runState = this.activeDurable?.state
843
- ? await this.persistDurable({
844
- ...this.activeDurable.state,
845
- status: "succeeded",
846
- pending: undefined,
847
- pendingCalls: undefined,
848
- nestedRuns: undefined,
849
- stickyDecisions: undefined,
850
- interruption: undefined,
851
- loopState: undefined,
852
- })
853
- : undefined;
854
- this.emit({
855
- type: "agent_finished",
856
- sessionId: this.id,
857
- runId,
858
- usage,
859
- // F4: loop strategies record why a ceiling ended the run cleanly (e.g. turn_limit).
860
- ...(ctx.finishReason ? { finishReason: ctx.finishReason } : {}),
861
- });
862
- return this.buildRunResult({ runId, status: "succeeded", usage, runState });
863
- }
864
- catch (error) {
865
- if (error instanceof AgentRunSuspended) {
866
- runStatus = "suspended";
867
- const version = error.state.version;
868
- this.emit({ type: "agent_suspended", sessionId: this.id, runId, interruption: error.interruption, version });
869
- return this.buildRunResult({ runId, status: "suspended", runState: error.state, interruption: error.interruption });
870
- }
871
- runError = errorToErrorInfo(error);
872
- this.emit({ type: "error", sessionId: this.id, runId, error: runError });
873
- const breach = error instanceof RunLimitError ? error.breach : limits.breach;
874
- runStatus = breach ? "failed" : controller.signal.aborted ? "aborted" : "failed";
875
- const runState = this.activeDurable?.state
876
- ? await this.persistDurable({
877
- ...this.activeDurable.state,
878
- status: runStatus,
879
- interruption: undefined,
880
- loopState: undefined,
881
- pendingCalls: undefined,
882
- nestedRuns: undefined,
883
- stickyDecisions: undefined,
884
- })
885
- : undefined;
886
- const result = this.buildRunResult({
887
- runId,
888
- status: runStatus,
889
- usage: runUsage.value() ?? usage,
890
- limit: breach,
891
- error: runError,
892
- abortReason: !breach && controller.signal.aborted ? String(controller.signal.reason) : undefined,
893
- runState,
894
- });
895
- throw new AgentRunError(result, { cause: error });
896
- }
897
- finally {
898
- if (this.activeRun === controller)
899
- this.activeRun = undefined;
900
- this.activeRunId = undefined;
901
- this.activeLoop = undefined;
902
- this.activeGatedRound = undefined;
903
- this.activeProviderTurnAbort = undefined;
904
- this.pendingSoftInterrupt = false;
905
- this.pendingSteers = [];
906
- this.pendingSteerBytes = 0;
907
- try {
908
- await this.drainLedger();
909
- if (this.activeLedger) {
910
- const status = runStatus;
911
- const finishRecord = {
912
- id: runId,
913
- sessionId: this.id,
914
- branchId: this.currentLeafId,
915
- model,
916
- provider: model.provider,
917
- idempotencyKey: this.activeIdempotencyKey,
918
- status,
919
- startedAt,
920
- finishedAt: new Date().toISOString(),
921
- abortReason: controller.signal.aborted ? String(controller.signal.reason) : undefined,
922
- error: runError,
923
- ...this.activeOwnership,
924
- };
925
- await this.activeLedger.appendRun(redactRunLedgerRecord(finishRecord, this.activeRedactor));
926
- if (isFlushableRunLedger(this.activeLedger) && this.activeLedger.durability === "flush_on_terminal")
927
- await this.activeLedger.flush();
928
- }
929
- }
930
- finally {
931
- this.activeLedger = undefined;
932
- this.activeEffectStore = undefined;
933
- this.activeOwnership = undefined;
934
- this.activeIdentity = undefined;
935
- this.activeIdempotencyKey = undefined;
936
- this.activeGuardrails = undefined;
937
- this.activeMetadata = undefined;
938
- this.activeLimits?.dispose();
939
- this.activeLimits = undefined;
940
- this.activeLimitOutputBuffer = false;
941
- this.activeRedactor = undefined;
942
- this.activeProvider = undefined;
943
- cleanupSignal();
944
- this.closeSubscribers();
945
- }
946
- }
163
+ return executeRun(asSessionHost(this), input, options, runId, resumed);
947
164
  }
948
165
  prompt(input, options) {
949
166
  return this.run(input, options);
@@ -993,158 +210,6 @@ export class RuntimeAgentSession {
993
210
  interruption: input.interruption,
994
211
  };
995
212
  }
996
- async suspendDurable(input) {
997
- const durable = this.activeDurable;
998
- if (!durable)
999
- throw new AgentRunStateError("Durable interruption is not configured");
1000
- // Capture loop-local state before persisting the suspension. Undefined before the loop
1001
- // starts (input-guardrail suspensions) and for snapshot-less built-ins.
1002
- const loop = this.activeLoop;
1003
- const loopState = loop?.snapshot ? boundedLoopSnapshot(loop.name, loop.revision ?? "1", loop.snapshot()) : undefined;
1004
- const state = durable.state ??
1005
- initialAgentRunState({
1006
- agent: this.agent,
1007
- options: durable.options,
1008
- runId: input.runId,
1009
- sessionId: this.id,
1010
- leafId: this.currentLeafId,
1011
- model: input.model,
1012
- counters: input.limits.snapshot(),
1013
- deadlineAt: input.limits.deadlineAt,
1014
- status: "suspended",
1015
- interruption: input.interruption,
1016
- messages: input.messages,
1017
- pending: input.pending,
1018
- pendingCalls: input.pendingCalls,
1019
- interruptBeforeTool: durable.options.interruptBeforeTool,
1020
- });
1021
- return this.persistDurable({
1022
- ...state,
1023
- leafId: this.currentLeafId,
1024
- status: "suspended",
1025
- interruption: input.interruption,
1026
- ...(input.messages ? { input: input.messages } : {}),
1027
- ...(input.pending ? { pending: input.pending } : {}),
1028
- ...(input.pendingCalls ? { pendingCalls: input.pendingCalls } : {}),
1029
- nestedRuns: input.nestedRuns ?? state.nestedRuns,
1030
- ...(loopState ? { loopState } : {}),
1031
- counters: input.limits.snapshot(),
1032
- });
1033
- }
1034
- /** First attributed sticky whose scope and delegation path exactly match a nested decision. */
1035
- matchNestedSticky(decision) {
1036
- const stickies = this.activeDurable?.state?.stickyDecisions;
1037
- return stickies?.find((sticky) => sticky.attribution !== undefined &&
1038
- pathsEqual(sticky.attribution.path, decision.attribution?.path) &&
1039
- decisionScopesEqual(sticky.scope, decision.scope));
1040
- }
1041
- /** First sticky decision whose scope exactly matches this call, if any. */
1042
- matchStickyDecision(call, registry) {
1043
- const stickies = this.activeDurable?.state?.stickyDecisions;
1044
- if (!stickies?.length)
1045
- return undefined;
1046
- const identityRef = decisionIdentityRef(this.activeIdentity);
1047
- let argumentsHash;
1048
- let effectKind;
1049
- let effectResolved = false;
1050
- return stickies.find((sticky) => {
1051
- if (sticky.attribution !== undefined)
1052
- return false; // nested-run stickies match decisions, not calls
1053
- const scope = sticky.scope;
1054
- if (scope.toolName !== undefined && scope.toolName !== call.name)
1055
- return false;
1056
- if (scope.identity !== undefined && scope.identity !== identityRef)
1057
- return false;
1058
- if (scope.argumentsHash !== undefined) {
1059
- argumentsHash ??= toolEffectArgumentsHash(call.arguments);
1060
- if (scope.argumentsHash !== argumentsHash)
1061
- return false;
1062
- }
1063
- if (scope.effectKind !== undefined) {
1064
- if (!effectResolved) {
1065
- effectResolved = true;
1066
- const tool = registry.get(call.name);
1067
- effectKind = tool?.effect
1068
- ? resolveToolEffectDeclaration(tool, call.arguments, { sessionId: this.id, runId: "", toolCallId: call.id })?.kind
1069
- : undefined;
1070
- }
1071
- if (scope.effectKind !== effectKind)
1072
- return false;
1073
- }
1074
- if (scope.actionConstraints) {
1075
- for (const [key, value] of Object.entries(scope.actionConstraints)) {
1076
- const actual = call.arguments[key];
1077
- if (canonicalToolEffectJson(actual === undefined ? null : actual) !== canonicalToolEffectJson(value))
1078
- return false;
1079
- }
1080
- }
1081
- return true;
1082
- });
1083
- }
1084
- /** Redacted pending-decision descriptor for one gated call; never carries raw arguments. */
1085
- buildPendingDecision(call, approvalId, registry, runId, metadata, signal) {
1086
- const tool = registry.get(call.name);
1087
- const declaration = tool?.effect
1088
- ? resolveToolEffectDeclaration(tool, call.arguments, {
1089
- sessionId: this.id,
1090
- runId,
1091
- toolCallId: call.id,
1092
- signal,
1093
- metadata,
1094
- })
1095
- : undefined;
1096
- const identityRef = decisionIdentityRef(this.activeIdentity);
1097
- const elicitation = toolElicitationRequest(tool, call.arguments, {
1098
- sessionId: this.id,
1099
- runId,
1100
- toolCallId: call.id,
1101
- signal,
1102
- metadata,
1103
- });
1104
- return {
1105
- approvalId,
1106
- kind: elicitation ? "elicitation" : "tool_approval",
1107
- toolCallId: call.id,
1108
- scope: {
1109
- toolName: call.name,
1110
- argumentsHash: toolEffectArgumentsHash(call.arguments),
1111
- ...(declaration && declaration.kind !== "none" ? { effectKind: declaration.kind } : {}),
1112
- ...(identityRef ? { identity: identityRef } : {}),
1113
- },
1114
- reason: elicitation?.reason ?? "Tool side effect requires approval",
1115
- ...(elicitation ? { elicitationSchema: elicitation.schema } : {}),
1116
- };
1117
- }
1118
- async persistDurable(state) {
1119
- const durable = this.activeDurable;
1120
- if (!durable)
1121
- throw new AgentRunStateError("Durable run state is not configured");
1122
- const persisted = durable.options.persistSessionState
1123
- ? {
1124
- ...state,
1125
- sessionState: {
1126
- loadedSkillNames: this.loadedSkills.list(),
1127
- ...(durable.options.includeSkillBodies
1128
- ? {
1129
- loadedSkillBodies: snapshotLoadedSkillBodies(this.activeRunSkills, this.loadedSkills, this.restoredSkillBodies.length ? new Map(this.restoredSkillBodies.map((e) => [e.name, e.instructions])) : undefined),
1130
- }
1131
- : {}),
1132
- },
1133
- }
1134
- : state;
1135
- const saved = await saveAgentRunState({
1136
- checkpoints: durable.options.checkpoints,
1137
- state: persisted,
1138
- expectedVersion: durable.version,
1139
- ownership: this.activeOwnership,
1140
- fencingToken: durable.options.fencingToken,
1141
- redactor: this.activeRedactor,
1142
- maxStateBytes: durable.options.maxStateBytes,
1143
- });
1144
- durable.state = saved.state;
1145
- durable.version = saved.record.version;
1146
- return publicState(saved.state);
1147
- }
1148
213
  async compact(options = {}) {
1149
214
  if (this.activeRun)
1150
215
  throw new Error("Agent session already has an active run");
@@ -1267,180 +332,6 @@ export class RuntimeAgentSession {
1267
332
  if (failure)
1268
333
  throw failure;
1269
334
  }
1270
- async generateWithRetry(request, runId, options, signal, requestSecrets = [], turn = 1, recordUsage) {
1271
- const retry = mergeRetry(this.agent.config.retry, options.retry);
1272
- const secrets = [...requestSecrets, ...(retry?.secrets ?? [])];
1273
- const policy = retry?.policy ?? (retry ? createDefaultRetryPolicy(retry) : undefined);
1274
- for (let attempt = 1;; attempt += 1) {
1275
- try {
1276
- return await this.generateProviderTurn(request, runId, signal, secrets, turn, attempt, recordUsage);
1277
- }
1278
- catch (error) {
1279
- if (error instanceof GuardrailError || isSteerSoftInterrupt(error))
1280
- throw error;
1281
- const failure = error instanceof ProviderTurnFailure ? error : undefined;
1282
- const info = failure ? redactSecrets(failure.info, secrets) : errorToErrorInfo(error, secrets);
1283
- if (!policy || failure?.observable)
1284
- throw errorFromInfo(info);
1285
- const context = { sessionId: this.id, runId, attempt, error: info, metadata: retry?.metadata, signal };
1286
- let decision = await policy.decide(context);
1287
- const payload = (await this.agent.config.middleware?.run("retry", { context, decision })) ?? {
1288
- context,
1289
- decision,
1290
- };
1291
- decision = payload.decision;
1292
- if (!decision.retry)
1293
- throw errorFromInfo(info);
1294
- const delayMs = decision.delayMs ?? 0;
1295
- this.emit({ type: "retry_scheduled", sessionId: this.id, runId, attempt, delayMs, error: info });
1296
- await waitForRetry(decision, signal);
1297
- }
1298
- }
1299
- }
1300
- async generateProviderTurn(request, runId, signal, secrets = [], turn = 1, attempt = 1, recordUsage) {
1301
- this.activeLimits.charge("maxProviderAttempts");
1302
- this.activeLimits.charge("maxRequestBytes", jsonBytes(request));
1303
- const startedAt = performance.now();
1304
- const providerId = this.activeProvider?.id ?? request.model.provider;
1305
- const buildMetadata = (extra = {}) => createProviderTurnMetadata(request, providerId, { attempt, ...extra });
1306
- this.emit({
1307
- type: "provider_turn_started",
1308
- sessionId: this.id,
1309
- runId,
1310
- turn,
1311
- metadata: buildMetadata(),
1312
- });
1313
- const content = [];
1314
- const calls = [];
1315
- const toolDeltas = [];
1316
- let messageId;
1317
- let started = false;
1318
- let usage;
1319
- let usageRecorded = false;
1320
- const bufferedOutput = [];
1321
- const bufferOutput = Boolean(this.activeGuardrails?.output?.length || this.activeLimitOutputBuffer);
1322
- const emitOutput = (event) => {
1323
- if (bufferOutput)
1324
- bufferedOutput.push(event);
1325
- else
1326
- this.emit(event);
1327
- };
1328
- const recordTurnUsage = async () => {
1329
- if (usageRecorded)
1330
- return;
1331
- usageRecorded = true;
1332
- await recordUsage?.(usage, turn, attempt);
1333
- };
1334
- const turnAbort = new AbortController();
1335
- const cleanupTurn = bridgeAbort(signal, turnAbort);
1336
- this.activeProviderTurnAbort = turnAbort;
1337
- if (this.pendingSoftInterrupt) {
1338
- this.pendingSoftInterrupt = false;
1339
- turnAbort.abort(new SteerSoftInterrupt());
1340
- }
1341
- const turnRequest = { ...request, signal: turnAbort.signal };
1342
- try {
1343
- throwIfAborted(turnAbort.signal);
1344
- for await (const event of this.activeProvider.generate(turnRequest)) {
1345
- throwIfAborted(turnAbort.signal);
1346
- this.activeLimits.charge("maxResponseBytes", jsonBytes(event));
1347
- if (event.type === "error")
1348
- throw new ProviderTurnFailure(event.error, started);
1349
- if (event.type === "usage")
1350
- usage = event.usage;
1351
- if (event.type === "done") {
1352
- usage = event.usage ?? usage;
1353
- break;
1354
- }
1355
- if (event.type === "message_start") {
1356
- started = true;
1357
- messageId = event.messageId;
1358
- emitOutput({ type: "message_started", sessionId: this.id, runId, message: { id: messageId, role: "assistant", content: [] } });
1359
- continue;
1360
- }
1361
- if (event.type === "content_delta" || event.type === "tool_call" || event.type === "tool_call_delta") {
1362
- if (!started) {
1363
- started = true;
1364
- emitOutput({ type: "message_started", sessionId: this.id, runId, message: { role: "assistant", content: [] } });
1365
- }
1366
- if (event.type === "tool_call_delta") {
1367
- toolDeltas.push(event);
1368
- emitOutput({ type: "message_delta", sessionId: this.id, runId, content: providerToolCallDeltaContent(event) });
1369
- continue;
1370
- }
1371
- const block = providerContent(event);
1372
- content.push(block);
1373
- if (block.type === "tool_call")
1374
- calls.push(block);
1375
- emitOutput({ type: "message_delta", sessionId: this.id, runId, content: block });
1376
- }
1377
- }
1378
- for (const call of reconstructMissingToolCalls(toolDeltas, calls)) {
1379
- content.push(call);
1380
- calls.push(call);
1381
- emitOutput({ type: "message_delta", sessionId: this.id, runId, content: call });
1382
- }
1383
- await recordTurnUsage();
1384
- if (this.activeGuardrails?.output?.length) {
1385
- assertGuardrailsAllowed(await runGuardrails({
1386
- stage: "output",
1387
- guardrails: this.activeGuardrails,
1388
- value: { content, calls, messageId, started, usage },
1389
- context: { sessionId: this.id, runId, metadata: this.activeMetadata ?? {}, signal: turnAbort.signal },
1390
- redactor: this.activeRedactor,
1391
- emit: (event) => this.emit(event),
1392
- }));
1393
- }
1394
- if (bufferOutput)
1395
- for (const event of bufferedOutput)
1396
- this.emit(event);
1397
- const latencyMs = Math.round(performance.now() - startedAt);
1398
- this.emit({
1399
- type: "provider_turn_finished",
1400
- sessionId: this.id,
1401
- runId,
1402
- turn,
1403
- metadata: buildMetadata({ latencyMs }),
1404
- usage,
1405
- });
1406
- return { content, calls, messageId, started, usage };
1407
- }
1408
- catch (error) {
1409
- if (isSteerSoftInterrupt(error) || isSteerSoftInterrupt(turnAbort.signal.reason)) {
1410
- await recordTurnUsage();
1411
- const latencyMs = Math.round(performance.now() - startedAt);
1412
- this.emit({
1413
- type: "provider_turn_finished",
1414
- sessionId: this.id,
1415
- runId,
1416
- turn,
1417
- metadata: buildMetadata({ latencyMs }),
1418
- usage,
1419
- });
1420
- throw new SteerSoftInterrupt();
1421
- }
1422
- const latencyMs = Math.round(performance.now() - startedAt);
1423
- const info = error instanceof ProviderTurnFailure ? redactSecrets(error.info, secrets) : errorToErrorInfo(error, secrets);
1424
- await recordTurnUsage();
1425
- this.emit({
1426
- type: "provider_turn_finished",
1427
- sessionId: this.id,
1428
- runId,
1429
- turn,
1430
- metadata: buildMetadata({ latencyMs, httpStatus: readProviderHttpStatus(info) }),
1431
- usage,
1432
- error: info,
1433
- });
1434
- if (error instanceof GuardrailError || error instanceof ProviderTurnFailure)
1435
- throw error;
1436
- throw new ProviderTurnFailure(info, started);
1437
- }
1438
- finally {
1439
- cleanupTurn();
1440
- if (this.activeProviderTurnAbort === turnAbort)
1441
- this.activeProviderTurnAbort = undefined;
1442
- }
1443
- }
1444
335
  async applyPendingSteers(runId, metadata, signal) {
1445
336
  if (this.pendingSteers.length === 0)
1446
337
  return false;