@fabric-harness/sdk 6.3.0 → 6.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (168) hide show
  1. package/connector-spec/voice-telephony.md +120 -104
  2. package/dist/agent-route.d.ts +22 -2
  3. package/dist/agent-route.d.ts.map +1 -1
  4. package/dist/agent-route.js +32 -1
  5. package/dist/agent-route.js.map +1 -1
  6. package/dist/agent-router.d.ts +46 -0
  7. package/dist/agent-router.d.ts.map +1 -1
  8. package/dist/agent-router.js +63 -2
  9. package/dist/agent-router.js.map +1 -1
  10. package/dist/agent.d.ts.map +1 -1
  11. package/dist/agent.js +3 -0
  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 +16 -2
  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 +376 -57
  74. package/dist/model.js.map +1 -1
  75. package/dist/otel-observer.d.ts +3 -1
  76. package/dist/otel-observer.d.ts.map +1 -1
  77. package/dist/otel-observer.js +40 -8
  78. package/dist/otel-observer.js.map +1 -1
  79. package/dist/persistent-agent.d.ts +5 -0
  80. package/dist/persistent-agent.d.ts.map +1 -1
  81. package/dist/persistent-agent.js +9 -1
  82. package/dist/persistent-agent.js.map +1 -1
  83. package/dist/pi-document-attachments.d.ts +43 -0
  84. package/dist/pi-document-attachments.d.ts.map +1 -0
  85. package/dist/pi-document-attachments.js +155 -0
  86. package/dist/pi-document-attachments.js.map +1 -0
  87. package/dist/pi-loop-runtime.d.ts +103 -1
  88. package/dist/pi-loop-runtime.d.ts.map +1 -1
  89. package/dist/pi-loop-runtime.js +850 -109
  90. package/dist/pi-loop-runtime.js.map +1 -1
  91. package/dist/prompt-attachments.d.ts +98 -0
  92. package/dist/prompt-attachments.d.ts.map +1 -0
  93. package/dist/prompt-attachments.js +279 -0
  94. package/dist/prompt-attachments.js.map +1 -0
  95. package/dist/session.d.ts +52 -0
  96. package/dist/session.d.ts.map +1 -1
  97. package/dist/session.js +410 -33
  98. package/dist/session.js.map +1 -1
  99. package/dist/stream-chunks.d.ts +15 -1
  100. package/dist/stream-chunks.d.ts.map +1 -1
  101. package/dist/stream-chunks.js +39 -18
  102. package/dist/stream-chunks.js.map +1 -1
  103. package/dist/strict.d.ts +23 -16
  104. package/dist/strict.d.ts.map +1 -1
  105. package/dist/strict.js +12 -8
  106. package/dist/strict.js.map +1 -1
  107. package/dist/submission-context.d.ts +7 -0
  108. package/dist/submission-context.d.ts.map +1 -1
  109. package/dist/submission-context.js.map +1 -1
  110. package/dist/submission-runner.d.ts +5 -0
  111. package/dist/submission-runner.d.ts.map +1 -1
  112. package/dist/submission-runner.js +97 -13
  113. package/dist/submission-runner.js.map +1 -1
  114. package/dist/submission-store-contract.d.ts.map +1 -1
  115. package/dist/submission-store-contract.js +15 -1
  116. package/dist/submission-store-contract.js.map +1 -1
  117. package/dist/submission-store.d.ts +12 -0
  118. package/dist/submission-store.d.ts.map +1 -1
  119. package/dist/submission-store.js +13 -4
  120. package/dist/submission-store.js.map +1 -1
  121. package/dist/trace-content.d.ts +21 -0
  122. package/dist/trace-content.d.ts.map +1 -0
  123. package/dist/trace-content.js +69 -0
  124. package/dist/trace-content.js.map +1 -0
  125. package/dist/types.d.ts +26 -0
  126. package/dist/types.d.ts.map +1 -1
  127. package/dist/types.js.map +1 -1
  128. package/dist/usage-completeness.d.ts +39 -0
  129. package/dist/usage-completeness.d.ts.map +1 -0
  130. package/dist/usage-completeness.js +135 -0
  131. package/dist/usage-completeness.js.map +1 -0
  132. package/dist/voice-openai-realtime.d.ts +24 -2
  133. package/dist/voice-openai-realtime.d.ts.map +1 -1
  134. package/dist/voice-openai-realtime.js +266 -49
  135. package/dist/voice-openai-realtime.js.map +1 -1
  136. package/dist/voice-pipeline.d.ts +81 -3
  137. package/dist/voice-pipeline.d.ts.map +1 -1
  138. package/dist/voice-pipeline.js +429 -60
  139. package/dist/voice-pipeline.js.map +1 -1
  140. package/dist/voice-stt-cartesia.d.ts +8 -0
  141. package/dist/voice-stt-cartesia.d.ts.map +1 -1
  142. package/dist/voice-stt-cartesia.js +77 -17
  143. package/dist/voice-stt-cartesia.js.map +1 -1
  144. package/dist/voice-stt-deepgram.d.ts +10 -2
  145. package/dist/voice-stt-deepgram.d.ts.map +1 -1
  146. package/dist/voice-stt-deepgram.js +78 -18
  147. package/dist/voice-stt-deepgram.js.map +1 -1
  148. package/dist/voice-stt.d.ts +13 -3
  149. package/dist/voice-stt.d.ts.map +1 -1
  150. package/dist/voice-tts-cartesia.d.ts +8 -0
  151. package/dist/voice-tts-cartesia.d.ts.map +1 -1
  152. package/dist/voice-tts-cartesia.js +48 -105
  153. package/dist/voice-tts-cartesia.js.map +1 -1
  154. package/dist/voice-tts-elevenlabs.d.ts +10 -1
  155. package/dist/voice-tts-elevenlabs.d.ts.map +1 -1
  156. package/dist/voice-tts-elevenlabs.js +50 -113
  157. package/dist/voice-tts-elevenlabs.js.map +1 -1
  158. package/dist/voice-ws-client.js +16 -3
  159. package/dist/voice-ws-client.js.map +1 -1
  160. package/dist/voice-ws-shared.d.ts +205 -6
  161. package/dist/voice-ws-shared.d.ts.map +1 -1
  162. package/dist/voice-ws-shared.js +510 -15
  163. package/dist/voice-ws-shared.js.map +1 -1
  164. package/dist/voice.d.ts +98 -4
  165. package/dist/voice.d.ts.map +1 -1
  166. package/dist/voice.js +71 -1
  167. package/dist/voice.js.map +1 -1
  168. 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
 
