@arnilo/prism 0.2.3 → 0.2.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (41) hide show
  1. package/CHANGELOG.md +10 -0
  2. package/README.md +3 -3
  3. package/dist/agent-session/create-agent.d.ts +6 -0
  4. package/dist/agent-session/create-agent.js +13 -0
  5. package/dist/agent-session/event-subscriber.d.ts +17 -0
  6. package/dist/agent-session/event-subscriber.js +68 -0
  7. package/dist/agent-session/helpers.d.ts +44 -0
  8. package/dist/agent-session/helpers.js +194 -0
  9. package/dist/agent-session/session.d.ts +101 -0
  10. package/dist/agent-session/session.js +1568 -0
  11. package/dist/agent-session.d.ts +6 -105
  12. package/dist/agent-session.js +6 -1833
  13. package/dist/contracts-core/agent.d.ts +257 -0
  14. package/dist/contracts-core/agent.js +5 -0
  15. package/dist/contracts-core/compaction.d.ts +72 -0
  16. package/dist/contracts-core/compaction.js +2 -0
  17. package/dist/contracts-core/content.d.ts +116 -0
  18. package/dist/contracts-core/content.js +2 -0
  19. package/dist/contracts-core/extensions.d.ts +163 -0
  20. package/dist/contracts-core/extensions.js +2 -0
  21. package/dist/contracts-core/loop.d.ts +98 -0
  22. package/dist/contracts-core/loop.js +2 -0
  23. package/dist/contracts-core/persistence.d.ts +366 -0
  24. package/dist/contracts-core/persistence.js +9 -0
  25. package/dist/contracts-core/provider.d.ts +97 -0
  26. package/dist/contracts-core/provider.js +2 -0
  27. package/dist/contracts-core/resources.d.ts +44 -0
  28. package/dist/contracts-core/resources.js +7 -0
  29. package/dist/contracts-core/run-limits.d.ts +81 -0
  30. package/dist/contracts-core/run-limits.js +2 -0
  31. package/dist/contracts-core/session.d.ts +187 -0
  32. package/dist/contracts-core/session.js +131 -0
  33. package/dist/contracts-core.d.ts +13 -1425
  34. package/dist/contracts-core.js +10 -138
  35. package/dist/index.d.ts +1 -1
  36. package/dist/index.js +1 -1
  37. package/docs/0.1.0-readiness.md +15 -13
  38. package/docs/index.md +2 -2
  39. package/docs/migration.md +8 -0
  40. package/docs/release-and-install.md +59 -8
  41. package/package.json +2 -2
