@fabric-harness/sdk 5.3.0 → 6.0.1

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 (104) hide show
  1. package/dist/agent.d.ts.map +1 -1
  2. package/dist/agent.js +4 -0
  3. package/dist/agent.js.map +1 -1
  4. package/dist/conversation-projection.d.ts +1 -1
  5. package/dist/conversation-projection.d.ts.map +1 -1
  6. package/dist/conversation-projection.js +61 -5
  7. package/dist/conversation-projection.js.map +1 -1
  8. package/dist/conversation-stream-contract.d.ts.map +1 -1
  9. package/dist/conversation-stream-contract.js +86 -0
  10. package/dist/conversation-stream-contract.js.map +1 -1
  11. package/dist/conversation-stream.d.ts +32 -1
  12. package/dist/conversation-stream.d.ts.map +1 -1
  13. package/dist/conversation-stream.js +81 -1
  14. package/dist/conversation-stream.js.map +1 -1
  15. package/dist/conversation-ui.d.ts +8 -0
  16. package/dist/conversation-ui.d.ts.map +1 -1
  17. package/dist/conversation-ui.js +20 -8
  18. package/dist/conversation-ui.js.map +1 -1
  19. package/dist/dispatch.d.ts +11 -0
  20. package/dist/dispatch.d.ts.map +1 -1
  21. package/dist/dispatch.js +4 -0
  22. package/dist/dispatch.js.map +1 -1
  23. package/dist/dynamic-agent.d.ts +66 -12
  24. package/dist/dynamic-agent.d.ts.map +1 -1
  25. package/dist/dynamic-agent.js +392 -97
  26. package/dist/dynamic-agent.js.map +1 -1
  27. package/dist/error.d.ts +3 -1
  28. package/dist/error.d.ts.map +1 -1
  29. package/dist/error.js +25 -0
  30. package/dist/error.js.map +1 -1
  31. package/dist/events.d.ts +30 -0
  32. package/dist/events.d.ts.map +1 -1
  33. package/dist/events.js.map +1 -1
  34. package/dist/history.d.ts.map +1 -1
  35. package/dist/history.js +57 -5
  36. package/dist/history.js.map +1 -1
  37. package/dist/in-memory-submission-store.d.ts +5 -0
  38. package/dist/in-memory-submission-store.d.ts.map +1 -1
  39. package/dist/in-memory-submission-store.js +70 -2
  40. package/dist/in-memory-submission-store.js.map +1 -1
  41. package/dist/index.d.ts +9 -9
  42. package/dist/index.d.ts.map +1 -1
  43. package/dist/index.js +4 -4
  44. package/dist/index.js.map +1 -1
  45. package/dist/loop.d.ts +12 -0
  46. package/dist/loop.d.ts.map +1 -1
  47. package/dist/loop.js +67 -2
  48. package/dist/loop.js.map +1 -1
  49. package/dist/model.d.ts +6 -0
  50. package/dist/model.d.ts.map +1 -1
  51. package/dist/model.js +22 -2
  52. package/dist/model.js.map +1 -1
  53. package/dist/operational-metrics.d.ts.map +1 -1
  54. package/dist/operational-metrics.js +4 -2
  55. package/dist/operational-metrics.js.map +1 -1
  56. package/dist/persistent-agent.d.ts +39 -2
  57. package/dist/persistent-agent.d.ts.map +1 -1
  58. package/dist/persistent-agent.js +153 -4
  59. package/dist/persistent-agent.js.map +1 -1
  60. package/dist/pi-loop-runtime.d.ts +9 -2
  61. package/dist/pi-loop-runtime.d.ts.map +1 -1
  62. package/dist/pi-loop-runtime.js +109 -39
  63. package/dist/pi-loop-runtime.js.map +1 -1
  64. package/dist/sandbox.d.ts +15 -0
  65. package/dist/sandbox.d.ts.map +1 -1
  66. package/dist/sandbox.js +45 -0
  67. package/dist/sandbox.js.map +1 -1
  68. package/dist/session.d.ts +4 -1
  69. package/dist/session.d.ts.map +1 -1
  70. package/dist/session.js +530 -67
  71. package/dist/session.js.map +1 -1
  72. package/dist/store.d.ts.map +1 -1
  73. package/dist/store.js +6 -0
  74. package/dist/store.js.map +1 -1
  75. package/dist/strict.d.ts +9 -9
  76. package/dist/strict.d.ts.map +1 -1
  77. package/dist/strict.js +4 -4
  78. package/dist/strict.js.map +1 -1
  79. package/dist/submission-runner.d.ts +9 -2
  80. package/dist/submission-runner.d.ts.map +1 -1
  81. package/dist/submission-runner.js +130 -10
  82. package/dist/submission-runner.js.map +1 -1
  83. package/dist/submission-state.d.ts +1 -1
  84. package/dist/submission-state.d.ts.map +1 -1
  85. package/dist/submission-state.js +13 -6
  86. package/dist/submission-state.js.map +1 -1
  87. package/dist/submission-store-contract.d.ts.map +1 -1
  88. package/dist/submission-store-contract.js +63 -0
  89. package/dist/submission-store-contract.js.map +1 -1
  90. package/dist/submission-store.d.ts +26 -1
  91. package/dist/submission-store.d.ts.map +1 -1
  92. package/dist/submission-store.js +6 -0
  93. package/dist/submission-store.js.map +1 -1
  94. package/dist/submission-telemetry.d.ts +19 -1
  95. package/dist/submission-telemetry.d.ts.map +1 -1
  96. package/dist/submission-telemetry.js.map +1 -1
  97. package/dist/tools.d.ts +14 -3
  98. package/dist/tools.d.ts.map +1 -1
  99. package/dist/tools.js +93 -12
  100. package/dist/tools.js.map +1 -1
  101. package/dist/types.d.ts +63 -4
  102. package/dist/types.d.ts.map +1 -1
  103. package/dist/types.js.map +1 -1
  104. package/package.json +28 -19
package/dist/session.js CHANGED
@@ -3,7 +3,7 @@ import { CostBudgetTracker } from "./cost-budget.js";
3
3
  import { inMemorySessionMemory } from "./session-memory.js";
4
4
  import { FabricError } from "./error.js";
5
5
  import { dynamicStateEntriesForTool, unwrapDynamicToolResult, } from "./dynamic-agent.js";
6
- import { approvalGrantFromState, approvalInputDigest, createApprovalGrant } from "./approval.js";
6
+ import { approvalGrantFromJson, approvalGrantFromState, approvalGrantToJson, approvalInputDigest, createApprovalGrant, sameApprovalOperation, } from "./approval.js";
7
7
  import { SessionHistory, buildModelMessagesFromHistory, findTrailingDanglingToolCalls, findTrailingUnfinishedTasks, } from "./history.js";
