@fabric-harness/sdk 6.8.0 → 6.9.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 (91) hide show
  1. package/dist/agent.d.ts +5 -4
  2. package/dist/agent.d.ts.map +1 -1
  3. package/dist/agent.js +37 -18
  4. package/dist/agent.js.map +1 -1
  5. package/dist/dynamic-agent.d.ts +24 -19
  6. package/dist/dynamic-agent.d.ts.map +1 -1
  7. package/dist/dynamic-agent.js +402 -239
  8. package/dist/dynamic-agent.js.map +1 -1
  9. package/dist/error.d.ts +1 -1
  10. package/dist/error.d.ts.map +1 -1
  11. package/dist/error.js.map +1 -1
  12. package/dist/events.d.ts +5 -0
  13. package/dist/events.d.ts.map +1 -1
  14. package/dist/events.js.map +1 -1
  15. package/dist/index.d.ts +1 -1
  16. package/dist/index.d.ts.map +1 -1
  17. package/dist/index.js +1 -1
  18. package/dist/index.js.map +1 -1
  19. package/dist/local-process.d.ts +8 -0
  20. package/dist/local-process.d.ts.map +1 -0
  21. package/dist/local-process.js +61 -0
  22. package/dist/local-process.js.map +1 -0
  23. package/dist/loop.d.ts +5 -0
  24. package/dist/loop.d.ts.map +1 -1
  25. package/dist/loop.js +18 -3
  26. package/dist/loop.js.map +1 -1
  27. package/dist/model-id.d.ts +3 -0
  28. package/dist/model-id.d.ts.map +1 -0
  29. package/dist/model-id.js +5 -0
  30. package/dist/model-id.js.map +1 -0
  31. package/dist/model-pricing.d.ts.map +1 -1
  32. package/dist/model-pricing.js +18 -1
  33. package/dist/model-pricing.js.map +1 -1
  34. package/dist/model.d.ts.map +1 -1
  35. package/dist/model.js +39 -14
  36. package/dist/model.js.map +1 -1
  37. package/dist/observability.d.ts +3 -2
  38. package/dist/observability.d.ts.map +1 -1
  39. package/dist/observability.js +42 -17
  40. package/dist/observability.js.map +1 -1
  41. package/dist/otel-observer.d.ts +2 -2
  42. package/dist/otel-observer.d.ts.map +1 -1
  43. package/dist/otel-observer.js +109 -26
  44. package/dist/otel-observer.js.map +1 -1
  45. package/dist/otel.d.ts +4 -4
  46. package/dist/otel.d.ts.map +1 -1
  47. package/dist/otel.js +28 -24
  48. package/dist/otel.js.map +1 -1
  49. package/dist/persistent-agent.d.ts +6 -6
  50. package/dist/persistent-agent.d.ts.map +1 -1
  51. package/dist/persistent-agent.js +79 -47
  52. package/dist/persistent-agent.js.map +1 -1
  53. package/dist/pi-loop-runtime.d.ts +6 -0
  54. package/dist/pi-loop-runtime.d.ts.map +1 -1
  55. package/dist/pi-loop-runtime.js +44 -22
  56. package/dist/pi-loop-runtime.js.map +1 -1
  57. package/dist/policy.d.ts +3 -1
  58. package/dist/policy.d.ts.map +1 -1
  59. package/dist/policy.js +13 -1
  60. package/dist/policy.js.map +1 -1
  61. package/dist/sandbox.d.ts +12 -12
  62. package/dist/sandbox.d.ts.map +1 -1
  63. package/dist/sandbox.js +408 -246
  64. package/dist/sandbox.js.map +1 -1
  65. package/dist/session-stream-recovery.d.ts +21 -0
  66. package/dist/session-stream-recovery.d.ts.map +1 -0
  67. package/dist/session-stream-recovery.js +115 -0
  68. package/dist/session-stream-recovery.js.map +1 -0
  69. package/dist/session.d.ts.map +1 -1
  70. package/dist/session.js +126 -39
  71. package/dist/session.js.map +1 -1
  72. package/dist/skills.d.ts +3 -1
  73. package/dist/skills.d.ts.map +1 -1
  74. package/dist/skills.js +7 -2
  75. package/dist/skills.js.map +1 -1
  76. package/dist/strict.d.ts +1 -1
  77. package/dist/strict.d.ts.map +1 -1
  78. package/dist/strict.js +1 -1
  79. package/dist/strict.js.map +1 -1
  80. package/dist/telemetry.d.ts +1 -1
  81. package/dist/telemetry.d.ts.map +1 -1
  82. package/dist/telemetry.js +30 -26
  83. package/dist/telemetry.js.map +1 -1
  84. package/dist/tools.d.ts +4 -0
  85. package/dist/tools.d.ts.map +1 -1
  86. package/dist/tools.js +6 -3
  87. package/dist/tools.js.map +1 -1
  88. package/dist/types.d.ts +14 -0
  89. package/dist/types.d.ts.map +1 -1
  90. package/dist/types.js.map +1 -1
  91. package/package.json +7 -23
