@fabric-harness/sdk 5.2.0 → 6.0.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 (105) hide show
  1. package/README.md +24 -0
  2. package/dist/agent.d.ts.map +1 -1
  3. package/dist/agent.js +7 -0
  4. package/dist/agent.js.map +1 -1
  5. package/dist/conversation-projection.d.ts +1 -1
  6. package/dist/conversation-projection.d.ts.map +1 -1
  7. package/dist/conversation-projection.js +61 -5
  8. package/dist/conversation-projection.js.map +1 -1
  9. package/dist/conversation-stream-contract.d.ts.map +1 -1
  10. package/dist/conversation-stream-contract.js +86 -0
  11. package/dist/conversation-stream-contract.js.map +1 -1
  12. package/dist/conversation-stream.d.ts +32 -1
  13. package/dist/conversation-stream.d.ts.map +1 -1
  14. package/dist/conversation-stream.js +81 -1
  15. package/dist/conversation-stream.js.map +1 -1
  16. package/dist/conversation-ui.d.ts +8 -0
  17. package/dist/conversation-ui.d.ts.map +1 -1
  18. package/dist/conversation-ui.js +82 -5
  19. package/dist/conversation-ui.js.map +1 -1
  20. package/dist/dispatch.d.ts +15 -1
  21. package/dist/dispatch.d.ts.map +1 -1
  22. package/dist/dispatch.js +14 -0
  23. package/dist/dispatch.js.map +1 -1
  24. package/dist/dynamic-agent.d.ts +186 -0
  25. package/dist/dynamic-agent.d.ts.map +1 -0
  26. package/dist/dynamic-agent.js +1068 -0
  27. package/dist/dynamic-agent.js.map +1 -0
  28. package/dist/error.d.ts +3 -1
  29. package/dist/error.d.ts.map +1 -1
  30. package/dist/error.js +25 -0
  31. package/dist/error.js.map +1 -1
  32. package/dist/events.d.ts +30 -0
  33. package/dist/events.d.ts.map +1 -1
  34. package/dist/events.js.map +1 -1
  35. package/dist/history.d.ts.map +1 -1
  36. package/dist/history.js +57 -5
  37. package/dist/history.js.map +1 -1
  38. package/dist/in-memory-submission-store.d.ts +5 -0
  39. package/dist/in-memory-submission-store.d.ts.map +1 -1
  40. package/dist/in-memory-submission-store.js +70 -2
  41. package/dist/in-memory-submission-store.js.map +1 -1
  42. package/dist/index.d.ts +11 -9
  43. package/dist/index.d.ts.map +1 -1
  44. package/dist/index.js +5 -4
  45. package/dist/index.js.map +1 -1
  46. package/dist/loop.d.ts +12 -0
  47. package/dist/loop.d.ts.map +1 -1
  48. package/dist/loop.js +67 -2
  49. package/dist/loop.js.map +1 -1
  50. package/dist/model.d.ts +6 -0
  51. package/dist/model.d.ts.map +1 -1
  52. package/dist/model.js +22 -2
  53. package/dist/model.js.map +1 -1
  54. package/dist/operational-metrics.d.ts.map +1 -1
  55. package/dist/operational-metrics.js +4 -2
  56. package/dist/operational-metrics.js.map +1 -1
  57. package/dist/persistent-agent.d.ts +45 -3
  58. package/dist/persistent-agent.d.ts.map +1 -1
  59. package/dist/persistent-agent.js +163 -3
  60. package/dist/persistent-agent.js.map +1 -1
  61. package/dist/pi-loop-runtime.d.ts +9 -2
  62. package/dist/pi-loop-runtime.d.ts.map +1 -1
  63. package/dist/pi-loop-runtime.js +109 -39
  64. package/dist/pi-loop-runtime.js.map +1 -1
  65. package/dist/sandbox.d.ts +15 -0
  66. package/dist/sandbox.d.ts.map +1 -1
  67. package/dist/sandbox.js +45 -0
  68. package/dist/sandbox.js.map +1 -1
  69. package/dist/session.d.ts +12 -4
  70. package/dist/session.d.ts.map +1 -1
  71. package/dist/session.js +798 -71
  72. package/dist/session.js.map +1 -1
  73. package/dist/store.d.ts.map +1 -1
  74. package/dist/store.js +6 -0
  75. package/dist/store.js.map +1 -1
  76. package/dist/strict.d.ts +11 -9
  77. package/dist/strict.d.ts.map +1 -1
  78. package/dist/strict.js +5 -4
  79. package/dist/strict.js.map +1 -1
  80. package/dist/submission-runner.d.ts +9 -2
  81. package/dist/submission-runner.d.ts.map +1 -1
  82. package/dist/submission-runner.js +130 -10
  83. package/dist/submission-runner.js.map +1 -1
  84. package/dist/submission-state.d.ts +1 -1
  85. package/dist/submission-state.d.ts.map +1 -1
  86. package/dist/submission-state.js +13 -6
  87. package/dist/submission-state.js.map +1 -1
  88. package/dist/submission-store-contract.d.ts.map +1 -1
  89. package/dist/submission-store-contract.js +63 -0
  90. package/dist/submission-store-contract.js.map +1 -1
  91. package/dist/submission-store.d.ts +30 -2
  92. package/dist/submission-store.d.ts.map +1 -1
  93. package/dist/submission-store.js +8 -0
  94. package/dist/submission-store.js.map +1 -1
  95. package/dist/submission-telemetry.d.ts +19 -1
  96. package/dist/submission-telemetry.d.ts.map +1 -1
  97. package/dist/submission-telemetry.js.map +1 -1
  98. package/dist/tools.d.ts +70 -1
  99. package/dist/tools.d.ts.map +1 -1
  100. package/dist/tools.js +119 -2
  101. package/dist/tools.js.map +1 -1
  102. package/dist/types.d.ts +67 -4
  103. package/dist/types.d.ts.map +1 -1
  104. package/dist/types.js.map +1 -1
  105. package/package.json +3 -3