8
8
  import { getLogger } from "./logger.js";
9
9
  import { defaultLoopRuntime } from "./loop.js";
@@ -13,17 +13,21 @@ import { buildResultRetryPrompt, validateResult } from "./result.js";
13
13
  import { estimateSessionEntryTokens, evaluateContextBudget, isContextOverflowError, } from "./context-budget.js";
14
14
  import { policiedSandboxEnv, runWithSandboxPolicyApproval } from "./policied-sandbox.js";
15
15
  import { currentSubmissionContext } from "./submission-context.js";
16
- import { createSandboxEnv, createScopedSandboxEnv } from "./sandbox.js";
16
+ import { deliveredSignalToEntryData, renderDeliveredMessage } from "./delivered-message.js";
17
+ import { createSandboxEnv, createScopedSandboxEnv, execSandboxCommand } from "./sandbox.js";
17
18
  import { createFabricFs } from "./filesystem.js";
18
19
  import { registerSandbox, serializeSandboxRef, unregisterSandbox } from "./sandbox-ref.js";
19
20
  import path from "node:path";
20
21
  import { defaultSessionStore } from "./store.js";
21
- import { createActivateSkillTool, createBuiltinTools, createCommandTools, shellQuote, } from "./tools.js";
22
+ import { createActivateSkillTool, createBuiltinTools, createCommandTools, shellQuote, unwrapHookToolRunResult, } from "./tools.js";
22
23
  import { formatPackagedSkillResourceList, readPackagedSkillFile } from "./skills.js";
23
24
  import { MAX_TASK_DEPTH } from "./types.js";
24
25
  let nextTaskId = 0;
25
26
  const CROCKFORD_ALPHABET = "0123456789ABCDEFGHJKMNPQRSTVWXYZ";
26
27
  const AFFINITY_KEY_REGEX = /^aff_[0-7][0-9A-HJKMNP-TV-Z]{25}$/;
