@fabric-harness/sdk 6.4.0 → 6.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (153) hide show
  1. package/connector-spec/voice-telephony.md +120 -104
  2. package/dist/agent-route.d.ts +20 -2
  3. package/dist/agent-route.d.ts.map +1 -1
  4. package/dist/agent-route.js +31 -1
  5. package/dist/agent-route.js.map +1 -1
  6. package/dist/agent-router.d.ts +42 -0
  7. package/dist/agent-router.d.ts.map +1 -1
  8. package/dist/agent-router.js +49 -1
  9. package/dist/agent-router.js.map +1 -1
  10. package/dist/agent.d.ts.map +1 -1
  11. package/dist/agent.js +7 -2
  12. package/dist/agent.js.map +1 -1
  13. package/dist/attachment-store.d.ts +69 -0
  14. package/dist/attachment-store.d.ts.map +1 -1
  15. package/dist/attachment-store.js +183 -14
  16. package/dist/attachment-store.js.map +1 -1
  17. package/dist/attachments.d.ts +136 -0
  18. package/dist/attachments.d.ts.map +1 -0
  19. package/dist/attachments.js +332 -0
  20. package/dist/attachments.js.map +1 -0
  21. package/dist/channel.d.ts.map +1 -1
  22. package/dist/channel.js +26 -3
  23. package/dist/channel.js.map +1 -1
  24. package/dist/conversation-history.d.ts +186 -0
  25. package/dist/conversation-history.d.ts.map +1 -0
  26. package/dist/conversation-history.js +481 -0
  27. package/dist/conversation-history.js.map +1 -0
  28. package/dist/conversation-ui.d.ts +43 -2
  29. package/dist/conversation-ui.d.ts.map +1 -1
  30. package/dist/conversation-ui.js +44 -14
  31. package/dist/conversation-ui.js.map +1 -1
  32. package/dist/cost-budget.d.ts +50 -0
  33. package/dist/cost-budget.d.ts.map +1 -1
  34. package/dist/cost-budget.js +74 -4
  35. package/dist/cost-budget.js.map +1 -1
  36. package/dist/cost-enforcement.d.ts +32 -0
  37. package/dist/cost-enforcement.d.ts.map +1 -0
  38. package/dist/cost-enforcement.js +116 -0
  39. package/dist/cost-enforcement.js.map +1 -0
  40. package/dist/delivered-message.d.ts +20 -6
  41. package/dist/delivered-message.d.ts.map +1 -1
  42. package/dist/delivered-message.js +37 -8
  43. package/dist/delivered-message.js.map +1 -1
  44. package/dist/events.d.ts +13 -1
  45. package/dist/events.d.ts.map +1 -1
  46. package/dist/events.js.map +1 -1
  47. package/dist/experimental.d.ts +2 -2
  48. package/dist/experimental.d.ts.map +1 -1
  49. package/dist/experimental.js +1 -1
  50. package/dist/experimental.js.map +1 -1
  51. package/dist/governed-voice.d.ts +6 -0
  52. package/dist/governed-voice.d.ts.map +1 -1
  53. package/dist/governed-voice.js +142 -35
  54. package/dist/governed-voice.js.map +1 -1
  55. package/dist/history.d.ts +3 -2
  56. package/dist/history.d.ts.map +1 -1
  57. package/dist/history.js +57 -23
  58. package/dist/history.js.map +1 -1
  59. package/dist/index.d.ts +21 -14
  60. package/dist/index.d.ts.map +1 -1
  61. package/dist/index.js +11 -7
  62. package/dist/index.js.map +1 -1
  63. package/dist/loop.d.ts +25 -2
  64. package/dist/loop.d.ts.map +1 -1
  65. package/dist/loop.js +409 -60
  66. package/dist/loop.js.map +1 -1
  67. package/dist/model-pricing.d.ts +77 -4
  68. package/dist/model-pricing.d.ts.map +1 -1
  69. package/dist/model-pricing.js +259 -18
  70. package/dist/model-pricing.js.map +1 -1
  71. package/dist/model.d.ts +115 -3
  72. package/dist/model.d.ts.map +1 -1
  73. package/dist/model.js +487 -75
  74. package/dist/model.js.map +1 -1
  75. package/dist/pi-document-attachments.d.ts +43 -0
  76. package/dist/pi-document-attachments.d.ts.map +1 -0
  77. package/dist/pi-document-attachments.js +155 -0
  78. package/dist/pi-document-attachments.js.map +1 -0
  79. package/dist/pi-loop-runtime.d.ts +103 -1
  80. package/dist/pi-loop-runtime.d.ts.map +1 -1
  81. package/dist/pi-loop-runtime.js +907 -114
  82. package/dist/pi-loop-runtime.js.map +1 -1
  83. package/dist/prompt-attachments.d.ts +98 -0
  84. package/dist/prompt-attachments.d.ts.map +1 -0
  85. package/dist/prompt-attachments.js +279 -0
  86. package/dist/prompt-attachments.js.map +1 -0
  87. package/dist/session.d.ts +55 -0
  88. package/dist/session.d.ts.map +1 -1
  89. package/dist/session.js +443 -41
  90. package/dist/session.js.map +1 -1
  91. package/dist/stream-chunks.d.ts +15 -1
  92. package/dist/stream-chunks.d.ts.map +1 -1
  93. package/dist/stream-chunks.js +39 -18
  94. package/dist/stream-chunks.js.map +1 -1
  95. package/dist/strict.d.ts +23 -16
  96. package/dist/strict.d.ts.map +1 -1
  97. package/dist/strict.js +12 -8
  98. package/dist/strict.js.map +1 -1
  99. package/dist/submission-context.d.ts +7 -0
  100. package/dist/submission-context.d.ts.map +1 -1
  101. package/dist/submission-context.js.map +1 -1
  102. package/dist/submission-runner.d.ts +5 -0
  103. package/dist/submission-runner.d.ts.map +1 -1
  104. package/dist/submission-runner.js +11 -2
  105. package/dist/submission-runner.js.map +1 -1
  106. package/dist/tools.d.ts +9 -0
  107. package/dist/tools.d.ts.map +1 -1
  108. package/dist/tools.js +1 -0
  109. package/dist/tools.js.map +1 -1
  110. package/dist/types.d.ts +26 -0
  111. package/dist/types.d.ts.map +1 -1
  112. package/dist/types.js.map +1 -1
  113. package/dist/usage-completeness.d.ts +39 -0
  114. package/dist/usage-completeness.d.ts.map +1 -0
  115. package/dist/usage-completeness.js +135 -0
  116. package/dist/usage-completeness.js.map +1 -0
  117. package/dist/voice-openai-realtime.d.ts +24 -2
  118. package/dist/voice-openai-realtime.d.ts.map +1 -1
  119. package/dist/voice-openai-realtime.js +266 -49
  120. package/dist/voice-openai-realtime.js.map +1 -1
  121. package/dist/voice-pipeline.d.ts +81 -3
  122. package/dist/voice-pipeline.d.ts.map +1 -1
  123. package/dist/voice-pipeline.js +429 -60
  124. package/dist/voice-pipeline.js.map +1 -1
  125. package/dist/voice-stt-cartesia.d.ts +8 -0
  126. package/dist/voice-stt-cartesia.d.ts.map +1 -1
  127. package/dist/voice-stt-cartesia.js +77 -17
  128. package/dist/voice-stt-cartesia.js.map +1 -1
  129. package/dist/voice-stt-deepgram.d.ts +10 -2
  130. package/dist/voice-stt-deepgram.d.ts.map +1 -1
  131. package/dist/voice-stt-deepgram.js +78 -18
  132. package/dist/voice-stt-deepgram.js.map +1 -1
  133. package/dist/voice-stt.d.ts +13 -3
  134. package/dist/voice-stt.d.ts.map +1 -1
  135. package/dist/voice-tts-cartesia.d.ts +8 -0
  136. package/dist/voice-tts-cartesia.d.ts.map +1 -1
  137. package/dist/voice-tts-cartesia.js +48 -105
  138. package/dist/voice-tts-cartesia.js.map +1 -1
  139. package/dist/voice-tts-elevenlabs.d.ts +10 -1
  140. package/dist/voice-tts-elevenlabs.d.ts.map +1 -1
  141. package/dist/voice-tts-elevenlabs.js +50 -113
  142. package/dist/voice-tts-elevenlabs.js.map +1 -1
  143. package/dist/voice-ws-client.js +16 -3
  144. package/dist/voice-ws-client.js.map +1 -1
  145. package/dist/voice-ws-shared.d.ts +205 -6
  146. package/dist/voice-ws-shared.d.ts.map +1 -1
  147. package/dist/voice-ws-shared.js +510 -15
  148. package/dist/voice-ws-shared.js.map +1 -1
  149. package/dist/voice.d.ts +98 -4
  150. package/dist/voice.d.ts.map +1 -1
  151. package/dist/voice.js +71 -1
  152. package/dist/voice.js.map +1 -1
  153. package/package.json +3 -3
