@arnilo/prism 0.2.4 → 0.2.6

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