28
+ function isResolvedDynamicModelProvider(value) {
29
+ return "provider" in value && !("generate" in value);
30
+ }
27
31
  function encodeBase32(buf, length) {
28
32
  let result = "";
29
33
  let bitIndex = 0; // 0 = MSB of buf[0]
@@ -77,7 +81,10 @@ Be concise. Focus on what's needed to understand the kept suffix.`;
77
81
  export class StubFabricSession {
78
82
  id;
79
83
  agent;
80
- sandbox;
84
+ sandboxPromise;
85
+ get sandbox() {
86
+ return this.sandboxPromise;
87
+ }
81
88
  checkpoint = {
82
89
  create: (options) => this.createCheckpoint(options),
83
90
  restore: (options) => this.restoreCheckpoint(options),
@@ -111,8 +118,8 @@ export class StubFabricSession {
111
118
  this.id = id;
112
119
  this.options = options;
113
120
  this.store = options.store ?? defaultSessionStore;
114
- this.sandbox = this.createSandbox();
115
- this.fs = createFabricFs(this.sandbox);
121
+ this.sandboxPromise = this.createSandbox();
122
+ this.fs = createFabricFs(() => this.sandboxPromise);
116
123
  this.costBudget = new CostBudgetTracker(options.costLimit);
117
124
  }
118
125
  getDurableRuntime() {
@@ -131,14 +138,37 @@ export class StubFabricSession {
131
138
  const options = ambientSignal
132
139
  ? { ...promptOptions, signal: ambientSignal }
133
140
  : promptOptions;
141
+ if (options.submission?.message &&
142
+ renderDeliveredMessage(options.submission.message) !== text) {
143
+ throw new FabricError({
144
+ code: "INVALID_CONFIG",
145
+ message: "The durable submission message does not match the rendered prompt text. " +
146
+ "Refusing to persist and execute contradictory inputs.",
147
+ publicMessage: "The durable submission input is inconsistent.",
148
+ });
149
+ }
134
150
  const durable = await this.getDurableRuntime();
135
151
  if (durable) {
152
+ if (this.options.dynamic && durable.supportsDynamicAgents !== true) {
153
+ throw new FabricError({
154
+ code: "INVALID_CONFIG",
155
+ message: "The configured durable session runtime does not support dynamic-agent rendering. " +
156
+ "Refusing to drop rendered tools, identity, state, lifecycle, sandbox, or MCP configuration.",
157
+ publicMessage: "This dynamic agent is not supported by the configured durable runtime.",
158
+ });
159
+ }
136
160
  // Delegate to the durable runtime; the runtime is responsible for
137
161
  // recording entries / events on its own side. We still emit a single
138
162
  // local prompt_start/end pair so local subscribers see activity.
139
163
  await this.emit("prompt_start", { text });
140
164
  try {
141
- const result = await durable.prompt({ text, ...(options ? { options } : {}) });
165
+ const result = await durable.prompt({
166
+ text,
167
+ ...(options ? { options } : {}),
168
+ ...(this.options.dynamic
169
+ ? { dynamic: this.options.dynamic.executionDescriptor() }
170
+ : {}),
171
+ });
142
172
  await this.emit("prompt_end", { text });
143
173
  return result;
144
174
  }
@@ -147,15 +177,120 @@ export class StubFabricSession {
147
177
  throw error;
148
178
  }
149
179
  }
150
- const role = this.resolveRole(options.role ?? this.options.role ?? this.agent.role);
180
+ let role = this.resolveRole(options.role ?? this.options.role ?? this.agent.role);
151
181
  const promptSubscriber = options.onEvent;
152
182
  if (promptSubscriber)
153
183
  this.eventSubscribers.add(promptSubscriber);
184
+ let dynamic = this.options.dynamic;
154
185
  try {
155
- const sandbox = createScopedSandboxEnv(await this.sandbox, options.cwd);
156
- const tools = this.resolveTools(sandbox, options.tools, options.commands);
186
+ let sandbox = createScopedSandboxEnv(await this.sandbox, options.cwd);
187
+ let tools = this.resolveTools(sandbox, options.tools, options.commands);
188
+ let joinedRenderReady = false;
189
+ const currentTurnConfiguration = () => ({
190
+ ...(typeof this.options.model === "string" ? { model: this.options.model } : {}),
191
+ ...(this.options.thinkingLevel !== undefined
192
+ ? { thinkingLevel: this.options.thinkingLevel }
193
+ : {}),
194
+ ...(this.options.modelProvider !== undefined
195
+ ? { modelProvider: this.options.modelProvider }
196
+ : {}),
197
+ tools,
198
+ sandbox,
199
+ ...(this.options.policy ? { policy: this.options.policy } : {}),
200
+ ...(options.role === undefined && typeof this.options.role === "object"
201
+ ? { systemInstruction: this.options.role.content }
202
+ : {}),
203
+ });
204
+ const refreshDynamic = async (input) => {
205
+ if (!dynamic)
206
+ return currentTurnConfiguration();
207
+ const prior = dynamic;
208
+ const config = await prior.refresh(input);
209
+ const priorModel = this.options.model;
210
+ if (config.sandbox !== this.options.sandbox) {
211
+ const previousSandbox = await this.sandboxPromise;
212
+ if (config.sandbox !== undefined)
213
+ this.options.sandbox = config.sandbox;
214
+ else
215
+ Reflect.deleteProperty(this.options, "sandbox");
216
+ const nextSandboxPromise = this.createSandbox();
217
+ this.sandboxPromise = nextSandboxPromise;
218
+ const nextSandbox = await nextSandboxPromise;
219
+ sandbox = createScopedSandboxEnv(nextSandbox, options.cwd);
220
+ if (previousSandbox !== nextSandbox)
221
+ await previousSandbox.cleanup();
222
+ }
223
+ this.options.tools = config.tools ?? [];
224
+ this.options.skills = config.skills ?? [];
225
+ if (config.policy !== undefined)
226
+ this.options.policy = config.policy;
227
+ else
228
+ Reflect.deleteProperty(this.options, "policy");
229
+ if (config.model !== undefined)
230
+ this.options.model = config.model;
231
+ else
232
+ Reflect.deleteProperty(this.options, "model");
233
+ if (typeof config.model === "string" &&
234
+ config.model !== priorModel &&
235
+ this.options.modelProviderResolver) {
236
+ const resolved = await this.options.modelProviderResolver(config.model);
237
+ if (isResolvedDynamicModelProvider(resolved)) {
238
+ this.options.modelProvider = resolved.provider;
239
+ if (resolved.model !== undefined)
240
+ this.options.model = resolved.model;
241
+ }
242
+ else {
243
+ this.options.modelProvider = resolved;
244
+ }
245
+ }
246
+ else if (config.modelProvider !== undefined) {
247
+ this.options.modelProvider = config.modelProvider;
248
+ }
249
+ if (config.thinkingLevel !== undefined)
250
+ this.options.thinkingLevel = config.thinkingLevel;
251
+ else
252
+ Reflect.deleteProperty(this.options, "thinkingLevel");
253
+ if (config.compaction !== undefined)
254
+ this.options.compaction = config.compaction;
255
+ else
256
+ Reflect.deleteProperty(this.options, "compaction");
257
+ if (options.role === undefined) {
258
+ if (config.instructions) {
259
+ this.options.role = { name: config.name ?? "instructions", content: config.instructions };
260
+ }
261
+ else {
262
+ Reflect.deleteProperty(this.options, "role");
263
+ }
264
+ role = this.resolveRole(this.options.role);
265
+ }
266
+ tools = this.resolveTools(sandbox, options.tools, options.commands);
267
+ if (!config.dynamic) {
268
+ throw new Error("[fabric-harness] A dynamic-agent refresh did not return its runtime.");
269
+ }
270
+ dynamic = config.dynamic;
271
+ this.options.dynamic = config.dynamic;
272
+ if (prior !== dynamic)
273
+ await prior.close();
274
+ return currentTurnConfiguration();
275
+ };
276
+ const activeSubmission = currentSubmissionContext();
277
+ const submissionCorrelation = activeSubmission
278
+ ? {
279
+ submissionId: activeSubmission.submissionId,
280
+ attemptId: activeSubmission.attemptId,
281
+ }
282
+ : options.submission
283
+ ? { submissionId: options.submission.submissionId }
284
+ : undefined;
285
+ const responseStartData = await this.history();
286
+ const responseStartPath = SessionHistory.fromData(responseStartData).getActivePath();
287
+ const firstRecoveredCall = findTrailingDanglingToolCalls(responseStartPath).at(0);
288
+ // A restarted response owns the dangling call it is about to repair. Use
289
+ // the call's parent as the response boundary so finish hooks observe both
290
+ // the original call and the recovered result, even when dynamic render
291
+ // narration was appended between them during worker initialization.
292
+ const responseStartLeafId = firstRecoveredCall?.parentId ?? responseStartData.leafId;
157
293
  await this.repairDanglingToolCalls(tools, sandbox, options.signal);
158
- const responseStartLeafId = (await this.history()).leafId;
159
294
  await this.emit("prompt_start", { text, ...(role ? { role: role.name } : {}) });
160
295
  // Submission-correlated prompts are idempotent by submission id: a
161
296
  // recovered attempt whose input entry already landed (crash after the
@@ -164,33 +299,43 @@ export class StubFabricSession {
164
299
  if (options.submission) {
165
300
  const prior = await this.history();
166
301
  const submissionId = options.submission.submissionId;
167
- inputAlreadyApplied = (prior.entries ?? []).some((entry) => entry.type === "user_prompt" &&
302
+ inputAlreadyApplied = (prior.entries ?? []).some((entry) => (entry.type === "user_prompt" || entry.type === "signal") &&
168
303
  entry.data?.submissionId === submissionId);
169
304
  }
170
305
  if (!inputAlreadyApplied) {
171
- await this.recordEntry("user_prompt", {
172
- text,
173
- ...(role ? { role: role.name } : {}),
174
- ...(options.submission ? { submissionId: options.submission.submissionId } : {}),
175
- });
306
+ if (options.submission?.message?.kind === "signal") {
307
+ await this.recordEntry("signal", {
308
+ ...deliveredSignalToEntryData(options.submission.message),
309
+ submissionId: options.submission.submissionId,
310
+ });
311
+ }
312
+ else {
313
+ await this.recordEntry("user_prompt", {
314
+ text,
315
+ ...(role ? { role: role.name } : {}),
316
+ ...(options.submission ? { submissionId: options.submission.submissionId } : {}),
317
+ });
318
+ }
176
319
  }
177
320
  // Input-applied boundary: the canonical input entry is durable and no
178
321
  // provider work has started. The submission runner's input-applied
179
322
  // marker CAS hangs off this callback; its failure aborts the turn
180
323
  // (the attempt lost ownership).
181
324
  await options.submission?.onInputApplied?.();
182
- if (this.options.dynamic) {
325
+ if (dynamic) {
183
326
  const submissionId = options.submission?.submissionId;
184
327
  const dynamicPath = SessionHistory.fromData(await this.history()).getActivePath();
185
328
  const belongsToSubmission = (entry) => submissionId === undefined || entry.data?.submissionId === submissionId;
186
329
  const responseStarted = dynamicPath.some((entry) => entry.type === "response_metadata" && entry.data?.phase === "start" && belongsToSubmission(entry));
187
330
  const agentStarted = dynamicPath.some((entry) => entry.type === "agent_lifecycle" && entry.data?.phase === "start" && belongsToSubmission(entry));
188
- if (!inputAlreadyApplied || !responseStarted)
189
- await this.options.dynamic.runResponseStart();
331
+ if (!inputAlreadyApplied || !responseStarted) {
332
+ await dynamic.runResponseStart(undefined, submissionCorrelation);
333
+ }
190
334
  if (!inputAlreadyApplied || !agentStarted) {
191
- await this.options.dynamic.runAgentStart({
335
+ await dynamic.runAgentStart({
192
336
  ...(options.signal ? { signal: options.signal } : {}),
193
337
  sandbox,
338
+ ...submissionCorrelation,
194
339
  });
195
340
  }
196
341
  }
@@ -257,6 +402,72 @@ export class StubFabricSession {
257
402
  ...(useResultTools ? { resultValidator: options.result } : {}),
258
403
  agentId: this.agent.id,
259
404
  ...(this.options.tenantId !== undefined ? { tenantId: this.options.tenantId } : {}),
405
+ ...(options.submission?.takeJoinedInputs
406
+ ? {
407
+ takeSteeringMessages: async () => {
408
+ const inputs = await options.submission?.takeJoinedInputs?.();
409
+ if (!inputs?.length)
410
+ return [];
411
+ const messages = [];
412
+ for (const input of inputs) {
413
+ if (input.message &&
414
+ renderDeliveredMessage(input.message) !== input.text) {
415
+ throw new FabricError({
416
+ code: "INVALID_CONFIG",
417
+ message: "A joined durable submission message does not match its rendered prompt text. " +
418
+ "Refusing to persist and execute contradictory inputs.",
419
+ publicMessage: "A joined durable submission input is inconsistent.",
420
+ });
421
+ }
422
+ const current = await this.history();
423
+ const exists = (current.entries ?? []).some((entry) => (entry.type === "user_prompt" || entry.type === "signal") &&
424
+ entry.data?.submissionId === input.submissionId);
425
+ if (!exists) {
426
+ if (input.message?.kind === "signal") {
427
+ await this.recordEntry("signal", {
428
+ ...deliveredSignalToEntryData(input.message),
429
+ submissionId: input.submissionId,
430
+ });
431
+ }
432
+ else {
433
+ await this.recordEntry("user_prompt", {
434
+ text: input.text,
435
+ submissionId: input.submissionId,
436
+ });
437
+ }
438
+ messages.push({ role: "user", content: input.text });
439
+ }
440
+ if (input.message && dynamic) {
441
+ await refreshDynamic({
442
+ delivery: input.message,
443
+ });
444
+ const lifecycleSignals = await dynamic?.runAgentStart({
445
+ ...(options.signal ? { signal: options.signal } : {}),
446
+ sandbox,
447
+ submissionId: input.submissionId,
448
+ });
449
+ for (const signal of lifecycleSignals ?? []) {
450
+ messages.push({ role: "user", content: renderDeliveredMessage(signal) });
451
+ }
452
+ joinedRenderReady = true;
453
+ }
454
+ await input.onInputApplied();
455
+ }
456
+ return messages;
457
+ },
458
+ }
459
+ : {}),
460
+ ...(dynamic
461
+ ? {
462
+ refreshTurn: async () => {
463
+ if (joinedRenderReady) {
464
+ joinedRenderReady = false;
465
+ return currentTurnConfiguration();
466
+ }
467
+ return refreshDynamic();
468
+ },
469
+ }
470
+ : {}),
260
471
  executeToolCalls: (calls, policy, approvalTimeoutMs, attribution) => this.executeToolCalls(calls, tools, sandbox, policy, approvalTimeoutMs, options.onApproval, attribution, options.signal),
261
472
  recordEntry: (type, data) => this.recordEntry(type, data),
262
473
  emit: (type, data) => this.emit(type, data),
@@ -316,7 +527,7 @@ export class StubFabricSession {
316
527
  }
317
528
  }
318
529
  }
319
- const finalized = await this.finalizeDynamicResult(value, responseStartLeafId);
530
+ const finalized = await this.finalizeDynamicResult(value, responseStartLeafId, result.usage);
320
531
  if (!finalized.continued)
321
532
  return finalized.value;
322
533
  continuationCount += 1;
@@ -331,7 +542,13 @@ export class StubFabricSession {
331
542
  finally {
332
543
  if (promptSubscriber)
333
544
  this.eventSubscribers.delete(promptSubscriber);
334
- await this.options.dynamic?.close();
545
+ // Dynamic-agent environments are interaction-scoped. The persistent
546
+ // runtimes create a fresh Session per admitted response, so retaining
547
+ // the final sandbox here would leak provider resources after local runs,
548
+ // server submissions, and recovered attempts settle.
549
+ if (dynamic)
550
+ await (await this.sandboxPromise).cleanup();
551
+ await dynamic?.close();
335
552
  }
336
553
  }
337
554
  async *stream(text, options = {}) {
@@ -396,6 +613,13 @@ export class StubFabricSession {
396
613
  async task(text, options = {}) {
397
614
  const durable = await this.getDurableRuntime();
398
615
  if (durable) {
616
+ if (this.options.dynamic && durable.supportsDynamicAgents !== true) {
617
+ throw new FabricError({
618
+ code: "INVALID_CONFIG",
619
+ message: "The configured durable session runtime does not support dynamic-agent rendering.",
620
+ publicMessage: "This dynamic agent is not supported by the configured durable runtime.",
621
+ });
622
+ }
399
623
  const taskId = options.id ?? `${this.id}:task-${++nextTaskId}`;
400
624
  await this.emit("task_start", { taskId, depth: 1, parentSessionId: this.id });
401
625
  try {
@@ -406,6 +630,9 @@ export class StubFabricSession {
406
630
  ...(Object.keys(taskOptions).length
407
631
  ? { options: taskOptions }
408
632
  : {}),
633
+ ...(this.options.dynamic
634
+ ? { dynamic: this.options.dynamic.executionDescriptor() }
635
+ : {}),
409
636
  });
410
637
  await this.emit("task_end", { taskId, depth: 1, parentSessionId: this.id });
411
638
  return result;
@@ -420,6 +647,15 @@ export class StubFabricSession {
420
647
  }
421
648
  }
422
649
  const taskId = options.id ?? `${this.id}:task-${++nextTaskId}`;
650
+ const delegatedRole = options.agent ? this.resolveRole(options.agent) : undefined;
651
+ if (options.agent && !delegatedRole) {
652
+ const roster = (this.options.roles ?? []).map((role) => role.name).sort();
653
+ throw new FabricError({
654
+ code: "ROLE_NOT_FOUND",
655
+ message: `Subagent not found: ${options.agent}. Declared subagents: ${roster.length > 0 ? roster.join(", ") : "none"}.`,
656
+ details: { role: options.agent, availableRoles: roster },
657
+ });
658
+ }
423
659
  const depth = (options.depth ?? this.options.metadata?.taskDepth ?? 0) + 1;
424
660
  if (depth > MAX_TASK_DEPTH) {
425
661
  throw new Error(`Task nesting exceeds MAX_TASK_DEPTH (${MAX_TASK_DEPTH}). Refusing to spawn deeper child task at depth ${depth}.`);
@@ -462,9 +698,39 @@ export class StubFabricSession {
462
698
  if (options.signal)
463
699
  options.signal.addEventListener("abort", forwardAbort, { once: true });
464
700
  try {
465
- const child = new StubFabricSession(this.agent, taskId, {
701
+ const { agent: _agent, checkpoint: _checkpoint, depth: _depth, id: _taskOptionId, metadata: _metadata, ...childPromptOptions } = options;
702
+ let delegatedModelResolution;
703
+ if (delegatedRole?.model &&
704
+ options.model === undefined &&
705
+ options.modelProvider === undefined &&
706
+ this.options.modelProviderResolver) {
707
+ const resolved = await this.options.modelProviderResolver(delegatedRole.model);
708
+ delegatedModelResolution = isResolvedDynamicModelProvider(resolved)
709
+ ? {
710
+ model: resolved.model ?? delegatedRole.model,
711
+ modelProvider: resolved.provider,
712
+ }
713
+ : { model: delegatedRole.model, modelProvider: resolved };
714
+ }
715
+ const childOptions = {
466
716
  ...this.options,
467
717
  ...options,
718
+ ...(delegatedRole
719
+ ? {
720
+ role: delegatedRole,
721
+ roles: delegatedRole.subagents ?? [],
722
+ tools: [...(delegatedRole.tools ?? []), ...(options.tools ?? [])],
723
+ skills: delegatedRole.skills ?? [],
724
+ commands: [],
725
+ ...(delegatedRole.model && options.model === undefined
726
+ ? { model: delegatedRole.model }
727
+ : {}),
728
+ ...(delegatedRole.thinkingLevel && options.thinkingLevel === undefined
729
+ ? { thinkingLevel: delegatedRole.thinkingLevel }
730
+ : {}),
731
+ }
732
+ : {}),
733
+ ...(delegatedModelResolution ?? {}),
468
734
  store: this.store,
469
735
  sandbox: await this.sandbox,
470
736
  // Propagate depth so nested tasks can enforce MAX_TASK_DEPTH.
@@ -473,8 +739,18 @@ export class StubFabricSession {
473
739
  ...(options.metadata ?? {}),
474
740
  taskDepth: depth,
475
741
  },
742
+ };
743
+ // A delegated role is the fully rendered child-agent configuration for
744
+ // this interaction. Reusing the parent's dynamic runtime would refresh
745
+ // the root agent on every child turn and replace the delegated role's
746
+ // instructions, model, and capabilities.
747
+ if (delegatedRole)
748
+ Reflect.deleteProperty(childOptions, "dynamic");
749
+ const child = new StubFabricSession(this.agent, taskId, childOptions);
750
+ const result = await child.prompt(text, {
751
+ ...childPromptOptions,
752
+ signal: taskAbort.signal,
476
753
  });
477
- const result = await child.prompt(text, { ...options, signal: taskAbort.signal });
478
754
  if (taskAbort.signal.aborted)
479
755
  throw abortError();
480
756
  if (options.checkpoint) {
@@ -618,12 +894,13 @@ export class StubFabricSession {
618
894
  if (timeout !== undefined)
619
895
  execOptions.timeout = timeout;
620
896
  await this.emit("command_start", { command });
621
- const execute = () => sandbox.exec(command, execOptions);
897
+ const toolCallId = `shell-${Date.now()}`;
898
+ execOptions.onOrphanSettled = (settlement) => this.recordSandboxOrphanSettlement("bash", toolCallId, settlement);
899
+ const execute = () => execSandboxCommand(sandbox, command, execOptions);
622
900
  const result = policyApproved
623
901
  ? await runWithSandboxPolicyApproval(sandbox, { tool: "bash", input: { command } }, execute)
624
902
  : await execute();
625
903
  const redactedCommand = redactEnvValues(command, options.env);
626
- const toolCallId = `shell-${Date.now()}`;
627
904
  await this.recordEntry("user_prompt", { text: `Run shell command: ${redactedCommand}` });
628
905
  await this.recordEntry("tool_call", {
629
906
  tool: "bash",
@@ -1128,7 +1405,12 @@ export class StubFabricSession {
1128
1405
  error,
1129
1406
  ...(call.id ? { id: call.id } : {}),
1130
1407
  });
1131
- await this.recordEntry("error", { tool: call.tool, error, approvalRequired: true });
1408
+ await this.recordEntry("error", {
1409
+ tool: call.tool,
1410
+ toolCallId,
1411
+ error,
1412
+ approvalRequired: true,
1413
+ });
1132
1414
  await this.emit("error", { tool: call.tool, error, approvalRequired: true });
1133
1415
  continue;
1134
1416
  }
@@ -1141,7 +1423,12 @@ export class StubFabricSession {
1141
1423
  error,
1142
1424
  ...(call.id ? { id: call.id } : {}),
1143
1425
  });
1144
- await this.recordEntry("error", { tool: call.tool, error, approvalRequired: false });
1426
+ await this.recordEntry("error", {
1427
+ tool: call.tool,
1428
+ toolCallId,
1429
+ error,
1430
+ approvalRequired: false,
1431
+ });
1145
1432
  await this.emit("error", { tool: call.tool, error, approvalRequired: false });
1146
1433
  continue;
1147
1434
  }
@@ -1179,7 +1466,12 @@ export class StubFabricSession {
1179
1466
  error,
1180
1467
  ...(call.id ? { id: call.id } : {}),
1181
1468
  });
1182
- await this.recordEntry("error", { tool: call.tool, error, approvalRequired: true });
1469
+ await this.recordEntry("error", {
1470
+ tool: call.tool,
1471
+ toolCallId,
1472
+ error,
1473
+ approvalRequired: true,
1474
+ });
1183
1475
  await this.emit("error", { tool: call.tool, error, approvalRequired: true });
1184
1476
  continue;
1185
1477
  }
@@ -1196,7 +1488,12 @@ export class StubFabricSession {
1196
1488
  error,
1197
1489
  ...(call.id ? { id: call.id } : {}),
1198
1490
  });
1199
- await this.recordEntry("error", { tool: call.tool, error, approvalRequired: false });
1491
+ await this.recordEntry("error", {
1492
+ tool: call.tool,
1493
+ toolCallId,
1494
+ error,
1495
+ approvalRequired: false,
1496
+ });
1200
1497
  await this.emit("error", { tool: call.tool, error, approvalRequired: false });
1201
1498
  continue;
1202
1499
  }
@@ -1204,6 +1501,10 @@ export class StubFabricSession {
1204
1501
  await this.recordEntry("tool_call", {
1205
1502
  tool: call.tool,
1206
1503
  input: call.input,
1504
+ inputDigest: approvalInputDigest(call.input),
1505
+ policyDigest: approvalInputDigest(policy ?? null),
1506
+ ...(executingPrincipal ? { executingPrincipal: executingPrincipal } : {}),
1507
+ ...(approvalGrant ? { approval: approvalGrantToJson(approvalGrant) } : {}),
1207
1508
  ...(tool?.metadata?.effect ? { effect: tool.metadata.effect } : {}),
1208
1509
  ...(tool?.durable ? { durable: true } : {}),
1209
1510
  toolCallId,
@@ -1221,7 +1522,12 @@ export class StubFabricSession {
1221
1522
  error,
1222
1523
  ...(call.id ? { id: call.id } : {}),
1223
1524
  });
1224
- await this.recordEntry("error", { tool: call.tool, error, approvalRequired: false });
1525
+ await this.recordEntry("error", {
1526
+ tool: call.tool,
1527
+ toolCallId,
1528
+ error,
1529
+ approvalRequired: false,
1530
+ });
1225
1531
  await this.emit("tool_end", {
1226
1532
  tool: call.tool,
1227
1533
  error,
@@ -1232,27 +1538,49 @@ export class StubFabricSession {
1232
1538
  try {
1233
1539
  const input = call.tool === "bash" ? this.clampBashToolInput(call.input, policy) : call.input;
1234
1540
  const startedAt = Date.now();
1541
+ const submission = currentSubmissionContext();
1235
1542
  const execute = () => Promise.resolve(tool.execute?.(input, {
1236
1543
  sandbox,
1237
1544
  toolCallId,
1238
1545
  ...(signal ? { signal } : {}),
1546
+ onOrphanSettled: (settlement) => this.recordSandboxOrphanSettlement(call.tool, toolCallId, settlement),
1239
1547
  ...(approvalGrant ? { approval: approvalGrant } : {}),
1548
+ ...(this.options.actor ? { actor: this.options.actor } : {}),
1549
+ ...(this.options.tenantId ? { tenantId: this.options.tenantId } : {}),
1550
+ policyVersion: approvalInputDigest(policy ?? null),
1551
+ inputDigest: approvalInputDigest(input),
1240
1552
  ...(tool.durable ? { step: this.createToolStep(toolCallId) } : {}),
1241
1553
  log: this.createToolProgressLogger(call.tool, toolCallId),
1242
1554
  harness: { sandbox },
1555
+ ...(submission
1556
+ ? {
1557
+ __fabricSubmission: {
1558
+ submissionId: submission.submissionId,
1559
+ attemptId: submission.attemptId,
1560
+ },
1561
+ }
1562
+ : {}),
1243
1563
  }));
1244
1564
  const rawOutput = await approvedSandboxCalls.reduceRight((next, approvedCall) => () => runWithSandboxPolicyApproval(sandbox, approvedCall, next), execute)();
1245
1565
  const dynamicOutput = unwrapDynamicToolResult(rawOutput);
1246
- const output = dynamicOutput.output;
1566
+ const hookOutput = unwrapHookToolRunResult(dynamicOutput.output);
1567
+ const output = hookOutput.output;
1247
1568
  const durationMs = Date.now() - startedAt;
1248
- results.push({ tool: call.tool, input, output, ...(call.id ? { id: call.id } : {}) });
1249
1569
  await this.recordToolResult({
1250
1570
  tool: call.tool,
1251
1571
  output: output,
1252
1572
  durationMs,
1253
1573
  toolCallId,
1574
+ ...(hookOutput.terminate ? { terminate: true } : {}),
1254
1575
  ...(attribution ? { attribution: attribution } : {}),
1255
1576
  }, dynamicOutput.stateWrites);
1577
+ results.push({
1578
+ tool: call.tool,
1579
+ input,
1580
+ output,
1581
+ ...(hookOutput.terminate ? { terminate: true } : {}),
1582
+ ...(call.id ? { id: toolCallId } : {}),
1583
+ });
1256
1584
  await this.emit("tool_end", {
1257
1585
  tool: call.tool,
1258
1586
  durationMs,
@@ -1265,9 +1593,9 @@ export class StubFabricSession {
1265
1593
  tool: call.tool,
1266
1594
  input: call.input,
1267
1595
  error: message,
1268
- ...(call.id ? { id: call.id } : {}),
1596
+ ...(call.id ? { id: toolCallId } : {}),
1269
1597
  });
1270
- await this.recordEntry("error", { tool: call.tool, error: message });
1598
+ await this.recordEntry("error", { tool: call.tool, toolCallId, error: message });
1271
1599
  await this.emit("tool_end", {
1272
1600
  tool: call.tool,
1273
1601
  error: message,
@@ -1619,19 +1947,40 @@ export class StubFabricSession {
1619
1947
  }
1620
1948
  await this.emit("tool_start", { tool: toolName, recovery: true, toolCallId });
1621
1949
  try {
1622
- const rawOutput = await tool.execute(call.data?.input, {
1950
+ const authorization = await this.authorizeRecoveredToolCall(call, toolName, tool, toolCallId);
1951
+ const submission = currentSubmissionContext();
1952
+ const execute = () => Promise.resolve(tool.execute?.(call.data?.input, {
1623
1953
  sandbox,
1624
1954
  toolCallId,
1625
1955
  ...(signal ? { signal } : {}),
1956
+ onOrphanSettled: (settlement) => this.recordSandboxOrphanSettlement(toolName, toolCallId, settlement),
1957
+ ...(authorization.approval ? { approval: authorization.approval } : {}),
1958
+ ...(this.options.actor ? { actor: this.options.actor } : {}),
1959
+ ...(this.options.tenantId ? { tenantId: this.options.tenantId } : {}),
1960
+ policyVersion: authorization.policyDigest,
1961
+ inputDigest: authorization.inputDigest,
1626
1962
  step: this.createToolStep(toolCallId),
1627
1963
  log: this.createToolProgressLogger(toolName, toolCallId),
1628
1964
  harness: { sandbox },
1629
- });
1965
+ ...(submission
1966
+ ? {
1967
+ __fabricSubmission: {
1968
+ submissionId: submission.submissionId,
1969
+ attemptId: submission.attemptId,
1970
+ },
1971
+ }
1972
+ : {}),
1973
+ }));
1974
+ const rawOutput = authorization.approvedCall
1975
+ ? await runWithSandboxPolicyApproval(sandbox, authorization.approvedCall, execute)
1976
+ : await execute();
1630
1977
  const dynamicOutput = unwrapDynamicToolResult(rawOutput);
1978
+ const hookOutput = unwrapHookToolRunResult(dynamicOutput.output);
1631
1979
  await this.recordToolResult({
1632
1980
  tool: toolName,
1633
1981
  toolCallId,
1634
- output: dynamicOutput.output,
1982
+ output: hookOutput.output,
1983
+ ...(hookOutput.terminate ? { terminate: true } : {}),
1635
1984
  recovered: true,
1636
1985
  }, dynamicOutput.stateWrites);
1637
1986
  await this.emit("tool_end", { tool: toolName, recovery: true, toolCallId });
@@ -1730,6 +2079,74 @@ export class StubFabricSession {
1730
2079
  }
1731
2080
  throw new Error(`Could not repair interrupted session ${this.id}: session leaf kept changing.`);
1732
2081
  }
2082
+ async authorizeRecoveredToolCall(call, toolName, tool, toolCallId) {
2083
+ const input = call.data?.input;
2084
+ const inputDigest = approvalInputDigest(input);
2085
+ if (call.data?.inputDigest !== inputDigest) {
2086
+ throw new FabricError({
2087
+ code: "POLICY_DENIED",
2088
+ message: `Recovered tool ${toolName} has no matching persisted input authorization digest.`,
2089
+ });
2090
+ }
2091
+ if (call.tenantId !== this.options.tenantId || !sameFabricActor(call.actor, this.options.actor)) {
2092
+ throw new FabricError({
2093
+ code: "POLICY_DENIED",
2094
+ message: `Recovered tool ${toolName} does not match the current tenant and actor context.`,
2095
+ });
2096
+ }
2097
+ const policy = this.options.policy;
2098
+ const policyDigest = approvalInputDigest(policy ?? null);
2099
+ const policyCall = {
2100
+ tool: tool.policyAlias ?? toolName,
2101
+ input,
2102
+ id: toolCallId,
2103
+ };
2104
+ const decisions = [
2105
+ this.checkMountWriteAccess({ tool: toolName, input, id: toolCallId }) ??
2106
+ evaluateToolCallPolicy(policyCall, policy),
2107
+ this.evaluateScopedCommandToolCall(tool, input, policy),
2108
+ ];
2109
+ const denied = decisions.find((decision) => !decision.allowed && !decision.approvalRequired);
2110
+ if (denied) {
2111
+ throw new FabricError({
2112
+ code: "POLICY_DENIED",
2113
+ message: denied.reason ?? `Recovered tool ${toolName} is denied by the current policy.`,
2114
+ });
2115
+ }
2116
+ const requiresApproval = decisions.some((decision) => decision.approvalRequired);
2117
+ if (!requiresApproval)
2118
+ return { inputDigest, policyDigest };
2119
+ const grant = approvalGrantFromJson(call.data?.approval);
2120
+ const principal = toolExecutingPrincipal(tool) ?? this.approvalPrincipal();
2121
+ if (!grant || !sameApprovalOperation(grant, { toolCallId, toolInput: input, principal })) {
2122
+ throw new FabricError({
2123
+ code: "POLICY_DENIED",
2124
+ message: `Recovered tool ${toolName} requires a current approval bound to this call and principal.`,
2125
+ });
2126
+ }
2127
+ if (!this.store.getApprovalState) {
2128
+ throw new FabricError({
2129
+ code: "POLICY_DENIED",
2130
+ message: `Recovered tool ${toolName} cannot prove that approval ${grant.approvalId} remains valid.`,
2131
+ });
2132
+ }
2133
+ const state = await this.store.getApprovalState(this.id, grant.approvalId);
2134
+ const currentGrant = state
2135
+ ? approvalGrantFromState(state, input, principal, toolCallId)
2136
+ : undefined;
2137
+ if (!currentGrant) {
2138
+ throw new FabricError({
2139
+ code: "POLICY_DENIED",
2140
+ message: `Recovered tool ${toolName} approval is expired, denied, revoked, or unavailable.`,
2141
+ });
2142
+ }
2143
+ return {
2144
+ approval: currentGrant,
2145
+ approvedCall: policyCall,
2146
+ inputDigest,
2147
+ policyDigest,
2148
+ };
2149
+ }
1733
2150
  async recordEntry(type, data) {
1734
2151
  await this.ensureData();
1735
2152
  const current = await this.store.load(this.id);
@@ -1755,30 +2172,43 @@ export class StubFabricSession {
1755
2172
  await this.store.appendEntry?.(this.id, entry);
1756
2173
  return entry;
1757
2174
  }
1758
- async finalizeDynamicResult(value, responseStartLeafId) {
2175
+ async finalizeDynamicResult(value, responseStartLeafId, usage) {
1759
2176
  const dynamic = this.options.dynamic;
1760
2177
  if (!dynamic)
1761
2178
  return { value, continued: false };
2179
+ const submission = currentSubmissionContext();
2180
+ const submissionCorrelation = submission
2181
+ ? { submissionId: submission.submissionId, attemptId: submission.attemptId }
2182
+ : undefined;
1762
2183
  const history = SessionHistory.fromData(await this.history());
1763
2184
  const path = responseStartLeafId
1764
2185
  ? history.getActivePathSince(responseStartLeafId)
1765
2186
  : history.getActivePath();
1766
2187
  const results = new Map();
2188
+ const errors = new Map();
1767
2189
  for (const entry of path) {
1768
- if (entry.type !== "tool_result")
1769
- continue;
1770
2190
  const id = typeof entry.data?.toolCallId === "string" ? entry.data.toolCallId : undefined;
1771
- if (id)
2191
+ if (!id)
2192
+ continue;
2193
+ if (entry.type === "tool_result")
1772
2194
  results.set(id, entry);
2195
+ if (entry.type === "error")
2196
+ errors.set(id, entry);
1773
2197
  }
2198
+ const responseId = path.findLast((entry) => entry.type === "assistant_message" ||
2199
+ entry.type === "tool_result" ||
2200
+ entry.type === "error")?.id;
1774
2201
  const response = {
2202
+ ...(responseId ? { responseId } : {}),
1775
2203
  result: value,
2204
+ ...(usage ? { usage: usage } : {}),
1776
2205
  toolCalls: path.flatMap((entry) => {
1777
2206
  if (entry.type !== "tool_call")
1778
2207
  return [];
1779
2208
  const id = typeof entry.data?.toolCallId === "string" ? entry.data.toolCallId : undefined;
1780
2209
  const tool = typeof entry.data?.tool === "string" ? entry.data.tool : "unknown";
1781
2210
  const outcome = id ? results.get(id) : undefined;
2211
+ const failure = id ? errors.get(id) : undefined;
1782
2212
  return [
1783
2213
  {
1784
2214
  tool,
@@ -1786,30 +2216,42 @@ export class StubFabricSession {
1786
2216
  ...(outcome?.data && "output" in outcome.data ? { output: outcome.data.output } : {}),
1787
2217
  ...(outcome?.data?.isError === true
1788
2218
  ? { error: String(outcome.data.output ?? "Tool failed") }
1789
- : {}),
2219
+ : failure?.data?.error !== undefined
2220
+ ? { error: String(failure.data.error) }
2221
+ : {}),
1790
2222
  },
1791
2223
  ];
1792
2224
  }),
1793
2225
  };
1794
- const appended = await dynamic.runAgentFinish(response);
1795
- for (const message of appended) {
1796
- if (message.kind === "signal") {
1797
- await this.createSignalEntry({
1798
- signalType: message.type,
1799
- content: message.body,
1800
- ...(message.attributes ? { attributes: message.attributes } : {}),
1801
- ...(message.tagName ? { tagName: message.tagName } : {}),
2226
+ const appended = await dynamic.runAgentFinish(response, submissionCorrelation);
2227
+ for (const [continuationIndex, message] of appended.entries()) {
2228
+ const signal = {
2229
+ signalType: message.type,
2230
+ content: message.body,
2231
+ ...(message.attributes ? { attributes: message.attributes } : {}),
2232
+ ...(message.tagName ? { tagName: message.tagName } : {}),
2233
+ };
2234
+ if (response.responseId) {
2235
+ const alreadyRecorded = SessionHistory.fromData(await this.store.load(this.id))
2236
+ .getActivePath()
2237
+ .some((entry) => entry.type === "signal" &&
2238
+ entry.data?.dynamicResponseId === response.responseId &&
2239
+ entry.data?.dynamicContinuationIndex === continuationIndex);
2240
+ if (alreadyRecorded)
2241
+ continue;
2242
+ await this.recordEntry("signal", {
2243
+ ...signal,
2244
+ dynamicResponseId: response.responseId,
2245
+ dynamicContinuationIndex: continuationIndex,
1802
2246
  });
1803
2247
  }
1804
2248
  else {
1805
- await this.recordEntry("user_prompt", {
1806
- text: message.body,
1807
- purpose: "agent_finish_continuation",
1808
- });
2249
+ await this.createSignalEntry(signal);
1809
2250
  }
1810
2251
  }
1811
- if (appended.length === 0)
1812
- await dynamic.runResponseFinish(response);
2252
+ if (appended.length === 0) {
2253
+ await dynamic.runResponseFinish(response, submissionCorrelation);
2254
+ }
1813
2255
  return { value, continued: appended.length > 0 };
1814
2256
  }
1815
2257
  createToolStep(toolCallId) {
@@ -1870,18 +2312,34 @@ export class StubFabricSession {
1870
2312
  error: (message, data) => write("error", message, data),
1871
2313
  };
1872
2314
  }
2315
+ async recordSandboxOrphanSettlement(tool, toolCallId, settlement) {
2316
+ await this.createSignalEntry({
2317
+ signalType: "sandbox.command.orphan_settled",
2318
+ content: `A sandbox command that outlived cancellation later ${settlement.status}. Verify its effects before retrying.`,
2319
+ attributes: {
2320
+ tool,
2321
+ toolCallId,
2322
+ status: settlement.status,
2323
+ ...(settlement.status === "fulfilled"
2324
+ ? { exitCode: String(settlement.exitCode) }
2325
+ : { error: settlement.error }),
2326
+ },
2327
+ });
2328
+ await this.emit("metric", {
2329
+ kind: "sandbox_orphan_settled",
2330
+ tool,
2331
+ toolCallId,
2332
+ status: settlement.status,
2333
+ });
2334
+ }
1873
2335
  async recordToolResult(data, stateWrites) {
1874
- if (stateWrites.length === 0 || !this.store.appendEntries) {
1875
- for (const write of stateWrites) {
1876
- await this.recordEntry("agent_state", {
1877
- name: write.name,
1878
- value: write.value,
1879
- toolCallId: data.toolCallId,
1880
- });
1881
- }
2336
+ if (stateWrites.length === 0) {
1882
2337
  await this.recordEntry("tool_result", data);
1883
2338
  return;
1884
2339
  }
2340
+ if (!this.store.appendEntries) {
2341
+ throw new Error(`[fabric-harness] Dynamic state for tool ${data.toolCallId} requires SessionStore.appendEntries(); refusing a non-atomic state/result commit.`);
2342
+ }
1885
2343
  await this.ensureData();
1886
2344
  for (let attempt = 0; attempt < 8; attempt += 1) {
1887
2345
  const current = await this.store.load(this.id);
@@ -1911,8 +2369,10 @@ export class StubFabricSession {
1911
2369
  const committed = await this.store.appendEntries(this.id, [...stateEntries, resultEntry], {
1912
2370
  expectedLeafId: current?.leafId,
1913
2371
  });
1914
- if (committed)
2372
+ if (committed) {
2373
+ this.options.dynamic?.acknowledgeStateWrites(stateWrites);
1915
2374
  return;
2375
+ }
1916
2376
  }
1917
2377
  throw new Error(`Could not atomically commit tool result and dynamic state for ${data.toolCallId}.`);
1918
2378
  }
@@ -2152,6 +2612,9 @@ function isAbortError(error) {
2152
2612
  return (error instanceof Error &&
2153
2613
  (error.name === "AbortError" || /aborted|cancelled|canceled/i.test(error.message)));
2154
2614
  }
2615
+ function sameFabricActor(a, b) {
2616
+ return approvalInputDigest(a ?? null) === approvalInputDigest(b ?? null);
2617
+ }
2155
2618
  function toolStepEntryId(toolCallId, name) {
2156
2619
  return `tool-step:${encodeURIComponent(toolCallId)}:${encodeURIComponent(name)}`;
2157
2620
  }