package/dist/session.js CHANGED
@@ -2,7 +2,8 @@ import { createHash, randomUUID } from "node:crypto";
2
2
  import { CostBudgetTracker } from "./cost-budget.js";
3
3
  import { inMemorySessionMemory } from "./session-memory.js";
4
4
  import { FabricError } from "./error.js";
5
- import { approvalGrantFromState, approvalInputDigest, createApprovalGrant } from "./approval.js";
5
+ import { dynamicStateEntriesForTool, unwrapDynamicToolResult, } from "./dynamic-agent.js";
6
+ import { approvalGrantFromJson, approvalGrantFromState, approvalGrantToJson, approvalInputDigest, createApprovalGrant, sameApprovalOperation, } from "./approval.js";
6
7
  import { SessionHistory, buildModelMessagesFromHistory, findTrailingDanglingToolCalls, findTrailingUnfinishedTasks, } from "./history.js";
7
8
  import { getLogger } from "./logger.js";
8
9
  import { defaultLoopRuntime } from "./loop.js";
@@ -12,17 +13,21 @@ import { buildResultRetryPrompt, validateResult } from "./result.js";
12
13
  import { estimateSessionEntryTokens, evaluateContextBudget, isContextOverflowError, } from "./context-budget.js";
13
14
  import { policiedSandboxEnv, runWithSandboxPolicyApproval } from "./policied-sandbox.js";
14
15
  import { currentSubmissionContext } from "./submission-context.js";
15
- import { createSandboxEnv, createScopedSandboxEnv } from "./sandbox.js";
16
+ import { deliveredSignalToEntryData, renderDeliveredMessage } from "./delivered-message.js";
17
+ import { createSandboxEnv, createScopedSandboxEnv, execSandboxCommand } from "./sandbox.js";
16
18
  import { createFabricFs } from "./filesystem.js";
17
19
  import { registerSandbox, serializeSandboxRef, unregisterSandbox } from "./sandbox-ref.js";
18
20
  import path from "node:path";
19
21
  import { defaultSessionStore } from "./store.js";
20
- import { createActivateSkillTool, createBuiltinTools, createCommandTools, shellQuote, } from "./tools.js";
22
+ import { createActivateSkillTool, createBuiltinTools, createCommandTools, shellQuote, unwrapHookToolRunResult, } from "./tools.js";
21
23
  import { formatPackagedSkillResourceList, readPackagedSkillFile } from "./skills.js";
22
24
  import { MAX_TASK_DEPTH } from "./types.js";
23
25
  let nextTaskId = 0;
24
26
  const CROCKFORD_ALPHABET = "0123456789ABCDEFGHJKMNPQRSTVWXYZ";
25
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
+ }
26
31
  function encodeBase32(buf, length) {
27
32
  let result = "";
28
33
  let bitIndex = 0; // 0 = MSB of buf[0]
@@ -76,7 +81,10 @@ Be concise. Focus on what's needed to understand the kept suffix.`;
76
81
  export class StubFabricSession {
77
82
  id;
78
83
  agent;
79
- sandbox;
84
+ sandboxPromise;
85
+ get sandbox() {
86
+ return this.sandboxPromise;
87
+ }
80
88
  checkpoint = {
81
89
  create: (options) => this.createCheckpoint(options),
82
90
  restore: (options) => this.restoreCheckpoint(options),
@@ -110,8 +118,8 @@ export class StubFabricSession {
110
118
  this.id = id;
111
119
  this.options = options;
112
120
  this.store = options.store ?? defaultSessionStore;
113
- this.sandbox = this.createSandbox();
114
- this.fs = createFabricFs(this.sandbox);
121
+ this.sandboxPromise = this.createSandbox();
122
+ this.fs = createFabricFs(() => this.sandboxPromise);
115
123
  this.costBudget = new CostBudgetTracker(options.costLimit);
116
124
  }
117
125
  getDurableRuntime() {
@@ -130,14 +138,37 @@ export class StubFabricSession {
130
138
  const options = ambientSignal
131
139
  ? { ...promptOptions, signal: ambientSignal }
132
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
+ }
133
150
  const durable = await this.getDurableRuntime();
134
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
+ }
135
160
  // Delegate to the durable runtime; the runtime is responsible for
136
161
  // recording entries / events on its own side. We still emit a single
137
162
  // local prompt_start/end pair so local subscribers see activity.
138
163
  await this.emit("prompt_start", { text });
139
164
  try {
140
- 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
+ });
141
172
  await this.emit("prompt_end", { text });
142
173
  return result;
143
174
  }
@@ -146,15 +177,121 @@ export class StubFabricSession {
146
177
  throw error;
147
178
  }
148
179
  }