@@ -117,6 +125,13 @@ export class StubFabricSession {
117
125
  costBudget;
118
126
  skillCache = new Map();
119
127
  effectivePackagedSkillsCache = null;
128
+ /**
129
+ * Process-local fallback when neither the session nor the runner supplies a
130
+ * store. Bounded (64 MiB, 256 blobs, least recently stored evicted first) so
131
+ * a long-lived session cannot retain attachment bytes without limit; an
132
+ * evicted blob hydrates as the "not available" placeholder.
133
+ */
134
+ localAttachmentStore;
120
135
  constructor(agent, id, options = {}) {
121
136
  this.agent = agent;
122
137
  this.id = id;
@@ -126,6 +141,51 @@ export class StubFabricSession {
126
141
  this.fs = createFabricFs(() => this.sandboxPromise);
127
142
  this.costBudget = new CostBudgetTracker(options.costLimit);
128
143
  }
144
+ /**
145
+ * Attachment store for this session: explicit option, else the executing
146
+ * submission runner's store, else a process-local in-memory store.
147
+ */
148
+ attachmentStore() {
149
+ const configured = this.options.attachmentStore ?? currentSubmissionContext()?.attachmentStore;
150
+ if (configured)
151
+ return configured;
152
+ this.localAttachmentStore ??= new BoundedInMemoryAttachmentStore();
153
+ return this.localAttachmentStore;
154
+ }
155
+ /**
156
+ * Fill attachment bytes on history-projected messages (refs only) from the
157
+ * in-flight map, then the attachment store. Every path that rebuilds model
158
+ * messages from history must pass through here before calling the model.
159
+ */
160
+ hydrateMessageAttachments(messages, inflight, budget) {
161
+ // A full transcript rebuild replaces the request, so it restarts the
162
+ // request-wide allowance; joined inputs appended later charge the rest.
163
+ if (budget)
164
+ budget.usedBytes = 0;
165
+ return hydrateModelMessageAttachments(messages, {
166
+ store: this.attachmentStore(),
167
+ scope: this.id,
168
+ ...(inflight ? { inflight } : {}),
169
+ ...(budget ? { budget } : {}),
170
+ });
171
+ }
172
+ /**
173
+ * Store an input's inline attachments and return refs-only records plus the
174
+ * in-flight bytes. Deterministic ids for submissions keep recovery stable.
175
+ */
176
+ async prepareInputAttachments(inline, message, submissionId) {
177
+ const delivered = message?.kind === "user" ? (message.attachments ?? []) : [];
178
+ if (inline.length === 0 && delivered.length === 0) {
179
+ return { records: [], inflight: new Map() };
180
+ }
181
+ return preparePromptAttachments({
182
+ inline,
183
+ delivered,
184
+ store: this.attachmentStore(),
185
+ scope: this.id,
186
+ idPrefix: submissionId ? `att_${submissionId}` : `att_prompt_${randomUUID()}`,
187
+ });
188
+ }
129
189
  getDurableRuntime() {
130
190
  if (this.durableRuntime)
131
191
  return this.durableRuntime;
@@ -175,6 +235,7 @@ export class StubFabricSession {
175
235
  publicMessage: "The durable submission input is inconsistent.",
176
236
  });
177
237
  }
238
+ const inlineAttachments = validatePromptAttachments(options.images, options.documents);
178
239
  const durable = await this.getDurableRuntime();
179
240
  if (durable) {
180
241
  if (this.options.dynamic && durable.supportsDynamicAgents !== true) {
@@ -185,6 +246,15 @@ export class StubFabricSession {
185
246
  publicMessage: "This dynamic agent is not supported by the configured durable runtime.",
186
247
  });
187
248
  }
249
+ if (inlineAttachments.length > 0) {
250
+ throw new FabricError({
251
+ code: "INVALID_CONFIG",
252
+ message: "Inline prompt images/documents are not supported with a durable session runtime: " +
253
+ "their bytes would enter durable workflow inputs. Admit them through a submission " +
254
+ "with an attachment store so only content-addressed refs are forwarded.",
255
+ publicMessage: "Inline attachments are not supported by the configured durable runtime.",
256
+ });
257
+ }
188
258
  // Delegate to the durable runtime; the runtime is responsible for
189
259
  // recording entries / events on its own side. We still emit a single
190
260
  // local prompt_start/end pair so local subscribers see activity.
@@ -325,27 +395,42 @@ export class StubFabricSession {
325
395
  // recovered attempt whose input entry already landed (crash after the
326
396
  // canonical write) resumes from history instead of double-applying.
327
397
  let inputAlreadyApplied = false;
398
+ // The entry carrying this prompt. Retention checks match it by id, since
399
+ // an earlier prompt with identical text (but other attachments) must not
400
+ // stand in for it.
401
+ let promptEntryId;
328
402
  if (options.submission) {
329
403
  const prior = await this.history();
330
404
  const submissionId = options.submission.submissionId;
331
- inputAlreadyApplied = (prior.entries ?? []).some((entry) => (entry.type === "user_prompt" || entry.type === "signal") &&
332
- entry.data?.submissionId === submissionId);
405
+ promptEntryId = (prior.entries ?? []).find((entry) => (entry.type === "user_prompt" || entry.type === "signal") &&
406
+ entry.data?.submissionId === submissionId)?.id;
407
+ inputAlreadyApplied = promptEntryId !== undefined;
333
408
  }
409
+ const promptAttachments = await this.prepareInputAttachments(inlineAttachments, options.submission?.message, options.submission?.submissionId);
334
410
  if (!inputAlreadyApplied) {
335
411
  if (options.submission?.message?.kind === "signal") {
336
- await this.recordEntry("signal", {
412
+ promptEntryId = (await this.recordEntry("signal", {
337
413
  ...deliveredSignalToEntryData(options.submission.message),
338
414
  submissionId: options.submission.submissionId,
339
- });
415
+ })).id;
340
416
  }
341
417
  else {
342
- await this.recordEntry("user_prompt", {
418
+ promptEntryId = (await this.recordEntry("user_prompt", {
343
419
  text,
344
420
  ...(role ? { role: role.name } : {}),
345
421
  ...(options.submission ? { submissionId: options.submission.submissionId } : {}),
346
- });
422
+ // Refs only: attachment bytes never enter session entries.
423
+ ...(promptAttachments.records.length > 0
424
+ ? { attachments: promptAttachments.records }
425
+ : {}),
426
+ })).id;
347
427
  }
348
428
  }
429
+ const promptInContext = (data, projected) => promptEntryId !== undefined
430
+ ? SessionHistory.fromData(data)
431
+ .buildContextEntries()
432
+ .some((entry) => entry.id === promptEntryId)
433
+ : projected.some((message) => message.role === "user" && message.content === text);
349
434
  // Input-applied boundary: the canonical input entry is durable and no
350
435
  // provider work has started. The submission runner's input-applied
351
436
  // marker CAS hangs off this callback; its failure aborts the turn
@@ -374,11 +459,27 @@ export class StubFabricSession {
374
459
  }
375
460
  const sessionData = await this.history();
376
461
  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);
462
+ if (!promptInContext(sessionData, messages))
463
+ messages.push({
464
+ role: "user",
465
+ content: text,
466
+ ...(promptAttachments.records.length > 0
467
+ ? { attachments: recordsToModelAttachments(promptAttachments.records) }
468
+ : {}),
469
+ });
470
+ // One hydration allowance for the whole model request, shared by the
471
+ // rebuilt transcript and any joined inputs appended while it runs.
472
+ const hydrationBudget = createAttachmentHydrationBudget();
473
+ messages = await this.hydrateMessageAttachments(messages, promptAttachments.inflight, hydrationBudget);
474
+ messages = await this.autoCompactIfNeeded(messages, role, options, hydrationBudget);
380
475
  if (options.toolCalls?.length) {
381
476
  const results = await this.executeToolCalls(options.toolCalls, tools, sandbox, options.policy, options.approvalTimeoutMs ?? this.options.approvalTimeoutMs, options.onApproval, undefined, options.signal);
477
+ // An abort before or during the batch settled its unstarted calls as
478
+ // interrupted so the transcript stays paired. The prompt itself was
479
+ // cancelled: reject with AbortError, like the model loop, and never
480
+ // record a result or emit prompt_end for it.
481
+ if (options.signal?.aborted)
482
+ throw promptAbortError(options.signal);
382
483
  await this.recordEntry("result", { result: results });
383
484
  await this.emit("prompt_end", { text, result: results });
384
485
  const value = await validateResult(results, options.result, options.resultExtraction);
@@ -463,14 +564,36 @@ export class StubFabricSession {
463
564
  ...deliveredSignalToEntryData(input.message),
464
565
  submissionId: input.submissionId,
465
566
  });
567
+ messages.push({ role: "user", content: input.text });
466
568
  }
