@fabric-harness/sdk 6.9.1 → 6.11.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 (102) hide show
  1. package/dist/agent.d.ts.map +1 -1
  2. package/dist/agent.js +8 -0
  3. package/dist/agent.js.map +1 -1
  4. package/dist/channel-runtime.d.ts +2 -0
  5. package/dist/channel-runtime.d.ts.map +1 -1
  6. package/dist/channel-runtime.js +1 -0
  7. package/dist/channel-runtime.js.map +1 -1
  8. package/dist/channel.d.ts +11 -0
  9. package/dist/channel.d.ts.map +1 -1
  10. package/dist/channel.js.map +1 -1
  11. package/dist/context.d.ts +28 -0
  12. package/dist/context.d.ts.map +1 -1
  13. package/dist/context.js +18 -0
  14. package/dist/context.js.map +1 -1
  15. package/dist/conversation-ownership.d.ts +151 -0
  16. package/dist/conversation-ownership.d.ts.map +1 -0
  17. package/dist/conversation-ownership.js +239 -0
  18. package/dist/conversation-ownership.js.map +1 -0
  19. package/dist/dispatch.d.ts +7 -0
  20. package/dist/dispatch.d.ts.map +1 -1
  21. package/dist/dispatch.js.map +1 -1
  22. package/dist/dynamic-agent.d.ts.map +1 -1
  23. package/dist/dynamic-agent.js +8 -0
  24. package/dist/dynamic-agent.js.map +1 -1
  25. package/dist/error.d.ts +1 -1
  26. package/dist/error.d.ts.map +1 -1
  27. package/dist/error.js.map +1 -1
  28. package/dist/events.d.ts +16 -4
  29. package/dist/events.d.ts.map +1 -1
  30. package/dist/events.js.map +1 -1
  31. package/dist/governed-voice.d.ts.map +1 -1
  32. package/dist/governed-voice.js +192 -125
  33. package/dist/governed-voice.js.map +1 -1
  34. package/dist/index.d.ts +9 -1
  35. package/dist/index.d.ts.map +1 -1
  36. package/dist/index.js +5 -1
  37. package/dist/index.js.map +1 -1
  38. package/dist/loop.d.ts +8 -0
  39. package/dist/loop.d.ts.map +1 -1
  40. package/dist/loop.js +22 -1
  41. package/dist/loop.js.map +1 -1
  42. package/dist/model-pricing.js +1 -1
  43. package/dist/model-pricing.js.map +1 -1
  44. package/dist/model.d.ts +20 -2
  45. package/dist/model.d.ts.map +1 -1
  46. package/dist/model.js +88 -9
  47. package/dist/model.js.map +1 -1
  48. package/dist/operational-metrics.d.ts.map +1 -1
  49. package/dist/operational-metrics.js +3 -1
  50. package/dist/operational-metrics.js.map +1 -1
  51. package/dist/otel-observer.d.ts.map +1 -1
  52. package/dist/otel-observer.js +32 -10
  53. package/dist/otel-observer.js.map +1 -1
  54. package/dist/persistent-agent.d.ts +1 -1
  55. package/dist/persistent-agent.d.ts.map +1 -1
  56. package/dist/persistent-agent.js.map +1 -1
  57. package/dist/pi-loop-runtime.d.ts.map +1 -1
  58. package/dist/pi-loop-runtime.js +152 -8
  59. package/dist/pi-loop-runtime.js.map +1 -1
  60. package/dist/policied-sandbox.d.ts.map +1 -1
  61. package/dist/policied-sandbox.js +16 -3
  62. package/dist/policied-sandbox.js.map +1 -1
  63. package/dist/proposal-tool.d.ts +260 -0
  64. package/dist/proposal-tool.d.ts.map +1 -0
  65. package/dist/proposal-tool.js +562 -0
  66. package/dist/proposal-tool.js.map +1 -0
  67. package/dist/session.d.ts +55 -0
  68. package/dist/session.d.ts.map +1 -1
  69. package/dist/session.js +528 -181
  70. package/dist/session.js.map +1 -1
  71. package/dist/stop-reason-guard.d.ts +89 -0
  72. package/dist/stop-reason-guard.d.ts.map +1 -0
  73. package/dist/stop-reason-guard.js +261 -0
  74. package/dist/stop-reason-guard.js.map +1 -0
  75. package/dist/strict.d.ts +8 -1
  76. package/dist/strict.d.ts.map +1 -1
  77. package/dist/strict.js +4 -1
  78. package/dist/strict.js.map +1 -1
  79. package/dist/tools.d.ts +2 -0
  80. package/dist/tools.d.ts.map +1 -1
  81. package/dist/tools.js +10 -2
  82. package/dist/tools.js.map +1 -1
  83. package/dist/trace-content.d.ts +1 -1
  84. package/dist/trace-content.d.ts.map +1 -1
  85. package/dist/trace-content.js +2 -2
  86. package/dist/trace-content.js.map +1 -1
  87. package/dist/types.d.ts +23 -1
  88. package/dist/types.d.ts.map +1 -1
  89. package/dist/types.js.map +1 -1
  90. package/dist/voice-pipeline.d.ts +70 -3
  91. package/dist/voice-pipeline.d.ts.map +1 -1
  92. package/dist/voice-pipeline.js +386 -44
  93. package/dist/voice-pipeline.js.map +1 -1
  94. package/dist/voice-sentences.d.ts +43 -0
  95. package/dist/voice-sentences.d.ts.map +1 -0
  96. package/dist/voice-sentences.js +99 -0
  97. package/dist/voice-sentences.js.map +1 -0
  98. package/dist/voice.d.ts +9 -0
  99. package/dist/voice.d.ts.map +1 -1
  100. package/dist/voice.js +6 -0
  101. package/dist/voice.js.map +1 -1
  102. package/package.json +30 -13
package/dist/session.js CHANGED
@@ -1,3 +1,4 @@
1
+ import { AsyncLocalStorage } from "node:async_hooks";
1
2
  import { createHash, randomUUID } from "node:crypto";
2
3
  import path from "node:path";
3
4
  import { abandonToolOnAbort } from "./abort.js";
@@ -26,9 +27,11 @@ import { formatPackagedSkillResourceList, readPackagedSkillFile } from "./skills
26
27
  import { defaultSessionStore } from "./store.js";
27
28
  import { currentSubmissionContext } from "./submission-context.js";
28
29
  import { executeTool } from "./tool-execution.js";
30
+ import { assertProposalToolConfiguration, classifyTools, createProposalCallTracker, isProposalTool, proposalApprovalRuleReason, proposalConfigurationError, proposalTranscriptRecord, unknownResult, } from "./proposal-tool.js";
29
31
  import { createActivateSkillTool, createBuiltinTools, createCommandTools, hasScopedCommandRenderer, renderScopedCommand, shellQuote, unwrapHookToolRunResult, } from "./tools.js";