@@ -0,0 +1,1568 @@
1
+ import { AgentDecisionError, AgentDelegationSuspendedError, AgentLoopStateError, AgentRunError, AgentRunStateError, DEFAULT_MAX_PENDING_DECISIONS, DEFAULT_MAX_PENDING_STEERS, DEFAULT_MAX_PENDING_STEER_BYTES, HARD_MAX_PENDING_DECISIONS, MAX_ATTRIBUTION_DEPTH, } from "../contracts.js";
2
+ import { AgentRunSuspended, decisionIdentityRef, decisionScopesEqual, nestedApprovalId, nestedOutcomeToolResult, pathsEqual, } from "../agent-approval.js";
3
+ import { identityTelemetryAttributes, ownershipFromIdentity, resolveRunIdentity } from "../identity.js";
4
+ import { assembleProviderInput } from "../input.js";
5
+ import { GuardrailError, assertGuardrailsAllowed, runGuardrails } from "../guardrails.js";
6
+ import { applyRestoredSkillBodies, snapshotLoadedSkillBodies, validateLoadedSkillBodies } from "../skill-load.js";
7
+ import { boundedLoopSnapshot, initialAgentRunState, publicState, saveAgentRunState, validateRunStateOptions } from "../agent-run-state.js";
8
+ import { RunLimitError, RunLimitTracker, resolveRunLimits } from "../run-limits.js";
9
+ import { errorToErrorInfo, redactAgentEvent, redactProviderRequest, redactRunLedgerRecord, redactSecrets, redactSessionEntry, } from "../redaction.js";
10
+ import { createMemorySessionStore, createSessionEntry, getSessionBranchEntries, rebuildSessionContext } from "../session-stores.js";
11
+ import { activeTools, policyList, toolElicitationRequest } from "../agent-tool-dispatch.js";
12
+ import { assertStructuredOutputRequestSupported, resolveRunProviderOptions } from "../structured-output.js";
13
+ import { canonicalToolEffectJson, toolEffectArgumentsHash } from "../tool-effects.js";
14
+ import { composeSystemPrompt, mergeSystemPromptConfig } from "../system-prompts.js";
15
+ import { createDefaultCompactionStrategy, isCompactionEntryData } from "../compaction.js";
16
+ import { createDefaultRetryPolicy, waitForRetry } from "../retry.js";
17
+ import { createLoadedSkillSet, resolveSkillsDisclosure } from "../skill-disclosure.js";
18
+ import { createProviderRequestPolicyChain, normalizeProviderRequestPolicyResult } from "../provider-request-policy.js";
19
+ import { createProviderTurnMetadata, readProviderHttpStatus } from "../observability.js";
20
+ import { dispatchToolCall, resolveToolEffectDeclaration } from "../tools.js";
21
+ import { isFlushableRunLedger } from "../run-ledger.js";
22
+ import { providerToolCallDeltaContent } from "../provider-events.js";
23
+ import { resolveActiveSkills } from "../skills.js";
24
+ import { resolveLoop, resolveToolConcurrency } from "../agent-loops.js";
25
+ import { resolveToolResultFold } from "../tool-result-fold.js";
26
+ import { EventSubscriber } from "./event-subscriber.js";
27
+ import { ProviderTurnFailure, SteerSoftInterrupt, bridgeAbort, createUsageAccumulator, errorFromInfo, finalAssistantMessage, inputToMessages, isDurableLoop, isSteerSoftInterrupt, jsonBytes, mergeCompaction, mergeGuardrails, mergeRetry, messageTextBytes, providerContent, randomId, reconstructMissingToolCalls, throwIfAborted, throwIfAbortedSignal, withoutTrailingInput, } from "./helpers.js";
28
+ import { createAgentSession } from "./create-agent.js";
29
+ export class RuntimeAgentSession {
30
+ id;
31
+ agent;
32
+ metadata;
33
+ store;
34
+ subscribers = new Set();
35
+ currentLeafId;
36
+ history = [];
37
+ activeRun;
38
+ activeRunId;
39
+ activeProviderTurnAbort;
40
+ pendingSoftInterrupt = false;
41
+ pendingSteers = [];
42
+ pendingSteerBytes = 0;
43
+ activeRedactor;
44
+ activeProvider;
45
+ activeLedger;
46
+ activeEffectStore;
47
+ activeOwnership;
48
+ activeIdentity;
49
+ activeIdempotencyKey;
50
+ activeGuardrails;
51
+ activeMetadata;
52
+ activeLimits;
53
+ activeLimitOutputBuffer = false;
54
+ activeDurable;
55
+ activeLoop;
56
+ /** Gated calls of the current tool round awaiting one collected suspension. */
57
+ activeGatedRound;
58
+ activeLoopTurn = 1;
59
+ loadedSkills = createLoadedSkillSet();
60
+ /** Plan 018 Task 6 (closeout `checkpoint-bodies`): persisted exact instructions, registry-independent. */
61
+ restoredSkillBodies = [];
62
+ /** Skills of the current run (for the bodies snapshot); replaced at each run start. */
63
+ activeRunSkills = [];
64
+ /** Plan 015 Task 4: re-add persisted loaded-skill names (names only; bodies re-resolve on demand). */
65
+ restoreLoadedSkills(names) {
66
+ for (const name of names)
67
+ this.loadedSkills.add(name);
68
+ }
69
+ /** Plan 018 Task 6: restore persisted loaded-skill bodies (already validated fail-closed at load). */
70
+ restoreLoadedSkillBodies(bodies) {
71
+ validateLoadedSkillBodies(bodies);
72
+ this.restoredSkillBodies = bodies;
73
+ for (const entry of bodies)
74
+ this.loadedSkills.add(entry.name);
75
+ }
76
+ ledgerChain = Promise.resolve();
77
+ ledgerFailure;
78
+ snapshotGeneration = 0;
79
+ snapshotCache;
80
+ constructor(config) {
81
+ this.id = config.id ?? randomId("session");
82
+ this.agent = config.agent;
83
+ this.metadata = config.metadata;
84
+ this.store = config.store ?? config.agent.config.store ?? createMemorySessionStore();
85
+ this.currentLeafId = config.leafId;
86
+ }
87
+ get leafId() {
88
+ return this.currentLeafId;
89
+ }
90
+ subscribe(options = {}) {
91
+ const subscriber = new EventSubscriber(this.id, options, () => this.subscribers.delete(subscriber));
92
+ this.subscribers.add(subscriber);
93
+ return subscriber;
94
+ }
95
+ async run(input, options = {}) {
96
+ return this.runInternal(input, options, randomId("run"));
97
+ }
98
+ steer(input, options = {}) {
99
+ if (!this.activeRun || !this.activeRunId)
100
+ throw new Error("Agent session has no active run to steer");
101
+ const messages = inputToMessages(input).map((message) => this.redact(message));
102
+ if (messages.length === 0)
103
+ throw new Error("steer requires non-empty input");
104
+ let addBytes = 0;
105
+ for (const message of messages)
106
+ addBytes += messageTextBytes(message);
107
+ if (this.pendingSteers.length + messages.length > DEFAULT_MAX_PENDING_STEERS) {
108
+ throw new Error(`steer queue exceeds max pending messages (${DEFAULT_MAX_PENDING_STEERS})`);
109
+ }
110
+ if (this.pendingSteerBytes + addBytes > DEFAULT_MAX_PENDING_STEER_BYTES) {
111
+ throw new Error(`steer queue exceeds max pending bytes (${DEFAULT_MAX_PENDING_STEER_BYTES})`);
112
+ }
113
+ this.pendingSteers.push(...messages);
114
+ this.pendingSteerBytes += addBytes;
115
+ this.emit({ type: "queue_updated", sessionId: this.id, runId: this.activeRunId, size: this.pendingSteers.length });
116
+ if (options.softInterrupt) {
117
+ if (this.activeProviderTurnAbort)
118
+ this.activeProviderTurnAbort.abort(new SteerSoftInterrupt());
119
+ else
120
+ this.pendingSoftInterrupt = true;
121
+ }
122
+ }
123
+ async resumeDurable(state, runState, ownership, signal, decisions) {
124
+ return this.runInternal(state.input ?? [], { runState, ownership, signal }, state.runId, {
125
+ options: runState,
126
+ state,
127
+ version: state.version,
128
+ decisions,
129
+ });
130
+ }
131
+ async recordDurableResumption(runId, interruption, version, ownership) {
132
+ this.activeLedger = this.agent.config.runLedger;
133
+ this.activeOwnership = ownership ?? this.agent.config.ownership;
134
+ this.activeRedactor = this.agent.config.redactor;
135
+ try {
136
+ this.emit({ type: "agent_suspended", sessionId: this.id, runId, interruption, version });
137
+ await this.drainLedger();
138
+ }
139
+ finally {
140
+ this.activeLedger = undefined;
141
+ this.activeOwnership = undefined;
142
+ this.activeRedactor = undefined;
143
+ this.closeSubscribers();
144
+ }
145
+ }
146
+ async recordDurableDenial(runId, interruption, version, ownership) {
147
+ this.activeLedger = this.agent.config.runLedger;
148
+ this.activeOwnership = ownership ?? this.agent.config.ownership;
149
+ this.activeRedactor = this.agent.config.redactor;
150
+ try {
151
+ this.emit({ type: "agent_denied", sessionId: this.id, runId, interruption, version });
152
+ await this.drainLedger();
153
+ }
154
+ finally {
155
+ this.activeLedger = undefined;
156
+ this.activeOwnership = undefined;
157
+ this.activeRedactor = undefined;
158
+ this.closeSubscribers();
159
+ }
160
+ }
161
+ async runInternal(input, options, runId, resumed) {
162
+ // 0.1.5 breaking cut: the deprecated RunOptions.maxToolRounds alias was removed. Reject
163
+ // untyped/legacy input fail-closed before any session mutation, provider call, or tool
164
+ // execution; silently honoring it would widen or mis-apply the intended tool-round cap.
165
+ const legacyMaxToolRounds = options.maxToolRounds;
166
+ if (legacyMaxToolRounds !== undefined) {
167
+ throw new TypeError("RunOptions.maxToolRounds was removed in 0.1.5; use RunOptions.limits.maxToolRounds instead");
168
+ }
169
+ if (this.agent.config.secure &&
170
+ (options.redactor !== undefined ||
171
+ options.ownership !== undefined ||
172
+ options.validate !== undefined ||
173
+ options.effectStore !== undefined ||
174
+ options.runState !== undefined)) {
175
+ throw new AgentRunStateError("Secure agent defaults cannot be replaced per run");
176
+ }
177
+ const requestedLimits = options.limits;
178
+ const resolvedLimits = resolveRunLimits(this.agent.config.limits, requestedLimits);
179
+ const durableOptions = options.runState ?? this.agent.config.runState;
180
+ if (this.agent.config.runState && options.runState && this.agent.config.runState !== options.runState) {
181
+ throw new AgentRunStateError("RunOptions cannot replace agent durable run-state configuration");
182
+ }
183
+ if (durableOptions) {
184
+ validateRunStateOptions(durableOptions);
185
+ if (options.model || options.guardrails || options.loop || options.effectStore)
186
+ throw new AgentRunStateError("Durable runs require model, guardrails, loop, and effect store on AgentConfig for fingerprinting");
187
+ const configuredLoop = this.agent.config.loop;
188
+ if (configuredLoop && !isDurableLoop(configuredLoop)) {
189
+ throw new AgentLoopStateError("ERR_PRISM_LOOP_NOT_DURABLE", "Custom AgentLoopStrategy on a durable run requires snapshot and restore hooks");
190
+ }
191
+ }
192
+ if (this.activeRun) {
193
+ const error = new Error("Agent session already has an active run");
194
+ this.emit({ type: "error", sessionId: this.id, runId, error: errorToErrorInfo(error) });
195
+ throw error;
196
+ }
197
+ const controller = new AbortController();
198
+ const cleanupSignal = bridgeAbort(options.signal, controller);
199
+ this.activeRun = controller;
200
+ this.activeRunId = runId;
201
+ this.pendingSteers = [];
202
+ this.pendingSteerBytes = 0;
203
+ this.pendingSoftInterrupt = false;
204
+ this.activeRedactor = options.redactor ?? this.agent.config.redactor;
205
+ this.activeLedger = options.runLedger ?? this.agent.config.runLedger;
206
+ this.activeEffectStore = options.effectStore ?? this.agent.config.effectStore;
207
+ this.activeOwnership = options.ownership ?? this.agent.config.ownership;
208
+ this.activeIdentity = resolveRunIdentity(options.identity, this.agent.config.identity, this.activeOwnership);
209
+ if (this.activeIdentity && !this.activeOwnership)
210
+ this.activeOwnership = ownershipFromIdentity(this.activeIdentity);
211
+ this.activeIdempotencyKey = options.idempotencyKey ?? this.agent.config.idempotencyKey;
212
+ this.activeGuardrails = mergeGuardrails(this.agent.config.guardrails, options.guardrails);
213
+ this.activeDurable = resumed ?? (durableOptions ? { options: durableOptions, version: 0 } : undefined);
214
+ this.activeGatedRound = undefined;
215
+ if (resumed)
216
+ this.invalidateSnapshot();
217
+ const model = options.model ?? this.agent.config.model;
218
+ const startedAt = new Date().toISOString();
219
+ let runError;
220
+ let runStatus = "succeeded";
221
+ const runUsage = createUsageAccumulator();
222
+ let usage;
223
+ const metadata = {
224
+ ...this.agent.config.metadata,
225
+ ...this.metadata,
226
+ ...options.metadata,
227
+ ...(this.activeIdentity ? identityTelemetryAttributes(this.activeIdentity) : {}),
228
+ };
229
+ this.activeMetadata = metadata;
230
+ const limits = new RunLimitTracker(resolvedLimits, {
231
+ onExceeded: (breach) => {
232
+ this.emit({ type: "run_limit_exceeded", sessionId: this.id, runId, breach });
233
+ controller.abort(new RunLimitError(breach));
234
+ },
235
+ snapshot: resumed?.state?.counters,
236
+ deadlineAt: resumed?.state?.deadlineAt,
237
+ });
238
+ this.activeLimits = limits;
239
+ this.activeLimitOutputBuffer = [this.agent.config.limits, requestedLimits].some((value) => value?.maxOutputTokens !== undefined || value?.maxTotalTokens !== undefined || value?.maxCost !== undefined);
240
+ try {
241
+ this.resolveRunProvider(options);
242
+ throwIfAborted(controller.signal);
243
+ this.emit({ type: "agent_started", sessionId: this.id, runId });
244
+ if (resumed)
245
+ this.emit({ type: "agent_resumed", sessionId: this.id, runId, version: resumed.version });
246
+ const startRecord = {
247
+ id: runId,
248
+ sessionId: this.id,
249
+ branchId: this.currentLeafId,
250
+ model,
251
+ provider: model.provider,
252
+ idempotencyKey: this.activeIdempotencyKey,
253
+ status: "running",
254
+ startedAt,
255
+ ...this.activeOwnership,
256
+ };
257
+ await this.activeLedger?.appendRun(redactRunLedgerRecord(startRecord, this.activeRedactor));
258
+ await this.rebuildHistory();
259
+ const { registry, tools } = activeTools(this.agent.config.tools);
260
+ const activeSkills = this.resolveRunSkills(options, tools);
261
+ this.activeRunSkills = activeSkills; // for the durable bodies snapshot (plan 018 Task 6)
262
+ if (options.model && JSON.stringify(options.model) !== JSON.stringify(this.agent.config.model)) {
263
+ await this.appendEntry(createSessionEntry({
264
+ sessionId: this.id,
265
+ parentId: this.currentLeafId,
266
+ runId,
267
+ kind: "model_change",
268
+ previousModel: this.agent.config.model,
269
+ model: options.model,
270
+ }));
271
+ }
272
+ const inputMessages = inputToMessages(input).map((message) => this.redact(message));
273
+ const inputGuardrails = await runGuardrails({
274
+ stage: "input",
275
+ guardrails: this.activeGuardrails,
276
+ value: inputMessages,
277
+ context: { sessionId: this.id, runId, metadata, signal: controller.signal },
278
+ redactor: this.activeRedactor,
279
+ emit: (event) => this.emit(event),
280
+ });
281
+ // Input-guardrail decision table:
282
+ // - interrupt + durable + fresh run → suspend for approval.
283
+ // - interrupt + durable + resumed run → proceed: resuming IS the operator approval.
284
+ // - interrupt without durable, or block/tripwire → fail via assertGuardrailsAllowed.
285
+ const approvedByResume = resumed !== undefined && inputGuardrails.terminal?.action === "interrupt" && this.activeDurable !== undefined;
286
+ if (inputGuardrails.terminal?.action === "interrupt" && this.activeDurable && !approvedByResume) {
287
+ const interruption = { kind: "input_guardrail", reason: inputGuardrails.terminal.reason ?? "Input requires approval" };
288
+ throw new AgentRunSuspended(await this.suspendDurable({ runId, model, limits, interruption, messages: inputMessages }), interruption);
289
+ }
290
+ if (inputGuardrails.terminal && !approvedByResume)
291
+ assertGuardrailsAllowed(inputGuardrails);
292
+ for (const message of inputMessages)
293
+ await this.appendMessage(message, runId);
294
+ await this.autoCompact(runId, options, controller.signal, inputMessages);
295
+ const maxToolRounds = resolvedLimits.maxToolRounds;
296
+ const systemInstructions = composeSystemPrompt(mergeSystemPromptConfig(this.agent.config.systemPrompt, options.systemPrompt), {
297
+ base: this.agent.config.instructions,
298
+ });
299
+ const contextProviders = [
300
+ ...(this.agent.config.context ?? []),
301
+ // ponytail: skill context after host context; no per-skill token budget yet.
302
+ ...activeSkills.flatMap((skill) => skill.context ?? []),
303
+ ];
304
+ const providerOptions = resolveRunProviderOptions(options, this.agent.config);
305
+ assertStructuredOutputRequestSupported(options.model ?? this.agent.config.model, providerOptions);
306
+ const validate = options.validate ?? this.agent.config.validator;
307
+ // ponytail: RunOptions.instructionInjectors overrides AgentConfig.instructionInjectors (mirrors validate/loop).
308
+ const instructionInjectors = options.instructionInjectors ?? this.agent.config.instructionInjectors ?? [];
309
+ const inputLayout = options.inputLayout ?? this.agent.config.inputLayout;
310
+ const loop = resolveLoop(options, this.agent.config);
311
+ this.activeLoop = loop;
312
+ const toolConcurrency = resolveToolConcurrency(options, this.agent.config);
313
+ this.activeLoopTurn = 1;
314
+ const recordProviderUsage = async (turnUsage, turn, attempt) => {
315
+ limits.recordUsage(turnUsage);
316
+ if (!turnUsage)
317
+ return;
318
+ runUsage.add(turnUsage);
319
+ if (!this.activeLedger)
320
+ return;
321
+ const usageRecord = {
322
+ id: randomId("usage"),
323
+ sessionId: this.id,
324
+ runId,
325
+ scope: "provider_turn",
326
+ turn,
327
+ attempt,
328
+ usage: turnUsage,
329
+ recordedAt: new Date().toISOString(),
330
+ ...this.activeOwnership,
331
+ };
332
+ await this.activeLedger.appendUsage(redactRunLedgerRecord(usageRecord, this.activeRedactor));
333
+ };
334
+ // Suspends the run when a round recorded gated calls. Fires at the next provider turn
335
+ // (generate) or after the loop ends, so ungated round siblings dispatch first.
336
+ const suspendGatedRound = async () => {
337
+ const gated = this.activeGatedRound;
338
+ if (!gated?.size)
339
+ return;
340
+ const entries = [...gated.values()];
341
+ const decisions = entries.map((gatedCall) => gatedCall.decision);
342
+ const single = decisions.length === 1 ? decisions[0] : undefined;
343
+ const interruption = {
344
+ kind: single?.kind === "elicitation" ? "elicitation" : "tool_approval",
345
+ reason: single ? single.reason : `${decisions.length} tool side effects require approval`,
346
+ ...(single?.toolCallId ? { toolCallId: single.toolCallId } : {}),
347
+ ...(single?.scope.toolName ? { toolName: single.scope.toolName } : {}),
348
+ pendingDecisions: decisions,
349
+ };
350
+ throw new AgentRunSuspended(await this.suspendDurable({ runId, model, limits, interruption, pendingCalls: entries.map((gatedCall) => gatedCall.entry) }), interruption);
351
+ };
352
+ // Suspends on a nested run's pending decisions, merging any still-ready round entries
353
+ // (with their decisions attached) so a nested signal mid-replay never drops own work.
354
+ const suspendNested = async (nested) => {
355
+ const state = this.activeDurable?.state;
356
+ const kept = (state?.pendingCalls ?? [])
357
+ .filter((entry) => entry.status === "ready")
358
+ .map((entry) => {
359
+ const decision = entry.decision ?? resumed?.decisions?.get(entry.approvalId);
360
+ return decision ? { ...entry, decision } : entry;
361
+ });
362
+ const gated = [...(this.activeGatedRound?.values() ?? [])];
363
+ const pendingCalls = [
364
+ ...kept,
365
+ ...gated.map((gatedCall) => gatedCall.entry),
366
+ { call: nested.toolCall, status: "ready", approvalId: `nr_${nested.entry.runId}` },
367
+ ];
368
+ const keptIds = new Set(kept.map((entry) => entry.approvalId));
369
+ const decisions = [
370
+ ...(state?.interruption?.pendingDecisions ?? []).filter((pending) => keptIds.has(pending.approvalId)),
371
+ ...gated.map((gatedCall) => gatedCall.decision),
372
+ ...nested.pending,
373
+ ];
374
+ if (decisions.length > HARD_MAX_PENDING_DECISIONS) {
375
+ throw new AgentDecisionError("ERR_PRISM_DECISION_LIMIT", `Pending decisions exceed ${HARD_MAX_PENDING_DECISIONS} per run`);
376
+ }
377
+ const single = decisions.length === 1 ? decisions[0] : undefined;
378
+ const interruption = {
379
+ kind: single?.kind ?? "tool_approval",
380
+ reason: single ? single.reason : `${decisions.length} approval request(s) need a decision`,
381
+ ...(single?.toolCallId ? { toolCallId: single.toolCallId } : {}),
382
+ ...(single?.scope.toolName ? { toolName: single.scope.toolName } : {}),
383
+ pendingDecisions: decisions,
384
+ };
385
+ throw new AgentRunSuspended(await this.suspendDurable({
386
+ runId,
387
+ model,
388
+ limits,
389
+ interruption,
390
+ pendingCalls,
391
+ nestedRuns: [...(state?.nestedRuns ?? []), nested.entry],
392
+ }), interruption);
393
+ };
394
+ // Converts a nested-run suspension into either root-visible pending decisions (hashed,
395
+ // attributed approval ids) or — when a root sticky covers every surfaced decision and a
396
+ // hook is available — an immediate child resume loop ending in a synthesized tool result.
397
+ const applyNestedRun = async (input) => {
398
+ let current = input.pending;
399
+ // ponytail: sticky auto-apply only when the whole surfaced set is covered; mixed sets
400
+ // surface to the host. Hook round-trips capped at 4 per suspension event.
401
+ for (let depth = 0;; depth += 1) {
402
+ const attributed = current.map((decision) => {
403
+ const id = nestedApprovalId(input.ref.runId, decision.approvalId);
404
+ return {
405
+ id,
406
+ childApprovalId: decision.approvalId,
407
+ decision: { ...decision, approvalId: id, attribution: decision.attribution ?? { path: input.path } },
408
+ };
409
+ });
410
+ if (attributed.some(({ decision }) => (decision.attribution?.path.length ?? 0) > MAX_ATTRIBUTION_DEPTH)) {
411
+ throw new AgentDecisionError("ERR_PRISM_DECISION_LIMIT", `Attribution path exceeds ${MAX_ATTRIBUTION_DEPTH} entries`);
412
+ }
413
+ const allSticky = attributed.length > 0 && attributed.every(({ decision }) => this.matchNestedSticky(decision) !== undefined);
414
+ if (!input.hook || !allSticky || depth >= 4) {
415
+ return {
416
+ entry: {
417
+ runId: input.ref.runId,
418
+ ...(input.ref.sessionId ? { sessionId: input.ref.sessionId } : {}),
419
+ toolCallId: input.toolCall.id,
420
+ path: attributed[0]?.decision.attribution?.path ?? input.path,
421
+ approvals: attributed.map(({ id, childApprovalId }) => ({ id, childApprovalId })),
422
+ },
423
+ pending: attributed.map(({ decision }) => decision),
424
+ };
425
+ }
426
+ const outcome = await input.hook({ ref: input.ref, toolCallId: input.toolCall.id, path: input.path }, attributed.map(({ childApprovalId, decision }) => {
427
+ const sticky = this.matchNestedSticky(decision);
428
+ return {
429
+ approvalId: childApprovalId,
430
+ outcome: sticky.outcome,
431
+ ...(sticky.reason !== undefined ? { reason: sticky.reason } : {}),
432
+ };
433
+ }));
434
+ if (outcome.status === "suspended") {
435
+ current = outcome.pendingDecisions;
436
+ continue;
437
+ }
438
+ return { toolResult: nestedOutcomeToolResult(outcome, input.toolCall.id, input.toolCall.name) };
439
+ }
440
+ };
441
+ // ponytail: LoopContext binds existing private helpers; loop orchestrates only.
442
+ let assembledTurn = false;
443
+ let artifactFinished = false;
444
+ let artifactFailedInfo;
445
+ const ctx = {
446
+ sessionId: this.id,
447
+ runId,
448
+ metadata,
449
+ signal: controller.signal,
450
+ history: this.history,
451
+ input,
452
+ inputMessages,
453
+ maxToolRounds,
454
+ toolConcurrency,
455
+ restoredLoopState: resumed?.state?.loopState?.snapshot,
456
+ assemble: async (nextInput, toolResults, turn) => {
457
+ limits.charge("maxTurns");
458
+ const request = await assembleProviderInput({
459
+ model: options.model ?? this.agent.config.model,
460
+ input: nextInput,
461
+ history: this.history,
462
+ summaries: (await this.snapshot()).summaries,
463
+ toolResults: toolResults ?? [],
464
+ turn,
465
+ instructionInjectors,
466
+ inputLayout,
467
+ systemInstructions,
468
+ inputBuilder: this.agent.config.inputBuilder,
469
+ promptBuilder: this.agent.config.promptBuilder,
470
+ contextProviders,
471
+ skills: this.restoredSkillBodies.length ? applyRestoredSkillBodies(activeSkills, this.restoredSkillBodies) : activeSkills,
472
+ skillsDisclosure: resolveSkillsDisclosure(options.skillsDisclosure, this.agent.config.skillsDisclosure),
473
+ toolResultFold: resolveToolResultFold(options.toolResultFold, this.agent.config.toolResultFold),
474
+ loadedSkills: this.loadedSkills,
475
+ tools,
476
+ resourceLoader: this.agent.config.resourceLoader,
477
+ permission: this.agent.config.permission,
478
+ trust: this.agent.config.trust,
479
+ providerOptions,
480
+ redactor: this.activeRedactor,
481
+ middleware: this.agent.config.middleware,
482
+ sessionId: this.id,
483
+ runId,
484
+ metadata,
485
+ signal: controller.signal,
486
+ });
487
+ assembledTurn = true;
488
+ return request;
489
+ },
490
+ chargeToolRound: (calls) => {
491
+ if (calls.length > 0)
492
+ limits.charge("maxToolRounds");
493
+ const durable = this.activeDurable;
494
+ if (!durable?.options.interruptBeforeTool || calls.length === 0)
495
+ return;
496
+ // Round-level gate: record one pending decision per uncovered gated call. Ungated
497
+ // and sticky-allowed calls still dispatch; the suspension fires at the next provider
498
+ // turn (or run end) via suspendGatedRound. Per-call beforeExecute is the backstop
499
+ // for loops that dispatch without charging a round.
500
+ for (const call of calls) {
501
+ if (this.matchStickyDecision(call, registry))
502
+ continue;
503
+ const approvalId = randomId("approval");
504
+ this.activeGatedRound ??= new Map();
505
+ this.activeGatedRound.set(call.id, {
506
+ entry: { call, status: "ready", approvalId },
507
+ decision: this.buildPendingDecision(call, approvalId, registry, runId, metadata, controller.signal),
508
+ });
509
+ }
510
+ if (this.activeGatedRound && this.activeGatedRound.size > DEFAULT_MAX_PENDING_DECISIONS) {
511
+ throw new AgentDecisionError("ERR_PRISM_DECISION_LIMIT", `Pending decisions exceed ${DEFAULT_MAX_PENDING_DECISIONS} per run`);
512
+ }
513
+ },
514
+ generate: async (request) => {
515
+ await suspendGatedRound();
516
+ if (!assembledTurn)
517
+ limits.charge("maxTurns");
518
+ assembledTurn = false;
519
+ const policyResult = await this.applyProviderRequestPolicies(request, runId, options, metadata, controller.signal);
520
+ const middlewareRequest = (await this.agent.config.middleware?.run("provider_request", policyResult.request)) ?? policyResult.request;
521
+ try {
522
+ return await this.generateWithRetry(this.redactProviderRequest(middlewareRequest), runId, options, controller.signal, policyResult.secrets, this.activeLoopTurn, recordProviderUsage);
523
+ }
524
+ catch (error) {
525
+ if (isSteerSoftInterrupt(error)) {
526
+ return { content: [], calls: [], started: false, usage: undefined };
527
+ }
528
+ throw error;
529
+ }
530
+ },
531
+ isToolCallExclusive: (call) => registry.get(call.name)?.exclusive === true,
532
+ dispatchToolCall: async (call) => {
533
+ const sticky = this.matchStickyDecision(call, registry);
534
+ if (sticky?.outcome === "reject_for_run") {
535
+ return {
536
+ toolCallId: call.id,
537
+ name: call.name,
538
+ error: { code: "approval_rejected", message: sticky.reason ?? "Rejected for this run" },
539
+ };
540
+ }
541
+ if (this.activeGatedRound?.has(call.id)) {
542
+ // Gated this round: never dispatched. The marker is skipped by
543
+ // dispatchToolCallsInOrder so the transcript stays free of phantom results.
544
+ return { toolCallId: call.id, name: call.name, metadata: { approvalPending: true } };
545
+ }
546
+ try {
547
+ return await dispatchToolCall({
548
+ call,
549
+ registry,
550
+ context: {
551
+ sessionId: this.id,
552
+ runId,
553
+ toolCallId: call.id,
554
+ signal: controller.signal,
555
+ metadata: {
556
+ ...metadata,
557
+ loadedSkills: this.loadedSkills,
558
+ activeTools: tools,
559
+ activeSkillNames: activeSkills.map((skill) => skill.name),
560
+ },
561
+ identity: this.activeIdentity,
562
+ },
563
+ middleware: this.agent.config.middleware,
564
+ emit: (event) => this.emit(event),
565
+ permission: this.agent.config.permission,
566
+ trust: this.agent.config.trust,
567
+ redactor: this.activeRedactor,
568
+ ledger: this.activeLedger,
569
+ effectStore: this.activeEffectStore,
570
+ ownership: this.activeOwnership,
571
+ identity: this.activeIdentity,
572
+ guardrails: this.activeGuardrails,
573
+ limitTracker: limits,
574
+ beforeExecute: async (mediatedCall) => {
575
+ const durable = this.activeDurable;
576
+ if (!durable)
577
+ return;
578
+ const pendingCalls = durable.state?.pendingCalls;
579
+ const matched = pendingCalls?.find((entry) => entry.call.id === mediatedCall.id && entry.status === "ready");
580
+ if (matched) {
581
+ await this.persistDurable({
582
+ ...durable.state,
583
+ status: "running",
584
+ pendingCalls: pendingCalls.map((entry) => (entry === matched ? { ...entry, status: "dispatched" } : entry)),
585
+ interruption: undefined,
586
+ });
587
+ return;
588
+ }
589
+ const pending = durable.state?.pending;
590
+ if (pending?.call.id === mediatedCall.id && pending.status === "ready") {
591
+ await this.persistDurable({
592
+ ...durable.state,
593
+ status: "running",
594
+ pending: { ...pending, status: "dispatched" },
595
+ interruption: undefined,
596
+ });
597
+ return;
598
+ }
599
+ if (!durable.options.interruptBeforeTool)
600
+ return;
601
+ if (this.matchStickyDecision(mediatedCall, registry)?.outcome === "allow_for_run")
602
+ return;
603
+ // Backstop for loops that dispatch without awaiting chargeToolRound: suspend on
604
+ // the first uncovered gated call with a single pending decision.
605
+ const approvalId = randomId("approval");
606
+ const decision = this.buildPendingDecision(mediatedCall, approvalId, registry, runId, metadata, controller.signal);
607
+ const interruption = {
608
+ kind: "tool_approval",
609
+ reason: decision.reason,
610
+ toolCallId: mediatedCall.id,
611
+ toolName: mediatedCall.name,
612
+ pendingDecisions: [decision],
613
+ };
614
+ throw new AgentRunSuspended(await this.suspendDurable({
615
+ runId,
616
+ model,
617
+ limits,
618
+ interruption,
619
+ pending: { call: mediatedCall, status: "ready" },
620
+ pendingCalls: [{ call: mediatedCall, status: "ready", approvalId }],
621
+ }), interruption);
622
+ },
623
+ // ponytail: RunOptions wins; array-compose deferred (roadmap: compose-later).
624
+ validate,
625
+ });
626
+ }
627
+ catch (error) {
628
+ // Link the suspension signal to the hosting call so the root suspension can
629
+ // synthesize this call's tool_result when the nested run later terminates.
630
+ if (error instanceof AgentDelegationSuspendedError && !error.toolCall)
631
+ error.toolCall = call;
632
+ throw error;
633
+ }
634
+ },
635
+ appendMessage: (message) => this.appendMessage(message, runId),
636
+ hasPendingSteers: () => this.pendingSteers.length > 0,
637
+ applyPendingSteers: () => this.applyPendingSteers(runId, metadata, controller.signal),
638
+ emit: (event) => {
639
+ if (event.type === "turn_started")
640
+ this.activeLoopTurn = event.turn;
641
+ if (event.type === "artifact_finished")
642
+ artifactFinished = true;
643
+ if (event.type === "artifact_failed") {
644
+ const first = event.result.errors?.[0];
645
+ const reason = event.result.metadata?.reason;
646
+ artifactFailedInfo = {
647
+ message: first?.message ?? "artifact failed",
648
+ code: typeof reason === "string" || typeof reason === "number" ? reason : "artifact_failed",
649
+ };
650
+ }
651
+ this.emit(event);
652
+ },
653
+ };
654
+ const replayToolResult = async (result) => {
655
+ await ctx.appendMessage({
656
+ role: "tool",
657
+ content: [
658
+ { type: "tool_result", toolCallId: result.toolCallId, name: result.name, result: result.value, error: result.error },
659
+ ...(result.content ?? []),
660
+ ],
661
+ metadata: result.metadata,
662
+ });
663
+ };
664
+ // Handles a nested-run suspension signal: sticky auto-apply appends a synthesized
665
+ // tool_result and returns; anything else re-suspends the root (throws AgentRunSuspended).
666
+ const handleNestedSignal = async (error) => {
667
+ const durableOptions = this.activeDurable?.options;
668
+ if (!durableOptions || !error.toolCall) {
669
+ throw new AgentDecisionError("ERR_PRISM_DECISION_INVALID", "Nested-run suspension requires durable run state and a hosting tool call");
670
+ }
671
+ if (error.pendingDecisions.length === 0) {
672
+ throw new AgentDecisionError("ERR_PRISM_DECISION_INVALID", "Nested-run suspension carried no pending decisions");
673
+ }
674
+ const applied = await applyNestedRun({
675
+ ref: error.ref,
676
+ toolCall: error.toolCall,
677
+ path: error.path ?? [],
678
+ pending: error.pendingDecisions,
679
+ hook: durableOptions.resumeNestedRun,
680
+ });
681
+ if ("toolResult" in applied) {
682
+ await replayToolResult(applied.toolResult);
683
+ return;
684
+ }
685
+ await suspendNested({ entry: applied.entry, toolCall: error.toolCall, pending: applied.pending });
686
+ };
687
+ // Route decided nested-run approvals back to their children before replaying own calls.
688
+ // Undecided or re-suspended children re-suspend the root with the surfaced remainder.
689
+ let resumePendingCalls = resumed?.state?.pendingCalls;
690
+ if (resumed?.state?.nestedRuns?.length) {
691
+ const nestedRuns = resumed.state.nestedRuns;
692
+ const hook = this.activeDurable?.options.resumeNestedRun;
693
+ const oldPending = resumed.state.interruption?.pendingDecisions ?? [];
694
+ const nestedApprovalIds = new Set(nestedRuns.flatMap((entry) => entry.approvals.map((approval) => approval.id)));
695
+ const remainingNested = [];
696
+ const surfacedPending = [];
697
+ const resolvedToolCallIds = new Set();
698
+ for (const entry of nestedRuns) {
699
+ const grouped = [];
700
+ for (const approval of entry.approvals) {
701
+ const decision = entry.decisions?.[approval.id] ?? resumed.decisions?.get(approval.id);
702
+ if (decision)
703
+ grouped.push({ ...decision, approvalId: approval.childApprovalId });
704
+ }
705
+ if (grouped.length === 0) {
706
+ remainingNested.push(entry);
707
+ surfacedPending.push(...oldPending.filter((pending) => entry.approvals.some((approval) => approval.id === pending.approvalId)));
708
+ continue;
709
+ }
710
+ if (!hook) {
711
+ throw new AgentDecisionError("ERR_PRISM_DECISION_INVALID", "Nested-run decisions require a resumeNestedRun hook");
712
+ }
713
+ const toolCall = resumePendingCalls?.find((pending) => pending.call.id === entry.toolCallId)?.call;
714
+ if (!toolCall)
715
+ throw new AgentRunStateError("Nested run link is missing its tool call");
716
+ const ref = { runId: entry.runId, ...(entry.sessionId ? { sessionId: entry.sessionId } : {}) };
717
+ const outcome = await hook({ ref, toolCallId: entry.toolCallId, path: entry.path }, grouped);
718
+ if (outcome.status !== "suspended") {
719
+ await replayToolResult(nestedOutcomeToolResult(outcome, entry.toolCallId, toolCall.name));
720
+ resolvedToolCallIds.add(entry.toolCallId);
721
+ continue;
722
+ }
723
+ const applied = await applyNestedRun({ ref, toolCall, path: entry.path, pending: outcome.pendingDecisions, hook });
724
+ if ("toolResult" in applied) {
725
+ await replayToolResult(applied.toolResult);
726
+ resolvedToolCallIds.add(entry.toolCallId);
727
+ }
728
+ else {
729
+ remainingNested.push(applied.entry);
730
+ surfacedPending.push(...applied.pending);
731
+ }
732
+ }
733
+ resumePendingCalls = resumePendingCalls
734
+ ?.filter((entry) => !resolvedToolCallIds.has(entry.call.id))
735
+ .map((entry) => {
736
+ const decision = resumed.decisions?.get(entry.approvalId);
737
+ return decision && !entry.decision ? { ...entry, decision } : entry;
738
+ });
739
+ if (this.activeDurable?.state) {
740
+ this.activeDurable.state = {
741
+ ...this.activeDurable.state,
742
+ pendingCalls: resumePendingCalls?.length ? resumePendingCalls : undefined,
743
+ nestedRuns: remainingNested.length ? remainingNested : undefined,
744
+ };
745
+ }
746
+ const remainingOwn = oldPending.filter((pending) => !nestedApprovalIds.has(pending.approvalId) &&
747
+ !resumed.decisions?.has(pending.approvalId) &&
748
+ !resumePendingCalls?.some((entry) => entry.approvalId === pending.approvalId && entry.decision !== undefined));
749
+ if (remainingOwn.length > 0 || surfacedPending.length > 0) {
750
+ const pendingDecisions = [...remainingOwn, ...surfacedPending];
751
+ const single = pendingDecisions.length === 1 ? pendingDecisions[0] : undefined;
752
+ const interruption = {
753
+ kind: single?.kind ?? "tool_approval",
754
+ reason: `${pendingDecisions.length} approval request(s) remain`,
755
+ ...(single?.toolCallId ? { toolCallId: single.toolCallId } : {}),
756
+ ...(single?.scope.toolName ? { toolName: single.scope.toolName } : {}),
757
+ pendingDecisions,
758
+ };
759
+ throw new AgentRunSuspended(await this.suspendDurable({
760
+ runId,
761
+ model,
762
+ limits,
763
+ interruption,
764
+ pendingCalls: resumePendingCalls,
765
+ nestedRuns: remainingNested,
766
+ }), interruption);
767
+ }
768
+ }
769
+ if (resumePendingCalls?.length) {
770
+ for (const entry of resumePendingCalls) {
771
+ if (entry.status !== "ready")
772
+ continue;
773
+ const decision = entry.decision ?? resumed?.decisions?.get(entry.approvalId);
774
+ if (decision && (decision.outcome === "reject_once" || decision.outcome === "reject_for_run")) {
775
+ await replayToolResult({
776
+ toolCallId: entry.call.id,
777
+ name: entry.call.name,
778
+ error: { code: "approval_rejected", message: decision.reason ?? "Approval rejected" },
779
+ });
780
+ continue;
781
+ }
782
+ if (decision?.elicitation !== undefined) {
783
+ // Elicitation acceptance resolves the suspended call with the validated payload.
784
+ await replayToolResult({ toolCallId: entry.call.id, name: entry.call.name, value: decision.elicitation });
785
+ continue;
786
+ }
787
+ const call = decision?.modifiedArguments ? { ...entry.call, arguments: decision.modifiedArguments } : entry.call;
788
+ try {
789
+ await replayToolResult(await ctx.dispatchToolCall(call));
790
+ }
791
+ catch (error) {
792
+ if (!(error instanceof AgentDelegationSuspendedError))
793
+ throw error;
794
+ await handleNestedSignal(error);
795
+ }
796
+ }
797
+ }
798
+ else if (resumed?.state?.pending?.status === "ready") {
799
+ await replayToolResult(await ctx.dispatchToolCall(resumed.state.pending.call));
800
+ }
801
+ const resumedLoopState = resumed?.state?.loopState;
802
+ if (resumedLoopState) {
803
+ if (loop.name !== resumedLoopState.name || (loop.revision ?? "1") !== resumedLoopState.revision) {
804
+ throw new AgentLoopStateError("ERR_PRISM_LOOP_REVISION", `Loop ${resumedLoopState.name} revision ${resumedLoopState.revision} does not match the resumed durable run`);
805
+ }
806
+ loop.restore?.(resumedLoopState.snapshot);
807
+ }
808
+ let loopUsage;
809
+ while (true) {
810
+ try {
811
+ loopUsage = await loop.run(ctx);
812
+ await suspendGatedRound();
813
+ break;
814
+ }
815
+ catch (error) {
816
+ if (!(error instanceof AgentDelegationSuspendedError))
817
+ throw error;
818
+ await handleNestedSignal(error);
819
+ }
820
+ }
821
+ if (loop.name === "generate-validate-revise" && !artifactFinished) {
822
+ throw Object.assign(new Error(artifactFailedInfo?.message ?? "artifact loop ended without a validated artifact"), {
823
+ name: "ArtifactFailed",
824
+ code: artifactFailedInfo?.code ?? "artifact_failed",
825
+ });
826
+ }
827
+ usage = runUsage.value() ?? loopUsage;
828
+ if (usage && this.activeLedger) {
829
+ const usageRecord = {
830
+ id: randomId("usage"),
831
+ sessionId: this.id,
832
+ runId,
833
+ scope: "run_total",
834
+ usage,
835
+ recordedAt: new Date().toISOString(),
836
+ ...this.activeOwnership,
837
+ };
838
+ await this.activeLedger.appendUsage(redactRunLedgerRecord(usageRecord, this.activeRedactor));
839
+ }
840
+ await this.drainLedger();
841
+ const runState = this.activeDurable?.state
842
+ ? await this.persistDurable({
843
+ ...this.activeDurable.state,
844
+ status: "succeeded",
845
+ pending: undefined,
846
+ pendingCalls: undefined,
847
+ nestedRuns: undefined,
848
+ stickyDecisions: undefined,
849
+ interruption: undefined,
850
+ loopState: undefined,
851
+ })
852
+ : undefined;
853
+ this.emit({ type: "agent_finished", sessionId: this.id, runId, usage });
854
+ return this.buildRunResult({ runId, status: "succeeded", usage, runState });
855
+ }
856
+ catch (error) {
857
+ if (error instanceof AgentRunSuspended) {
858
+ runStatus = "suspended";
859
+ const version = error.state.version;
860
+ this.emit({ type: "agent_suspended", sessionId: this.id, runId, interruption: error.interruption, version });
861
+ return this.buildRunResult({ runId, status: "suspended", runState: error.state, interruption: error.interruption });
862
+ }
863
+ runError = errorToErrorInfo(error);
864
+ this.emit({ type: "error", sessionId: this.id, runId, error: runError });
865
+ const breach = error instanceof RunLimitError ? error.breach : limits.breach;
866
+ runStatus = breach ? "failed" : controller.signal.aborted ? "aborted" : "failed";
867
+ const runState = this.activeDurable?.state
868
+ ? await this.persistDurable({
869
+ ...this.activeDurable.state,
870
+ status: runStatus,
871
+ interruption: undefined,
872
+ loopState: undefined,
873
+ pendingCalls: undefined,
874
+ nestedRuns: undefined,
875
+ stickyDecisions: undefined,
876
+ })
877
+ : undefined;
878
+ const result = this.buildRunResult({
879
+ runId,
880
+ status: runStatus,
881
+ usage: runUsage.value() ?? usage,
882
+ limit: breach,
883
+ error: runError,
884
+ abortReason: !breach && controller.signal.aborted ? String(controller.signal.reason) : undefined,
885
+ runState,
886
+ });
887
+ throw new AgentRunError(result, { cause: error });
888
+ }
889
+ finally {
890
+ if (this.activeRun === controller)
891
+ this.activeRun = undefined;
892
+ this.activeRunId = undefined;
893
+ this.activeLoop = undefined;
894
+ this.activeGatedRound = undefined;
895
+ this.activeProviderTurnAbort = undefined;
896
+ this.pendingSoftInterrupt = false;
897
+ this.pendingSteers = [];
898
+ this.pendingSteerBytes = 0;
899
+ try {
900
+ await this.drainLedger();
901
+ if (this.activeLedger) {
902
+ const status = runStatus;
903
+ const finishRecord = {
904
+ id: runId,
905
+ sessionId: this.id,
906
+ branchId: this.currentLeafId,
907
+ model,
908
+ provider: model.provider,
909
+ idempotencyKey: this.activeIdempotencyKey,
910
+ status,
911
+ startedAt,
912
+ finishedAt: new Date().toISOString(),
913
+ abortReason: controller.signal.aborted ? String(controller.signal.reason) : undefined,
914
+ error: runError,
915
+ ...this.activeOwnership,
916
+ };
917
+ await this.activeLedger.appendRun(redactRunLedgerRecord(finishRecord, this.activeRedactor));
918
+ if (isFlushableRunLedger(this.activeLedger) && this.activeLedger.durability === "flush_on_terminal")
919
+ await this.activeLedger.flush();
920
+ }
921
+ }
922
+ finally {
923
+ this.activeLedger = undefined;
924
+ this.activeEffectStore = undefined;
925
+ this.activeOwnership = undefined;
926
+ this.activeIdentity = undefined;
927
+ this.activeIdempotencyKey = undefined;
928
+ this.activeGuardrails = undefined;
929
+ this.activeMetadata = undefined;
930
+ this.activeLimits?.dispose();
931
+ this.activeLimits = undefined;
932
+ this.activeLimitOutputBuffer = false;
933
+ this.activeRedactor = undefined;
934
+ this.activeProvider = undefined;
935
+ cleanupSignal();
936
+ this.closeSubscribers();
937
+ }
938
+ }
939
+ }
940
+ prompt(input, options) {
941
+ return this.run(input, options);
942
+ }
943
+ async *stream(input, options = {}) {
944
+ const { maxQueuedEvents, overflow, ...runOptions } = options;
945
+ const subscription = this.subscribe({ maxQueuedEvents, overflow });
946
+ let runOwnedId;
947
+ let settled = false;
948
+ const runPromise = this.run(input, runOptions).finally(() => {
949
+ settled = true;
950
+ });
951
+ try {
952
+ for await (const event of subscription) {
953
+ if ("runId" in event && typeof event.runId === "string") {
954
+ if (runOwnedId === undefined && event.type === "agent_started")
955
+ runOwnedId = event.runId;
956
+ if (runOwnedId !== undefined && event.runId !== runOwnedId)
957
+ continue;
958
+ }
959
+ yield event;
960
+ }
961
+ await runPromise;
962
+ }
963
+ finally {
964
+ if (!settled) {
965
+ this.abort(new Error("stream consumer closed"));
966
+ await runPromise.catch(() => undefined);
967
+ }
968
+ }
969
+ }
970
+ buildRunResult(input) {
971
+ const final = finalAssistantMessage(this.history);
972
+ return {
973
+ sessionId: this.id,
974
+ runId: input.runId,
975
+ status: input.status,
976
+ leafId: this.currentLeafId,
977
+ text: final.text,
978
+ content: final.content,
979
+ message: final.message,
980
+ usage: input.usage,
981
+ limit: input.limit,
982
+ error: input.error,
983
+ abortReason: input.abortReason,
984
+ runState: input.runState,
985
+ interruption: input.interruption,
986
+ };
987
+ }
988
+ async suspendDurable(input) {
989
+ const durable = this.activeDurable;
990
+ if (!durable)
991
+ throw new AgentRunStateError("Durable interruption is not configured");
992
+ // Capture loop-local state before persisting the suspension. Undefined before the loop
993
+ // starts (input-guardrail suspensions) and for snapshot-less built-ins.
994
+ const loop = this.activeLoop;
995
+ const loopState = loop?.snapshot ? boundedLoopSnapshot(loop.name, loop.revision ?? "1", loop.snapshot()) : undefined;
996
+ const state = durable.state ??
997
+ initialAgentRunState({
998
+ agent: this.agent,
999
+ options: durable.options,
1000
+ runId: input.runId,
1001
+ sessionId: this.id,
1002
+ leafId: this.currentLeafId,
1003
+ model: input.model,
1004
+ counters: input.limits.snapshot(),
1005
+ deadlineAt: input.limits.deadlineAt,
1006
+ status: "suspended",
1007
+ interruption: input.interruption,
1008
+ messages: input.messages,
1009
+ pending: input.pending,
1010
+ pendingCalls: input.pendingCalls,
1011
+ interruptBeforeTool: durable.options.interruptBeforeTool,
1012
+ });
1013
+ return this.persistDurable({
1014
+ ...state,
1015
+ leafId: this.currentLeafId,
1016
+ status: "suspended",
1017
+ interruption: input.interruption,
1018
+ ...(input.messages ? { input: input.messages } : {}),
1019
+ ...(input.pending ? { pending: input.pending } : {}),
1020
+ ...(input.pendingCalls ? { pendingCalls: input.pendingCalls } : {}),
1021
+ nestedRuns: input.nestedRuns ?? state.nestedRuns,
1022
+ ...(loopState ? { loopState } : {}),
1023
+ counters: input.limits.snapshot(),
1024
+ });
1025
+ }
1026
+ /** First attributed sticky whose scope and delegation path exactly match a nested decision. */
1027
+ matchNestedSticky(decision) {
1028
+ const stickies = this.activeDurable?.state?.stickyDecisions;
1029
+ return stickies?.find((sticky) => sticky.attribution !== undefined &&
1030
+ pathsEqual(sticky.attribution.path, decision.attribution?.path) &&
1031
+ decisionScopesEqual(sticky.scope, decision.scope));
1032
+ }
1033
+ /** First sticky decision whose scope exactly matches this call, if any. */
1034
+ matchStickyDecision(call, registry) {
1035
+ const stickies = this.activeDurable?.state?.stickyDecisions;
1036
+ if (!stickies?.length)
1037
+ return undefined;
1038
+ const identityRef = decisionIdentityRef(this.activeIdentity);
1039
+ let argumentsHash;
1040
+ let effectKind;
1041
+ let effectResolved = false;
1042
+ return stickies.find((sticky) => {
1043
+ if (sticky.attribution !== undefined)
1044
+ return false; // nested-run stickies match decisions, not calls
1045
+ const scope = sticky.scope;
1046
+ if (scope.toolName !== undefined && scope.toolName !== call.name)
1047
+ return false;
1048
+ if (scope.identity !== undefined && scope.identity !== identityRef)
1049
+ return false;
1050
+ if (scope.argumentsHash !== undefined) {
1051
+ argumentsHash ??= toolEffectArgumentsHash(call.arguments);
1052
+ if (scope.argumentsHash !== argumentsHash)
1053
+ return false;
1054
+ }
1055
+ if (scope.effectKind !== undefined) {
1056
+ if (!effectResolved) {
1057
+ effectResolved = true;
1058
+ const tool = registry.get(call.name);
1059
+ effectKind = tool?.effect
1060
+ ? resolveToolEffectDeclaration(tool, call.arguments, { sessionId: this.id, runId: "", toolCallId: call.id })?.kind
1061
+ : undefined;
1062
+ }
1063
+ if (scope.effectKind !== effectKind)
1064
+ return false;
1065
+ }
1066
+ if (scope.actionConstraints) {
1067
+ for (const [key, value] of Object.entries(scope.actionConstraints)) {
1068
+ const actual = call.arguments[key];
1069
+ if (canonicalToolEffectJson(actual === undefined ? null : actual) !== canonicalToolEffectJson(value))
1070
+ return false;
1071
+ }
1072
+ }
1073
+ return true;
1074
+ });
1075
+ }
1076
+ /** Redacted pending-decision descriptor for one gated call; never carries raw arguments. */
1077
+ buildPendingDecision(call, approvalId, registry, runId, metadata, signal) {
1078
+ const tool = registry.get(call.name);
1079
+ const declaration = tool?.effect
1080
+ ? resolveToolEffectDeclaration(tool, call.arguments, {
1081
+ sessionId: this.id,
1082
+ runId,
1083
+ toolCallId: call.id,
1084
+ signal,
1085
+ metadata,
1086
+ })
1087
+ : undefined;
1088
+ const identityRef = decisionIdentityRef(this.activeIdentity);
1089
+ const elicitation = toolElicitationRequest(tool, call.arguments, {
1090
+ sessionId: this.id,
1091
+ runId,
1092
+ toolCallId: call.id,
1093
+ signal,
1094
+ metadata,
1095
+ });
1096
+ return {
1097
+ approvalId,
1098
+ kind: elicitation ? "elicitation" : "tool_approval",
1099
+ toolCallId: call.id,
1100
+ scope: {
1101
+ toolName: call.name,
1102
+ argumentsHash: toolEffectArgumentsHash(call.arguments),
1103
+ ...(declaration && declaration.kind !== "none" ? { effectKind: declaration.kind } : {}),
1104
+ ...(identityRef ? { identity: identityRef } : {}),
1105
+ },
1106
+ reason: elicitation?.reason ?? "Tool side effect requires approval",
1107
+ ...(elicitation ? { elicitationSchema: elicitation.schema } : {}),
1108
+ };
1109
+ }
1110
+ async persistDurable(state) {
1111
+ const durable = this.activeDurable;
1112
+ if (!durable)
1113
+ throw new AgentRunStateError("Durable run state is not configured");
1114
+ const persisted = durable.options.persistSessionState
1115
+ ? {
1116
+ ...state,
1117
+ sessionState: {
1118
+ loadedSkillNames: this.loadedSkills.list(),
1119
+ ...(durable.options.includeSkillBodies
1120
+ ? {
1121
+ loadedSkillBodies: snapshotLoadedSkillBodies(this.activeRunSkills, this.loadedSkills, this.restoredSkillBodies.length ? new Map(this.restoredSkillBodies.map((e) => [e.name, e.instructions])) : undefined),
1122
+ }
1123
+ : {}),
1124
+ },
1125
+ }
1126
+ : state;
1127
+ const saved = await saveAgentRunState({
1128
+ checkpoints: durable.options.checkpoints,
1129
+ state: persisted,
1130
+ expectedVersion: durable.version,
1131
+ ownership: this.activeOwnership,
1132
+ fencingToken: durable.options.fencingToken,
1133
+ redactor: this.activeRedactor,
1134
+ maxStateBytes: durable.options.maxStateBytes,
1135
+ });
1136
+ durable.state = saved.state;
1137
+ durable.version = saved.record.version;
1138
+ return publicState(saved.state);
1139
+ }
1140
+ async compact(options = {}) {
1141
+ if (this.activeRun)
1142
+ throw new Error("Agent session already has an active run");
1143
+ return this.compactBranch(options, undefined, options.signal, "manual");
1144
+ }
1145
+ abort(reason) {
1146
+ this.activeRun?.abort(reason);
1147
+ }
1148
+ async entries() {
1149
+ const reader = this.branchReader();
1150
+ return reader
1151
+ ? getSessionBranchEntries(reader, { sessionId: this.id, leafId: this.currentLeafId })
1152
+ : getSessionBranchEntries(await this.store.list(this.id), { leafId: this.currentLeafId });
1153
+ }
1154
+ async checkout(leafId) {
1155
+ this.currentLeafId = leafId;
1156
+ this.invalidateSnapshot();
1157
+ await this.rebuildHistory();
1158
+ }
1159
+ fork(options = {}) {
1160
+ return createAgentSession({
1161
+ agent: this.agent,
1162
+ id: this.id,
1163
+ store: this.store,
1164
+ leafId: options.leafId ?? this.currentLeafId,
1165
+ metadata: this.metadata,
1166
+ });
1167
+ }
1168
+ async clone(options = {}) {
1169
+ const id = options.id ?? randomId("session");
1170
+ const leafId = options.leafId ?? this.currentLeafId;
1171
+ const reader = this.branchReader();
1172
+ const branch = reader
1173
+ ? await getSessionBranchEntries(reader, { sessionId: this.id, leafId })
1174
+ : getSessionBranchEntries(await this.store.list(this.id), { leafId });
1175
+ const remap = new Map();
1176
+ for (const entry of branch) {
1177
+ const nextId = randomId("entry");
1178
+ remap.set(entry.id, nextId);
1179
+ const { id: _oldId, parentId: _oldParentId, sessionId: _oldSessionId, ...rest } = entry;
1180
+ await this.store.append({ ...rest, id: nextId, parentId: entry.parentId ? remap.get(entry.parentId) : undefined, sessionId: id });
1181
+ }
1182
+ return createAgentSession({
1183
+ agent: this.agent,
1184
+ id,
1185
+ store: this.store,
1186
+ leafId: branch.length ? remap.get(branch[branch.length - 1].id) : undefined,
1187
+ metadata: this.metadata,
1188
+ });
1189
+ }
1190
+ branchReader() {
1191
+ // ponytail: prefer the store's readBranchPath (one ancestor-chain query) when present so a
1192
+ // DB-backed store never loads the full session; else fall back to list() + in-memory walk.
1193
+ const read = this.store.readBranchPath;
1194
+ return read ? (query) => read.call(this.store, query) : undefined;
1195
+ }
1196
+ resolveRunProvider(options) {
1197
+ const model = options.model ?? this.agent.config.model;
1198
+ // Provider precedence: an explicit `AgentConfig.provider` wins and bypasses
1199
+ // the resolver entirely; otherwise `RunOptions.providerSource` overrides
1200
+ // `AgentConfig.providerSource` for this run. A miss on every source fails
1201
+ // closed with `Unknown provider: ${model.provider}` before any provider turn.
1202
+ const provider = this.agent.config.provider ?? options.providerSource?.(model) ?? this.agent.config.providerSource?.(model);
1203
+ if (!provider)
1204
+ throw new Error(`Unknown provider: ${model.provider}`);
1205
+ this.activeProvider = provider;
1206
+ }
1207
+ resolveRunSkills(options, tools) {
1208
+ const configured = this.agent.config.skills;
1209
+ if (configured && typeof configured === "object" && "list" in configured) {
1210
+ if (options.activeSkills)
1211
+ return resolveActiveSkills({ registry: configured, names: options.activeSkills, tools });
1212
+ if (options.skills !== undefined)
1213
+ return options.skills;
1214
+ if (options.activateAllSkills ?? this.agent.config.activateAllSkills)
1215
+ return configured.list();
1216
+ return [];
1217
+ }
1218
+ const arr = options.skills ?? (Array.isArray(configured) ? configured : []);
1219
+ return arr;
1220
+ }
1221
+ emit(event) {
1222
+ const redacted = redactAgentEvent(event, this.activeRedactor);
1223
+ for (const subscriber of this.subscribers)
1224
+ subscriber.push(redacted);
1225
+ if (this.activeLedger) {
1226
+ const record = {
1227
+ id: randomId("event"),
1228
+ sessionId: event.sessionId ?? this.id,
1229
+ runId: event.runId,
1230
+ type: event.type,
1231
+ timestamp: new Date().toISOString(),
1232
+ event: redacted,
1233
+ redacted: Boolean(this.activeRedactor),
1234
+ ...this.activeOwnership,
1235
+ };
1236
+ const ledger = this.activeLedger;
1237
+ this.ledgerChain = this.ledgerChain.then(async () => {
1238
+ if (this.ledgerFailure)
1239
+ return;
1240
+ try {
1241
+ await ledger.appendEvent(redactRunLedgerRecord(record, this.activeRedactor));
1242
+ }
1243
+ catch (error) {
1244
+ this.ledgerFailure = error;
1245
+ }
1246
+ });
1247
+ }
1248
+ }
1249
+ closeSubscribers() {
1250
+ for (const subscriber of this.subscribers)
1251
+ subscriber.close();
1252
+ this.subscribers.clear();
1253
+ }
1254
+ async drainLedger() {
1255
+ await this.ledgerChain;
1256
+ const failure = this.ledgerFailure;
1257
+ this.ledgerChain = Promise.resolve();
1258
+ this.ledgerFailure = undefined;
1259
+ if (failure)
1260
+ throw failure;
1261
+ }
1262
+ async generateWithRetry(request, runId, options, signal, requestSecrets = [], turn = 1, recordUsage) {
1263
+ const retry = mergeRetry(this.agent.config.retry, options.retry);
1264
+ const secrets = [...requestSecrets, ...(retry?.secrets ?? [])];
1265
+ const policy = retry?.policy ?? (retry ? createDefaultRetryPolicy(retry) : undefined);
1266
+ for (let attempt = 1;; attempt += 1) {
1267
+ try {
1268
+ return await this.generateProviderTurn(request, runId, signal, secrets, turn, attempt, recordUsage);
1269
+ }
1270
+ catch (error) {
1271
+ if (error instanceof GuardrailError || isSteerSoftInterrupt(error))
1272
+ throw error;
1273
+ const failure = error instanceof ProviderTurnFailure ? error : undefined;
1274
+ const info = failure ? redactSecrets(failure.info, secrets) : errorToErrorInfo(error, secrets);
1275
+ if (!policy || failure?.observable)
1276
+ throw errorFromInfo(info);
1277
+ const context = { sessionId: this.id, runId, attempt, error: info, metadata: retry?.metadata, signal };
1278
+ let decision = await policy.decide(context);
1279
+ const payload = (await this.agent.config.middleware?.run("retry", { context, decision })) ?? {
1280
+ context,
1281
+ decision,
1282
+ };
1283
+ decision = payload.decision;
1284
+ if (!decision.retry)
1285
+ throw errorFromInfo(info);
1286
+ const delayMs = decision.delayMs ?? 0;
1287
+ this.emit({ type: "retry_scheduled", sessionId: this.id, runId, attempt, delayMs, error: info });
1288
+ await waitForRetry(decision, signal);
1289
+ }
1290
+ }
1291
+ }
1292
+ async generateProviderTurn(request, runId, signal, secrets = [], turn = 1, attempt = 1, recordUsage) {
1293
+ this.activeLimits.charge("maxProviderAttempts");
1294
+ this.activeLimits.charge("maxRequestBytes", jsonBytes(request));
1295
+ const startedAt = performance.now();
1296
+ const providerId = this.activeProvider?.id ?? request.model.provider;
1297
+ const buildMetadata = (extra = {}) => createProviderTurnMetadata(request, providerId, { attempt, ...extra });
1298
+ this.emit({
1299
+ type: "provider_turn_started",
1300
+ sessionId: this.id,
1301
+ runId,
1302
+ turn,
1303
+ metadata: buildMetadata(),
1304
+ });
1305
+ const content = [];
1306
+ const calls = [];
1307
+ const toolDeltas = [];
1308
+ let messageId;
1309
+ let started = false;
1310
+ let usage;
1311
+ let usageRecorded = false;
1312
+ const bufferedOutput = [];
1313
+ const bufferOutput = Boolean(this.activeGuardrails?.output?.length || this.activeLimitOutputBuffer);
1314
+ const emitOutput = (event) => {
1315
+ if (bufferOutput)
1316
+ bufferedOutput.push(event);
1317
+ else
1318
+ this.emit(event);
1319
+ };
1320
+ const recordTurnUsage = async () => {
1321
+ if (usageRecorded)
1322
+ return;
1323
+ usageRecorded = true;
1324
+ await recordUsage?.(usage, turn, attempt);
1325
+ };
1326
+ const turnAbort = new AbortController();
1327
+ const cleanupTurn = bridgeAbort(signal, turnAbort);
1328
+ this.activeProviderTurnAbort = turnAbort;
1329
+ if (this.pendingSoftInterrupt) {
1330
+ this.pendingSoftInterrupt = false;
1331
+ turnAbort.abort(new SteerSoftInterrupt());
1332
+ }
1333
+ const turnRequest = { ...request, signal: turnAbort.signal };
1334
+ try {
1335
+ throwIfAborted(turnAbort.signal);
1336
+ for await (const event of this.activeProvider.generate(turnRequest)) {
1337
+ throwIfAborted(turnAbort.signal);
1338
+ this.activeLimits.charge("maxResponseBytes", jsonBytes(event));
1339
+ if (event.type === "error")
1340
+ throw new ProviderTurnFailure(event.error, started);
1341
+ if (event.type === "usage")
1342
+ usage = event.usage;
1343
+ if (event.type === "done") {
1344
+ usage = event.usage ?? usage;
1345
+ break;
1346
+ }
1347
+ if (event.type === "message_start") {
1348
+ started = true;
1349
+ messageId = event.messageId;
1350
+ emitOutput({ type: "message_started", sessionId: this.id, runId, message: { id: messageId, role: "assistant", content: [] } });
1351
+ continue;
1352
+ }
1353
+ if (event.type === "content_delta" || event.type === "tool_call" || event.type === "tool_call_delta") {
1354
+ if (!started) {
1355
+ started = true;
1356
+ emitOutput({ type: "message_started", sessionId: this.id, runId, message: { role: "assistant", content: [] } });
1357
+ }
1358
+ if (event.type === "tool_call_delta") {
1359
+ toolDeltas.push(event);
1360
+ emitOutput({ type: "message_delta", sessionId: this.id, runId, content: providerToolCallDeltaContent(event) });
1361
+ continue;
1362
+ }
1363
+ const block = providerContent(event);
1364
+ content.push(block);
1365
+ if (block.type === "tool_call")
1366
+ calls.push(block);
1367
+ emitOutput({ type: "message_delta", sessionId: this.id, runId, content: block });
1368
+ }
1369
+ }
1370
+ for (const call of reconstructMissingToolCalls(toolDeltas, calls)) {
1371
+ content.push(call);
1372
+ calls.push(call);
1373
+ emitOutput({ type: "message_delta", sessionId: this.id, runId, content: call });
1374
+ }
1375
+ await recordTurnUsage();
1376
+ if (this.activeGuardrails?.output?.length) {
1377
+ assertGuardrailsAllowed(await runGuardrails({
1378
+ stage: "output",
1379
+ guardrails: this.activeGuardrails,
1380
+ value: { content, calls, messageId, started, usage },
1381
+ context: { sessionId: this.id, runId, metadata: this.activeMetadata ?? {}, signal: turnAbort.signal },
1382
+ redactor: this.activeRedactor,
1383
+ emit: (event) => this.emit(event),
1384
+ }));
1385
+ }
1386
+ if (bufferOutput)
1387
+ for (const event of bufferedOutput)
1388
+ this.emit(event);
1389
+ const latencyMs = Math.round(performance.now() - startedAt);
1390
+ this.emit({
1391
+ type: "provider_turn_finished",
1392
+ sessionId: this.id,
1393
+ runId,
1394
+ turn,
1395
+ metadata: buildMetadata({ latencyMs }),
1396
+ usage,
1397
+ });
1398
+ return { content, calls, messageId, started, usage };
1399
+ }
1400
+ catch (error) {
1401
+ if (isSteerSoftInterrupt(error) || isSteerSoftInterrupt(turnAbort.signal.reason)) {
1402
+ await recordTurnUsage();
1403
+ const latencyMs = Math.round(performance.now() - startedAt);
1404
+ this.emit({
1405
+ type: "provider_turn_finished",
1406
+ sessionId: this.id,
1407
+ runId,
1408
+ turn,
1409
+ metadata: buildMetadata({ latencyMs }),
1410
+ usage,
1411
+ });
1412
+ throw new SteerSoftInterrupt();
1413
+ }
1414
+ const latencyMs = Math.round(performance.now() - startedAt);
1415
+ const info = error instanceof ProviderTurnFailure ? redactSecrets(error.info, secrets) : errorToErrorInfo(error, secrets);
1416
+ await recordTurnUsage();
1417
+ this.emit({
1418
+ type: "provider_turn_finished",
1419
+ sessionId: this.id,
1420
+ runId,
1421
+ turn,
1422
+ metadata: buildMetadata({ latencyMs, httpStatus: readProviderHttpStatus(info) }),
1423
+ usage,
1424
+ error: info,
1425
+ });
1426
+ if (error instanceof GuardrailError || error instanceof ProviderTurnFailure)
1427
+ throw error;
1428
+ throw new ProviderTurnFailure(info, started);
1429
+ }
1430
+ finally {
1431
+ cleanupTurn();
1432
+ if (this.activeProviderTurnAbort === turnAbort)
1433
+ this.activeProviderTurnAbort = undefined;
1434
+ }
1435
+ }
1436
+ async applyPendingSteers(runId, metadata, signal) {
1437
+ if (this.pendingSteers.length === 0)
1438
+ return false;
1439
+ const drained = this.pendingSteers.splice(0);
1440
+ this.pendingSteerBytes = 0;
1441
+ this.emit({ type: "queue_updated", sessionId: this.id, runId, size: 0 });
1442
+ for (const message of drained) {
1443
+ throwIfAborted(signal);
1444
+ const inputGuardrails = await runGuardrails({
1445
+ stage: "input",
1446
+ guardrails: this.activeGuardrails,
1447
+ value: [message],
1448
+ context: { sessionId: this.id, runId, metadata, signal },
1449
+ redactor: this.activeRedactor,
1450
+ emit: (event) => this.emit(event),
1451
+ });
1452
+ // Mid-run steer: a terminal decision drops the message (never enters history or
1453
+ // the session store) and the run continues. Run-start input blocking still fails
1454
+ // the run — only the blast radius of steered input is narrowed.
1455
+ const terminal = inputGuardrails.terminal;
1456
+ if (terminal) {
1457
+ if (terminal.action === "interrupt")
1458
+ throw new GuardrailError(terminal);
1459
+ this.emit({
1460
+ type: "steer_rejected",
1461
+ sessionId: this.id,
1462
+ runId,
1463
+ message: this.activeRedactor ? this.activeRedactor.redact(message) : message,
1464
+ record: terminal,
1465
+ });
1466
+ continue;
1467
+ }
1468
+ this.history.push(message);
1469
+ await this.appendMessage(message, runId);
1470
+ }
1471
+ return true;
1472
+ }
1473
+ async applyProviderRequestPolicies(request, runId, options, metadata, signal) {
1474
+ const policies = [...policyList(this.agent.config.providerRequestPolicies), ...policyList(options.providerRequestPolicies)];
1475
+ if (policies.length === 0)
1476
+ return { request, secrets: [] };
1477
+ const result = await createProviderRequestPolicyChain(policies).apply({ request, sessionId: this.id, runId, metadata, signal });
1478
+ return normalizeProviderRequestPolicyResult(result);
1479
+ }
1480
+ async appendMessage(message, runId) {
1481
+ await this.appendEntry(createSessionEntry({ sessionId: this.id, parentId: this.currentLeafId, runId, kind: "message", message }));
1482
+ }
1483
+ async autoCompact(runId, options, signal, inputMessages) {
1484
+ const compaction = mergeCompaction(this.agent.config.compaction, options.compaction);
1485
+ if (!compaction || compaction.thresholdEntries === undefined)
1486
+ return;
1487
+ const snapshot = await this.snapshot();
1488
+ if (snapshot.entries.length <= compaction.thresholdEntries || snapshot.entries.at(-1)?.kind === "compaction")
1489
+ return;
1490
+ await this.compactBranch(compaction, runId, signal, "auto");
1491
+ const compacted = await this.snapshot();
1492
+ this.history = withoutTrailingInput(compacted.messages, inputMessages);
1493
+ }
1494
+ async compactBranch(options, runId, signal, trigger) {
1495
+ throwIfAbortedSignal(signal);
1496
+ const entries = await this.entries();
1497
+ const secrets = options.secrets ?? [];
1498
+ const strategy = options.strategy ??
1499
+ createDefaultCompactionStrategy({ keepRecentEntries: options.keepRecentEntries, maxSummaryChars: options.maxSummaryChars, secrets });
1500
+ const context = {
1501
+ sessionId: this.id,
1502
+ entries,
1503
+ keepRecentEntries: options.keepRecentEntries,
1504
+ trigger,
1505
+ secrets,
1506
+ metadata: options.metadata,
1507
+ signal,
1508
+ };
1509
+ this.emit({ type: "compaction_started", sessionId: this.id, runId });
1510
+ let result = await strategy.compact(context);
1511
+ result = { ...result, summary: redactSecrets(result.summary, secrets) };
1512
+ const payload = (await this.agent.config.middleware?.run("compaction", { context, result })) ?? {
1513
+ context,
1514
+ result,
1515
+ };
1516
+ result = { ...payload.result, summary: redactSecrets(payload.result.summary, secrets) };
1517
+ const source = result.entries?.find((entry) => entry.kind === "compaction");
1518
+ const data = isCompactionEntryData(source?.data) ? source.data : undefined;
1519
+ const entry = createSessionEntry({
1520
+ sessionId: this.id,
1521
+ parentId: this.currentLeafId,
1522
+ runId,
1523
+ kind: "compaction",
1524
+ summary: result.summary,
1525
+ data,
1526
+ });
1527
+ await this.appendEntry(entry);
1528
+ const finalResult = { ...result, entries: [entry] };
1529
+ this.emit({ type: "compaction_finished", sessionId: this.id, runId, summary: finalResult.summary });
1530
+ await this.rebuildHistory();
1531
+ return finalResult;
1532
+ }
1533
+ async appendEntry(entry) {
1534
+ const redacted = redactSessionEntry(entry, this.activeRedactor);
1535
+ await this.store.append(redacted, {
1536
+ expectedParentId: this.currentLeafId,
1537
+ idempotencyKey: this.activeIdempotencyKey,
1538
+ });
1539
+ this.currentLeafId = redacted.id;
1540
+ this.invalidateSnapshot();
1541
+ }
1542
+ invalidateSnapshot() {
1543
+ this.snapshotGeneration += 1;
1544
+ this.snapshotCache = undefined;
1545
+ }
1546
+ redact(value) {
1547
+ return this.activeRedactor?.redact(value) ?? value;
1548
+ }
1549
+ redactProviderRequest(request) {
1550
+ return redactProviderRequest(request, this.activeRedactor);
1551
+ }
1552
+ async rebuildHistory() {
1553
+ this.history = (await this.snapshot()).messages.slice();
1554
+ }
1555
+ async snapshot() {
1556
+ const now = performance.now();
1557
+ const cached = this.snapshotCache;
1558
+ if (cached && cached.leafId === this.currentLeafId && cached.generation === this.snapshotGeneration && cached.expiresAt > now)
1559
+ return cached.value;
1560
+ const reader = this.branchReader();
1561
+ const value = reader
1562
+ ? await rebuildSessionContext(reader, { sessionId: this.id, leafId: this.currentLeafId })
1563
+ : rebuildSessionContext(await this.store.list(this.id), { leafId: this.currentLeafId });
1564
+ this.snapshotCache = { leafId: this.currentLeafId, generation: this.snapshotGeneration, expiresAt: now + 1_000, value };
1565
+ return value;
1566
+ }
1567
+ }
1568
+ //# sourceMappingURL=session.js.map