149
- 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);
150
181
  const promptSubscriber = options.onEvent;
151
182
  if (promptSubscriber)
152
183
  this.eventSubscribers.add(promptSubscriber);
184
+ let dynamic = this.options.dynamic;
153
185
  try {
154
- await this.repairDanglingToolCalls();
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;
293
+ await this.repairDanglingToolCalls(tools, sandbox, options.signal);
155
294
  await this.emit("prompt_start", { text, ...(role ? { role: role.name } : {}) });
156
- const sandbox = createScopedSandboxEnv(await this.sandbox, options.cwd);
157
- const tools = this.resolveTools(sandbox, options.tools, options.commands);
158
295
  // Submission-correlated prompts are idempotent by submission id: a
159
296
  // recovered attempt whose input entry already landed (crash after the
160
297
  // canonical write) resumes from history instead of double-applying.
@@ -162,21 +299,46 @@ export class StubFabricSession {
162
299
  if (options.submission) {
163
300
  const prior = await this.history();
164
301
  const submissionId = options.submission.submissionId;
165
- inputAlreadyApplied = (prior.entries ?? []).some((entry) => entry.type === "user_prompt" &&
302
+ inputAlreadyApplied = (prior.entries ?? []).some((entry) => (entry.type === "user_prompt" || entry.type === "signal") &&
166
303
  entry.data?.submissionId === submissionId);
167
304
  }
168
305
  if (!inputAlreadyApplied) {
169
- await this.recordEntry("user_prompt", {
170
- text,
171
- ...(role ? { role: role.name } : {}),
172
- ...(options.submission ? { submissionId: options.submission.submissionId } : {}),
173
- });
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
+ }
174
319
  }
175
320
  // Input-applied boundary: the canonical input entry is durable and no
176
321
  // provider work has started. The submission runner's input-applied
177
322
  // marker CAS hangs off this callback; its failure aborts the turn
178
323
  // (the attempt lost ownership).
179
324
  await options.submission?.onInputApplied?.();
325
+ if (dynamic) {
326
+ const submissionId = options.submission?.submissionId;
327
+ const dynamicPath = SessionHistory.fromData(await this.history()).getActivePath();
328
+ const belongsToSubmission = (entry) => submissionId === undefined || entry.data?.submissionId === submissionId;
329
+ const responseStarted = dynamicPath.some((entry) => entry.type === "response_metadata" && entry.data?.phase === "start" && belongsToSubmission(entry));
330
+ const agentStarted = dynamicPath.some((entry) => entry.type === "agent_lifecycle" && entry.data?.phase === "start" && belongsToSubmission(entry));
331
+ if (!inputAlreadyApplied || !responseStarted) {
332
+ await dynamic.runResponseStart(undefined, submissionCorrelation);
333
+ }
334
+ if (!inputAlreadyApplied || !agentStarted) {
335
+ await dynamic.runAgentStart({
336
+ ...(options.signal ? { signal: options.signal } : {}),
337
+ sandbox,
338
+ ...submissionCorrelation,
339
+ });
340
+ }
341
+ }
180
342
  const sessionData = await this.history();
181
343
  let messages = buildModelMessagesFromHistory(sessionData, role);
182
344
  if (!messages.some((message) => message.role === "user" && message.content === text))
@@ -186,7 +348,12 @@ export class StubFabricSession {
186
348
  const results = await this.executeToolCalls(options.toolCalls, tools, sandbox, options.policy, options.approvalTimeoutMs ?? this.options.approvalTimeoutMs, options.onApproval, undefined, options.signal);
187
349
  await this.recordEntry("result", { result: results });
188
350
  await this.emit("prompt_end", { text, result: results });
189
- return validateResult(results, options.result, options.resultExtraction);
351
+ const value = await validateResult(results, options.result, options.resultExtraction);
352
+ const finalized = await this.finalizeDynamicResult(value, responseStartLeafId);
353
+ if (finalized.continued) {
354
+ throw new Error("useAgentFinish().append() cannot continue a prompt that uses PromptOptions.toolCalls; run the normal model loop instead.");
355
+ }
356
+ return finalized.value;
190
357
  }
191
358
  // Use tool-based result extraction when a validator is provided and the caller
192
359
  // has not explicitly opted into delimiter-based extraction.
@@ -235,6 +402,72 @@ export class StubFabricSession {
235
402
  ...(useResultTools ? { resultValidator: options.result } : {}),
236
403
  agentId: this.agent.id,
237
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
+ : {}),
238
471
  executeToolCalls: (calls, policy, approvalTimeoutMs, attribution) => this.executeToolCalls(calls, tools, sandbox, policy, approvalTimeoutMs, options.onApproval, attribution, options.signal),
239
472
  recordEntry: (type, data) => this.recordEntry(type, data),
240
473
  emit: (type, data) => this.emit(type, data),
@@ -259,45 +492,63 @@ export class StubFabricSession {
259
492
  messages = buildModelMessagesFromHistory(await this.history(), role);
260
493
  result = await runRuntime();
261
494
  }
262
- // If the loop produced a validated result via finish/give_up tools, return it directly.
263
- if (result.validatedResult !== undefined) {
264
- return result.validatedResult;
265
- }
266
- const resultRetries = options.resultRetries ?? (options.result ? 1 : 0);
267
- for (let attempt = 0; attempt <= resultRetries; attempt += 1) {
268
- try {
269
- return await validateResult(result.raw, options.result, options.resultExtraction);
495
+ let continuationCount = 0;
496
+ for (;;) {
497
+ let value;
498
+ if (result.validatedResult !== undefined) {
499
+ value = result.validatedResult;
270
500
  }
271
- catch (error) {
272
- if (attempt >= resultRetries)
273
- throw error;
274
- const message = error instanceof Error ? error.message : String(error);
275
- await this.recordEntry("result_retry", {
276
- error: message,
277
- retryAttempt: attempt + 1,
278
- maxRetries: resultRetries,
279
- });
280
- await this.emit("result_retry", {
281
- error: message,
282
- retryAttempt: attempt + 1,
283
- maxRetries: resultRetries,
284
- });
285
- messages.push({
286
- role: "user",
287
- content: buildResultRetryPrompt(error, options.resultExtraction),
288
- });
289
- result = await runRuntime();
501
+ else {
502
+ const resultRetries = options.resultRetries ?? (options.result ? 1 : 0);
503
+ for (let attempt = 0; attempt <= resultRetries; attempt += 1) {
504
+ try {
505
+ value = await validateResult(result.raw, options.result, options.resultExtraction);
506
+ break;
507
+ }
508
+ catch (error) {
509
+ if (attempt >= resultRetries)
510
+ throw error;
511
+ const message = error instanceof Error ? error.message : String(error);
512
+ await this.recordEntry("result_retry", {
513
+ error: message,
514
+ retryAttempt: attempt + 1,
515
+ maxRetries: resultRetries,
516
+ });
517
+ await this.emit("result_retry", {
518
+ error: message,
519
+ retryAttempt: attempt + 1,
520
+ maxRetries: resultRetries,
521
+ });
522
+ messages.push({
523
+ role: "user",
524
+ content: buildResultRetryPrompt(error, options.resultExtraction),
525
+ });
526
+ result = await runRuntime();
527
+ }
528
+ }
290
529
  }
530
+ const finalized = await this.finalizeDynamicResult(value, responseStartLeafId, result.usage);
531
+ if (!finalized.continued)
532
+ return finalized.value;
533
+ continuationCount += 1;
534
+ if (continuationCount > 8) {
535
+ throw new Error("useAgentFinish() exceeded the maximum of 8 continuation cycles.");
536
+ }
537
+ messages = buildModelMessagesFromHistory(await this.history(), role);
538
+ messages = await this.autoCompactIfNeeded(messages, role, options);
539
+ result = await runRuntime();
291
540
  }
292
- throw new FabricError({
293
- code: "RESULT_VALIDATION_FAILED",
294
- message: "Typed result validation failed.",
295
- retryable: true,
296
- });
297
541
  }
298
542
  finally {
299
543
  if (promptSubscriber)
300
544
  this.eventSubscribers.delete(promptSubscriber);
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();
301
552
  }
302
553
  }
303
554
  async *stream(text, options = {}) {
@@ -362,6 +613,13 @@ export class StubFabricSession {
362
613
  async task(text, options = {}) {
363
614
  const durable = await this.getDurableRuntime();
364
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
+ }
365
623
  const taskId = options.id ?? `${this.id}:task-${++nextTaskId}`;
366
624
  await this.emit("task_start", { taskId, depth: 1, parentSessionId: this.id });
367
625
  try {
@@ -372,6 +630,9 @@ export class StubFabricSession {
372
630
  ...(Object.keys(taskOptions).length
373
631
  ? { options: taskOptions }
374
632
  : {}),
633
+ ...(this.options.dynamic
634
+ ? { dynamic: this.options.dynamic.executionDescriptor() }
635
+ : {}),
375
636
  });
376
637
  await this.emit("task_end", { taskId, depth: 1, parentSessionId: this.id });
377
638
  return result;
@@ -386,6 +647,15 @@ export class StubFabricSession {
386
647
  }
387
648
  }
388
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
+ }
389
659
  const depth = (options.depth ?? this.options.metadata?.taskDepth ?? 0) + 1;
390
660
  if (depth > MAX_TASK_DEPTH) {
391
661
  throw new Error(`Task nesting exceeds MAX_TASK_DEPTH (${MAX_TASK_DEPTH}). Refusing to spawn deeper child task at depth ${depth}.`);
@@ -428,9 +698,39 @@ export class StubFabricSession {
428
698
  if (options.signal)
429
699
  options.signal.addEventListener("abort", forwardAbort, { once: true });
430
700
  try {
431
- 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 = {
432
716
  ...this.options,
433
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 ?? {}),
434
734
  store: this.store,
435
735
  sandbox: await this.sandbox,
436
736
  // Propagate depth so nested tasks can enforce MAX_TASK_DEPTH.
@@ -439,8 +739,18 @@ export class StubFabricSession {
439
739
  ...(options.metadata ?? {}),
440
740
  taskDepth: depth,
441
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,
442
753
  });
443
- const result = await child.prompt(text, { ...options, signal: taskAbort.signal });
444
754
  if (taskAbort.signal.aborted)
445
755
  throw abortError();
446
756
  if (options.checkpoint) {
@@ -584,12 +894,13 @@ export class StubFabricSession {
584
894
  if (timeout !== undefined)
585
895
  execOptions.timeout = timeout;
586
896
  await this.emit("command_start", { command });
587
- 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);
588
900
  const result = policyApproved
589
901
  ? await runWithSandboxPolicyApproval(sandbox, { tool: "bash", input: { command } }, execute)
590
902
  : await execute();
591
903
  const redactedCommand = redactEnvValues(command, options.env);
592
- const toolCallId = `shell-${Date.now()}`;
593
904
  await this.recordEntry("user_prompt", { text: `Run shell command: ${redactedCommand}` });
594
905
  await this.recordEntry("tool_call", {
595
906
  tool: "bash",
@@ -1094,7 +1405,12 @@ export class StubFabricSession {
1094
1405
  error,
1095
1406
  ...(call.id ? { id: call.id } : {}),
1096
1407
  });
1097
- 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
+ });
1098
1414
  await this.emit("error", { tool: call.tool, error, approvalRequired: true });
1099
1415
  continue;
1100
1416
  }
@@ -1107,7 +1423,12 @@ export class StubFabricSession {
1107
1423
  error,
1108
1424
  ...(call.id ? { id: call.id } : {}),
1109
1425
  });
1110
- 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
+ });
1111
1432
  await this.emit("error", { tool: call.tool, error, approvalRequired: false });
1112
1433
  continue;
1113
1434
  }