30
32
  import { MAX_TASK_DEPTH } from "./types.js";
31
33
  let nextTaskId = 0;
34
+ const promptEventScope = new AsyncLocalStorage();
32
35
  const CROCKFORD_ALPHABET = "0123456789ABCDEFGHJKMNPQRSTVWXYZ";
33
36
  const AFFINITY_KEY_REGEX = /^aff_[0-7][0-9A-HJKMNP-TV-Z]{25}$/;
34
37
  function isResolvedDynamicModelProvider(value) {
@@ -129,6 +132,12 @@ export class StubFabricSession {
129
132
  options;
130
133
  store;
131
134
  eventSubscribers = new Set();
135
+ /**
136
+ * The proposal tools of each tool map `resolveTools()` returned, decided
137
+ * once at resolution (#274). Dispatch and recovery read only this: a tool
138
+ * not found here runs as an ordinary tool, whatever its `execute` is later.
139
+ */
140
+ resolvedProposals = new WeakMap();
132
141
  durableRuntime;
133
142
  mounts = [];
134
143
  /** Set when this session has registered its sandbox in the in-process ref registry. */
@@ -148,6 +157,11 @@ export class StubFabricSession {
148
157
  this.id = id;
149
158
  this.options = options;
150
159
  this.store = options.store ?? defaultSessionStore;
160
+ // Session start: a proposal tool the policy would gate, that has no
161
+ // authority, or that shares a name is refused before anything runs. Each
162
+ // prompt and dynamic render checks again with its effective policy.
163
+ if (options.tools?.some(isProposalTool))
164
+ this.resolveTools([], [], options.policy);
151
165
  this.sandboxPromise = this.createSandbox();
152
166
  this.fs = createFabricFs(() => this.sandboxPromise);
153
167
  this.costBudget = new CostBudgetTracker(options.costLimit);
@@ -197,6 +211,17 @@ export class StubFabricSession {
197
211
  idPrefix: submissionId ? `att_${submissionId}` : `att_prompt_${randomUUID()}`,
198
212
  });
199
213
  }
214
+ /**
215
+ * A durable runtime receives neither this session's or the call's tools nor
216
+ * its proposal authority, so a proposal tool would silently not be offered.
217
+ * Refused here, called immediately before each delegation (prompt, task).
218
+ */
219
+ refuseProposalToolsOnDurableRuntime(callTools) {
220
+ const delegated = [...(this.options.tools ?? []), ...(callTools ?? [])].find((tool) => isProposalTool(tool));
221
+ if (delegated) {
222
+ throw proposalConfigurationError(delegated.name, "cannot run on a durable session runtime: the runtime does not receive this session's tools or its proposal authority. Run proposal tools in an inline session.");
223
+ }
224
+ }
200
225
  getDurableRuntime() {
201
226
  if (this.durableRuntime)
202
227
  return this.durableRuntime;
@@ -233,6 +258,33 @@ export class StubFabricSession {
233
258
  });
234
259
  }
235
260
  async prompt(text, promptOptions = {}) {
261
+ return promptEventScope.run({ session: this, id: randomUUID() }, () => this.runPrompt(text, promptOptions));
262
+ }
263
+ async runPrompt(text, promptOptions) {
264
+ const metadata = promptOptions.metadata === undefined ? {} : { metadata: promptOptions.metadata };
265
+ const promptData = { text, ...metadata };
266
+ let promptOpen = false;
267
+ const startPrompt = async (role) => {
268
+ promptOpen = true;
269
+ await this.emit("prompt_start", { ...promptData, ...(role ? { role } : {}) });
270
+ };
271
+ const endPrompt = async (result, data) => {
272
+ promptOpen = false;
273
+ await this.emit("prompt_end", {
274
+ ...data,
275
+ ...promptData,
276
+ result: result,
277
+ });
278
+ };
279
+ const failPrompt = async (error) => {
280
+ if (!promptOpen)
281
+ return;
282
+ // Preserve the original prompt failure if an event subscriber also fails.
283
+ await this.emit("prompt_error", {
284
+ ...metadata,
285
+ error: isAbortError(error) ? "Prompt cancelled." : "Prompt failed.",
286
+ }).catch(() => undefined);
287
+ };
236
288
  const ambientSignal = promptOptions.signal === undefined ? currentSubmissionContext()?.signal : undefined;
237
289
  const options = ambientSignal
238
290
  ? { ...promptOptions, signal: ambientSignal }
@@ -277,22 +329,36 @@ export class StubFabricSession {
277
329
  publicMessage: "Inline attachments are not supported by the configured durable runtime.",
278
330
  });
279
331
  }
332
+ this.refuseProposalToolsOnDurableRuntime(options.tools);
280
333
  // Delegate to the durable runtime; the runtime is responsible for
281
334
  // recording entries / events on its own side. We still emit a single
282
- // local prompt_start/end pair so local subscribers see activity.
283
- await this.emit("prompt_start", { text });
335
+ // local prompt lifecycle so local subscribers see activity.
284
336
  try {
285
- const forwardedPolicy = this.durablePolicy(options.policy);
286
- const result = await durable.prompt({
287
- text,
288
- options: forwardedPolicy !== undefined ? { ...options, policy: forwardedPolicy } : options,
289
- ...(this.options.dynamic ? { dynamic: this.options.dynamic.executionDescriptor() } : {}),
290
- });
291
- await this.emit("prompt_end", { text });
292
- return result;
337
+ await startPrompt();
338
+ try {
339
+ // Checked again here: a prompt_start subscriber ran since the first check.
340
+ this.refuseProposalToolsOnDurableRuntime(options.tools);
341
+ const forwardedPolicy = this.durablePolicy(options.policy);
342
+ const result = await durable.prompt({
343
+ text,
344
+ options: this.durablePromptOptions(options, forwardedPolicy),
345
+ ...(this.options.dynamic
346
+ ? { dynamic: this.options.dynamic.executionDescriptor() }
347
+ : {}),
348
+ });
349
+ await endPrompt(result);
350
+ return result;
351
+ }
352
+ catch (error) {
353
+ await this.emit("error", {
354
+ error: error instanceof Error ? error.message : String(error),
355
+ ...(isAbortError(error) ? { cancelled: true } : {}),
356
+ });
357
+ throw error;
358
+ }
293
359
  }
294
360
  catch (error) {
295
- await this.emit("error", { error: error instanceof Error ? error.message : String(error) });
361
+ await failPrompt(error);
296
362
  throw error;
297
363
  }
298
364
  }