467
569
  else {
570
+ const joinedAttachments = await this.prepareInputAttachments([], input.message, input.submissionId);
468
571
  await this.recordEntry("user_prompt", {
469
572
  text: input.text,
470
573
  submissionId: input.submissionId,
574
+ ...(joinedAttachments.records.length > 0
575
+ ? { attachments: joinedAttachments.records }
576
+ : {}),
471
577
  });
578
+ const [joinedMessage] = await hydrateModelMessageAttachments([
579
+ {
580
+ role: "user",
581
+ content: input.text,
582
+ ...(joinedAttachments.records.length > 0
583
+ ? { attachments: recordsToModelAttachments(joinedAttachments.records) }
584
+ : {}),
585
+ },
586
+ ], {
587
+ store: this.attachmentStore(),
588
+ scope: this.id,
589
+ inflight: joinedAttachments.inflight,
590
+ // Charged against the running request's allowance,
591
+ // not a fresh 50 MiB per joined input.
592
+ budget: hydrationBudget,
593
+ });
594
+ if (joinedMessage)
595
+ messages.push(joinedMessage);
472
596
  }
473
- messages.push({ role: "user", content: input.text });
474
597
  }
475
598
  if (input.message && dynamic) {
476
599
  await refreshDynamic({
@@ -524,17 +647,42 @@ export class StubFabricSession {
524
647
  catch (error) {
525
648
  const compactionSettings = this.options.compaction;
526
649
  const recoverFromOverflow = options.recoverContextOverflow ?? compactionSettings?.recoverFromOverflow ?? true;
527
- if (!isContextOverflowError(error) || !recoverFromOverflow)
650
+ if (!isProviderContextOverflow(error, options.signal) || !recoverFromOverflow)
528
651
  throw error;
529
652
  await this.emit("error", {
530
653
  error: "Context overflow detected; compacting and retrying once.",
531
654
  });
532
- await this.compact({
655
+ await this.compactWithControl({
533
656
  keepRecentEntries: options.compactionKeepRecentEntries ?? compactionSettings?.keepRecentEntries ?? 20,
534
657
  generateSummary: true,
535
658
  reason: "overflow",
536
- });
537
- messages = buildModelMessagesFromHistory(await this.history(), role);
659
+ }, compactionControlFor(options));
660
+ const compactedData = await this.history();
661
+ messages = buildModelMessagesFromHistory(compactedData, role);
662
+ // Compaction may summarize the entry that carried this prompt, and an
663
+ // in-memory follow-up (result-tool nudge, steering) after a completed
664
+ // response is not durable. Keep the pending input as the final user
665
+ // turn so the retry never asks the provider to continue from a
666
+ // completed assistant response.
667
+ const tail = messages.at(-1);
668
+ const promptRetained = promptInContext(compactedData, messages);
669
+ if (!promptRetained || (tail?.role === "assistant" && !tail.toolCalls?.length)) {
670
+ // When compaction summarized the prompt away, its attachments go
671
+ // with it; restore them so the retry still carries the image/PDF.
672
+ // A retained prompt already carries its refs earlier in the
673
+ // transcript, so the re-added tail turn stays text-only rather
674
+ // than doubling attachment bytes on an overflow retry.
675
+ messages.push({
676
+ role: "user",
677
+ content: text,
678
+ ...(!promptRetained && promptAttachments.records.length > 0
679
+ ? { attachments: recordsToModelAttachments(promptAttachments.records) }
680
+ : {}),
681
+ });
682
+ }
683
+ // History projections carry refs only; rehydrate bytes exactly as
684
+ // the initial prompt path does.
685
+ messages = await this.hydrateMessageAttachments(messages, promptAttachments.inflight, hydrationBudget);
538
686
  result = await runRuntime();
539
687
  }
540
688
  let continuationCount = 0;
@@ -573,14 +721,18 @@ export class StubFabricSession {
573
721
  }
574
722
  }
575
723
  const finalized = await this.finalizeDynamicResult(value, responseStartLeafId, result.usage);
576
- if (!finalized.continued)
724
+ if (!finalized.continued) {
725
+ if (result.terminatedByTool)
726
+ await this.compactAfterTermination(role, options);
577
727
  return finalized.value;
728
+ }
578
729
  continuationCount += 1;
579
730
  if (continuationCount > 8) {
580
731
  throw new Error("useAgentFinish() exceeded the maximum of 8 continuation cycles.");
581
732
  }
582
733
  messages = buildModelMessagesFromHistory(await this.history(), role);
583
- messages = await this.autoCompactIfNeeded(messages, role, options);
734
+ messages = await this.hydrateMessageAttachments(messages, promptAttachments.inflight, hydrationBudget);
735
+ messages = await this.autoCompactIfNeeded(messages, role, options, hydrationBudget);
584
736
  result = await runRuntime();
585
737
  }
586
738
  }
@@ -665,6 +817,14 @@ export class StubFabricSession {
665
817
  publicMessage: "This dynamic agent is not supported by the configured durable runtime.",
666
818
  });