@@ -1145,7 +1466,12 @@ export class StubFabricSession {
1145
1466
  error,
1146
1467
  ...(call.id ? { id: call.id } : {}),
1147
1468
  });
1148
- 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
+ });
1149
1475
  await this.emit("error", { tool: call.tool, error, approvalRequired: true });
1150
1476
  continue;
1151
1477
  }
@@ -1162,7 +1488,12 @@ export class StubFabricSession {
1162
1488
  error,
1163
1489
  ...(call.id ? { id: call.id } : {}),
1164
1490
  });
1165
- 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
+ });
1166
1497
  await this.emit("error", { tool: call.tool, error, approvalRequired: false });
1167
1498
  continue;
1168
1499
  }
@@ -1170,7 +1501,12 @@ export class StubFabricSession {
1170
1501
  await this.recordEntry("tool_call", {
1171
1502
  tool: call.tool,
1172
1503
  input: call.input,
1504
+ inputDigest: approvalInputDigest(call.input),
1505
+ policyDigest: approvalInputDigest(policy ?? null),
1506
+ ...(executingPrincipal ? { executingPrincipal: executingPrincipal } : {}),
1507
+ ...(approvalGrant ? { approval: approvalGrantToJson(approvalGrant) } : {}),
1173
1508
  ...(tool?.metadata?.effect ? { effect: tool.metadata.effect } : {}),
1509
+ ...(tool?.durable ? { durable: true } : {}),
1174
1510
  toolCallId,
1175
1511
  ...(attribution ? { attribution: attribution } : {}),
1176
1512
  });
@@ -1186,7 +1522,12 @@ export class StubFabricSession {
1186
1522
  error,
1187
1523
  ...(call.id ? { id: call.id } : {}),
1188
1524
  });