package/dist/session.js CHANGED
@@ -4,14 +4,15 @@ import { inMemorySessionMemory } from "./session-memory.js";
4
4
  import { FabricError } from "./error.js";
5
5
  import { abandonToolOnAbort } from "./abort.js";
6
6
  import { executeTool } from "./tool-execution.js";
7
- import { openGovernedVoice } from "./governed-voice.js";
7
+ import { openGovernedVoice, } from "./governed-voice.js";
8
8
  import { dynamicStateEntriesForTool, unwrapDynamicToolResult } from "./dynamic-agent.js";
9
9
  import { approvalGrantFromJson, approvalGrantFromState, approvalGrantToJson, approvalInputDigest, createApprovalGrant, sameApprovalOperation, } from "./approval.js";
10
10
  import { SessionHistory, buildModelMessagesFromHistory, findTrailingDanglingToolCalls, findTrailingUnfinishedTasks, } from "./history.js";
11
11
  import { getLogger } from "./logger.js";
12
12
  import { defaultLoopRuntime } from "./loop.js";
13
+ import { SessionStreamRecovery } from "./session-stream-recovery.js";
13
14
  import { defaultModelProvider, generateWithRuntime } from "./model.js";
14
- import { clampCommandTimeout, evaluateCommandPolicy, evaluateToolCallPolicy } from "./policy.js";
15
+ import { canonicalizeToolCall, clampCommandTimeout, evaluateCommandPolicy, evaluateToolCallPolicy, } from "./policy.js";
15
16
  import { buildResultRetryPrompt, validateResult } from "./result.js";
16
17
  import { estimateSessionEntryTokens, evaluateContextBudget, isContextOverflowError, } from "./context-budget.js";
17
18
  import { policiedSandboxEnv, runWithSandboxPolicyApproval } from "./policied-sandbox.js";
@@ -209,24 +210,24 @@ export class StubFabricSession {
209
210
  }