package/dist/session.js CHANGED
@@ -17,6 +17,8 @@ import { estimateSessionEntryTokens, evaluateContextBudget, isContextOverflowErr
17
17
  import { policiedSandboxEnv, runWithSandboxPolicyApproval } from "./policied-sandbox.js";
18
18
  import { currentSubmissionContext } from "./submission-context.js";
19
19
  import { deliveredSignalToEntryData, renderDeliveredMessage } from "./delivered-message.js";
20
+ import { BoundedInMemoryAttachmentStore } from "./attachment-store.js";
21
+ import { createAttachmentHydrationBudget, hydrateModelMessageAttachments, preparePromptAttachments, recordsToModelAttachments, validatePromptAttachments, } from "./prompt-attachments.js";
20
22
  import { createSandboxEnv, createScopedSandboxEnv, execSandboxCommand } from "./sandbox.js";
21
23
  import { createFabricFs } from "./filesystem.js";
22
24
  import { registerSandbox, serializeSandboxRef, unregisterSandbox } from "./sandbox-ref.js";
@@ -66,6 +68,12 @@ export function generateAffinityKey(agentId, sessionId) {
66
68
  export function isValidAffinityKey(key) {
67
69
  return AFFINITY_KEY_REGEX.test(key);
68
70
  }
71
+ /**
72
+ * Upper bound on one model-generated compaction summary (both attempts and
73
+ * the retry delay) when the prompt sets no `modelTimeoutMs`. A summary that
74
+ * does not arrive in time falls back to the deterministic summary.
75
+ */
76
+ const COMPACTION_SUMMARY_TIMEOUT_MS = 120_000;
69
77
  const COMPACTION_SUMMARIZATION_SYSTEM_PROMPT = "Summarize durable agent session history for future context. Preserve user goals, decisions, tool/command effects, files touched, errors, policy/approval events, and pending work. Do not include secrets.";
70
78
  const TURN_PREFIX_SUMMARIZATION_PROMPT = `This is the PREFIX of a turn that was too large to keep. The SUFFIX (recent work) is retained.
71
79
 
@@ -81,6 +89,16 @@ Summarize the prefix to provide context for the retained suffix:
81
89
  - [Information needed to understand the retained recent work]
82
90
 
83
91
  Be concise. Focus on what's needed to understand the kept suffix.`;
92
+ /**
93
+ * Policies a caller passed to `agent.session()` itself, as distinct from the
94
+ * agent's policy copied into the session's options. A dynamic agent's refresh
95
+ * replaces the agent's policy, never one of these (session over agent).
96
+ */
97
+ const explicitSessionPolicies = new WeakMap();
98
+ /** Records that `options.policy` was set by the caller of `agent.session()`. */
99
+ export function markExplicitSessionPolicy(options, policy) {
100
+ explicitSessionPolicies.set(options, policy);
101
+ }
84
102
  export class StubFabricSession {
85
103
  id;
86
104
  agent;
@@ -117,6 +135,13 @@ export class StubFabricSession {
117
135
  costBudget;
118
136
  skillCache = new Map();
119
137
  effectivePackagedSkillsCache = null;
138
+ /**
139
+ * Process-local fallback when neither the session nor the runner supplies a
140
+ * store. Bounded (64 MiB, 256 blobs, least recently stored evicted first) so
141
+ * a long-lived session cannot retain attachment bytes without limit; an
142
+ * evicted blob hydrates as the "not available" placeholder.
143
+ */
144
+ localAttachmentStore;
120
145
  constructor(agent, id, options = {}) {
121
146
  this.agent = agent;
122
147
  this.id = id;
@@ -126,6 +151,51 @@ export class StubFabricSession {
126
151
  this.fs = createFabricFs(() => this.sandboxPromise);
127
152
  this.costBudget = new CostBudgetTracker(options.costLimit);
128
153
  }
154
+ /**
155
+ * Attachment store for this session: explicit option, else the executing
156
+ * submission runner's store, else a process-local in-memory store.
157
+ */
158
+ attachmentStore() {
159
+ const configured = this.options.attachmentStore ?? currentSubmissionContext()?.attachmentStore;
160
+ if (configured)
161
+ return configured;
162
+ this.localAttachmentStore ??= new BoundedInMemoryAttachmentStore();
163
+ return this.localAttachmentStore;
164
+ }
165
+ /**
166
+ * Fill attachment bytes on history-projected messages (refs only) from the
167
+ * in-flight map, then the attachment store. Every path that rebuilds model
168
+ * messages from history must pass through here before calling the model.
169
+ */
170
+ hydrateMessageAttachments(messages, inflight, budget) {
171
+ // A full transcript rebuild replaces the request, so it restarts the
172
+ // request-wide allowance; joined inputs appended later charge the rest.
173
+ if (budget)
174
+ budget.usedBytes = 0;
175
+ return hydrateModelMessageAttachments(messages, {
176
+ store: this.attachmentStore(),
177
+ scope: this.id,
178
+ ...(inflight ? { inflight } : {}),
179
+ ...(budget ? { budget } : {}),
180
+ });
181
+ }
182
+ /**
183
+ * Store an input's inline attachments and return refs-only records plus the
184
+ * in-flight bytes. Deterministic ids for submissions keep recovery stable.
185
+ */
186
+ async prepareInputAttachments(inline, message, submissionId) {
187
+ const delivered = message?.kind === "user" ? (message.attachments ?? []) : [];
188
+ if (inline.length === 0 && delivered.length === 0) {
189
+ return { records: [], inflight: new Map() };
190
+ }
191
+ return preparePromptAttachments({
192
+ inline,
193
+ delivered,
194
+ store: this.attachmentStore(),
195
+ scope: this.id,
196
+ idPrefix: submissionId ? `att_${submissionId}` : `att_prompt_${randomUUID()}`,
197
+ });
198
+ }
129
199
  getDurableRuntime() {
130
200
  if (this.durableRuntime)
131
201
  return this.durableRuntime;
@@ -175,6 +245,7 @@ export class StubFabricSession {
175
245
  publicMessage: "The durable submission input is inconsistent.",
176
246
  });
177
247
  }
248
+ const inlineAttachments = validatePromptAttachments(options.images, options.documents);
178
249
  const durable = await this.getDurableRuntime();
179
250
  if (durable) {
180
251
  if (this.options.dynamic && durable.supportsDynamicAgents !== true) {
@@ -185,6 +256,15 @@ export class StubFabricSession {
185
256
  publicMessage: "This dynamic agent is not supported by the configured durable runtime.",
186
257
  });
187
258
  }
259
+ if (inlineAttachments.length > 0) {
260
+ throw new FabricError({
261
+ code: "INVALID_CONFIG",
262
+ message: "Inline prompt images/documents are not supported with a durable session runtime: " +
263
+ "their bytes would enter durable workflow inputs. Admit them through a submission " +
264
+ "with an attachment store so only content-addressed refs are forwarded.",
265
+ publicMessage: "Inline attachments are not supported by the configured durable runtime.",
266
+ });
267
+ }
188
268
  // Delegate to the durable runtime; the runtime is responsible for
189
269
  // recording entries / events on its own side. We still emit a single
190
270
  // local prompt_start/end pair so local subscribers see activity.
@@ -222,7 +302,11 @@ export class StubFabricSession {
222
302
  : {}),
223
303
  tools,
224
304
  sandbox,
225
- ...(this.options.policy ? { policy: this.options.policy } : {}),
305
+ // The prompt's policy over the rendered agent's (call over session over agent), so a
306
+ // dynamic agent's turn refresh never widens what this prompt allowed.
307
+ ...((options.policy ?? this.options.policy)
308
+ ? { policy: (options.policy ?? this.options.policy) }
309
+ : {}),
226
310
  ...(options.role === undefined && typeof this.options.role === "object"
227
311
  ? { systemInstruction: this.options.role.content }
228
312
  : {}),
@@ -248,7 +332,11 @@ export class StubFabricSession {
248
332
  }
249
333
  this.options.tools = config.tools ?? [];
250
334
  this.options.skills = config.skills ?? [];
251
- if (config.policy !== undefined)
335
+ // A policy the caller gave this session outranks the rendered agent's.
336
+ const explicitPolicy = explicitSessionPolicies.get(this.options);
337
+ if (explicitPolicy !== undefined)
338
+ this.options.policy = explicitPolicy;
339
+ else if (config.policy !== undefined)
252
340
  this.options.policy = config.policy;
253
341
  else
254
342
  Reflect.deleteProperty(this.options, "policy");
@@ -319,33 +407,48 @@ export class StubFabricSession {
319
407
  // the original call and the recovered result, even when dynamic render
320
408
  // narration was appended between them during worker initialization.
321
409
  const responseStartLeafId = firstRecoveredCall?.parentId ?? responseStartData.leafId;
322
- await this.repairDanglingToolCalls(tools, sandbox, options.signal);
410
+ await this.repairDanglingToolCalls(tools, sandbox, options.signal, options.policy);
323
411
  await this.emit("prompt_start", { text, ...(role ? { role: role.name } : {}) });
324
412
  // Submission-correlated prompts are idempotent by submission id: a
325
413
  // recovered attempt whose input entry already landed (crash after the
326
414
  // canonical write) resumes from history instead of double-applying.
327
415
  let inputAlreadyApplied = false;
416
+ // The entry carrying this prompt. Retention checks match it by id, since
417
+ // an earlier prompt with identical text (but other attachments) must not
418
+ // stand in for it.
419
+ let promptEntryId;
328
420
  if (options.submission) {
329
421
  const prior = await this.history();
330
422
  const submissionId = options.submission.submissionId;
331
- inputAlreadyApplied = (prior.entries ?? []).some((entry) => (entry.type === "user_prompt" || entry.type === "signal") &&
332
- entry.data?.submissionId === submissionId);
423
+ promptEntryId = (prior.entries ?? []).find((entry) => (entry.type === "user_prompt" || entry.type === "signal") &&
424
+ entry.data?.submissionId === submissionId)?.id;
425
+ inputAlreadyApplied = promptEntryId !== undefined;
333
426
  }
427
+ const promptAttachments = await this.prepareInputAttachments(inlineAttachments, options.submission?.message, options.submission?.submissionId);
334
428
  if (!inputAlreadyApplied) {
335
429
  if (options.submission?.message?.kind === "signal") {
336
- await this.recordEntry("signal", {
430
+ promptEntryId = (await this.recordEntry("signal", {
337
431
  ...deliveredSignalToEntryData(options.submission.message),
338
432
  submissionId: options.submission.submissionId,
339
- });
433
+ })).id;
340
434
  }
341
435
  else {
342
- await this.recordEntry("user_prompt", {
436
+ promptEntryId = (await this.recordEntry("user_prompt", {
343
437
  text,
344
438
  ...(role ? { role: role.name } : {}),
345
439
  ...(options.submission ? { submissionId: options.submission.submissionId } : {}),
346
- });
440
+ // Refs only: attachment bytes never enter session entries.
441
+ ...(promptAttachments.records.length > 0
442
+ ? { attachments: promptAttachments.records }
443
+ : {}),
444
+ })).id;
347
445
  }
348
446
  }
447
+ const promptInContext = (data, projected) => promptEntryId !== undefined
448
+ ? SessionHistory.fromData(data)
449
+ .buildContextEntries()
450
+ .some((entry) => entry.id === promptEntryId)
451
+ : projected.some((message) => message.role === "user" && message.content === text);
349
452
  // Input-applied boundary: the canonical input entry is durable and no
350
453
  // provider work has started. The submission runner's input-applied
351
454
  // marker CAS hangs off this callback; its failure aborts the turn
@@ -374,11 +477,27 @@ export class StubFabricSession {
374
477
  }
375
478
  const sessionData = await this.history();
376
479
  let messages = buildModelMessagesFromHistory(sessionData, role);
377
- if (!messages.some((message) => message.role === "user" && message.content === text))
378
- messages.push({ role: "user", content: text });
379
- messages = await this.autoCompactIfNeeded(messages, role, options);
480
+ if (!promptInContext(sessionData, messages))
481
+ messages.push({
482
+ role: "user",
483
+ content: text,
484
+ ...(promptAttachments.records.length > 0
485
+ ? { attachments: recordsToModelAttachments(promptAttachments.records) }
486
+ : {}),
487
+ });
488
+ // One hydration allowance for the whole model request, shared by the
489
+ // rebuilt transcript and any joined inputs appended while it runs.
490
+ const hydrationBudget = createAttachmentHydrationBudget();
491
+ messages = await this.hydrateMessageAttachments(messages, promptAttachments.inflight, hydrationBudget);
492
+ messages = await this.autoCompactIfNeeded(messages, role, options, hydrationBudget);
380
493
  if (options.toolCalls?.length) {
381
494
  const results = await this.executeToolCalls(options.toolCalls, tools, sandbox, options.policy, options.approvalTimeoutMs ?? this.options.approvalTimeoutMs, options.onApproval, undefined, options.signal);
495
+ // An abort before or during the batch settled its unstarted calls as
496
+ // interrupted so the transcript stays paired. The prompt itself was
497
+ // cancelled: reject with AbortError, like the model loop, and never
498
+ // record a result or emit prompt_end for it.
499
+ if (options.signal?.aborted)
500
+ throw promptAbortError(options.signal);
382
501
  await this.recordEntry("result", { result: results });
383
502
  await this.emit("prompt_end", { text, result: results });
384
503
  const value = await validateResult(results, options.result, options.resultExtraction);
@@ -463,14 +582,36 @@ export class StubFabricSession {
463
582
  ...deliveredSignalToEntryData(input.message),
464
583
  submissionId: input.submissionId,
465
584
  });
585
+ messages.push({ role: "user", content: input.text });
466
586
  }
467
587
  else {
588
+ const joinedAttachments = await this.prepareInputAttachments([], input.message, input.submissionId);
468
589
  await this.recordEntry("user_prompt", {
469
590
  text: input.text,
470
591
  submissionId: input.submissionId,
592
+ ...(joinedAttachments.records.length > 0
593
+ ? { attachments: joinedAttachments.records }
594
+ : {}),
595
+ });
596
+ const [joinedMessage] = await hydrateModelMessageAttachments([
597
+ {
598
+ role: "user",
599
+ content: input.text,
600
+ ...(joinedAttachments.records.length > 0
601
+ ? { attachments: recordsToModelAttachments(joinedAttachments.records) }
602
+ : {}),
603
+ },
604
+ ], {
605
+ store: this.attachmentStore(),
606
+ scope: this.id,
607
+ inflight: joinedAttachments.inflight,
608
+ // Charged against the running request's allowance,
609
+ // not a fresh 50 MiB per joined input.
610
+ budget: hydrationBudget,
471
611
  });
612
+ if (joinedMessage)
613
+ messages.push(joinedMessage);
472
614
  }
473
- messages.push({ role: "user", content: input.text });
474
615
  }
475
616
  if (input.message && dynamic) {
476
617
  await refreshDynamic({
@@ -503,7 +644,10 @@ export class StubFabricSession {
503
644
  },
504
645
  }
505
646
  : {}),
506
- executeToolCalls: (calls, policy, approvalTimeoutMs, attribution) => this.executeToolCalls(calls, tools, sandbox, policy, approvalTimeoutMs, options.onApproval, attribution, options.signal),
647
+ executeToolCalls: (calls, policy, approvalTimeoutMs, attribution) => this.executeToolCalls(calls, tools, sandbox,
648
+ // The prompt's policy wins (call over session over agent). A loop may pass none for
649
+ // model-issued calls, and a dynamic agent's turn refresh passes its rendered agent policy.
650
+ options.policy ?? policy, approvalTimeoutMs, options.onApproval, attribution, options.signal),
507
651
  recordToolAdditions: async (toolCallId, names) => {
508
652
  if (names.length === 0)
509
653
  return;
@@ -524,17 +668,42 @@ export class StubFabricSession {
524
668
  catch (error) {
525
669
  const compactionSettings = this.options.compaction;
526
670
  const recoverFromOverflow = options.recoverContextOverflow ?? compactionSettings?.recoverFromOverflow ?? true;
527
- if (!isContextOverflowError(error) || !recoverFromOverflow)
671
+ if (!isProviderContextOverflow(error, options.signal) || !recoverFromOverflow)
528
672
  throw error;
529
673
  await this.emit("error", {
530
674
  error: "Context overflow detected; compacting and retrying once.",
531
675
  });
532
- await this.compact({
676
+ await this.compactWithControl({
533
677
  keepRecentEntries: options.compactionKeepRecentEntries ?? compactionSettings?.keepRecentEntries ?? 20,
534
678
  generateSummary: true,
535
679
  reason: "overflow",
536
- });
537
- messages = buildModelMessagesFromHistory(await this.history(), role);
680
+ }, compactionControlFor(options));
681
+ const compactedData = await this.history();
682
+ messages = buildModelMessagesFromHistory(compactedData, role);
683
+ // Compaction may summarize the entry that carried this prompt, and an
684
+ // in-memory follow-up (result-tool nudge, steering) after a completed
685
+ // response is not durable. Keep the pending input as the final user
686
+ // turn so the retry never asks the provider to continue from a
687
+ // completed assistant response.
688
+ const tail = messages.at(-1);
689
+ const promptRetained = promptInContext(compactedData, messages);
690
+ if (!promptRetained || (tail?.role === "assistant" && !tail.toolCalls?.length)) {
691
+ // When compaction summarized the prompt away, its attachments go
692
+ // with it; restore them so the retry still carries the image/PDF.
693
+ // A retained prompt already carries its refs earlier in the
694
+ // transcript, so the re-added tail turn stays text-only rather
695
+ // than doubling attachment bytes on an overflow retry.
696
+ messages.push({
697
+ role: "user",
698
+ content: text,
699
+ ...(!promptRetained && promptAttachments.records.length > 0
700
+ ? { attachments: recordsToModelAttachments(promptAttachments.records) }
701
+ : {}),
702
+ });
703
+ }
704
+ // History projections carry refs only; rehydrate bytes exactly as
705
+ // the initial prompt path does.
706
+ messages = await this.hydrateMessageAttachments(messages, promptAttachments.inflight, hydrationBudget);
538
707
  result = await runRuntime();
539
708
  }
540
709
  let continuationCount = 0;
@@ -573,14 +742,18 @@ export class StubFabricSession {
573
742
  }
574
743
  }
575
744
  const finalized = await this.finalizeDynamicResult(value, responseStartLeafId, result.usage);
576
- if (!finalized.continued)
745
+ if (!finalized.continued) {
746
+ if (result.terminatedByTool)
747
+ await this.compactAfterTermination(role, options);
577
748
  return finalized.value;
749
+ }
578
750
  continuationCount += 1;
579
751
  if (continuationCount > 8) {
580
752
  throw new Error("useAgentFinish() exceeded the maximum of 8 continuation cycles.");
581
753
  }
582
754
  messages = buildModelMessagesFromHistory(await this.history(), role);
583
- messages = await this.autoCompactIfNeeded(messages, role, options);
755
+ messages = await this.hydrateMessageAttachments(messages, promptAttachments.inflight, hydrationBudget);
756
+ messages = await this.autoCompactIfNeeded(messages, role, options, hydrationBudget);
584
757
  result = await runRuntime();
585
758
  }
586
759
  }
@@ -665,6 +838,14 @@ export class StubFabricSession {
665
838
  publicMessage: "This dynamic agent is not supported by the configured durable runtime.",
666
839
  });
667
840
  }
841
+ if (validatePromptAttachments(options.images, options.documents).length > 0) {
842
+ throw new FabricError({
843
+ code: "INVALID_CONFIG",
844
+ message: "Inline task images/documents are not supported with a durable session runtime: " +
845
+ "their bytes would enter durable workflow inputs.",
846
+ publicMessage: "Inline attachments are not supported by the configured durable runtime.",
847
+ });
848
+ }
668
849
  const taskId = options.id ?? `${this.id}:task-${++nextTaskId}`;
669
850
  await this.emit("task_start", { taskId, depth: 1, parentSessionId: this.id });
670
851
  try {
@@ -1137,6 +1318,16 @@ export class StubFabricSession {
1137
1318
  return ref;
1138
1319
  }
1139
1320
  async compact(options = {}) {
1321
+ return this.compactWithControl(options, {});
1322
+ }
1323
+ /**
1324
+ * `compact()` with the running prompt's abort signal and model timeout.
1325
+ * An abort rejects with `AbortError` before anything is recorded; a summary
1326
+ * that exceeds the deadline falls back to the deterministic summary.
1327
+ */
1328
+ async compactWithControl(options, control) {
1329
+ if (control.signal?.aborted)
1330
+ throw promptAbortError(control.signal);
1140
1331
  const history = await this.history();
1141
1332
  const entries = history.entries ?? [];
1142
1333
  const settings = this.options.compaction;
@@ -1146,8 +1337,9 @@ export class StubFabricSession {
1146
1337
  let firstKeptEntry;
1147
1338
  let prep;
1148
1339
  if (explicitKeepRecentEntries !== undefined) {
1149
- // Backward-compatible count-based cut.
1150
- const compactedCount = Math.max(0, entries.length - explicitKeepRecentEntries);
1340
+ // Backward-compatible count-based cut, moved to a tool-batch boundary so
1341
+ // a kept tool_result never loses its summarized tool_call.
1342
+ const compactedCount = safeCountBasedCut(entries, Math.max(0, entries.length - explicitKeepRecentEntries));
1151
1343
  firstKeptEntry = compactedCount > 0 ? entries[compactedCount] : undefined;
1152
1344
  compacted = compactedCount > 0 ? entries.slice(0, compactedCount) : [];
1153
1345
  }
@@ -1169,8 +1361,11 @@ export class StubFabricSession {
1169
1361
  };
1170
1362
  const baseSummary = options.summary ??
1171
1363
  (options.generateSummary
1172
- ? await this.generateCompactionSummary(summaryInput)
1364
+ ? await this.generateCompactionSummary(summaryInput, control)
1173
1365
  : summarizeEntries(compacted));
1366
+ // Never record a compaction for a prompt that was cancelled meanwhile.
1367
+ if (control.signal?.aborted)
1368
+ throw promptAbortError(control.signal);
1174
1369
  const summary = appendFileReferenceTags(baseSummary, fileRefs);
1175
1370
  const compactedEntries = compacted.length;
1176
1371
  const entry = await this.recordEntry("compaction", {
@@ -1197,7 +1392,7 @@ export class StubFabricSession {
1197
1392
  details: { readFiles: fileRefs.readFiles, modifiedFiles: fileRefs.modifiedFiles },
1198
1393
  };
1199
1394
  }
1200
- async autoCompactIfNeeded(messages, role, options) {
1395
+ async autoCompactIfNeeded(messages, role, options, hydrationBudget) {
1201
1396
  if (options.autoCompact === false)
1202
1397
  return messages;
1203
1398
  const settings = this.options.compaction;
@@ -1231,9 +1426,39 @@ export class StubFabricSession {
1231
1426
  else {
1232
1427
  compactOpts.keepRecentTokens = settings?.keepRecentTokens ?? budget.keepRecentTokens ?? 8_000;
1233
1428
  }
1234
- await this.compact(compactOpts);
1429
+ await this.compactWithControl(compactOpts, compactionControlFor(options));
1235
1430
  const compacted = buildModelMessagesFromHistory(await this.history(), role);
1236
- return compacted;
1431
+ // The rebuilt projection carries attachment refs only; rehydrate from
1432
+ // the attachment store so retained image/PDF turns keep their bytes.
1433
+ return this.hydrateMessageAttachments(compacted, undefined, hydrationBudget);
1434
+ }
1435
+ /**
1436
+ * A run that ended through a terminating tool skips the loop's final
1437
+ * assistant turn, so apply the auto-compaction budget immediately and let
1438
+ * the next turn start from a manageable context. Best effort: the
1439
+ * terminating result is already durable, and the next prompt re-evaluates
1440
+ * the budget before calling the model if this compaction fails.
1441
+ *
1442
+ * The summary call receives the prompt's abort signal and deadline. An
1443
+ * abort that arrives while it runs skips the compaction and the prompt
1444
+ * still resolves with its finalized result, the same as an abort that
1445
+ * arrives after the result is final. A summary that exceeds the deadline
1446
+ * falls back to the deterministic summary.
1447
+ */
1448
+ async compactAfterTermination(role, options) {
1449
+ if (options.signal?.aborted)
1450
+ return;
1451
+ try {
1452
+ const messages = buildModelMessagesFromHistory(await this.history(), role);
1453
+ await this.autoCompactIfNeeded(messages, role, options);
1454
+ }
1455
+ catch (error) {
1456
+ if (options.signal?.aborted || isAbortError(error))
1457
+ return;
1458
+ await this.emit("error", {
1459
+ error: `Post-termination compaction failed; the next prompt will retry it: ${error instanceof Error ? error.message : String(error)}`,
1460
+ });
1461
+ }
1237
1462
  }
1238
1463
  resolveModelContextWindow(options) {
1239
1464
  const provider = options.modelProvider ?? this.options.modelProvider;
@@ -1252,21 +1477,49 @@ export class StubFabricSession {
1252
1477
  return undefined;
1253
1478
  }
1254
1479
  }
1255
- async generateCompactionSummary(prep) {
1480
+ async generateCompactionSummary(prep, control) {
1256
1481
  if (prep.isSplitTurn && prep.turnPrefixMessages.length > 0) {
1257
1482
  const [historyResult, prefixResult] = await Promise.all([
1258
- this.summarizeEntrySet(prep.messagesToSummarize),
1259
- this.summarizeEntrySet(prep.turnPrefixMessages, TURN_PREFIX_SUMMARIZATION_PROMPT),
1483
+ this.summarizeEntrySet(prep.messagesToSummarize, undefined, control),
1484
+ this.summarizeEntrySet(prep.turnPrefixMessages, TURN_PREFIX_SUMMARIZATION_PROMPT, control),
1260
1485
  ]);
1261
1486
  return `${historyResult}\n\n---\n\n**Turn Context (split turn):**\n\n${prefixResult}`;
1262
1487
  }
1263
- return this.summarizeEntrySet(prep.messagesToSummarize);
1488
+ return this.summarizeEntrySet(prep.messagesToSummarize, undefined, control);
1264
1489
  }
1265
- async summarizeEntrySet(entries, prefixPrompt) {
1490
+ /**
1491
+ * Model-generated summary with a deterministic fallback. The call is
1492
+ * bounded by `control.timeoutMs` (default {@link COMPACTION_SUMMARY_TIMEOUT_MS})
1493
+ * and cancelled by `control.signal`; both also stop waiting on a provider
1494
+ * that ignores its abort signal. A provider failure or an elapsed deadline
1495
+ * returns the deterministic summary; a cancellation rejects with
1496
+ * `AbortError`.
1497
+ */
1498
+ async summarizeEntrySet(entries, prefixPrompt, control) {
1266
1499
  if (entries.length === 0)
1267
1500
  return summarizeEntries(entries);
1268
1501
  const deterministic = summarizeEntries(entries);
1269
1502
  const provider = this.options.modelProvider ?? defaultModelProvider;
1503
+ const timeoutMs = control.timeoutMs !== undefined && control.timeoutMs > 0
1504
+ ? control.timeoutMs
1505
+ : COMPACTION_SUMMARY_TIMEOUT_MS;
1506
+ const deadline = new AbortController();
1507
+ const onCallerAbort = () => deadline.abort(control.signal?.reason);
1508
+ if (control.signal?.aborted)
1509
+ throw promptAbortError(control.signal);
1510
+ control.signal?.addEventListener("abort", onCallerAbort, { once: true });
1511
+ let timedOut = false;
1512
+ const timer = setTimeout(() => {
1513
+ timedOut = true;
1514
+ deadline.abort(new Error(`Compaction summary timed out after ${timeoutMs}ms`));
1515
+ }, timeoutMs);
1516
+ let stop;
1517
+ const stopped = new Promise((_, reject) => {
1518
+ stop = reject;
1519
+ });
1520
+ stopped.catch(() => undefined);
1521
+ const onDeadline = () => stop?.(deadline.signal.reason);
1522
+ deadline.signal.addEventListener("abort", onDeadline, { once: true });
1270
1523
  try {
1271
1524
  const serialized = JSON.stringify(entries
1272
1525
  .map((entry) => ({
@@ -1276,18 +1529,30 @@ export class StubFabricSession {
1276
1529
  }))
1277
1530
  .slice(0, 200));
1278
1531
  const userContent = prefixPrompt ? `${serialized}\n\n${prefixPrompt}` : serialized;
1279
- const response = await generateWithRuntime(provider, {
1532
+ const summary = generateWithRuntime(provider, {
1280
1533
  ...(this.agent.model !== undefined ? { model: this.agent.model } : {}),
1281
1534
  messages: [
1282
1535
  { role: "system", content: COMPACTION_SUMMARIZATION_SYSTEM_PROMPT },
1283
1536
  { role: "user", content: userContent },
1284
1537
  ],
1285
- }, { retries: 1, retryDelayMs: 250 });
1538
+ }, { retries: 1, retryDelayMs: 250, signal: deadline.signal });
1539
+ const response = await Promise.race([summary, stopped]);
1286
1540
  return response.message?.content?.trim() || deterministic;
1287
1541
  }
1288
- catch {
1542
+ catch (error) {
1543
+ if (control.signal?.aborted)
1544
+ throw promptAbortError(control.signal);
1545
+ if (timedOut)
1546
+ return deterministic;
1547
+ if (isAbortError(error))
1548
+ throw error;
1289
1549
  return deterministic;
1290
1550
  }
1551
+ finally {
1552
+ clearTimeout(timer);
1553
+ control.signal?.removeEventListener("abort", onCallerAbort);
1554
+ deadline.signal.removeEventListener("abort", onDeadline);
1555
+ }
1291
1556
  }
1292
1557
  async requestCustomApproval(input) {
1293
1558
  const timeoutMs = input.timeoutMs ?? this.options.approvalTimeoutMs;
@@ -1412,6 +1677,14 @@ export class StubFabricSession {
1412
1677
  // boundary so approvals, lineage, history, and tool execution all refer
1413
1678
  // to the same unique logical operation.
1414
1679
  const toolCallId = call.id ?? `${this.id}:${call.tool}:${randomUUID()}`;
1680
+ if (signal?.aborted) {
1681
+ // Abort landed mid-batch: completed calls above keep their recorded
1682
+ // outcomes; calls that never started are settled as interrupted (and
1683
+ // never executed, approved, or policy-evaluated) so the transcript
1684
+ // keeps every requested call paired with an outcome.
1685
+ results.push(await this.recordUnexecutedInterruptedToolCall(call, toolCallId));
1686
+ continue;
1687
+ }
1415
1688
  const approvedSandboxCalls = [];
1416
1689
  let approvalGrant;
1417
1690
  const tool = tools.get(call.tool);
@@ -1593,6 +1866,7 @@ export class StubFabricSession {
1593
1866
  ...(this.options.actor ? { actor: this.options.actor } : {}),
1594
1867
  ...(this.options.tenantId ? { tenantId: this.options.tenantId } : {}),
1595
1868
  policyVersion: approvalInputDigest(policy ?? null),
1869
+ ...(policy ? { policy } : {}),
1596
1870
  inputDigest: approvalInputDigest(input),
1597
1871
  ...(tool.durable ? { step: this.createToolStep(toolCallId) } : {}),
1598
1872
  log: this.createToolProgressLogger(call.tool, toolCallId),
@@ -1655,6 +1929,32 @@ export class StubFabricSession {
1655
1929
  }
1656
1930
  return results;
1657
1931
  }
1932
+ async recordUnexecutedInterruptedToolCall(call, toolCallId) {
1933
+ const message = "Tool call was not executed: the prompt was aborted before this call started.";
1934
+ await this.recordEntry("tool_call", {
1935
+ tool: call.tool,
1936
+ input: call.input,
1937
+ inputDigest: approvalInputDigest(call.input),
1938
+ toolCallId,
1939
+ // Never ran: compaction's file references skip it.
1940
+ executed: false,
1941
+ });
1942
+ await this.recordEntry("tool_result", {
1943
+ tool: call.tool,
1944
+ toolCallId,
1945
+ output: { type: "interrupted", message },
1946
+ isError: true,
1947
+ interrupted: true,
1948
+ executed: false,
1949
+ });
1950
+ await this.emit("tool_end", { tool: call.tool, toolCallId, error: message, interrupted: true });
1951
+ return {
1952
+ tool: call.tool,
1953
+ input: call.input,
1954
+ error: message,
1955
+ ...(call.id ? { id: toolCallId } : {}),
1956
+ };
1957
+ }
1658
1958
  async requestCostLimitApproval(ctx, approvalTimeoutMs, approvalHandler) {
1659
1959
  return Boolean(await this.requestApproval({
1660
1960
  kind: "cost-limit",
@@ -2018,7 +2318,10 @@ export class StubFabricSession {
2018
2318
  * appends one advisory `signal` entry so the model knows the previous turn
2019
2319
  * was cut short. Idempotent: a repaired window has no dangling calls.
2020
2320
  */
2021
- async repairDanglingToolCalls(tools, sandbox, signal) {
2321
+ async repairDanglingToolCalls(tools, sandbox, signal,
2322
+ /** The resuming prompt's policy; the session's applies when absent. */
2323
+ promptPolicy) {
2324
+ const recoveryPolicy = promptPolicy ?? this.options.policy;
2022
2325
  for (let attempt = 0; attempt < 8; attempt += 1) {
2023
2326
  let data = await this.history();
2024
2327
  let path = SessionHistory.fromData(data).getActivePath();
@@ -2036,7 +2339,7 @@ export class StubFabricSession {
2036
2339
  }
2037
2340
  await this.emit("tool_start", { tool: toolName, recovery: true, toolCallId });
2038
2341
  try {
2039
- const authorization = await this.authorizeRecoveredToolCall(call, toolName, tool, toolCallId);
2342
+ const authorization = await this.authorizeRecoveredToolCall(call, toolName, tool, toolCallId, recoveryPolicy);
2040
2343
  const submission = currentSubmissionContext();
2041
2344
  const execute = () => Promise.resolve(executeTool(tool, call.data?.input, {
2042
2345
  sandbox,
@@ -2047,6 +2350,7 @@ export class StubFabricSession {
2047
2350
  ...(this.options.actor ? { actor: this.options.actor } : {}),
2048
2351
  ...(this.options.tenantId ? { tenantId: this.options.tenantId } : {}),
2049
2352
  policyVersion: authorization.policyDigest,
2353
+ ...(recoveryPolicy ? { policy: recoveryPolicy } : {}),
2050
2354
  inputDigest: authorization.inputDigest,
2051
2355
  step: this.createToolStep(toolCallId),
2052
2356
  log: this.createToolProgressLogger(toolName, toolCallId),
@@ -2169,7 +2473,7 @@ export class StubFabricSession {
2169
2473
  }
2170
2474
  throw new Error(`Could not repair interrupted session ${this.id}: session leaf kept changing.`);
2171
2475
  }
2172
- async authorizeRecoveredToolCall(call, toolName, tool, toolCallId) {
2476
+ async authorizeRecoveredToolCall(call, toolName, tool, toolCallId, policy) {
2173
2477
  const input = call.data?.input;
2174
2478
  const inputDigest = approvalInputDigest(input);
2175
2479
  if (call.data?.inputDigest !== inputDigest) {
@@ -2185,7 +2489,6 @@ export class StubFabricSession {
2185
2489
  message: `Recovered tool ${toolName} does not match the current tenant and actor context.`,
2186
2490
  });
2187
2491
  }
2188
- const policy = this.options.policy;
2189
2492
  const policyDigest = approvalInputDigest(policy ?? null);
2190
2493
  const policyCall = {
2191
2494
  tool: tool.policyAlias ?? toolName,
@@ -2564,7 +2867,9 @@ function collectFileReferences(entries) {
2564
2867
  const readFiles = new Set();
2565
2868
  const modifiedFiles = new Set();
2566
2869
  for (const entry of entries) {
2567
- if (entry.type === "tool_call") {
2870
+ // Length-truncated and abort-skipped calls are recorded with
2871
+ // `executed: false` and never ran.
2872
+ if (entry.type === "tool_call" && entry.data?.executed !== false) {
2568
2873
  const tool = typeof entry.data?.tool === "string" ? entry.data.tool : undefined;
2569
2874
  const effect = typeof entry.data?.effect === "string" ? entry.data.effect : undefined;
2570
2875
  const input = entry.data?.input;
@@ -2591,17 +2896,81 @@ function appendFileReferenceTags(summary, refs) {
2591
2896
  function recoveryEntryId(sourceEntryId, suffix) {
2592
2897
  return `session-recovery:${encodeURIComponent(sourceEntryId)}:${encodeURIComponent(suffix)}`;
2593
2898
  }
2594
- /** Valid cut points: user prompts and assistant messages. Never cut at tool_result. */
2899
+ /**
2900
+ * Valid cut points: user prompts and assistant messages outside an open tool
2901
+ * batch. Never cut at tool_result, and never between a tool_call and its
2902
+ * outcome.
2903
+ */
2595
2904
  function findValidCutPoints(entries, start, end) {
2905
+ const safe = toolBatchSafeCuts(entries);
2596
2906
  const cutPoints = [];
2597
2907
  for (let i = start; i < end; i++) {
2598
2908
  const type = entries[i]?.type;
2599
- if (type === "user_prompt" || type === "assistant_message") {
2909
+ if ((type === "user_prompt" || type === "assistant_message") && safe[i]) {
2600
2910
  cutPoints.push(i);
2601
2911
  }
2602
2912
  }
2603
2913
  return cutPoints;
2604
2914
  }
2915
+ /**
2916
+ * `safe[i]` is true when cutting before `entries[i]` keeps every tool_call
2917
+ * and its outcome on the same side of the cut. A kept tool_result whose
2918
+ * tool_call was summarized away replays as an orphaned tool message, which
2919
+ * strict providers reject. Outcomes pair by `toolCallId` when both records
2920
+ * carry one, else by tool name for legacy id-less entries. A call whose
2921
+ * outcome never arrives (abandoned by a crashed turn) spans no
2922
+ * outcome, so it never blocks a cut.
2923
+ */
2924
+ function toolBatchSafeCuts(entries) {
2925
+ // spans[i] counts call/outcome pairs with call < i <= outcome.
2926
+ const delta = new Array(entries.length + 2).fill(0);
2927
+ const open = [];
2928
+ entries.forEach((entry, position) => {
2929
+ const id = typeof entry.data?.toolCallId === "string" ? entry.data.toolCallId : undefined;
2930
+ const tool = typeof entry.data?.tool === "string" ? entry.data.tool : undefined;
2931
+ if (entry.type === "tool_call") {
2932
+ open.push({ index: position, id, tool });
2933
+ return;
2934
+ }
2935
+ if (entry.type !== "tool_result" && entry.type !== "error")
2936
+ return;
2937
+ let match = id !== undefined ? open.findIndex((call) => call.id === id) : -1;
2938
+ if (match < 0) {
2939
+ match = open.findIndex((call) => tool !== undefined && (id === undefined || call.id === undefined) && call.tool === tool);
2940
+ }
2941
+ if (match < 0)
2942
+ return;
2943
+ const [call] = open.splice(match, 1);
2944
+ if (!call)
2945
+ return;
2946
+ delta[call.index + 1] = (delta[call.index + 1] ?? 0) + 1;
2947
+ delta[position + 1] = (delta[position + 1] ?? 0) - 1;
2948
+ });
2949
+ const safe = [];
2950
+ let spans = 0;
2951
+ for (let i = 0; i <= entries.length; i += 1) {
2952
+ spans += delta[i] ?? 0;
2953
+ safe.push(spans === 0);
2954
+ }
2955
+ return safe;
2956
+ }
2957
+ /**
2958
+ * Move a count-based cut to the nearest tool-batch boundary: backwards first
2959
+ * (keeping more entries than requested), else forwards so compaction can
2960
+ * still make progress. Returns 0 when no boundary compacts anything.
2961
+ */
2962
+ function safeCountBasedCut(entries, cut) {
2963
+ if (cut <= 0)
2964
+ return 0;
2965
+ const safe = toolBatchSafeCuts(entries);
2966
+ for (let i = cut; i > 0; i -= 1)
2967
+ if (safe[i])
2968
+ return i;
2969
+ for (let i = cut + 1; i < entries.length; i += 1)
2970
+ if (safe[i])
2971
+ return i;
2972
+ return 0;
2973
+ }
2605
2974
  function findTurnStartIndex(entries, index, start) {
2606
2975
  for (let i = index; i >= start; i--) {
2607
2976
  if (entries[i]?.type === "user_prompt")
@@ -2703,6 +3072,39 @@ function abortError() {
2703
3072
  error.name = "AbortError";
2704
3073
  return error;
2705
3074
  }
3075
+ /** Compaction inside a prompt shares the prompt's abort signal and model timeout. */
3076
+ function compactionControlFor(options) {
3077
+ return {
3078
+ ...(options.signal !== undefined ? { signal: options.signal } : {}),
3079
+ ...(options.modelTimeoutMs !== undefined ? { timeoutMs: options.modelTimeoutMs } : {}),
3080
+ };
3081
+ }
3082
+ /** AbortError for a cancelled prompt, carrying the signal's reason when it has one. */
3083
+ function promptAbortError(signal) {
3084
+ const reason = signal.reason;
3085
+ if (reason instanceof Error && reason.name === "AbortError")
3086
+ return reason;
3087
+ const message = reason instanceof Error && reason.message
3088
+ ? reason.message
3089
+ : typeof reason === "string" && reason
3090
+ ? reason
3091
+ : "The operation was aborted.";
3092
+ const error = new Error(message, { cause: reason });
3093
+ error.name = "AbortError";
3094
+ return error;
3095
+ }
3096
+ /**
3097
+ * Only a genuine provider context-overflow failure triggers compact-and-retry.
3098
+ * Cancellation, and harness failures that merely mention context or tokens
3099
+ * (tool, policy, validation, cost, or turn-budget errors), surface unchanged.
3100
+ */
3101
+ function isProviderContextOverflow(error, signal) {
3102
+ if (signal?.aborted || isAbortError(error))
3103
+ return false;
3104
+ if (error instanceof FabricError && error.code !== "MODEL_CONTEXT_OVERFLOW")
3105
+ return false;
3106
+ return isContextOverflowError(error);
3107
+ }
2706
3108
  function isAbortError(error) {
2707
3109
  return (error instanceof Error &&
2708
3110
  (error.name === "AbortError" || /aborted|cancelled|canceled/i.test(error.message)));