1189
- 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
+ });
1190
1531
  await this.emit("tool_end", {
1191
1532
  tool: call.tool,
1192
1533
  error,
@@ -1197,21 +1538,48 @@ export class StubFabricSession {
1197
1538
  try {
1198
1539
  const input = call.tool === "bash" ? this.clampBashToolInput(call.input, policy) : call.input;
1199
1540
  const startedAt = Date.now();
1541
+ const submission = currentSubmissionContext();
1200
1542
  const execute = () => Promise.resolve(tool.execute?.(input, {
1201
1543
  sandbox,
1202
1544
  toolCallId,
1203
1545
  ...(signal ? { signal } : {}),
1546
+ onOrphanSettled: (settlement) => this.recordSandboxOrphanSettlement(call.tool, toolCallId, settlement),
1204
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),
1552
+ ...(tool.durable ? { step: this.createToolStep(toolCallId) } : {}),
1553
+ log: this.createToolProgressLogger(call.tool, toolCallId),
1554
+ harness: { sandbox },
1555
+ ...(submission
1556
+ ? {
1557
+ __fabricSubmission: {
1558
+ submissionId: submission.submissionId,
1559
+ attemptId: submission.attemptId,
1560
+ },
1561
+ }
1562
+ : {}),
1205
1563
  }));
1206
- const output = await approvedSandboxCalls.reduceRight((next, approvedCall) => () => runWithSandboxPolicyApproval(sandbox, approvedCall, next), execute)();
1564
+ const rawOutput = await approvedSandboxCalls.reduceRight((next, approvedCall) => () => runWithSandboxPolicyApproval(sandbox, approvedCall, next), execute)();
1565
+ const dynamicOutput = unwrapDynamicToolResult(rawOutput);
1566
+ const hookOutput = unwrapHookToolRunResult(dynamicOutput.output);
1567
+ const output = hookOutput.output;
1207
1568
  const durationMs = Date.now() - startedAt;
1208
- results.push({ tool: call.tool, input, output, ...(call.id ? { id: call.id } : {}) });
1209
- await this.recordEntry("tool_result", {
1569
+ await this.recordToolResult({
1210
1570
  tool: call.tool,
1211
1571
  output: output,
1212
1572
  durationMs,
1213
1573
  toolCallId,
1574
+ ...(hookOutput.terminate ? { terminate: true } : {}),
1214
1575
  ...(attribution ? { attribution: attribution } : {}),
1576
+ }, dynamicOutput.stateWrites);
1577
+ results.push({
1578
+ tool: call.tool,
1579
+ input,
1580
+ output,
1581
+ ...(hookOutput.terminate ? { terminate: true } : {}),
1582
+ ...(call.id ? { id: toolCallId } : {}),
1215
1583
  });
1216
1584
  await this.emit("tool_end", {
1217
1585
  tool: call.tool,
@@ -1225,9 +1593,9 @@ export class StubFabricSession {
1225
1593
  tool: call.tool,
1226
1594
  input: call.input,
1227
1595
  error: message,
1228
- ...(call.id ? { id: call.id } : {}),
1596
+ ...(call.id ? { id: toolCallId } : {}),
1229
1597
  });
1230
- await this.recordEntry("error", { tool: call.tool, error: message });
1598
+ await this.recordEntry("error", { tool: call.tool, toolCallId, error: message });
1231
1599
  await this.emit("tool_end", {
1232
1600
  tool: call.tool,
1233
1601
  error: message,
@@ -1558,17 +1926,84 @@ export class StubFabricSession {
1558
1926
  *
1559
1927
  * A crash/abort between recording a `tool_call` and its outcome leaves an
1560
1928
  * assistant tool_use with no tool_result, which providers reject on the
1561
- * next turn. For each trailing dangling call this appends a synthetic
1562
- * `tool_result` marked interrupted (never re-executes the tool — the real
1563
- * outcome is unknown), settles trailing unfinished `task_start`s, and
1929
+ * next turn. A call declared durable is re-entered with the same logical
1930
+ * call id, replaying completed `step.do()` checkpoints. Other calls receive
1931
+ * a synthetic interrupted result because their real outcome is unknown.
1932
+ * The repair also settles trailing unfinished `task_start`s and
1564
1933
  * appends one advisory `signal` entry so the model knows the previous turn
1565
1934
  * was cut short. Idempotent: a repaired window has no dangling calls.
1566
1935
  */
1567
- async repairDanglingToolCalls() {
1936
+ async repairDanglingToolCalls(tools, sandbox, signal) {
1568
1937
  for (let attempt = 0; attempt < 8; attempt += 1) {
1569
- const data = await this.history();
1570
- const path = SessionHistory.fromData(data).getActivePath();
1571
- const dangling = findTrailingDanglingToolCalls(path);
1938
+ let data = await this.history();
1939
+ let path = SessionHistory.fromData(data).getActivePath();
1940
+ let dangling = findTrailingDanglingToolCalls(path);
1941
+ for (const call of dangling) {
1942
+ const toolName = typeof call.data?.tool === "string" ? call.data.tool : undefined;
1943
+ const toolCallId = typeof call.data?.toolCallId === "string" ? call.data.toolCallId : undefined;
1944
+ const tool = toolName ? tools.get(toolName) : undefined;
1945
+ if (call.data?.durable !== true || !tool?.durable || !tool.execute || !toolCallId || !toolName) {
1946
+ continue;
1947
+ }
1948
+ await this.emit("tool_start", { tool: toolName, recovery: true, toolCallId });
1949
+ try {
1950
+ const authorization = await this.authorizeRecoveredToolCall(call, toolName, tool, toolCallId);
1951
+ const submission = currentSubmissionContext();
1952
+ const execute = () => Promise.resolve(tool.execute?.(call.data?.input, {
1953
+ sandbox,
1954
+ toolCallId,
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,
1962
+ step: this.createToolStep(toolCallId),
1963
+ log: this.createToolProgressLogger(toolName, toolCallId),
1964
+ harness: { sandbox },
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();
1977
+ const dynamicOutput = unwrapDynamicToolResult(rawOutput);
1978
+ const hookOutput = unwrapHookToolRunResult(dynamicOutput.output);
1979
+ await this.recordToolResult({
1980
+ tool: toolName,
1981
+ toolCallId,
1982
+ output: hookOutput.output,
1983
+ ...(hookOutput.terminate ? { terminate: true } : {}),
1984
+ recovered: true,
1985
+ }, dynamicOutput.stateWrites);
1986
+ await this.emit("tool_end", { tool: toolName, recovery: true, toolCallId });
1987
+ }
1988
+ catch (error) {
1989
+ const message = error instanceof Error ? error.message : String(error);
1990
+ await this.recordEntry("error", {
1991
+ tool: toolName,
1992
+ toolCallId,
1993
+ error: message,
1994
+ recovery: true,
1995
+ });
1996
+ await this.emit("tool_end", {
1997
+ tool: toolName,
1998
+ recovery: true,
1999
+ toolCallId,
2000
+ error: message,
2001
+ });
2002
+ }
2003
+ }
2004
+ data = await this.history();
2005
+ path = SessionHistory.fromData(data).getActivePath();
2006
+ dangling = findTrailingDanglingToolCalls(path);
1572
2007
  const unfinishedTasks = findTrailingUnfinishedTasks(path);
1573
2008
  if (dangling.length === 0 && unfinishedTasks.length === 0)
1574
2009
  return;
@@ -1644,6 +2079,74 @@ export class StubFabricSession {
1644
2079
  }
1645
2080
  throw new Error(`Could not repair interrupted session ${this.id}: session leaf kept changing.`);
1646
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
+ }
1647
2150
  async recordEntry(type, data) {
1648
2151
  await this.ensureData();
1649
2152
  const current = await this.store.load(this.id);
@@ -1669,6 +2172,210 @@ export class StubFabricSession {
1669
2172
  await this.store.appendEntry?.(this.id, entry);
1670
2173
  return entry;
1671
2174
  }
2175
+ async finalizeDynamicResult(value, responseStartLeafId, usage) {
2176
+ const dynamic = this.options.dynamic;
2177
+ if (!dynamic)
2178
+ return { value, continued: false };
2179
+ const submission = currentSubmissionContext();
2180
+ const submissionCorrelation = submission
2181
+ ? { submissionId: submission.submissionId, attemptId: submission.attemptId }
2182
+ : undefined;
2183
+ const history = SessionHistory.fromData(await this.history());
2184
+ const path = responseStartLeafId
2185
+ ? history.getActivePathSince(responseStartLeafId)
2186
+ : history.getActivePath();
2187
+ const results = new Map();
2188
+ const errors = new Map();
2189
+ for (const entry of path) {
2190
+ const id = typeof entry.data?.toolCallId === "string" ? entry.data.toolCallId : undefined;
2191
+ if (!id)
2192
+ continue;
2193
+ if (entry.type === "tool_result")
2194
+ results.set(id, entry);
2195
+ if (entry.type === "error")
2196
+ errors.set(id, entry);
2197
+ }
2198
+ const responseId = path.findLast((entry) => entry.type === "assistant_message" ||
2199
+ entry.type === "tool_result" ||
2200
+ entry.type === "error")?.id;
2201
+ const response = {
2202
+ ...(responseId ? { responseId } : {}),
2203
+ result: value,
2204
+ ...(usage ? { usage: usage } : {}),
2205
+ toolCalls: path.flatMap((entry) => {
2206
+ if (entry.type !== "tool_call")
2207
+ return [];
2208
+ const id = typeof entry.data?.toolCallId === "string" ? entry.data.toolCallId : undefined;
2209
+ const tool = typeof entry.data?.tool === "string" ? entry.data.tool : "unknown";
2210
+ const outcome = id ? results.get(id) : undefined;
2211
+ const failure = id ? errors.get(id) : undefined;
2212
+ return [
2213
+ {
2214
+ tool,
2215
+ ...(id ? { toolCallId: id } : {}),
2216
+ ...(outcome?.data && "output" in outcome.data ? { output: outcome.data.output } : {}),
2217
+ ...(outcome?.data?.isError === true
2218
+ ? { error: String(outcome.data.output ?? "Tool failed") }
2219
+ : failure?.data?.error !== undefined
2220
+ ? { error: String(failure.data.error) }
2221
+ : {}),
2222
+ },
2223
+ ];
2224
+ }),
2225
+ };
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,
2246
+ });
2247
+ }
2248
+ else {
2249
+ await this.createSignalEntry(signal);
2250
+ }
2251
+ }
2252
+ if (appended.length === 0) {
2253
+ await dynamic.runResponseFinish(response, submissionCorrelation);
2254
+ }
2255
+ return { value, continued: appended.length > 0 };
2256
+ }
2257
+ createToolStep(toolCallId) {
2258
+ const used = new Set();
2259
+ return {
2260
+ do: async (name, run) => {
2261
+ if (!name || typeof name !== "string") {
2262
+ throw new Error("Durable tool step names must be non-empty strings.");
2263
+ }
2264
+ if (used.has(name)) {
2265
+ throw new Error(`Durable tool step name was reused in one call: ${name}`);
2266
+ }
2267
+ used.add(name);
2268
+ const entryId = toolStepEntryId(toolCallId, name);
2269
+ const existing = SessionHistory.fromData(await this.store.load(this.id))
2270
+ .getActivePath()
2271
+ .find((entry) => entry.id === entryId && entry.type === "tool_step");
2272
+ if (existing?.data && "value" in existing.data)
2273
+ return existing.data.value;
2274
+ const value = normalizeDurableValue(await run(), `Durable tool step "${name}"`);
2275
+ await this.ensureData();
2276
+ const current = await this.store.load(this.id);
2277
+ const submission = currentSubmissionContext();
2278
+ const entry = {
2279
+ id: entryId,
2280
+ type: "tool_step",
2281
+ timestamp: new Date().toISOString(),
2282
+ ...(current?.leafId ? { parentId: current.leafId } : {}),
2283
+ ...(this.options.actor ? { actor: this.options.actor } : {}),
2284
+ ...(this.options.tenantId ? { tenantId: this.options.tenantId } : {}),
2285
+ data: {
2286
+ toolCallId,
2287
+ name,
2288
+ value,
2289
+ ...(submission ? { submissionId: submission.submissionId, attemptId: submission.attemptId } : {}),
2290
+ },
2291
+ };
2292
+ await this.store.appendEntry?.(this.id, entry);
2293
+ return value;
2294
+ },
2295
+ };
2296
+ }
2297
+ createToolProgressLogger(tool, toolCallId) {
2298
+ const write = (level, message, data) => {
2299
+ void this.recordEntry("metric", {
2300
+ kind: "tool_progress",
2301
+ level,
2302
+ tool,
2303
+ toolCallId,
2304
+ message,
2305
+ ...(data ? { data } : {}),
2306
+ });
2307
+ void this.emit("metric", { kind: "tool_progress", level, tool, toolCallId, message });
2308
+ };
2309
+ return {
2310
+ info: (message, data) => write("info", message, data),
2311
+ warn: (message, data) => write("warn", message, data),
2312
+ error: (message, data) => write("error", message, data),
2313
+ };
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
+ }
2335
+ async recordToolResult(data, stateWrites) {
2336
+ if (stateWrites.length === 0) {
2337
+ await this.recordEntry("tool_result", data);
2338
+ return;
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
+ }
2343
+ await this.ensureData();
2344
+ for (let attempt = 0; attempt < 8; attempt += 1) {
2345
+ const current = await this.store.load(this.id);
2346
+ const timestamp = new Date().toISOString();
2347
+ const stateEntries = dynamicStateEntriesForTool({
2348
+ sessionId: this.id,
2349
+ toolCallId: data.toolCallId,
2350
+ ...(current?.leafId ? { parentId: current.leafId } : {}),
2351
+ timestamp,
2352
+ ...(this.options.actor ? { actor: this.options.actor } : {}),
2353
+ ...(this.options.tenantId ? { tenantId: this.options.tenantId } : {}),
2354
+ }, stateWrites);
2355
+ const submission = currentSubmissionContext();
2356
+ const parentId = stateEntries.at(-1)?.id ?? current?.leafId;
2357
+ const resultEntry = {
2358
+ id: `${this.id}-entry-${Date.now()}-${randomUUID()}`,
2359
+ type: "tool_result",
2360
+ timestamp,
2361
+ ...(parentId ? { parentId } : {}),
2362
+ ...(this.options.actor ? { actor: this.options.actor } : {}),
2363
+ ...(this.options.tenantId ? { tenantId: this.options.tenantId } : {}),
2364
+ data: {
2365
+ ...data,
2366
+ ...(submission ? { submissionId: submission.submissionId, attemptId: submission.attemptId } : {}),
2367
+ },
2368
+ };
2369
+ const committed = await this.store.appendEntries(this.id, [...stateEntries, resultEntry], {
2370
+ expectedLeafId: current?.leafId,
2371
+ });
2372
+ if (committed) {
2373
+ this.options.dynamic?.acknowledgeStateWrites(stateWrites);
2374
+ return;
2375
+ }
2376
+ }
2377
+ throw new Error(`Could not atomically commit tool result and dynamic state for ${data.toolCallId}.`);
2378
+ }
1672
2379
  async emit(type, data) {
1673
2380
  await this.ensureData();
1674
2381
  const event = {
@@ -1905,6 +2612,26 @@ function isAbortError(error) {
1905
2612
  return (error instanceof Error &&
1906
2613
  (error.name === "AbortError" || /aborted|cancelled|canceled/i.test(error.message)));
1907
2614
  }
2615
+ function sameFabricActor(a, b) {
2616
+ return approvalInputDigest(a ?? null) === approvalInputDigest(b ?? null);
2617
+ }
2618
+ function toolStepEntryId(toolCallId, name) {
2619
+ return `tool-step:${encodeURIComponent(toolCallId)}:${encodeURIComponent(name)}`;
2620
+ }
2621
+ function normalizeDurableValue(value, label) {
2622
+ if (value === undefined)
2623
+ throw new Error(`${label} cannot be undefined.`);
2624
+ let encoded;
2625
+ try {
2626
+ encoded = JSON.stringify(value);
2627
+ }
2628
+ catch (error) {
2629
+ throw new Error(`${label} is not JSON-serializable: ${error instanceof Error ? error.message : String(error)}`);
2630
+ }
2631
+ if (encoded === undefined)
2632
+ throw new Error(`${label} is not JSON-serializable.`);
2633
+ return JSON.parse(encoded);
2634
+ }
1908
2635
  function wrapWithPolicy(env, policy, bypass) {
1909
2636
  if (bypass === true)
1910
2637
  return env;