210
211
  async voice(options) {
211
212
  if (this.options.sessionRuntime)
212
- throw new Error('Open voice in an activity or server runtime, not a durable workflow');
213
+ throw new Error("Open voice in an activity or server runtime, not a durable workflow");
213
214
  await this.ensureData();
214
215
  const sandbox = await this.sandbox;
215
216
  return openGovernedVoice(options, {
216
217
  sessionId: this.id,
217
- tenantId: this.options.tenantId ?? '',
218
- actorId: this.options.actor?.principal?.id ?? '',
218
+ tenantId: this.options.tenantId ?? "",
219
+ actorId: this.options.actor?.principal?.id ?? "",
219
220
  store: this.store,
220
221
  execute: async (call, tools, signal) => {
221
- const result = await this.executeToolCalls([call], new Map(tools.map(tool => [tool.name, tool])), sandbox, undefined, this.options.approvalTimeoutMs, this.options.onApproval, undefined, signal, async (name, output) => {
222
+ const result = await this.executeToolCalls([call], new Map(tools.map((tool) => [tool.name, tool])), sandbox, undefined, this.options.approvalTimeoutMs, this.options.onApproval, undefined, signal, async (name, output) => {
222
223
  const safe = await options.prepareToolOutput(name, output);
223
224
  const json = JSON.stringify(safe ?? null);
224
225
  if (json.length > 65_536)
225
- throw new Error('Voice tool output too large');
226
+ throw new Error("Voice tool output too large");
226
227
  return JSON.parse(json);
227
228
  });
228
229
  if (!result[0])
229
- throw new Error('Voice tool did not settle');
230
+ throw new Error("Voice tool did not settle");
230
231
  return result[0];
231
232
  },
232
233
  });
@@ -247,6 +248,17 @@ export class StubFabricSession {
247
248
  }
248
249
  const inlineAttachments = validatePromptAttachments(options.images, options.documents);
249
250
  const durable = await this.getDurableRuntime();
251
+ if (this.options.streamRecovery !== undefined &&
252
+ (this.options.streamRecovery !== "replace" ||
253
+ durable ||
254
+ !this.store.appendEntry ||
255
+ (options.loopRuntime ?? this.options.loopRuntime ?? defaultLoopRuntime)
256
+ .supportsStreamRecovery !== true)) {
257
+ throw new FabricError({
258
+ code: "INVALID_CONFIG",
259
+ message: "streamRecovery: 'replace' requires an inline loop with supportsStreamRecovery: true and SessionStore.appendEntry. Delegated durable runtimes own their recovery contract.",
260
+ });
261
+ }
250
262
  if (durable) {
251
263
  if (this.options.dynamic && durable.supportsDynamicAgents !== true) {
252
264
  throw new FabricError({
@@ -288,6 +300,7 @@ export class StubFabricSession {
288
300
  if (promptSubscriber)
289
301
  this.eventSubscribers.add(promptSubscriber);
290
302
  let dynamic = this.options.dynamic;
303
+ const lifecycleSignal = options.signal ?? new AbortController().signal;
291
304
  try {
292
305
  let sandbox = createScopedSandboxEnv(await this.sandbox, options.cwd);
293
306
  let tools = this.resolveTools(sandbox, options.tools, options.commands);
@@ -385,11 +398,23 @@ export class StubFabricSession {
385
398
  }
386
399
  dynamic = config.dynamic;
387
400
  this.options.dynamic = config.dynamic;
401
+ dynamic.bindLifecycleContext({ signal: lifecycleSignal, sandbox });
388
402
  if (prior !== dynamic)
389
403
  await prior.close();
390
404
  return currentTurnConfiguration();
391
405
  };
392
406
  const activeSubmission = currentSubmissionContext();
407
+ const streamRecovery = this.options.streamRecovery === "replace"
408
+ ? new SessionStreamRecovery((type, data) => this.recordEntry(type, data), (type, data) => this.emit(type, data))
409
+ : undefined;
410
+ if (streamRecovery) {
411
+ if (options.signal?.aborted)
412
+ throw promptAbortError(options.signal);
413
+ const path = SessionHistory.fromData(await this.history()).getActivePath();
414
+ await streamRecovery.recover(path.filter((entry) => entry.tenantId === this.options.tenantId &&
415
+ sameFabricActor(entry.actor, this.options.actor)));
416
+ }
417
+ dynamic?.bindLifecycleContext({ signal: lifecycleSignal, sandbox });
393
418
  const submissionCorrelation = activeSubmission
394
419
  ? {
395
420
  submissionId: activeSubmission.submissionId,
@@ -500,7 +525,7 @@ export class StubFabricSession {
500
525
  await this.recordEntry("result", { result: results });
501
526
  await this.emit("prompt_end", { text, result: results });
502
527
  const value = await validateResult(results, options.result, options.resultExtraction);
503
- const finalized = await this.finalizeDynamicResult(value, responseStartLeafId);
528
+ const finalized = await this.finalizeDynamicResult(value, responseStartLeafId, undefined, submissionCorrelation);
504
529
  if (finalized.continued) {
505
530
  throw new Error("useAgentFinish().append() cannot continue a prompt that uses PromptOptions.toolCalls; run the normal model loop instead.");
506
531
  }
@@ -512,6 +537,7 @@ export class StubFabricSession {
512
537
  const runtime = options.loopRuntime ?? this.options.loopRuntime ?? defaultLoopRuntime;
513
538
  const runRuntime = () => runtime.runPrompt({
514
539
  sessionId: this.id,
540
+ ...(streamRecovery ? { streamRecovery: "replace" } : {}),
515
541
  ...(sessionData.affinityKey !== undefined
516
542
  ? { affinityKey: sessionData.affinityKey }
517
543
  : {}),
@@ -597,7 +623,9 @@ export class StubFabricSession {
597
623
  role: "user",
598
624
  content: input.text,
599
625
  ...(joinedAttachments.records.length > 0
600
- ? { attachments: recordsToModelAttachments(joinedAttachments.records) }
626
+ ? {
627
+ attachments: recordsToModelAttachments(joinedAttachments.records),
628
+ }
601
629
  : {}),
602
630
  },
603
631
  ], {
@@ -646,7 +674,7 @@ export class StubFabricSession {
646
674
  executeToolCalls: (calls, policy, approvalTimeoutMs, attribution) => this.executeToolCalls(calls, tools, sandbox,
647
675
  // The prompt's policy wins (call over session over agent). A loop may pass none for
648
676
  // model-issued calls, and a dynamic agent's turn refresh passes its rendered agent policy.
649
- options.policy ?? policy, approvalTimeoutMs, options.onApproval, attribution, options.signal),
677
+ options.policy ?? policy, approvalTimeoutMs, options.onApproval, attribution, options.signal, undefined, streamRecovery ? (data) => streamRecovery.record("tool_call", data) : undefined),
650
678
  recordToolAdditions: async (toolCallId, names) => {
651
679
  if (names.length === 0)
652
680
  return;
@@ -657,8 +685,8 @@ export class StubFabricSession {
657
685
  names,
658
686
  });
659
687
  },
660
- recordEntry: (type, data) => this.recordEntry(type, data),
661
- emit: (type, data) => this.emit(type, data),
688
+ recordEntry: (type, data) => streamRecovery ? streamRecovery.record(type, data) : this.recordEntry(type, data),
689
+ emit: (type, data) => streamRecovery ? streamRecovery.emit(type, data) : this.emit(type, data),
662
690
  });
663
691
  let result;
664
692
  try {
@@ -740,7 +768,7 @@ export class StubFabricSession {
740
768
  }
741
769
  }
742
770
  }
743
- const finalized = await this.finalizeDynamicResult(value, responseStartLeafId, result.usage);
771
+ const finalized = await this.finalizeDynamicResult(value, responseStartLeafId, result.usage, submissionCorrelation);
744
772
  if (!finalized.continued) {
745
773
  if (result.terminatedByTool)
746
774
  await this.compactAfterTermination(role, options);
@@ -1495,9 +1523,11 @@ export class StubFabricSession {
1495
1523
  * `AbortError`.
1496
1524
  */
1497
1525
  async summarizeEntrySet(entries, prefixPrompt, control) {
1498
- if (entries.length === 0)
1499
- return summarizeEntries(entries);
1500
- const deterministic = summarizeEntries(entries);
1526
+ // Recovery output is presentation-only even when history is compacted.
1527
+ const canonicalEntries = entries.filter((entry) => entry.type !== "model_attempt" || entry.data?.kind !== "stream_recovery");
1528
+ if (canonicalEntries.length === 0)
1529
+ return summarizeEntries(canonicalEntries);
1530
+ const deterministic = summarizeEntries(canonicalEntries);
1501
1531
  const provider = this.options.modelProvider ?? defaultModelProvider;
1502
1532
  const timeoutMs = control.timeoutMs !== undefined && control.timeoutMs > 0
1503
1533
  ? control.timeoutMs
@@ -1520,11 +1550,11 @@ export class StubFabricSession {
1520
1550
  const onDeadline = () => stop?.(deadline.signal.reason);
1521
1551
  deadline.signal.addEventListener("abort", onDeadline, { once: true });
1522
1552
  try {
1523
- const serialized = JSON.stringify(entries
1553
+ const serialized = JSON.stringify(canonicalEntries
1524
1554
  .map((entry) => ({
1525
1555
  type: entry.type,
1526
1556
  timestamp: entry.timestamp,
1527
- data: entry.data ?? {},
1557
+ data: Object.fromEntries(Object.entries(entry.data ?? {}).filter(([key]) => key !== "streamRecoveryKeys")),
1528
1558
  }))
1529
1559
  .slice(0, 200));
1530
1560
  const userContent = prefixPrompt ? `${serialized}\n\n${prefixPrompt}` : serialized;
@@ -1668,10 +1698,16 @@ export class StubFabricSession {
1668
1698
  const scoped = createScopedSandboxEnv(env, this.options.cwd);
1669
1699
  return wrapWithPolicy(scoped, this.options.policy, this.options.bypassPolicyEnforcement);
1670
1700
  }
1671
- async executeToolCalls(calls, tools, sandbox, callPolicy, approvalTimeoutMs, approvalHandler, attribution, signal, prepareOutput) {
1701
+ async executeToolCalls(calls, tools, sandbox, callPolicy, approvalTimeoutMs, approvalHandler, attribution, signal, prepareOutput, recordToolCall) {
1672
1702
  const results = [];
1673
1703
  const policy = callPolicy ?? this.options.policy;
1674
- for (const call of calls) {
1704
+ for (const requestedCall of calls) {
1705
+ const tool = tools.get(requestedCall.tool);
1706
+ const canonical = canonicalizeToolCall({
1707
+ ...requestedCall,
1708
+ tool: tool?.policyAlias ?? requestedCall.tool,
1709
+ });
1710
+ const call = { ...requestedCall, input: canonical.input };
1675
1711
  // Providers are allowed to omit a call id. Mint one once at the session
1676
1712
  // boundary so approvals, lineage, history, and tool execution all refer
1677
1713
  // to the same unique logical operation.
@@ -1681,12 +1717,11 @@ export class StubFabricSession {
1681
1717
  // outcomes; calls that never started are settled as interrupted (and
1682
1718
  // never executed, approved, or policy-evaluated) so the transcript
1683
1719
  // keeps every requested call paired with an outcome.
1684
- results.push(await this.recordUnexecutedInterruptedToolCall(call, toolCallId));
1720
+ results.push(await this.recordUnexecutedInterruptedToolCall(call, toolCallId, recordToolCall));
1685
1721
  continue;
1686
1722
  }
1687
1723
  const approvedSandboxCalls = [];
1688
1724
  let approvalGrant;
1689
- const tool = tools.get(call.tool);
1690
1725
  const executingPrincipal = toolExecutingPrincipal(tool);
1691
1726
  const mountDecision = this.checkMountWriteAccess(call);
1692
1727
  const policyCall = tool?.policyAlias ? { ...call, tool: tool.policyAlias } : call;
@@ -1813,7 +1848,7 @@ export class StubFabricSession {
1813
1848
  continue;
1814
1849
  }
1815
1850
  }
1816
- await this.recordEntry("tool_call", {
1851
+ await (recordToolCall ?? ((data) => this.recordEntry("tool_call", data)))({
1817
1852
  tool: call.tool,
1818
1853
  input: call.input,
1819
1854
  inputDigest: approvalInputDigest(call.input),
@@ -1827,8 +1862,13 @@ export class StubFabricSession {
1827
1862
  toolCallId,
1828
1863
  ...(attribution ? { attribution: attribution } : {}),
1829
1864
  });
1865
+ const effectiveInput = tool?.execute && call.tool === "bash"
1866
+ ? this.clampBashToolInput(call.input, policy)
1867
+ : call.input;
1830
1868
  await this.emit("tool_start", {
1831
1869
  tool: call.tool,
1870
+ toolCallId,
1871
+ ...(effectiveInput !== undefined ? { input: effectiveInput } : {}),
1832
1872
  ...(attribution ? { attribution: attribution } : {}),
1833
1873
  });
1834
1874
  if (!tool?.execute) {
@@ -1847,15 +1887,17 @@ export class StubFabricSession {
1847
1887
  });
1848
1888
  await this.emit("tool_end", {
1849
1889
  tool: call.tool,
1890
+ toolCallId,
1850
1891
  error,
1851
1892
  ...(attribution ? { attribution: attribution } : {}),
1852
1893
  });
1853
1894
  continue;
1854
1895
  }
1896
+ const startedAt = performance.now();
1855
1897
  try {
1856
- const input = call.tool === "bash" ? this.clampBashToolInput(call.input, policy) : call.input;
1857
- const startedAt = Date.now();
1898
+ const input = effectiveInput;
1858
1899
  const submission = currentSubmissionContext();
1900
+ const agentName = this.agent.name ?? submission?.agent;
1859
1901
  const execute = () => Promise.resolve(executeTool(tool, input, {
1860
1902
  sandbox,
1861
1903
  toolCallId,
@@ -1864,6 +1906,8 @@ export class StubFabricSession {
1864
1906
  ...(approvalGrant ? { approval: approvalGrant } : {}),
1865
1907
  ...(this.options.actor ? { actor: this.options.actor } : {}),
1866
1908
  ...(this.options.tenantId ? { tenantId: this.options.tenantId } : {}),
1909
+ ...(this.agent.id ? { agentId: this.agent.id } : {}),
1910
+ ...(agentName ? { agentName } : {}),
1867
1911
  policyVersion: approvalInputDigest(policy ?? null),
1868
1912
  ...(policy ? { policy } : {}),
1869
1913
  inputDigest: approvalInputDigest(input),
@@ -1883,12 +1927,12 @@ export class StubFabricSession {
1883
1927
  const dynamicOutput = unwrapDynamicToolResult(rawOutput);
1884
1928
  const hookOutput = unwrapHookToolRunResult(dynamicOutput.output);
1885
1929
  if (prepareOutput && dynamicOutput.stateWrites.length) {
1886
- throw new Error('Voice tools must commit domain state through governed application actions');
1930
+ throw new Error("Voice tools must commit domain state through governed application actions");
1887
1931
  }
1888
1932
  const output = prepareOutput
1889
1933
  ? await abandonToolOnAbort(() => prepareOutput(call.tool, hookOutput.output), signal)
1890
1934
  : hookOutput.output;
1891
- const durationMs = Date.now() - startedAt;
1935
+ const durationMs = Math.max(0, Math.round(performance.now() - startedAt));
1892
1936
  await this.recordToolResult({
1893
1937
  tool: call.tool,
1894
1938
  output: output,
@@ -1906,12 +1950,19 @@ export class StubFabricSession {
1906
1950
  });
1907
1951
  await this.emit("tool_end", {
1908
1952
  tool: call.tool,
1953
+ toolCallId,
1909
1954
  durationMs,
1955
+ ...(output !== undefined ? { output: output } : {}),
1910
1956
  ...(attribution ? { attribution: attribution } : {}),
1911
1957
  });
1912
1958
  }
1913
1959
  catch (error) {
1914
- const message = prepareOutput ? 'Voice tool rejected or failed' : error instanceof Error ? error.message : String(error);
1960
+ const durationMs = Math.max(0, Math.round(performance.now() - startedAt));
1961
+ const message = prepareOutput
1962
+ ? "Voice tool rejected or failed"
1963
+ : error instanceof Error
1964
+ ? error.message
1965
+ : String(error);
1915
1966
  results.push({
1916
1967
  tool: call.tool,
1917
1968
  input: call.input,
@@ -1921,6 +1972,8 @@ export class StubFabricSession {
1921
1972
  await this.recordEntry("error", { tool: call.tool, toolCallId, error: message });
1922
1973
  await this.emit("tool_end", {
1923
1974
  tool: call.tool,
1975
+ toolCallId,
1976
+ durationMs,
1924
1977
  error: message,
1925
1978
  ...(attribution ? { attribution: attribution } : {}),
1926
1979
  });
@@ -1928,9 +1981,9 @@ export class StubFabricSession {
1928
1981
  }
1929
1982
  return results;
1930
1983
  }
1931
- async recordUnexecutedInterruptedToolCall(call, toolCallId) {
1984
+ async recordUnexecutedInterruptedToolCall(call, toolCallId, recordToolCall) {
1932
1985
  const message = "Tool call was not executed: the prompt was aborted before this call started.";
1933
- await this.recordEntry("tool_call", {
1986
+ await (recordToolCall ?? ((data) => this.recordEntry("tool_call", data)))({
1934
1987
  tool: call.tool,
1935
1988
  input: call.input,
1936
1989
  inputDigest: approvalInputDigest(call.input),
@@ -2336,10 +2389,17 @@ export class StubFabricSession {
2336
2389
  !toolName) {
2337
2390
  continue;
2338
2391
  }
2339
- await this.emit("tool_start", { tool: toolName, recovery: true, toolCallId });
2392
+ await this.emit("tool_start", {
2393
+ tool: toolName,
2394
+ recovery: true,
2395
+ toolCallId,
2396
+ ...(call.data?.input !== undefined ? { input: call.data.input } : {}),
2397
+ });
2398
+ const recoveryStartedAt = performance.now();
2340
2399
  try {
2341
2400
  const authorization = await this.authorizeRecoveredToolCall(call, toolName, tool, toolCallId, recoveryPolicy);
2342
2401
  const submission = currentSubmissionContext();
2402
+ const agentName = this.agent.name ?? submission?.agent;
2343
2403
  const execute = () => Promise.resolve(executeTool(tool, call.data?.input, {
2344
2404
  sandbox,
2345
2405
  toolCallId,
@@ -2348,6 +2408,8 @@ export class StubFabricSession {
2348
2408
  ...(authorization.approval ? { approval: authorization.approval } : {}),
2349
2409
  ...(this.options.actor ? { actor: this.options.actor } : {}),
2350
2410
  ...(this.options.tenantId ? { tenantId: this.options.tenantId } : {}),
2411
+ ...(this.agent.id ? { agentId: this.agent.id } : {}),
2412
+ ...(agentName ? { agentName } : {}),
2351
2413
  policyVersion: authorization.policyDigest,
2352
2414
  ...(recoveryPolicy ? { policy: recoveryPolicy } : {}),
2353
2415
  inputDigest: authorization.inputDigest,
@@ -2369,16 +2431,25 @@ export class StubFabricSession {
2369
2431
  : execute, signal);
2370
2432
  const dynamicOutput = unwrapDynamicToolResult(rawOutput);
2371
2433
  const hookOutput = unwrapHookToolRunResult(dynamicOutput.output);
2434
+ const recoveryDurationMs = Math.max(0, Math.round(performance.now() - recoveryStartedAt));
2372
2435
  await this.recordToolResult({
2373
2436
  tool: toolName,
2374
2437
  toolCallId,
2375
2438
  output: hookOutput.output,
2439
+ durationMs: recoveryDurationMs,
2376
2440
  ...(hookOutput.terminate ? { terminate: true } : {}),
2377
2441
  recovered: true,
2378
2442
  }, dynamicOutput.stateWrites);
2379
- await this.emit("tool_end", { tool: toolName, recovery: true, toolCallId });
2443
+ await this.emit("tool_end", {
2444
+ tool: toolName,
2445
+ recovery: true,
2446
+ toolCallId,
2447
+ durationMs: recoveryDurationMs,
2448
+ ...(hookOutput.output !== undefined ? { output: hookOutput.output } : {}),
2449
+ });
2380
2450
  }
2381
2451
  catch (error) {
2452
+ const recoveryDurationMs = Math.max(0, Math.round(performance.now() - recoveryStartedAt));
2382
2453
  const message = error instanceof Error ? error.message : String(error);
2383
2454
  await this.recordEntry("error", {
2384
2455
  tool: toolName,
@@ -2390,6 +2461,7 @@ export class StubFabricSession {
2390
2461
  tool: toolName,
2391
2462
  recovery: true,
2392
2463
  toolCallId,
2464
+ durationMs: recoveryDurationMs,
2393
2465
  error: message,
2394
2466
  });
2395
2467
  }
@@ -2466,7 +2538,13 @@ export class StubFabricSession {
2466
2538
  }
2467
2539
  for (const call of dangling) {
2468
2540
  const tool = typeof call.data?.tool === "string" ? call.data.tool : "unknown";
2469
- await this.emit("tool_end", { tool, error: "interrupted", synthetic: true });
2541
+ const toolCallId = typeof call.data?.toolCallId === "string" ? call.data.toolCallId : undefined;
2542
+ await this.emit("tool_end", {
2543
+ tool,
2544
+ ...(toolCallId ? { toolCallId } : {}),
2545
+ error: "interrupted",
2546
+ synthetic: true,
2547
+ });
2470
2548
  }
2471
2549
  return;
2472
2550
  }
@@ -2565,14 +2643,15 @@ export class StubFabricSession {
2565
2643
  await this.store.appendEntry?.(this.id, entry);
2566
2644
  return entry;
2567
2645
  }
2568
- async finalizeDynamicResult(value, responseStartLeafId, usage) {
2646
+ async finalizeDynamicResult(value, responseStartLeafId, usage, correlationOverride) {
2569
2647
  const dynamic = this.options.dynamic;
2570
2648
  if (!dynamic)
2571
2649
  return { value, continued: false };
2572
2650
  const submission = currentSubmissionContext();
2573
- const submissionCorrelation = submission
2574
- ? { submissionId: submission.submissionId, attemptId: submission.attemptId }
2575
- : undefined;
2651
+ const submissionCorrelation = correlationOverride ??
2652
+ (submission
2653
+ ? { submissionId: submission.submissionId, attemptId: submission.attemptId }
2654
+ : undefined);
2576
2655
  const history = SessionHistory.fromData(await this.history());
2577
2656
  const path = responseStartLeafId
2578
2657
  ? history.getActivePathSince(responseStartLeafId)
@@ -2590,7 +2669,10 @@ export class StubFabricSession {
2590
2669
  }
2591
2670
  const responseId = path.findLast((entry) => entry.type === "assistant_message" ||
2592
2671
  entry.type === "tool_result" ||
2593
- entry.type === "error")?.id;
2672
+ entry.type === "error" ||
2673
+ entry.type === "result")?.id ??
2674
+ path.at(-1)?.id ??
2675
+ responseStartLeafId;
2594
2676
  const response = {
2595
2677
  ...(responseId ? { responseId } : {}),
2596
2678
  result: value,
@@ -2775,11 +2857,16 @@ export class StubFabricSession {
2775
2857
  }
2776
2858
  async emit(type, data) {
2777
2859
  await this.ensureData();
2860
+ const submission = currentSubmissionContext();
2861
+ const agentName = this.agent.name ?? submission?.agent;
2778
2862
  const event = {
2779
2863
  id: `${this.id}-${Date.now()}-${Math.random().toString(16).slice(2)}`,
2780
2864
  type,
2781
2865
  timestamp: new Date().toISOString(),
2782
2866
  sessionId: this.id,
2867
+ ...(this.agent.id ? { agentId: this.agent.id } : {}),
2868
+ ...(agentName ? { agentName } : {}),
2869
+ ...(submission?.submissionId ? { submissionId: submission.submissionId } : {}),
2783
2870
  ...(this.options.tenantId ? { tenantId: this.options.tenantId } : {}),
2784
2871
  ...(data ? { data } : {}),
2785
2872
  };