@@ -304,7 +370,7 @@ export class StubFabricSession {
304
370
  const lifecycleSignal = options.signal ?? new AbortController().signal;
305
371
  try {
306
372
  let sandbox = createScopedSandboxEnv(await this.sandbox, options.cwd);
307
- let tools = this.resolveTools(options.tools, options.commands);
373
+ let tools = this.resolveTools(options.tools, options.commands, options.policy ?? this.options.policy);
308
374
  let joinedRenderReady = false;
309
375
  const currentTurnConfiguration = () => ({
310
376
  ...(typeof this.options.model === "string" ? { model: this.options.model } : {}),
@@ -393,7 +459,7 @@ export class StubFabricSession {
393
459
  }
394
460
  role = this.resolveRole(this.options.role);
395
461
  }
396
- tools = this.resolveTools(options.tools, options.commands);
462
+ tools = this.resolveTools(options.tools, options.commands, options.policy ?? this.options.policy);
397
463
  if (!config.dynamic) {
398
464
  throw new Error("[fabric-harness] A dynamic-agent refresh did not return its runtime.");
399
465
  }
@@ -433,7 +499,7 @@ export class StubFabricSession {
433
499
  // narration was appended between them during worker initialization.
434
500
  const responseStartLeafId = firstRecoveredCall?.parentId ?? responseStartData.leafId;
435
501
  await this.repairDanglingToolCalls(tools, sandbox, options.signal, options.policy);
436
- await this.emit("prompt_start", { text, ...(role ? { role: role.name } : {}) });
502
+ await startPrompt(role?.name);
437
503
  // Submission-correlated prompts are idempotent by submission id: a
438
504
  // recovered attempt whose input entry already landed (crash after the
439
505
  // canonical write) resumes from history instead of double-applying.
@@ -524,171 +590,186 @@ export class StubFabricSession {
524
590
  if (options.signal?.aborted)
525
591
  throw promptAbortError(options.signal);
526
592
  await this.recordEntry("result", { result: results });
527
- await this.emit("prompt_end", { text, result: results });
528
593
  const value = await validateResult(results, options.result, options.resultExtraction);
529
594
  const finalized = await this.finalizeDynamicResult(value, responseStartLeafId, undefined, submissionCorrelation);
530
595
  if (finalized.continued) {
531
596
  throw new Error("useAgentFinish().append() cannot continue a prompt that uses PromptOptions.toolCalls; run the normal model loop instead.");
532
597
  }
598
+ await endPrompt(finalized.value);
533
599
  return finalized.value;
534
600
  }
535
601
  // Use tool-based result extraction when a validator is provided and the caller
536
602
  // has not explicitly opted into delimiter-based extraction.
537
603
  const useResultTools = options.result !== undefined && options.resultExtraction === undefined;
538
604
  const runtime = options.loopRuntime ?? this.options.loopRuntime ?? defaultLoopRuntime;
539
- const runRuntime = () => runtime.runPrompt({
540
- sessionId: this.id,
541
- ...(streamRecovery ? { streamRecovery: "replace" } : {}),
542
- ...(sessionData.affinityKey !== undefined
543
- ? { affinityKey: sessionData.affinityKey }
544
- : {}),
545
- text,
546
- ...(options.submission?.message !== undefined
547
- ? { delivery: options.submission.message }
548
- : {}),
549
- messages,
550
- tools,
551
- sandbox,
552
- ...(typeof (options.model ?? this.options.model ?? this.agent.model) === "string"
553
- ? { model: (options.model ?? this.options.model ?? this.agent.model) }
554
- : {}),
555
- ...((options.thinkingLevel ?? this.options.thinkingLevel ?? this.agent.thinkingLevel) !==
556
- undefined
557
- ? {
558
- thinkingLevel: options.thinkingLevel ?? this.options.thinkingLevel ?? this.agent.thinkingLevel,
559
- }
560
- : {}),
561
- ...((options.modelProvider ?? this.options.modelProvider) !== undefined
562
- ? { modelProvider: options.modelProvider ?? this.options.modelProvider }
563
- : {}),
564
- ...(options.maxIterations !== undefined ? { maxIterations: options.maxIterations } : {}),
565
- ...(options.modelTimeoutMs !== undefined
566
- ? { modelTimeoutMs: options.modelTimeoutMs }
567
- : {}),
568
- ...(options.modelRetries !== undefined ? { modelRetries: options.modelRetries } : {}),
569
- ...(options.modelRetryDelayMs !== undefined
570
- ? { modelRetryDelayMs: options.modelRetryDelayMs }
571
- : {}),
572
- ...(options.signal !== undefined ? { signal: options.signal } : {}),
573
- ...(options.policy !== undefined ? { policy: options.policy } : {}),
574
- ...((options.approvalTimeoutMs ?? this.options.approvalTimeoutMs) !== undefined
575
- ? { approvalTimeoutMs: options.approvalTimeoutMs ?? this.options.approvalTimeoutMs }
576
- : {}),
577
- ...(this.costBudget.enabled()
578
- ? {
579
- costBudget: this.costBudget,
580
- requestCostLimitApproval: (ctx) => this.requestCostLimitApproval(ctx, options.approvalTimeoutMs ?? this.options.approvalTimeoutMs, options.onApproval),
581
- }
582
- : {}),
583
- ...(useResultTools ? { resultValidator: options.result } : {}),
584
- agentId: this.agent.id,
585
- ...(this.options.tenantId !== undefined ? { tenantId: this.options.tenantId } : {}),
586
- ...(options.submission?.takeJoinedInputs
587
- ? {
588
- takeSteeringMessages: async () => {
589
- const inputs = await options.submission?.takeJoinedInputs?.();
590
- if (!inputs?.length)
591
- return [];
592
- const messages = [];
593
- for (const input of inputs) {
594
- if (input.message && renderDeliveredMessage(input.message) !== input.text) {
595
- throw new FabricError({
596
- code: "INVALID_CONFIG",
597
- message: "A joined durable submission message does not match its rendered prompt text. " +
598
- "Refusing to persist and execute contradictory inputs.",
599
- publicMessage: "A joined durable submission input is inconsistent.",
600
- });
601
- }
602
- const current = await this.history();
603
- const exists = (current.entries ?? []).some((entry) => (entry.type === "user_prompt" || entry.type === "signal") &&
604
- entry.data?.submissionId === input.submissionId);
605
- if (!exists) {
606
- if (input.message?.kind === "signal") {
607
- await this.recordEntry("signal", {
608
- ...deliveredSignalToEntryData(input.message),
609
- submissionId: input.submissionId,
605
+ let runtimeEndData;
606
+ const runRuntime = () => {
607
+ runtimeEndData = undefined;
608
+ return runtime.runPrompt({
609
+ sessionId: this.id,
610
+ ...(streamRecovery ? { streamRecovery: "replace" } : {}),
611
+ ...(sessionData.affinityKey !== undefined
612
+ ? { affinityKey: sessionData.affinityKey }
613
+ : {}),
614
+ text,
615
+ ...(options.submission?.message !== undefined
616
+ ? { delivery: options.submission.message }
617
+ : {}),
618
+ messages,
619
+ tools,
620
+ sandbox,
621
+ ...(typeof (options.model ?? this.options.model ?? this.agent.model) === "string"
622
+ ? { model: (options.model ?? this.options.model ?? this.agent.model) }
623
+ : {}),
624
+ ...((options.thinkingLevel ?? this.options.thinkingLevel ?? this.agent.thinkingLevel) !==
625
+ undefined
626
+ ? {
627
+ thinkingLevel: options.thinkingLevel ?? this.options.thinkingLevel ?? this.agent.thinkingLevel,
628
+ }
629
+ : {}),
630
+ ...((options.modelProvider ?? this.options.modelProvider) !== undefined
631
+ ? { modelProvider: options.modelProvider ?? this.options.modelProvider }
632
+ : {}),
633
+ ...(options.maxIterations !== undefined ? { maxIterations: options.maxIterations } : {}),
634
+ ...(options.modelTimeoutMs !== undefined
635
+ ? { modelTimeoutMs: options.modelTimeoutMs }
636
+ : {}),
637
+ ...(options.modelRetries !== undefined ? { modelRetries: options.modelRetries } : {}),
638
+ ...(options.modelRetryDelayMs !== undefined
639
+ ? { modelRetryDelayMs: options.modelRetryDelayMs }
640
+ : {}),
641
+ ...((options.stopReasonGuard ?? this.options.stopReasonGuard) !== undefined
642
+ ? { stopReasonGuard: options.stopReasonGuard ?? this.options.stopReasonGuard }
643
+ : {}),
644
+ ...(options.signal !== undefined ? { signal: options.signal } : {}),
645
+ ...(options.policy !== undefined ? { policy: options.policy } : {}),
646
+ ...((options.approvalTimeoutMs ?? this.options.approvalTimeoutMs) !== undefined
647
+ ? { approvalTimeoutMs: options.approvalTimeoutMs ?? this.options.approvalTimeoutMs }
648
+ : {}),
649
+ ...(this.costBudget.enabled()
650
+ ? {
651
+ costBudget: this.costBudget,
652
+ requestCostLimitApproval: (ctx) => this.requestCostLimitApproval(ctx, options.approvalTimeoutMs ?? this.options.approvalTimeoutMs, options.onApproval),
653
+ }
654
+ : {}),
655
+ ...(useResultTools ? { resultValidator: options.result } : {}),
656
+ agentId: this.agent.id,
657
+ ...(this.options.tenantId !== undefined ? { tenantId: this.options.tenantId } : {}),
658
+ ...(options.submission?.takeJoinedInputs
659
+ ? {
660
+ takeSteeringMessages: async () => {
661
+ const inputs = await options.submission?.takeJoinedInputs?.();
662
+ if (!inputs?.length)
663
+ return [];
664
+ const messages = [];
665
+ for (const input of inputs) {
666
+ if (input.message && renderDeliveredMessage(input.message) !== input.text) {
667
+ throw new FabricError({
668
+ code: "INVALID_CONFIG",
669
+ message: "A joined durable submission message does not match its rendered prompt text. " +
670
+ "Refusing to persist and execute contradictory inputs.",
671
+ publicMessage: "A joined durable submission input is inconsistent.",
610
672
  });
611
- messages.push({ role: "user", content: input.text });
612
673
  }
613
- else {
614
- const joinedAttachments = await this.prepareInputAttachments([], input.message, input.submissionId);
615
- await this.recordEntry("user_prompt", {
616
- text: input.text,
617
- submissionId: input.submissionId,
618
- ...(joinedAttachments.records.length > 0
619
- ? { attachments: joinedAttachments.records }
620
- : {}),
621
- });
622
- const [joinedMessage] = await hydrateModelMessageAttachments([
623
- {
624
- role: "user",
625
- content: input.text,
674
+ const current = await this.history();
675
+ const exists = (current.entries ?? []).some((entry) => (entry.type === "user_prompt" || entry.type === "signal") &&
676
+ entry.data?.submissionId === input.submissionId);
677
+ if (!exists) {
678
+ if (input.message?.kind === "signal") {
679
+ await this.recordEntry("signal", {
680
+ ...deliveredSignalToEntryData(input.message),
681
+ submissionId: input.submissionId,
682
+ });
683
+ messages.push({ role: "user", content: input.text });
684
+ }
685
+ else {
686
+ const joinedAttachments = await this.prepareInputAttachments([], input.message, input.submissionId);
687
+ await this.recordEntry("user_prompt", {
688
+ text: input.text,
689
+ submissionId: input.submissionId,
626
690
  ...(joinedAttachments.records.length > 0
627
- ? {
628
- attachments: recordsToModelAttachments(joinedAttachments.records),
629
- }
691
+ ? { attachments: joinedAttachments.records }
630
692
  : {}),
631
- },
632
- ], {
633
- store: this.attachmentStore(),
634
- scope: this.id,
635
- inflight: joinedAttachments.inflight,
636
- // Charged against the running request's allowance,
637
- // not a fresh 50 MiB per joined input.
638
- budget: hydrationBudget,
693
+ });
694
+ const [joinedMessage] = await hydrateModelMessageAttachments([
695
+ {
696
+ role: "user",
697
+ content: input.text,
698
+ ...(joinedAttachments.records.length > 0
699
+ ? {
700
+ attachments: recordsToModelAttachments(joinedAttachments.records),
701
+ }
702
+ : {}),
703
+ },
704
+ ], {
705
+ store: this.attachmentStore(),
706
+ scope: this.id,
707
+ inflight: joinedAttachments.inflight,
708
+ // Charged against the running request's allowance,
709
+ // not a fresh 50 MiB per joined input.
710
+ budget: hydrationBudget,
711
+ });
712
+ if (joinedMessage)
713
+ messages.push(joinedMessage);
714
+ }
715
+ }
716
+ if (input.message && dynamic) {
717
+ await refreshDynamic({
718
+ delivery: input.message,
639
719
  });
640
- if (joinedMessage)
641
- messages.push(joinedMessage);
720
+ const lifecycleSignals = await dynamic?.runAgentStart({
721
+ ...(options.signal ? { signal: options.signal } : {}),
722
+ sandbox,
723
+ submissionId: input.submissionId,
724
+ });
725
+ for (const signal of lifecycleSignals ?? []) {
726
+ messages.push({ role: "user", content: renderDeliveredMessage(signal) });
727
+ }
728
+ joinedRenderReady = true;
642
729
  }
730
+ await input.onInputApplied();
643
731
  }
644
- if (input.message && dynamic) {
645
- await refreshDynamic({
646
- delivery: input.message,
647
- });
648
- const lifecycleSignals = await dynamic?.runAgentStart({
649
- ...(options.signal ? { signal: options.signal } : {}),
650
- sandbox,
651
- submissionId: input.submissionId,
652
- });
653
- for (const signal of lifecycleSignals ?? []) {
654
- messages.push({ role: "user", content: renderDeliveredMessage(signal) });
655
- }
656
- joinedRenderReady = true;
732
+ return messages;
733
+ },
734
+ }
735
+ : {}),
736
+ ...(dynamic
737
+ ? {
738
+ refreshTurn: async () => {
739
+ if (joinedRenderReady) {
740
+ joinedRenderReady = false;
741
+ return currentTurnConfiguration();
657
742
  }
658
- await input.onInputApplied();
659
- }
660
- return messages;
661
- },
662
- }
663
- : {}),
664
- ...(dynamic
665
- ? {
666
- refreshTurn: async () => {
667
- if (joinedRenderReady) {
668
- joinedRenderReady = false;
669
- return currentTurnConfiguration();
670
- }
671
- return refreshDynamic();
672
- },
673
- }
674
- : {}),
675
- executeToolCalls: (calls, policy, approvalTimeoutMs, attribution) => this.executeToolCalls(calls, tools, sandbox,
676
- // The prompt's policy wins (call over session over agent). A loop may pass none for
677
- // model-issued calls, and a dynamic agent's turn refresh passes its rendered agent policy.
678
- options.policy ?? policy, approvalTimeoutMs, options.onApproval, attribution, options.signal, undefined, streamRecovery ? (data) => streamRecovery.record("tool_call", data) : undefined),
679
- recordToolAdditions: async (toolCallId, names) => {
680
- if (names.length === 0)
681
- return;
682
- await this.recordEntry("signal", {
683
- signalType: "resources.tool_additions",
684
- content: "Conditional tools became available after this tool result.",
685
- toolCallId,
686
- names,
687
- });
688
- },
689
- recordEntry: (type, data) => streamRecovery ? streamRecovery.record(type, data) : this.recordEntry(type, data),
690
- emit: (type, data) => streamRecovery ? streamRecovery.emit(type, data) : this.emit(type, data),
691
- });
743
+ return refreshDynamic();
744
+ },
745
+ }
746
+ : {}),
747
+ executeToolCalls: (calls, policy, approvalTimeoutMs, attribution) => this.executeToolCalls(calls, tools, sandbox,
748
+ // The prompt's policy wins (call over session over agent). A loop may pass none for
749
+ // model-issued calls, and a dynamic agent's turn refresh passes its rendered agent policy.
750
+ options.policy ?? policy, approvalTimeoutMs, options.onApproval, attribution, options.signal, undefined, streamRecovery ? (data) => streamRecovery.record("tool_call", data) : undefined),
751
+ recordToolAdditions: async (toolCallId, names) => {
752
+ if (names.length === 0)
753
+ return;
754
+ await this.recordEntry("signal", {
755
+ signalType: "resources.tool_additions",
756
+ content: "Conditional tools became available after this tool result.",
757
+ toolCallId,
758
+ names,
759
+ });
760
+ },
761
+ recordEntry: (type, data) => streamRecovery ? streamRecovery.record(type, data) : this.recordEntry(type, data),
762
+ // A runtime can finish more than once during validation retries or
763
+ // finish-hook continuations. The session emits the terminal event.
764
+ emit: async (type, data) => {
765
+ if (type === "prompt_end") {
766
+ runtimeEndData = data;
767
+ return;
768
+ }
769
+ await (streamRecovery ? streamRecovery.emit(type, data) : this.emit(type, data));
770
+ },
771
+ });
772
+ };
692
773
  let result;
693
774
  try {
694
775
  result = await runRuntime();
@@ -771,6 +852,10 @@ export class StubFabricSession {
771
852
  }
772
853
  const finalized = await this.finalizeDynamicResult(value, responseStartLeafId, result.usage, submissionCorrelation);
773
854
  if (!finalized.continued) {
855
+ await endPrompt(finalized.value, {
856
+ ...runtimeEndData,
857
+ ...(result.terminatedByTool ? { terminatedByTool: true } : {}),
858
+ });
774
859
  if (result.terminatedByTool)
775
860
  await this.compactAfterTermination(role, options);
776
861
  return finalized.value;
@@ -785,6 +870,10 @@ export class StubFabricSession {
785
870
  result = await runRuntime();
786
871
  }
787
872
  }
873
+ catch (error) {
874
+ await failPrompt(error);
875
+ throw error;
876
+ }
788
877
  finally {
789
878
  if (promptSubscriber)
790
879
  this.eventSubscribers.delete(promptSubscriber);
@@ -874,14 +963,15 @@ export class StubFabricSession {
874
963
  publicMessage: "Inline attachments are not supported by the configured durable runtime.",
875
964
  });
876
965
  }
966
+ this.refuseProposalToolsOnDurableRuntime(options.tools);
877
967
  const taskId = options.id ?? `${this.id}:task-${++nextTaskId}`;
878
968
  await this.emit("task_start", { taskId, depth: 1, parentSessionId: this.id });
879
969
  try {
970
+ // Checked again here: a task_start subscriber ran since the first check.
971
+ this.refuseProposalToolsOnDurableRuntime(options.tools);
880
972
  const { id: _id, ...requestedTaskOptions } = options;
881
973
  const forwardedPolicy = this.durablePolicy(options.policy);
882
- const taskOptions = forwardedPolicy !== undefined
883
- ? { ...requestedTaskOptions, policy: forwardedPolicy }
884
- : requestedTaskOptions;
974
+ const taskOptions = this.durablePromptOptions(requestedTaskOptions, forwardedPolicy);
885
975
  const result = await durable.task({
886
976
  text,
887
977
  taskId,
@@ -1718,6 +1808,19 @@ export class StubFabricSession {
1718
1808
  * agent's rendered policy is re-rendered by the runtime, so for one only a
1719
1809
  * policy the caller set on the session is forwarded.
1720
1810
  */
1811
+ /**
1812
+ * Prompt options forwarded to a durable runtime, with the policy above and
1813
+ * the resolved `stopReasonGuard` (call over session over agent), so a
1814
+ * setting made on `init()` or `agent.session()` reaches the worker's loop.
1815
+ */
1816
+ durablePromptOptions(options, policy) {
1817
+ const stopReasonGuard = options.stopReasonGuard ?? this.options.stopReasonGuard;
1818
+ return {
1819
+ ...options,
1820
+ ...(policy !== undefined ? { policy } : {}),
1821
+ ...(stopReasonGuard !== undefined ? { stopReasonGuard } : {}),
1822
+ };
1823
+ }
1721
1824
  durablePolicy(callPolicy, reRendered = true) {
1722
1825
  if (callPolicy !== undefined)
1723
1826
  return callPolicy;
@@ -1754,6 +1857,9 @@ export class StubFabricSession {
1754
1857
  const sandbox = this.sandboxUnderPolicy(sessionSandbox, policy);
1755
1858
  for (const requestedCall of calls) {
1756
1859
  const tool = tools.get(requestedCall.tool);
1860
+ // Decided when these tools were resolved, and never derived again from
1861
+ // the definition: a tool not classified then runs as an ordinary tool.
1862
+ const proposal = this.resolvedProposal(tools, requestedCall.tool, tool);
1757
1863
  const canonical = canonicalizeToolCall({
1758
1864
  ...requestedCall,
1759
1865
  tool: tool?.policyAlias ?? requestedCall.tool,
@@ -1782,7 +1888,8 @@ export class StubFabricSession {
1782
1888
  : (renderedCommand ?? this.commandTextForApproval(tool, call.input));
1783
1889
  const executingPrincipal = toolExecutingPrincipal(tool);
1784
1890
  const mountDecision = this.checkMountWriteAccess(call);
1785
- const policyCall = tool?.policyAlias ? { ...call, tool: tool.policyAlias } : call;
1891
+ // Policy judges a proposal tool by its own name; resolution refuses an alias.
1892
+ const policyCall = !proposal && tool?.policyAlias ? { ...call, tool: tool.policyAlias } : call;
1786
1893
  // File paths are judged in every form the sandbox reaches, as its layer
1787
1894
  // judges them, so an approval is asked for here when one is needed there.
1788
1895
  const decision = mountDecision ?? evaluateToolCallPolicyInSandbox(policyCall, policy, sandbox);
@@ -1822,6 +1929,12 @@ export class StubFabricSession {
1822
1929
  continue;
1823
1930
  }
1824
1931
  if (!decision.allowed && decision.approvalRequired) {
1932
+ // Policy wins: a proposal tool matched by an approval rule here (a
1933
+ // call-level policy from a custom loop) is refused, never prompted.
1934
+ if (proposal) {
1935
+ await this.refuseProposalCall(call, toolCallId, proposalApprovalRuleReason(decision.matchedPattern), results);
1936
+ continue;
1937
+ }
1825
1938
  const grant = await this.requestApproval({
1826
1939
  kind: "tool",
1827
1940
  tool: call.tool,
@@ -1863,6 +1976,10 @@ export class StubFabricSession {
1863
1976
  }
1864
1977
  }
1865
1978
  if (!commandDecision.allowed && commandDecision.approvalRequired) {
1979
+ if (proposal) {
1980
+ await this.refuseProposalCall(call, toolCallId, proposalApprovalRuleReason(commandDecision.matchedPattern), results);
1981
+ continue;
1982
+ }
1866
1983
  // The approval names the exact command the tool will run.
1867
1984
  const grant = await this.requestApproval({
1868
1985
  kind: "command",
@@ -1910,11 +2027,16 @@ export class StubFabricSession {
1910
2027
  if (boundCommand !== undefined)
1911
2028
  approvedSandboxCalls.push({ tool: "bash", input: { command: boundCommand } });
1912
2029
  }
1913
- await (recordToolCall ?? ((data) => this.recordEntry("tool_call", data)))({
2030
+ const toolCallEntry = await (recordToolCall ?? ((data) => this.recordEntry("tool_call", data)))({
1914
2031
  tool: call.tool,
1915
2032
  input: call.input,
1916
2033
  inputDigest: approvalInputDigest(call.input),
1917
2034
  policyDigest: approvalInputDigest(policy ?? null),
2035
+ // Harness-set from the resolution-time classification: recovery settles
2036
+ // a trailing dangling call carrying it as unknown and does not run it
2037
+ // again. A call hidden behind a later turn boundary (a signal, say)
2038
+ // is outside the trailing window and is not settled by recovery.
2039
+ ...(proposal ? { proposal: { actionId: proposal.runner.actionId } } : {}),
1918
2040
  ...(executingPrincipal
1919
2041
  ? { executingPrincipal: executingPrincipal }
1920
2042
  : {}),
@@ -1938,6 +2060,18 @@ export class StubFabricSession {
1938
2060
  ...(effectiveInput !== undefined ? { input: effectiveInput } : {}),
1939
2061
  ...(attribution ? { attribution: attribution } : {}),
1940
2062
  });
2063
+ if (proposal) {
2064
+ await this.executeProposalCall({
2065
+ call,
2066
+ proposal,
2067
+ toolCallId,
2068
+ sandbox,
2069
+ results,
2070
+ ...(signal ? { signal } : {}),
2071
+ ...(attribution ? { attribution: attribution } : {}),
2072
+ });
2073
+ continue;
2074
+ }
1941
2075
  if (!tool?.execute) {
1942
2076
  const error = `Tool is not available: ${call.tool}`;
1943
2077
  results.push({
@@ -2284,31 +2418,63 @@ export class StubFabricSession {
2284
2418
  const timeout = typeof record.timeout === "number" ? record.timeout : undefined;
2285
2419
  return { ...record, timeout: clampCommandTimeout(timeout, policy) };
2286
2420
  }
2287
- resolveTools(promptTools = [], promptCommands = []) {
2288
- const tools = new Map();
2421
+ /**
2422
+ * Combine the session's and the prompt's tools. Later definitions replace
2423
+ * earlier ones of the same name. `policy` is the effective policy the tools
2424
+ * will run under: proposal tools are checked against it here. Each tool is
2425
+ * classified here, once, and the proposal tools are kept with the returned
2426
+ * map for dispatch and recovery (#274).
2427
+ */
2428
+ resolveTools(promptTools, promptCommands, policy) {
2429
+ const ordered = [];
2289
2430
  const commandToolOptions = this.options.resolveSecret
2290
2431
  ? { resolveSecret: this.options.resolveSecret }
2291
2432
  : {};
2292
2433
  // Built-ins run on the sandbox each call is handed (`context.sandbox`),
2293
2434
  // which carries that call's effective policy, not one captured here.
2294
- for (const tool of createBuiltinTools(undefined, this.effectivePackagedSkills()))
2295
- tools.set(tool.name, tool);
2296
- for (const tool of createCommandTools(this.options.commands ?? [], commandToolOptions))
2297
- tools.set(tool.name, tool);
2298
- for (const tool of this.options.tools ?? [])
2299
- tools.set(tool.name, tool);
2300
- for (const tool of createCommandTools(promptCommands ?? [], commandToolOptions))
2301
- tools.set(tool.name, tool);
2302
- for (const tool of promptTools)
2303
- tools.set(tool.name, tool);
2435
+ // One push per tool: a spread argument list has an engine limit, and the
2436
+ // base resolved lists of any length.
2437
+ for (const list of [
2438
+ createBuiltinTools(undefined, this.effectivePackagedSkills()),
2439
+ createCommandTools(this.options.commands ?? [], commandToolOptions),
2440
+ this.options.tools ?? [],
2441
+ createCommandTools(promptCommands ?? [], commandToolOptions),
2442
+ promptTools ?? [],
2443
+ ]) {
2444
+ for (const tool of list)
2445
+ ordered.push(tool);
2446
+ }
2304
2447
  const skills = this.options.skills ?? [];
2305
2448
  if (skills.length > 0) {
2306
2449
  const skillNames = skills.map((skill) => skill.name);
2307
- const activateSkillTool = createActivateSkillTool(skillNames, (name) => this.activateSkillForTool(name));
2308
- tools.set(activateSkillTool.name, activateSkillTool);
2450
+ ordered.push(createActivateSkillTool(skillNames, (name) => this.activateSkillForTool(name)));
2309
2451
  }
2452
+ const classified = classifyTools(ordered);
2453
+ const authority = this.options.proposalAuthority;
2454
+ assertProposalToolConfiguration({ tools: classified, policy, authority });
2455
+ const tools = new Map();
2456
+ for (const tool of ordered)
2457
+ tools.set(tool.name, tool);
2458
+ const proposals = new Map();
2459
+ for (const { tool, runner } of classified) {
2460
+ // The configuration check above refused a proposal tool without an
2461
+ // authority or sharing its name, so each one is its name's only tool.
2462
+ if (runner && authority)
2463
+ proposals.set(tool.name, { tool, runner, authority });
2464
+ }
2465
+ if (proposals.size > 0)
2466
+ this.resolvedProposals.set(tools, proposals);
2310
2467
  return tools;
2311
2468
  }
2469
+ /**
2470
+ * The resolution-time classification of `tool`, found in `tools` under
2471
+ * `name`, if it was classified a proposal tool. A definition that replaced
2472
+ * the classified one in the map afterwards is not a proposal tool.
2473
+ */
2474
+ resolvedProposal(tools, name, tool) {
2475
+ const resolved = this.resolvedProposals.get(tools)?.get(name);
2476
+ return resolved !== undefined && resolved.tool === tool ? resolved : undefined;
2477
+ }
2312
2478
  async activateSkillForTool(name) {
2313
2479
  const cached = this.skillCache.get(name);
2314
2480
  if (cached !== undefined)
@@ -2466,12 +2632,23 @@ export class StubFabricSession {
2466
2632
  for (const call of dangling) {
2467
2633
  const toolName = typeof call.data?.tool === "string" ? call.data.tool : undefined;
2468
2634
  const toolCallId = typeof call.data?.toolCallId === "string" ? call.data.toolCallId : undefined;
2635
+ // A proposal call carries the harness's marker on its tool_call entry.
2636
+ // It is settled as unknown, from the marker alone: it is never run
2637
+ // again, the port is not called, and the current tool of that name,
2638
+ // if any, is not consulted.
2639
+ if (call.data?.proposal !== undefined && toolName && toolCallId) {
2640
+ await this.settleRecoveredProposal(call, toolName, toolCallId);
2641
+ continue;
2642
+ }
2469
2643
  const tool = toolName ? tools.get(toolName) : undefined;
2470
2644
  if (call.data?.durable !== true ||
2471
2645
  !tool?.durable ||
2472
2646
  !tool.execute ||
2473
2647
  !toolCallId ||
2474
- !toolName) {
2648
+ !toolName ||
2649
+ // An unmarked call never runs through a tool that is now a proposal
2650
+ // tool; it is settled below like any call that cannot be re-entered.
2651
+ this.resolvedProposal(tools, toolName, tool) !== undefined) {
2475
2652
  continue;
2476
2653
  }
2477
2654
  await this.emit("tool_start", {
@@ -2860,6 +3037,145 @@ export class StubFabricSession {
2860
3037
  }
2861
3038
  return { value, continued: appended.length > 0 };
2862
3039
  }
3040
+ /**
3041
+ * Run one proposal call through the SDK-owned runner kept with the resolved
3042
+ * tool, and settle it once. On the normal path this code writes no entry of
3043
+ * its own between the call's tool_call entry and its tool_result. A failure
3044
+ * after the port was called settles as a non-error `unknown` result; a
3045
+ * failure before it is an ordinary error. This path attempts the result
3046
+ * write once, unconditionally, as an ordinary tool does: if it fails, the
3047
+ * error propagates, and a later prompt that finds the call trailing and
3048
+ * dangling settles it as unknown. If a second prompt starts while the
3049
+ * proposal is still in flight, that prompt can settle the call as unknown
3050
+ * first and this path then appends the real result, so the call ends with
3051
+ * two results; the port is still called at most once. Known and tracked in
3052
+ * https://github.com/Fabric-Pro/fabric-harness/issues/335.
3053
+ */
3054
+ async executeProposalCall(input) {
3055
+ const { call, proposal, toolCallId, results, attribution } = input;
3056
+ const tracker = createProposalCallTracker({
3057
+ sessionId: this.id,
3058
+ ...(this.options.tenantId !== undefined ? { tenantId: this.options.tenantId } : {}),
3059
+ ...(this.options.actor !== undefined ? { actor: this.options.actor } : {}),
3060
+ authority: proposal.authority,
3061
+ });
3062
+ const startedAt = performance.now();
3063
+ let result;
3064
+ let failure;
3065
+ try {
3066
+ // No progress logger: it writes transcript entries of its own, which
3067
+ // would land between this call's tool_call and its tool_result.
3068
+ await executeTool(proposalDispatchTool(proposal, tracker.binding), call.input, {
3069
+ sandbox: input.sandbox,
3070
+ toolCallId,
3071
+ ...(input.signal ? { signal: input.signal } : {}),
3072
+ });
3073
+ result = tracker.outcome()?.result;
3074
+ }
3075
+ catch (error) {
3076
+ failure = error;
3077
+ }
3078
+ const durationMs = Math.max(0, Math.round(performance.now() - startedAt));
3079
+ // An abort before submission reaches here from the shared abort helper,
3080
+ // which copies the abort reason's text into an AbortError. That text is
3081
+ // not this tool's to publish: replace it with a fixed message. Errors
3082
+ // proposal-tool.ts itself throws are not AbortErrors and keep their text.
3083
+ // Matched by name: the looser isAbortError() also matches message text, and
3084
+ // a validation error that mentions "cancelled" must keep its message.
3085
+ if (failure instanceof Error &&
3086
+ failure.name === "AbortError" &&
3087
+ tracker.submittedKey() === undefined) {
3088
+ failure = new Error(`Proposal tool "${call.tool}" was cancelled before submission; nothing was submitted.`);
3089
+ }
3090
+ // A failure after the port was called (an answer that could not be read,
3091
+ // say) may still have landed: unknown, not an error.
3092
+ const submittedKey = tracker.submittedKey();
3093
+ if (result === undefined && submittedKey !== undefined)
3094
+ result = unknownResult(submittedKey);
3095
+ if (result === undefined) {
3096
+ const message = failure instanceof Error ? failure.message : String(failure);
3097
+ results.push({
3098
+ tool: call.tool,
3099
+ input: call.input,
3100
+ error: message,
3101
+ ...(call.id ? { id: toolCallId } : {}),
3102
+ });
3103
+ await this.recordEntry("error", { tool: call.tool, toolCallId, error: message });
3104
+ await deliverAfterSettlement(call.tool, () => this.emit("tool_end", {
3105
+ tool: call.tool,
3106
+ toolCallId,
3107
+ durationMs,
3108
+ error: message,
3109
+ ...(attribution ? { attribution } : {}),
3110
+ }));
3111
+ return;
3112
+ }
3113
+ const output = result;
3114
+ await this.recordToolResult({
3115
+ tool: call.tool,
3116
+ output,
3117
+ durationMs,
3118
+ toolCallId,
3119
+ // Harness-set: only the SDK-owned runner's outcome produces it.
3120
+ proposal: proposalTranscriptRecord({ actionId: proposal.runner.actionId, result }),
3121
+ ...(attribution ? { attribution } : {}),
3122
+ }, []);
3123
+ results.push({
3124
+ tool: call.tool,
3125
+ input: call.input,
3126
+ output: result,
3127
+ ...(call.id ? { id: toolCallId } : {}),
3128
+ });
3129
+ await deliverAfterSettlement(call.tool, () => this.emit("tool_end", {
3130
+ tool: call.tool,
3131
+ toolCallId,
3132
+ durationMs,
3133
+ output,
3134
+ ...(attribution ? { attribution } : {}),
3135
+ }));
3136
+ }
3137
+ /**
3138
+ * Settle a dangling proposal call after a crash, as a non-error `unknown`
3139
+ * result: the harness cannot tell whether the port was called, and it does
3140
+ * not call it again. Only the tool_call entry's marker is read.
3141
+ */
3142
+ async settleRecoveredProposal(call, toolName, toolCallId) {
3143
+ const marker = call.data?.proposal;
3144
+ const markedAction = typeof marker === "object" && marker !== null && !Array.isArray(marker)
3145
+ ? marker.actionId
3146
+ : undefined;
3147
+ const result = unknownResult();
3148
+ const output = result;
3149
+ await this.recordToolResult({
3150
+ tool: toolName,
3151
+ toolCallId,
3152
+ output,
3153
+ durationMs: 0,
3154
+ proposal: proposalTranscriptRecord({
3155
+ actionId: typeof markedAction === "string" ? markedAction : "",
3156
+ result,
3157
+ }),
3158
+ recovered: true,
3159
+ }, []);
3160
+ await deliverAfterSettlement(toolName, () => this.emit("tool_end", { tool: toolName, recovery: true, toolCallId, durationMs: 0, output }));
3161
+ }
3162
+ /** Refuse a proposal call with its configuration error; nothing is submitted. */
3163
+ async refuseProposalCall(call, toolCallId, reason, results) {
3164
+ const error = proposalConfigurationError(call.tool, reason).message;
3165
+ results.push({
3166
+ tool: call.tool,
3167
+ input: call.input,
3168
+ error,
3169
+ ...(call.id ? { id: call.id } : {}),
3170
+ });
3171
+ await this.recordEntry("error", {
3172
+ tool: call.tool,
3173
+ toolCallId,
3174
+ error,
3175
+ approvalRequired: false,
3176
+ });
3177
+ await this.emit("error", { tool: call.tool, error, approvalRequired: false });
3178
+ }
2863
3179
  createToolStep(toolCallId) {
2864
3180
  const used = new Set();
2865
3181
  return {
@@ -2990,6 +3306,7 @@ export class StubFabricSession {
2990
3306
  await this.ensureData();
2991
3307
  const submission = currentSubmissionContext();
2992
3308
  const agentName = this.agent.name ?? submission?.agent;
3309
+ const prompt = promptEventScope.getStore();
2993
3310
  const event = {
2994
3311
  id: `${this.id}-${Date.now()}-${Math.random().toString(16).slice(2)}`,
2995
3312
  type,
@@ -2999,7 +3316,11 @@ export class StubFabricSession {
2999
3316
  ...(agentName ? { agentName } : {}),
3000
3317
  ...(submission?.submissionId ? { submissionId: submission.submissionId } : {}),
3001
3318
  ...(this.options.tenantId ? { tenantId: this.options.tenantId } : {}),
3002
- ...(data ? { data } : {}),
3319
+ ...(prompt?.session === this
3320
+ ? { data: { ...data, promptRunId: prompt.id } }
3321
+ : data
3322
+ ? { data }
3323
+ : {}),
3003
3324
  };
3004
3325
  await this.store.appendEvent?.(this.id, event);
3005
3326
  await this.options.onEvent?.(event);
@@ -3346,6 +3667,32 @@ function isAbortError(error) {
3346
3667
  function sameFabricActor(a, b) {
3347
3668
  return approvalInputDigest(a ?? null) === approvalInputDigest(b ?? null);
3348
3669
  }
3670
+ /** The tool the session dispatches for a proposal call: the stored SDK-owned runner, never `tool.execute`. */
3671
+ function proposalDispatchTool(proposal, binding) {
3672
+ const timeoutMs = proposal.tool.timeoutMs;
3673
+ return {
3674
+ name: proposal.tool.name,
3675
+ ...(timeoutMs !== undefined ? { timeoutMs } : {}),
3676
+ execute: (input, context) => proposal.runner.run(input, context, binding),
3677
+ };
3678
+ }
3679
+ /**
3680
+ * Run event delivery after a proposal call settled. A failing subscriber is
3681
+ * logged with a fixed label and cannot re-enter settlement.
3682
+ */
3683
+ async function deliverAfterSettlement(tool, deliver) {
3684
+ try {
3685
+ await deliver();
3686
+ }
3687
+ catch {
3688
+ try {
3689
+ getLogger().warn("tool_end delivery failed after a proposal call settled", { tool });
3690
+ }
3691
+ catch {
3692
+ // Diagnostics never decide the outcome.
3693
+ }
3694
+ }
3695
+ }
3349
3696
  function toolStepEntryId(toolCallId, name) {
3350
3697
  return `tool-step:${encodeURIComponent(toolCallId)}:${encodeURIComponent(name)}`;
3351
3698
  }