667
819
  }
820
+ if (validatePromptAttachments(options.images, options.documents).length > 0) {
821
+ throw new FabricError({
822
+ code: "INVALID_CONFIG",
823
+ message: "Inline task images/documents are not supported with a durable session runtime: " +
824
+ "their bytes would enter durable workflow inputs.",
825
+ publicMessage: "Inline attachments are not supported by the configured durable runtime.",
826
+ });
827
+ }
668
828
  const taskId = options.id ?? `${this.id}:task-${++nextTaskId}`;
669
829
  await this.emit("task_start", { taskId, depth: 1, parentSessionId: this.id });
670
830
  try {
@@ -1137,6 +1297,16 @@ export class StubFabricSession {
1137
1297
  return ref;
1138
1298
  }
1139
1299
  async compact(options = {}) {
1300
+ return this.compactWithControl(options, {});
1301
+ }
1302
+ /**
1303
+ * `compact()` with the running prompt's abort signal and model timeout.
1304
+ * An abort rejects with `AbortError` before anything is recorded; a summary
1305
+ * that exceeds the deadline falls back to the deterministic summary.
1306
+ */
1307
+ async compactWithControl(options, control) {
1308
+ if (control.signal?.aborted)
1309
+ throw promptAbortError(control.signal);
1140
1310
  const history = await this.history();
1141
1311
  const entries = history.entries ?? [];
1142
1312
  const settings = this.options.compaction;
@@ -1146,8 +1316,9 @@ export class StubFabricSession {
1146
1316
  let firstKeptEntry;
1147
1317
  let prep;
1148
1318
  if (explicitKeepRecentEntries !== undefined) {
1149
- // Backward-compatible count-based cut.
1150
- const compactedCount = Math.max(0, entries.length - explicitKeepRecentEntries);
1319
+ // Backward-compatible count-based cut, moved to a tool-batch boundary so
1320
+ // a kept tool_result never loses its summarized tool_call.
1321
+ const compactedCount = safeCountBasedCut(entries, Math.max(0, entries.length - explicitKeepRecentEntries));
1151
1322
  firstKeptEntry = compactedCount > 0 ? entries[compactedCount] : undefined;
1152
1323
  compacted = compactedCount > 0 ? entries.slice(0, compactedCount) : [];
1153
1324
  }
@@ -1169,8 +1340,11 @@ export class StubFabricSession {
1169
1340
  };
1170
1341
  const baseSummary = options.summary ??
1171
1342
  (options.generateSummary
1172
- ? await this.generateCompactionSummary(summaryInput)
1343
+ ? await this.generateCompactionSummary(summaryInput, control)
1173
1344
  : summarizeEntries(compacted));
1345
+ // Never record a compaction for a prompt that was cancelled meanwhile.
1346
+ if (control.signal?.aborted)
1347
+ throw promptAbortError(control.signal);
1174
1348
  const summary = appendFileReferenceTags(baseSummary, fileRefs);
1175
1349
  const compactedEntries = compacted.length;
1176
1350
  const entry = await this.recordEntry("compaction", {
@@ -1197,7 +1371,7 @@ export class StubFabricSession {
1197
1371
  details: { readFiles: fileRefs.readFiles, modifiedFiles: fileRefs.modifiedFiles },
1198
1372
  };
1199
1373
  }
1200
- async autoCompactIfNeeded(messages, role, options) {
1374
+ async autoCompactIfNeeded(messages, role, options, hydrationBudget) {
1201
1375
  if (options.autoCompact === false)
1202
1376
  return messages;
1203
1377
  const settings = this.options.compaction;
@@ -1231,9 +1405,39 @@ export class StubFabricSession {
1231
1405
  else {
1232
1406
  compactOpts.keepRecentTokens = settings?.keepRecentTokens ?? budget.keepRecentTokens ?? 8_000;
1233
1407
  }
1234
- await this.compact(compactOpts);
1408
+ await this.compactWithControl(compactOpts, compactionControlFor(options));
1235
1409
  const compacted = buildModelMessagesFromHistory(await this.history(), role);
1236
- return compacted;
1410
+ // The rebuilt projection carries attachment refs only; rehydrate from
1411
+ // the attachment store so retained image/PDF turns keep their bytes.
1412
+ return this.hydrateMessageAttachments(compacted, undefined, hydrationBudget);
1413
+ }
1414
+ /**
1415
+ * A run that ended through a terminating tool skips the loop's final
1416
+ * assistant turn, so apply the auto-compaction budget immediately and let
1417
+ * the next turn start from a manageable context. Best effort: the
1418
+ * terminating result is already durable, and the next prompt re-evaluates
1419
+ * the budget before calling the model if this compaction fails.
1420
+ *
1421
+ * The summary call receives the prompt's abort signal and deadline. An
1422
+ * abort that arrives while it runs skips the compaction and the prompt
1423
+ * still resolves with its finalized result, the same as an abort that
1424
+ * arrives after the result is final. A summary that exceeds the deadline
1425
+ * falls back to the deterministic summary.
1426
+ */
1427
+ async compactAfterTermination(role, options) {
1428
+ if (options.signal?.aborted)
1429
+ return;
1430
+ try {
1431
+ const messages = buildModelMessagesFromHistory(await this.history(), role);
1432
+ await this.autoCompactIfNeeded(messages, role, options);
1433
+ }
1434
+ catch (error) {
1435
+ if (options.signal?.aborted || isAbortError(error))
1436
+ return;
1437
+ await this.emit("error", {
1438
+ error: `Post-termination compaction failed; the next prompt will retry it: ${error instanceof Error ? error.message : String(error)}`,
1439
+ });
1440
+ }
1237
1441
  }
1238
1442
  resolveModelContextWindow(options) {
1239
1443
  const provider = options.modelProvider ?? this.options.modelProvider;
@@ -1252,21 +1456,49 @@ export class StubFabricSession {
1252
1456
  return undefined;
1253
1457
  }
1254
1458
  }
1255
- async generateCompactionSummary(prep) {
1459
+ async generateCompactionSummary(prep, control) {
1256
1460
  if (prep.isSplitTurn && prep.turnPrefixMessages.length > 0) {
1257
1461
  const [historyResult, prefixResult] = await Promise.all([
1258
- this.summarizeEntrySet(prep.messagesToSummarize),
1259
- this.summarizeEntrySet(prep.turnPrefixMessages, TURN_PREFIX_SUMMARIZATION_PROMPT),
1462
+ this.summarizeEntrySet(prep.messagesToSummarize, undefined, control),
1463
+ this.summarizeEntrySet(prep.turnPrefixMessages, TURN_PREFIX_SUMMARIZATION_PROMPT, control),
1260
1464
  ]);
1261
1465
  return `${historyResult}\n\n---\n\n**Turn Context (split turn):**\n\n${prefixResult}`;
1262
1466
  }
1263
- return this.summarizeEntrySet(prep.messagesToSummarize);
1467
+ return this.summarizeEntrySet(prep.messagesToSummarize, undefined, control);
1264
1468
  }
1265
- async summarizeEntrySet(entries, prefixPrompt) {
1469
+ /**
1470
+ * Model-generated summary with a deterministic fallback. The call is
1471
+ * bounded by `control.timeoutMs` (default {@link COMPACTION_SUMMARY_TIMEOUT_MS})
1472
+ * and cancelled by `control.signal`; both also stop waiting on a provider
1473
+ * that ignores its abort signal. A provider failure or an elapsed deadline
1474
+ * returns the deterministic summary; a cancellation rejects with
1475
+ * `AbortError`.
1476
+ */
1477
+ async summarizeEntrySet(entries, prefixPrompt, control) {
1266
1478
  if (entries.length === 0)
1267
1479
  return summarizeEntries(entries);
1268
1480
  const deterministic = summarizeEntries(entries);
1269
1481
  const provider = this.options.modelProvider ?? defaultModelProvider;
1482
+ const timeoutMs = control.timeoutMs !== undefined && control.timeoutMs > 0
1483
+ ? control.timeoutMs
1484
+ : COMPACTION_SUMMARY_TIMEOUT_MS;
1485
+ const deadline = new AbortController();
1486
+ const onCallerAbort = () => deadline.abort(control.signal?.reason);
1487
+ if (control.signal?.aborted)
1488
+ throw promptAbortError(control.signal);
1489
+ control.signal?.addEventListener("abort", onCallerAbort, { once: true });
1490
+ let timedOut = false;
1491
+ const timer = setTimeout(() => {
1492
+ timedOut = true;
1493
+ deadline.abort(new Error(`Compaction summary timed out after ${timeoutMs}ms`));
1494
+ }, timeoutMs);
1495
+ let stop;
1496
+ const stopped = new Promise((_, reject) => {
1497
+ stop = reject;
1498
+ });
1499
+ stopped.catch(() => undefined);
1500
+ const onDeadline = () => stop?.(deadline.signal.reason);
1501
+ deadline.signal.addEventListener("abort", onDeadline, { once: true });
1270
1502
  try {
1271
1503
  const serialized = JSON.stringify(entries
1272
1504
  .map((entry) => ({
@@ -1276,18 +1508,30 @@ export class StubFabricSession {
1276
1508
  }))
1277
1509
  .slice(0, 200));
1278
1510
  const userContent = prefixPrompt ? `${serialized}\n\n${prefixPrompt}` : serialized;
1279
- const response = await generateWithRuntime(provider, {
1511
+ const summary = generateWithRuntime(provider, {
1280
1512
  ...(this.agent.model !== undefined ? { model: this.agent.model } : {}),
1281
1513
  messages: [
1282
1514
  { role: "system", content: COMPACTION_SUMMARIZATION_SYSTEM_PROMPT },
1283
1515
  { role: "user", content: userContent },
1284
1516
  ],
1285
- }, { retries: 1, retryDelayMs: 250 });
1517
+ }, { retries: 1, retryDelayMs: 250, signal: deadline.signal });
1518
+ const response = await Promise.race([summary, stopped]);
1286
1519
  return response.message?.content?.trim() || deterministic;
1287
1520
  }
1288
- catch {
1521
+ catch (error) {
1522
+ if (control.signal?.aborted)
1523
+ throw promptAbortError(control.signal);
1524
+ if (timedOut)
1525
+ return deterministic;
1526
+ if (isAbortError(error))
1527
+ throw error;
1289
1528
  return deterministic;
1290
1529
  }
1530
+ finally {
1531
+ clearTimeout(timer);
1532
+ control.signal?.removeEventListener("abort", onCallerAbort);
1533
+ deadline.signal.removeEventListener("abort", onDeadline);
1534
+ }
1291
1535
  }
1292
1536
  async requestCustomApproval(input) {
1293
1537
  const timeoutMs = input.timeoutMs ?? this.options.approvalTimeoutMs;
@@ -1412,6 +1656,14 @@ export class StubFabricSession {
1412
1656
  // boundary so approvals, lineage, history, and tool execution all refer
1413
1657
  // to the same unique logical operation.
1414
1658
  const toolCallId = call.id ?? `${this.id}:${call.tool}:${randomUUID()}`;
1659
+ if (signal?.aborted) {
1660
+ // Abort landed mid-batch: completed calls above keep their recorded
1661
+ // outcomes; calls that never started are settled as interrupted (and
1662
+ // never executed, approved, or policy-evaluated) so the transcript
1663
+ // keeps every requested call paired with an outcome.
1664
+ results.push(await this.recordUnexecutedInterruptedToolCall(call, toolCallId));
1665
+ continue;
1666
+ }
1415
1667
  const approvedSandboxCalls = [];
1416
1668
  let approvalGrant;
1417
1669
  const tool = tools.get(call.tool);
@@ -1655,6 +1907,32 @@ export class StubFabricSession {
1655
1907
  }
1656
1908
  return results;
1657
1909
  }
1910
+ async recordUnexecutedInterruptedToolCall(call, toolCallId) {
1911
+ const message = "Tool call was not executed: the prompt was aborted before this call started.";
1912
+ await this.recordEntry("tool_call", {
1913
+ tool: call.tool,
1914
+ input: call.input,
1915
+ inputDigest: approvalInputDigest(call.input),
1916
+ toolCallId,
1917
+ // Never ran: compaction's file references skip it.
1918
+ executed: false,
1919
+ });
1920
+ await this.recordEntry("tool_result", {
1921
+ tool: call.tool,
1922
+ toolCallId,
1923
+ output: { type: "interrupted", message },
1924
+ isError: true,
1925
+ interrupted: true,
1926
+ executed: false,
1927
+ });
1928
+ await this.emit("tool_end", { tool: call.tool, toolCallId, error: message, interrupted: true });
1929
+ return {
1930
+ tool: call.tool,
1931
+ input: call.input,
1932
+ error: message,
1933
+ ...(call.id ? { id: toolCallId } : {}),
1934
+ };
1935
+ }
1658
1936
  async requestCostLimitApproval(ctx, approvalTimeoutMs, approvalHandler) {
1659
1937
  return Boolean(await this.requestApproval({
1660
1938
  kind: "cost-limit",
@@ -2564,7 +2842,9 @@ function collectFileReferences(entries) {
2564
2842
  const readFiles = new Set();
2565
2843
  const modifiedFiles = new Set();
2566
2844
  for (const entry of entries) {
2567
- if (entry.type === "tool_call") {
2845
+ // Length-truncated and abort-skipped calls are recorded with
2846
+ // `executed: false` and never ran.
2847
+ if (entry.type === "tool_call" && entry.data?.executed !== false) {
2568
2848
  const tool = typeof entry.data?.tool === "string" ? entry.data.tool : undefined;
2569
2849
  const effect = typeof entry.data?.effect === "string" ? entry.data.effect : undefined;
2570
2850
  const input = entry.data?.input;
@@ -2591,17 +2871,81 @@ function appendFileReferenceTags(summary, refs) {
2591
2871
  function recoveryEntryId(sourceEntryId, suffix) {
2592
2872
  return `session-recovery:${encodeURIComponent(sourceEntryId)}:${encodeURIComponent(suffix)}`;
2593
2873
  }
2594
- /** Valid cut points: user prompts and assistant messages. Never cut at tool_result. */
2874
+ /**
2875
+ * Valid cut points: user prompts and assistant messages outside an open tool
2876
+ * batch. Never cut at tool_result, and never between a tool_call and its
2877
+ * outcome.
2878
+ */
2595
2879
  function findValidCutPoints(entries, start, end) {
2880
+ const safe = toolBatchSafeCuts(entries);
2596
2881
  const cutPoints = [];
2597
2882
  for (let i = start; i < end; i++) {
2598
2883
  const type = entries[i]?.type;
2599
- if (type === "user_prompt" || type === "assistant_message") {
2884
+ if ((type === "user_prompt" || type === "assistant_message") && safe[i]) {
2600
2885
  cutPoints.push(i);
2601
2886
  }
2602
2887
  }
2603
2888
  return cutPoints;
2604
2889
  }
2890
+ /**
2891
+ * `safe[i]` is true when cutting before `entries[i]` keeps every tool_call
2892
+ * and its outcome on the same side of the cut. A kept tool_result whose
2893
+ * tool_call was summarized away replays as an orphaned tool message, which
2894
+ * strict providers reject. Outcomes pair by `toolCallId` when both records
2895
+ * carry one, else by tool name for legacy id-less entries. A call whose
2896
+ * outcome never arrives (abandoned by a crashed turn) spans no
2897
+ * outcome, so it never blocks a cut.
2898
+ */
2899
+ function toolBatchSafeCuts(entries) {
2900
+ // spans[i] counts call/outcome pairs with call < i <= outcome.
2901
+ const delta = new Array(entries.length + 2).fill(0);
2902
+ const open = [];
2903
+ entries.forEach((entry, position) => {
2904
+ const id = typeof entry.data?.toolCallId === "string" ? entry.data.toolCallId : undefined;
2905
+ const tool = typeof entry.data?.tool === "string" ? entry.data.tool : undefined;
2906
+ if (entry.type === "tool_call") {
2907
+ open.push({ index: position, id, tool });
2908
+ return;
2909
+ }
2910
+ if (entry.type !== "tool_result" && entry.type !== "error")
2911
+ return;
2912
+ let match = id !== undefined ? open.findIndex((call) => call.id === id) : -1;
2913
+ if (match < 0) {
2914
+ match = open.findIndex((call) => tool !== undefined && (id === undefined || call.id === undefined) && call.tool === tool);
2915
+ }
2916
+ if (match < 0)
2917
+ return;
2918
+ const [call] = open.splice(match, 1);
2919
+ if (!call)
2920
+ return;
2921
+ delta[call.index + 1] = (delta[call.index + 1] ?? 0) + 1;
2922
+ delta[position + 1] = (delta[position + 1] ?? 0) - 1;
2923
+ });
2924
+ const safe = [];
2925
+ let spans = 0;
2926
+ for (let i = 0; i <= entries.length; i += 1) {
2927
+ spans += delta[i] ?? 0;
2928
+ safe.push(spans === 0);
2929
+ }
2930
+ return safe;
2931
+ }
2932
+ /**
2933
+ * Move a count-based cut to the nearest tool-batch boundary: backwards first
2934
+ * (keeping more entries than requested), else forwards so compaction can
2935
+ * still make progress. Returns 0 when no boundary compacts anything.
2936
+ */
2937
+ function safeCountBasedCut(entries, cut) {
2938
+ if (cut <= 0)
2939
+ return 0;
2940
+ const safe = toolBatchSafeCuts(entries);
2941
+ for (let i = cut; i > 0; i -= 1)
2942
+ if (safe[i])
2943
+ return i;
2944
+ for (let i = cut + 1; i < entries.length; i += 1)
2945
+ if (safe[i])
2946
+ return i;
2947
+ return 0;
2948
+ }
2605
2949
  function findTurnStartIndex(entries, index, start) {
2606
2950
  for (let i = index; i >= start; i--) {
2607
2951
  if (entries[i]?.type === "user_prompt")
@@ -2703,6 +3047,39 @@ function abortError() {
2703
3047
  error.name = "AbortError";
2704
3048
  return error;
2705
3049
  }
3050
+ /** Compaction inside a prompt shares the prompt's abort signal and model timeout. */
3051
+ function compactionControlFor(options) {
3052
+ return {
3053
+ ...(options.signal !== undefined ? { signal: options.signal } : {}),
3054
+ ...(options.modelTimeoutMs !== undefined ? { timeoutMs: options.modelTimeoutMs } : {}),
3055
+ };
3056
+ }
3057
+ /** AbortError for a cancelled prompt, carrying the signal's reason when it has one. */
3058
+ function promptAbortError(signal) {
3059
+ const reason = signal.reason;
3060
+ if (reason instanceof Error && reason.name === "AbortError")
3061
+ return reason;
3062
+ const message = reason instanceof Error && reason.message
3063
+ ? reason.message
3064
+ : typeof reason === "string" && reason
3065
+ ? reason
3066
+ : "The operation was aborted.";
3067
+ const error = new Error(message, { cause: reason });
3068
+ error.name = "AbortError";
3069
+ return error;
3070
+ }
3071
+ /**
3072
+ * Only a genuine provider context-overflow failure triggers compact-and-retry.
3073
+ * Cancellation, and harness failures that merely mention context or tokens
3074
+ * (tool, policy, validation, cost, or turn-budget errors), surface unchanged.
3075
+ */
3076
+ function isProviderContextOverflow(error, signal) {
3077
+ if (signal?.aborted || isAbortError(error))
3078
+ return false;
3079
+ if (error instanceof FabricError && error.code !== "MODEL_CONTEXT_OVERFLOW")
3080
+ return false;
3081
+ return isContextOverflowError(error);
3082
+ }
2706
3083
  function isAbortError(error) {
2707
3084
  return (error instanceof Error &&
2708
3085
  (error.name === "AbortError" || /aborted|cancelled|canceled/i.test(error.message)));