@fabric-harness/sdk 6.9.0 → 6.10.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 (106) hide show
  1. package/dist/agent.d.ts.map +1 -1
  2. package/dist/agent.js +8 -0
  3. package/dist/agent.js.map +1 -1
  4. package/dist/channel-runtime.d.ts +2 -0
  5. package/dist/channel-runtime.d.ts.map +1 -1
  6. package/dist/channel-runtime.js +1 -0
  7. package/dist/channel-runtime.js.map +1 -1
  8. package/dist/channel.d.ts +11 -0
  9. package/dist/channel.d.ts.map +1 -1
  10. package/dist/channel.js.map +1 -1
  11. package/dist/context.d.ts +28 -0
  12. package/dist/context.d.ts.map +1 -1
  13. package/dist/context.js +18 -0
  14. package/dist/context.js.map +1 -1
  15. package/dist/conversation-ownership.d.ts +151 -0
  16. package/dist/conversation-ownership.d.ts.map +1 -0
  17. package/dist/conversation-ownership.js +239 -0
  18. package/dist/conversation-ownership.js.map +1 -0
  19. package/dist/dispatch.d.ts +7 -0
  20. package/dist/dispatch.d.ts.map +1 -1
  21. package/dist/dispatch.js.map +1 -1
  22. package/dist/dynamic-agent.d.ts.map +1 -1
  23. package/dist/dynamic-agent.js +8 -0
  24. package/dist/dynamic-agent.js.map +1 -1
  25. package/dist/error.d.ts +1 -1
  26. package/dist/error.d.ts.map +1 -1
  27. package/dist/error.js.map +1 -1
  28. package/dist/experimental.d.ts +6 -5
  29. package/dist/experimental.d.ts.map +1 -1
  30. package/dist/experimental.js +5 -3
  31. package/dist/experimental.js.map +1 -1
  32. package/dist/governed-voice.d.ts.map +1 -1
  33. package/dist/governed-voice.js +5 -0
  34. package/dist/governed-voice.js.map +1 -1
  35. package/dist/index.d.ts +8 -1
  36. package/dist/index.d.ts.map +1 -1
  37. package/dist/index.js +4 -1
  38. package/dist/index.js.map +1 -1
  39. package/dist/loop.d.ts +8 -0
  40. package/dist/loop.d.ts.map +1 -1
  41. package/dist/loop.js +22 -1
  42. package/dist/loop.js.map +1 -1
  43. package/dist/model-pricing.js +1 -1
  44. package/dist/model-pricing.js.map +1 -1
  45. package/dist/model.d.ts +20 -2
  46. package/dist/model.d.ts.map +1 -1
  47. package/dist/model.js +88 -9
  48. package/dist/model.js.map +1 -1
  49. package/dist/persistent-agent.d.ts +1 -1
  50. package/dist/persistent-agent.d.ts.map +1 -1
  51. package/dist/persistent-agent.js.map +1 -1
  52. package/dist/pi-loop-runtime.d.ts.map +1 -1
  53. package/dist/pi-loop-runtime.js +142 -8
  54. package/dist/pi-loop-runtime.js.map +1 -1
  55. package/dist/policied-sandbox.d.ts +9 -3
  56. package/dist/policied-sandbox.d.ts.map +1 -1
  57. package/dist/policied-sandbox.js +290 -54
  58. package/dist/policied-sandbox.js.map +1 -1
  59. package/dist/policy.d.ts +3 -3
  60. package/dist/policy.d.ts.map +1 -1
  61. package/dist/policy.js +115 -64
  62. package/dist/policy.js.map +1 -1
  63. package/dist/proposal-tool.d.ts +260 -0
  64. package/dist/proposal-tool.d.ts.map +1 -0
  65. package/dist/proposal-tool.js +562 -0
  66. package/dist/proposal-tool.js.map +1 -0
  67. package/dist/sandbox-ref.d.ts +2 -2
  68. package/dist/sandbox-ref.d.ts.map +1 -1
  69. package/dist/sandbox-ref.js +143 -70
  70. package/dist/sandbox-ref.js.map +1 -1
  71. package/dist/sandbox.d.ts +8 -0
  72. package/dist/sandbox.d.ts.map +1 -1
  73. package/dist/sandbox.js +22 -1
  74. package/dist/sandbox.js.map +1 -1
  75. package/dist/session.d.ts +71 -3
  76. package/dist/session.d.ts.map +1 -1
  77. package/dist/session.js +590 -160
  78. package/dist/session.js.map +1 -1
  79. package/dist/stop-reason-guard.d.ts +89 -0
  80. package/dist/stop-reason-guard.d.ts.map +1 -0
  81. package/dist/stop-reason-guard.js +261 -0
  82. package/dist/stop-reason-guard.js.map +1 -0
  83. package/dist/strict.d.ts +8 -1
  84. package/dist/strict.d.ts.map +1 -1
  85. package/dist/strict.js +4 -1
  86. package/dist/strict.js.map +1 -1
  87. package/dist/suspending-sandbox.d.ts +2 -2
  88. package/dist/suspending-sandbox.d.ts.map +1 -1
  89. package/dist/suspending-sandbox.js +65 -26
  90. package/dist/suspending-sandbox.js.map +1 -1
  91. package/dist/tools.d.ts +17 -3
  92. package/dist/tools.d.ts.map +1 -1
  93. package/dist/tools.js +104 -48
  94. package/dist/tools.js.map +1 -1
  95. package/dist/types.d.ts +20 -0
  96. package/dist/types.d.ts.map +1 -1
  97. package/dist/types.js.map +1 -1
  98. package/dist/voice-pipeline.d.ts +67 -0
  99. package/dist/voice-pipeline.d.ts.map +1 -1
  100. package/dist/voice-pipeline.js +350 -20
  101. package/dist/voice-pipeline.js.map +1 -1
  102. package/dist/voice-sentences.d.ts +43 -0
  103. package/dist/voice-sentences.d.ts.map +1 -0
  104. package/dist/voice-sentences.js +99 -0
  105. package/dist/voice-sentences.js.map +1 -0
  106. package/package.json +30 -13
package/dist/session.js CHANGED
@@ -1,32 +1,33 @@
1
1
  import { createHash, randomUUID } from "node:crypto";
2
+ import path from "node:path";
3
+ import { abandonToolOnAbort } from "./abort.js";
4
+ import { approvalGrantFromJson, approvalGrantFromState, approvalGrantToJson, approvalInputDigest, createApprovalGrant, sameApprovalOperation, } from "./approval.js";
5
+ import { BoundedInMemoryAttachmentStore } from "./attachment-store.js";
6
+ import { estimateSessionEntryTokens, evaluateContextBudget, isContextOverflowError, } from "./context-budget.js";
2
7
  import { CostBudgetTracker } from "./cost-budget.js";
3
- import { inMemorySessionMemory } from "./session-memory.js";
8
+ import { deliveredSignalToEntryData, renderDeliveredMessage } from "./delivered-message.js";
9
+ import { dynamicStateEntriesForTool, unwrapDynamicToolResult } from "./dynamic-agent.js";
4
10
  import { FabricError } from "./error.js";
5
- import { abandonToolOnAbort } from "./abort.js";
6
- import { executeTool } from "./tool-execution.js";
11
+ import { createFabricFs } from "./filesystem.js";
7
12
  import { openGovernedVoice, } from "./governed-voice.js";
8
- import { dynamicStateEntriesForTool, unwrapDynamicToolResult } from "./dynamic-agent.js";
9
- import { approvalGrantFromJson, approvalGrantFromState, approvalGrantToJson, approvalInputDigest, createApprovalGrant, sameApprovalOperation, } from "./approval.js";
10
13
  import { SessionHistory, buildModelMessagesFromHistory, findTrailingDanglingToolCalls, findTrailingUnfinishedTasks, } from "./history.js";
11
14
  import { getLogger } from "./logger.js";
12
15
  import { defaultLoopRuntime } from "./loop.js";
13
- import { SessionStreamRecovery } from "./session-stream-recovery.js";
14
16
  import { defaultModelProvider, generateWithRuntime } from "./model.js";
15
- import { canonicalizeToolCall, clampCommandTimeout, evaluateCommandPolicy, evaluateToolCallPolicy, } from "./policy.js";
16
- import { buildResultRetryPrompt, validateResult } from "./result.js";
17
- import { estimateSessionEntryTokens, evaluateContextBudget, isContextOverflowError, } from "./context-budget.js";
18
- import { policiedSandboxEnv, runWithSandboxPolicyApproval } from "./policied-sandbox.js";
19
- import { currentSubmissionContext } from "./submission-context.js";
20
- import { deliveredSignalToEntryData, renderDeliveredMessage } from "./delivered-message.js";
21
- import { BoundedInMemoryAttachmentStore } from "./attachment-store.js";
17
+ import { evaluateToolCallPolicyInSandbox, policiedSandboxEnv, runWithSandboxPolicyApproval, } from "./policied-sandbox.js";
18
+ import { canonicalizeToolCall, clampCommandTimeout, evaluateCommandPolicy } from "./policy.js";
22
19
  import { createAttachmentHydrationBudget, hydrateModelMessageAttachments, preparePromptAttachments, recordsToModelAttachments, validatePromptAttachments, } from "./prompt-attachments.js";
23
- import { createSandboxEnv, createScopedSandboxEnv, execSandboxCommand } from "./sandbox.js";
24
- import { createFabricFs } from "./filesystem.js";
20
+ import { buildResultRetryPrompt, validateResult } from "./result.js";
25
21
  import { registerSandbox, serializeSandboxRef, unregisterSandbox } from "./sandbox-ref.js";
26
- import path from "node:path";
27
- import { defaultSessionStore } from "./store.js";
28
- import { createActivateSkillTool, createBuiltinTools, createCommandTools, shellQuote, unwrapHookToolRunResult, } from "./tools.js";
22
+ import { createSandboxEnv, createScopedSandboxEnv, execSandboxCommand } from "./sandbox.js";
23
+ import { inMemorySessionMemory } from "./session-memory.js";
24
+ import { SessionStreamRecovery } from "./session-stream-recovery.js";
29
25
  import { formatPackagedSkillResourceList, readPackagedSkillFile } from "./skills.js";
26
+ import { defaultSessionStore } from "./store.js";
27
+ import { currentSubmissionContext } from "./submission-context.js";
28
+ import { executeTool } from "./tool-execution.js";
29
+ import { assertProposalToolConfiguration, classifyTools, createProposalCallTracker, isProposalTool, proposalApprovalRuleReason, proposalConfigurationError, proposalTranscriptRecord, unknownResult, } from "./proposal-tool.js";
30
+ import { createActivateSkillTool, createBuiltinTools, createCommandTools, hasScopedCommandRenderer, renderScopedCommand, shellQuote, unwrapHookToolRunResult, } from "./tools.js";
30
31
  import { MAX_TASK_DEPTH } from "./types.js";
31
32
  let nextTaskId = 0;
32
33
  const CROCKFORD_ALPHABET = "0123456789ABCDEFGHJKMNPQRSTVWXYZ";
@@ -129,6 +130,12 @@ export class StubFabricSession {
129
130
  options;
130
131
  store;
131
132
  eventSubscribers = new Set();
133
+ /**
134
+ * The proposal tools of each tool map `resolveTools()` returned, decided
135
+ * once at resolution (#274). Dispatch and recovery read only this: a tool
136
+ * not found here runs as an ordinary tool, whatever its `execute` is later.
137
+ */
138
+ resolvedProposals = new WeakMap();
132
139
  durableRuntime;
133
140
  mounts = [];
134
141
  /** Set when this session has registered its sandbox in the in-process ref registry. */
@@ -148,6 +155,11 @@ export class StubFabricSession {
148
155
  this.id = id;
149
156
  this.options = options;
150
157
  this.store = options.store ?? defaultSessionStore;
158
+ // Session start: a proposal tool the policy would gate, that has no
159
+ // authority, or that shares a name is refused before anything runs. Each
160
+ // prompt and dynamic render checks again with its effective policy.
161
+ if (options.tools?.some(isProposalTool))
162
+ this.resolveTools([], [], options.policy);
151
163
  this.sandboxPromise = this.createSandbox();
152
164
  this.fs = createFabricFs(() => this.sandboxPromise);
153
165
  this.costBudget = new CostBudgetTracker(options.costLimit);
@@ -197,6 +209,17 @@ export class StubFabricSession {
197
209
  idPrefix: submissionId ? `att_${submissionId}` : `att_prompt_${randomUUID()}`,
198
210
  });
199
211
  }
212
+ /**
213
+ * A durable runtime receives neither this session's or the call's tools nor
214
+ * its proposal authority, so a proposal tool would silently not be offered.
215
+ * Refused here, called immediately before each delegation (prompt, task).
216
+ */
217
+ refuseProposalToolsOnDurableRuntime(callTools) {
218
+ const delegated = [...(this.options.tools ?? []), ...(callTools ?? [])].find((tool) => isProposalTool(tool));
219
+ if (delegated) {
220
+ throw proposalConfigurationError(delegated.name, "cannot run on a durable session runtime: the runtime does not receive this session's tools or its proposal authority. Run proposal tools in an inline session.");
221
+ }
222
+ }
200
223
  getDurableRuntime() {
201
224
  if (this.durableRuntime)
202
225
  return this.durableRuntime;
@@ -277,14 +300,18 @@ export class StubFabricSession {
277
300
  publicMessage: "Inline attachments are not supported by the configured durable runtime.",
278
301
  });
279
302
  }
303
+ this.refuseProposalToolsOnDurableRuntime(options.tools);
280
304
  // Delegate to the durable runtime; the runtime is responsible for
281
305
  // recording entries / events on its own side. We still emit a single
282
306
  // local prompt_start/end pair so local subscribers see activity.
283
307
  await this.emit("prompt_start", { text });
284
308
  try {
309
+ // Checked again here: a prompt_start subscriber ran since the first check.
310
+ this.refuseProposalToolsOnDurableRuntime(options.tools);
311
+ const forwardedPolicy = this.durablePolicy(options.policy);
285
312
  const result = await durable.prompt({
286
313
  text,
287
- ...(options ? { options } : {}),
314
+ options: this.durablePromptOptions(options, forwardedPolicy),
288
315
  ...(this.options.dynamic ? { dynamic: this.options.dynamic.executionDescriptor() } : {}),
289
316
  });
290
317
  await this.emit("prompt_end", { text });
@@ -303,7 +330,7 @@ export class StubFabricSession {
303
330
  const lifecycleSignal = options.signal ?? new AbortController().signal;
304
331
  try {
305
332
  let sandbox = createScopedSandboxEnv(await this.sandbox, options.cwd);
306
- let tools = this.resolveTools(sandbox, options.tools, options.commands);
333
+ let tools = this.resolveTools(options.tools, options.commands, options.policy ?? this.options.policy);
307
334
  let joinedRenderReady = false;
308
335
  const currentTurnConfiguration = () => ({
309
336
  ...(typeof this.options.model === "string" ? { model: this.options.model } : {}),
@@ -392,7 +419,7 @@ export class StubFabricSession {
392
419
  }
393
420
  role = this.resolveRole(this.options.role);
394
421
  }
395
- tools = this.resolveTools(sandbox, options.tools, options.commands);
422
+ tools = this.resolveTools(options.tools, options.commands, options.policy ?? this.options.policy);
396
423
  if (!config.dynamic) {
397
424
  throw new Error("[fabric-harness] A dynamic-agent refresh did not return its runtime.");
398
425
  }
@@ -568,6 +595,9 @@ export class StubFabricSession {
568
595
  ...(options.modelRetryDelayMs !== undefined
569
596
  ? { modelRetryDelayMs: options.modelRetryDelayMs }
570
597
  : {}),
598
+ ...((options.stopReasonGuard ?? this.options.stopReasonGuard) !== undefined
599
+ ? { stopReasonGuard: options.stopReasonGuard ?? this.options.stopReasonGuard }
600
+ : {}),
571
601
  ...(options.signal !== undefined ? { signal: options.signal } : {}),
572
602
  ...(options.policy !== undefined ? { policy: options.policy } : {}),
573
603
  ...((options.approvalTimeoutMs ?? this.options.approvalTimeoutMs) !== undefined
@@ -873,10 +903,15 @@ export class StubFabricSession {
873
903
  publicMessage: "Inline attachments are not supported by the configured durable runtime.",
874
904
  });
875
905
  }
906
+ this.refuseProposalToolsOnDurableRuntime(options.tools);
876
907
  const taskId = options.id ?? `${this.id}:task-${++nextTaskId}`;
877
908
  await this.emit("task_start", { taskId, depth: 1, parentSessionId: this.id });
878
909
  try {
879
- const { id: _id, ...taskOptions } = options;
910
+ // Checked again here: a task_start subscriber ran since the first check.
911
+ this.refuseProposalToolsOnDurableRuntime(options.tools);
912
+ const { id: _id, ...requestedTaskOptions } = options;
913
+ const forwardedPolicy = this.durablePolicy(options.policy);
914
+ const taskOptions = this.durablePromptOptions(requestedTaskOptions, forwardedPolicy);
880
915
  const result = await durable.task({
881
916
  text,
882
917
  taskId,
@@ -997,6 +1032,13 @@ export class StubFabricSession {
997
1032
  // instructions, model, and capabilities.
998
1033
  if (delegatedRole)
999
1034
  Reflect.deleteProperty(childOptions, "dynamic");
1035
+ // A policy the caller set on this session, or on the task itself, stays
1036
+ // explicit for the child, so the child's dynamic refresh cannot replace it.
1037
+ const childExplicitPolicy = options.policy ?? explicitSessionPolicies.get(this.options);
1038
+ if (childExplicitPolicy !== undefined) {
1039
+ childOptions.policy = childExplicitPolicy;
1040
+ markExplicitSessionPolicy(childOptions, childExplicitPolicy);
1041
+ }
1000
1042
  const child = new StubFabricSession(this.agent, taskId, childOptions);
1001
1043
  const result = await child.prompt(text, {
1002
1044
  ...childPromptOptions,
@@ -1094,7 +1136,11 @@ export class StubFabricSession {
1094
1136
  const durable = await this.getDurableRuntime();
1095
1137
  if (durable) {
1096
1138
  await this.emit("command_start", { command });
1097
- const result = await durable.shell({ command, ...(options ? { options } : {}) });
1139
+ const forwardedPolicy = this.durablePolicy(options.policy, false);
1140
+ const result = await durable.shell({
1141
+ command,
1142
+ options: forwardedPolicy !== undefined ? { ...options, policy: forwardedPolicy } : options,
1143
+ });
1098
1144
  await this.emit("command_end", { command, exitCode: result.exitCode });
1099
1145
  return result;
1100
1146
  }
@@ -1292,6 +1338,7 @@ export class StubFabricSession {
1292
1338
  const sandboxFork = sandbox.fork;
1293
1339
  const agent = this.agent;
1294
1340
  const baseOptions = this.options;
1341
+ const baseExplicitPolicy = explicitSessionPolicies.get(this.options);
1295
1342
  await this.recordEntry("checkpoint_created", {
1296
1343
  label: label ?? `fork:${snapshot.id}`,
1297
1344
  ...(label ? { metadata: { fork: true } } : { metadata: { fork: true } }),
@@ -1320,6 +1367,13 @@ export class StubFabricSession {
1320
1367
  ...(label !== undefined ? { forkLabel: label } : {}),
1321
1368
  },
1322
1369
  };
1370
+ // attach() creates a session like agent.session() does: a policy passed
1371
+ // here, else the origin's explicit one, outranks a dynamic agent's render.
1372
+ const explicitPolicy = attachOptions.policy ?? baseExplicitPolicy;
1373
+ if (explicitPolicy !== undefined) {
1374
+ merged.policy = explicitPolicy;
1375
+ markExplicitSessionPolicy(merged, explicitPolicy);
1376
+ }
1323
1377
  return new StubFabricSession(agent, newId, merged);
1324
1378
  },
1325
1379
  };
@@ -1679,6 +1733,43 @@ export class StubFabricSession {
1679
1733
  ...(isSnapshot(snapshot) ? { snapshotId: snapshot.id } : {}),
1680
1734
  };
1681
1735
  }
1736
+ /**
1737
+ * The sandbox a tool sees under `policy`. The session's sandbox already
1738
+ * enforces the policy it was created with; this layers the call's effective
1739
+ * policy on top, so the two intersect and a call can narrow, never widen.
1740
+ */
1741
+ sandboxUnderPolicy(sandbox, policy) {
1742
+ return wrapWithPolicy(sandbox, policy, this.options.bypassPolicyEnforcement);
1743
+ }
1744
+ /**
1745
+ * The policy forwarded to a durable runtime: the call's, else the session's
1746
+ * (which `agent.session()` fills from the agent's), so the worker enforces
1747
+ * call over session over agent rather than its own default. A dynamic
1748
+ * agent's rendered policy is re-rendered by the runtime, so for one only a
1749
+ * policy the caller set on the session is forwarded.
1750
+ */
1751
+ /**
1752
+ * Prompt options forwarded to a durable runtime, with the policy above and
1753
+ * the resolved `stopReasonGuard` (call over session over agent), so a
1754
+ * setting made on `init()` or `agent.session()` reaches the worker's loop.
1755
+ */
1756
+ durablePromptOptions(options, policy) {
1757
+ const stopReasonGuard = options.stopReasonGuard ?? this.options.stopReasonGuard;
1758
+ return {
1759
+ ...options,
1760
+ ...(policy !== undefined ? { policy } : {}),
1761
+ ...(stopReasonGuard !== undefined ? { stopReasonGuard } : {}),
1762
+ };
1763
+ }
1764
+ durablePolicy(callPolicy, reRendered = true) {
1765
+ if (callPolicy !== undefined)
1766
+ return callPolicy;
1767
+ // Only prompts and tasks re-render a dynamic agent on the worker; a
1768
+ // shell call does not, so it carries the rendered policy itself.
1769
+ if (this.options.dynamic && reRendered)
1770
+ return explicitSessionPolicies.get(this.options);
1771
+ return this.options.policy;
1772
+ }
1682
1773
  async createSandbox() {
1683
1774
  const sandbox = this.options.sandbox;
1684
1775
  let env;
@@ -1698,11 +1789,17 @@ export class StubFabricSession {
1698
1789
  const scoped = createScopedSandboxEnv(env, this.options.cwd);
1699
1790
  return wrapWithPolicy(scoped, this.options.policy, this.options.bypassPolicyEnforcement);
1700
1791
  }
1701
- async executeToolCalls(calls, tools, sandbox, callPolicy, approvalTimeoutMs, approvalHandler, attribution, signal, prepareOutput, recordToolCall) {
1792
+ async executeToolCalls(calls, tools, sessionSandbox, callPolicy, approvalTimeoutMs, approvalHandler, attribution, signal, prepareOutput, recordToolCall) {
1702
1793
  const results = [];
1703
1794
  const policy = callPolicy ?? this.options.policy;
1795
+ // Tools get the sandbox under the call's effective policy, layered over
1796
+ // the session's, so a narrower prompt policy reaches `context.sandbox`.
1797
+ const sandbox = this.sandboxUnderPolicy(sessionSandbox, policy);
1704
1798
  for (const requestedCall of calls) {
1705
1799
  const tool = tools.get(requestedCall.tool);
1800
+ // Decided when these tools were resolved, and never derived again from
1801
+ // the definition: a tool not classified then runs as an ordinary tool.
1802
+ const proposal = this.resolvedProposal(tools, requestedCall.tool, tool);
1706
1803
  const canonical = canonicalizeToolCall({
1707
1804
  ...requestedCall,
1708
1805
  tool: tool?.policyAlias ?? requestedCall.tool,
@@ -1722,51 +1819,86 @@ export class StubFabricSession {
1722
1819
  }
1723
1820
  const approvedSandboxCalls = [];
1724
1821
  let approvalGrant;
1822
+ const approvalGrants = [];
1823
+ // A scoped command tool's command, rendered once: the same command is
1824
+ // judged, shown to the approver, recorded and granted to the sandbox.
1825
+ const renderedCommand = renderScopedCommand(tool, call.input);
1826
+ const boundCommand = hasScopedCommandRenderer(tool)
1827
+ ? renderedCommand
1828
+ : (renderedCommand ?? this.commandTextForApproval(tool, call.input));
1725
1829
  const executingPrincipal = toolExecutingPrincipal(tool);
1726
1830
  const mountDecision = this.checkMountWriteAccess(call);
1727
- const policyCall = tool?.policyAlias ? { ...call, tool: tool.policyAlias } : call;
1728
- const decision = mountDecision ?? evaluateToolCallPolicy(policyCall, policy);
1729
- if (!decision.allowed) {
1730
- if (decision.approvalRequired) {
1731
- const grant = await this.requestApproval({
1732
- kind: "tool",
1733
- tool: call.tool,
1734
- toolCallId,
1735
- ...(executingPrincipal ? { executingPrincipal } : {}),
1736
- input: call.input,
1737
- reason: decision.reason ?? `Approval required for tool: ${call.tool}`,
1738
- ...(decision.risk ? { risk: decision.risk } : {}),
1739
- ...(decision.matchedPattern ? { matchedPattern: decision.matchedPattern } : {}),
1740
- ...(decision.approvalAudience ? { audience: decision.approvalAudience } : {}),
1741
- ...(decision.approvalTtlSeconds !== undefined
1742
- ? { ttlSeconds: decision.approvalTtlSeconds }
1743
- : {}),
1744
- affectedPaths: affectedPathsFromInput(call.input),
1745
- }, policy, approvalTimeoutMs, approvalHandler);
1746
- if (grant) {
1747
- approvalGrant = grant;
1748
- approvedSandboxCalls.push(policyCall);
1749
- }
1750
- else {
1751
- const error = decision.reason ?? `Approval required for tool call: ${call.tool}`;
1752
- results.push({
1753
- tool: call.tool,
1754
- input: call.input,
1755
- error,
1756
- ...(call.id ? { id: call.id } : {}),
1757
- });
1758
- await this.recordEntry("error", {
1759
- tool: call.tool,
1760
- toolCallId,
1761
- error,
1762
- approvalRequired: true,
1763
- });
1764
- await this.emit("error", { tool: call.tool, error, approvalRequired: true });
1765
- continue;
1766
- }
1831
+ // Policy judges a proposal tool by its own name; resolution refuses an alias.
1832
+ const policyCall = !proposal && tool?.policyAlias ? { ...call, tool: tool.policyAlias } : call;
1833
+ // File paths are judged in every form the sandbox reaches, as its layer
1834
+ // judges them, so an approval is asked for here when one is needed there.
1835
+ const decision = mountDecision ?? evaluateToolCallPolicyInSandbox(policyCall, policy, sandbox);
1836
+ const commandDecision = this.evaluateScopedCommandToolCall(tool, call.input, policy, renderedCommand);
1837
+ if (!decision.allowed && !decision.approvalRequired) {
1838
+ const error = decision.reason ?? `Tool call denied by policy: ${call.tool}`;
1839
+ results.push({
1840
+ tool: call.tool,
1841
+ input: call.input,
1842
+ error,
1843
+ ...(call.id ? { id: call.id } : {}),
1844
+ });
1845
+ await this.recordEntry("error", {
1846
+ tool: call.tool,
1847
+ toolCallId,
1848
+ error,
1849
+ approvalRequired: false,
1850
+ });
1851
+ await this.emit("error", { tool: call.tool, error, approvalRequired: false });
1852
+ continue;
1853
+ }
1854
+ if (!commandDecision.allowed && !commandDecision.approvalRequired) {
1855
+ const error = commandDecision.reason ?? `Command denied by policy: ${call.tool}`;
1856
+ results.push({
1857
+ tool: call.tool,
1858
+ input: call.input,
1859
+ error,
1860
+ ...(call.id ? { id: call.id } : {}),
1861
+ });
1862
+ await this.recordEntry("error", {
1863
+ tool: call.tool,
1864
+ toolCallId,
1865
+ error,
1866
+ approvalRequired: false,
1867
+ });
1868
+ await this.emit("error", { tool: call.tool, error, approvalRequired: false });
1869
+ continue;
1870
+ }
1871
+ if (!decision.allowed && decision.approvalRequired) {
1872
+ // Policy wins: a proposal tool matched by an approval rule here (a
1873
+ // call-level policy from a custom loop) is refused, never prompted.
1874
+ if (proposal) {
1875
+ await this.refuseProposalCall(call, toolCallId, proposalApprovalRuleReason(decision.matchedPattern), results);
1876
+ continue;
1877
+ }
1878
+ const grant = await this.requestApproval({
1879
+ kind: "tool",
1880
+ tool: call.tool,
1881
+ subject: call.tool,
1882
+ toolCallId,
1883
+ ...(executingPrincipal ? { executingPrincipal } : {}),
1884
+ ...(boundCommand !== undefined ? { command: boundCommand } : {}),
1885
+ input: call.input,
1886
+ reason: decision.reason ?? `Approval required for tool: ${call.tool}`,
1887
+ ...(decision.risk ? { risk: decision.risk } : {}),
1888
+ ...(decision.matchedPattern ? { matchedPattern: decision.matchedPattern } : {}),
1889
+ ...(decision.approvalAudience ? { audience: decision.approvalAudience } : {}),
1890
+ ...(decision.approvalTtlSeconds !== undefined
1891
+ ? { ttlSeconds: decision.approvalTtlSeconds }
1892
+ : {}),
1893
+ affectedPaths: affectedPathsFromInput(call.input, call.tool),
1894
+ }, policy, approvalTimeoutMs, approvalHandler);
1895
+ if (grant) {
1896
+ approvalGrant = grant;
1897
+ approvalGrants.push(grant);
1898
+ approvedSandboxCalls.push(policyCall);
1767
1899
  }
1768
1900
  else {
1769
- const error = decision.reason ?? `Tool call denied by policy: ${call.tool}`;
1901
+ const error = decision.reason ?? `Approval required for tool call: ${call.tool}`;
1770
1902
  results.push({
1771
1903
  tool: call.tool,
1772
1904
  input: call.input,
@@ -1777,61 +1909,41 @@ export class StubFabricSession {
1777
1909
  tool: call.tool,
1778
1910
  toolCallId,
1779
1911
  error,
1780
- approvalRequired: false,
1912
+ approvalRequired: true,
1781
1913
  });
1782
- await this.emit("error", { tool: call.tool, error, approvalRequired: false });
1914
+ await this.emit("error", { tool: call.tool, error, approvalRequired: true });
1783
1915
  continue;
1784
1916
  }
1785
1917
  }
1786
- const commandDecision = this.evaluateScopedCommandToolCall(tool, call.input, policy);
1787
- if (!commandDecision.allowed) {
1788
- if (commandDecision.approvalRequired) {
1789
- const command = this.commandTextForApproval(tool, call.input);
1790
- const grant = await this.requestApproval({
1791
- kind: "command",
1792
- tool: call.tool,
1793
- toolCallId,
1794
- ...(executingPrincipal ? { executingPrincipal } : {}),
1795
- ...(command ? { command } : {}),
1796
- input: call.input,
1797
- reason: commandDecision.reason ?? `Approval required for command: ${call.tool}`,
1798
- ...(commandDecision.risk ? { risk: commandDecision.risk } : {}),
1799
- ...(commandDecision.matchedPattern
1800
- ? { matchedPattern: commandDecision.matchedPattern }
1801
- : {}),
1802
- ...(commandDecision.approvalAudience
1803
- ? { audience: commandDecision.approvalAudience }
1804
- : {}),
1805
- ...(commandDecision.approvalTtlSeconds !== undefined
1806
- ? { ttlSeconds: commandDecision.approvalTtlSeconds }
1807
- : {}),
1808
- envKeys: commandEnvKeys(tool),
1809
- affectedPaths: affectedPathsFromInput(call.input),
1810
- }, policy, approvalTimeoutMs, approvalHandler);
1811
- if (!grant) {
1812
- const error = commandDecision.reason ?? `Approval required for command: ${call.tool}`;
1813
- results.push({
1814
- tool: call.tool,
1815
- input: call.input,
1816
- error,
1817
- ...(call.id ? { id: call.id } : {}),
1818
- });
1819
- await this.recordEntry("error", {
1820
- tool: call.tool,
1821
- toolCallId,
1822
- error,
1823
- approvalRequired: true,
1824
- });
1825
- await this.emit("error", { tool: call.tool, error, approvalRequired: true });
1826
- continue;
1827
- }
1828
- approvalGrant = grant;
1829
- const approvedCommand = this.commandTextForApproval(tool, call.input);
1830
- if (approvedCommand)
1831
- approvedSandboxCalls.push({ tool: "bash", input: { command: approvedCommand } });
1918
+ if (!commandDecision.allowed && commandDecision.approvalRequired) {
1919
+ if (proposal) {
1920
+ await this.refuseProposalCall(call, toolCallId, proposalApprovalRuleReason(commandDecision.matchedPattern), results);
1921
+ continue;
1832
1922
  }
1833
- else {
1834
- const error = commandDecision.reason ?? `Command denied by policy: ${call.tool}`;
1923
+ // The approval names the exact command the tool will run.
1924
+ const grant = await this.requestApproval({
1925
+ kind: "command",
1926
+ tool: call.tool,
1927
+ toolCallId,
1928
+ ...(executingPrincipal ? { executingPrincipal } : {}),
1929
+ ...(boundCommand !== undefined ? { command: boundCommand } : {}),
1930
+ input: call.input,
1931
+ reason: commandDecision.reason ?? `Approval required for command: ${call.tool}`,
1932
+ ...(commandDecision.risk ? { risk: commandDecision.risk } : {}),
1933
+ ...(commandDecision.matchedPattern
1934
+ ? { matchedPattern: commandDecision.matchedPattern }
1935
+ : {}),
1936
+ ...(commandDecision.approvalAudience
1937
+ ? { audience: commandDecision.approvalAudience }
1938
+ : {}),
1939
+ ...(commandDecision.approvalTtlSeconds !== undefined
1940
+ ? { ttlSeconds: commandDecision.approvalTtlSeconds }
1941
+ : {}),
1942
+ envKeys: commandEnvKeys(tool),
1943
+ affectedPaths: affectedPathsFromInput(call.input, call.tool),
1944
+ }, policy, approvalTimeoutMs, approvalHandler);
1945
+ if (!grant) {
1946
+ const error = commandDecision.reason ?? `Approval required for command: ${call.tool}`;
1835
1947
  results.push({
1836
1948
  tool: call.tool,
1837
1949
  input: call.input,
@@ -1842,23 +1954,40 @@ export class StubFabricSession {
1842
1954
  tool: call.tool,
1843
1955
  toolCallId,
1844
1956
  error,
1845
- approvalRequired: false,
1957
+ approvalRequired: true,
1846
1958
  });
1847
- await this.emit("error", { tool: call.tool, error, approvalRequired: false });
1959
+ await this.emit("error", { tool: call.tool, error, approvalRequired: true });
1848
1960
  continue;
1849
1961
  }
1962
+ approvalGrant = grant;
1963
+ approvalGrants.push(grant);
1964
+ // The sandbox grant names the exact command the tool will run.
1965
+ // A metadata-only command tool runs its command itself; the grant
1966
+ // names the command its approval described.
1967
+ if (boundCommand !== undefined)
1968
+ approvedSandboxCalls.push({ tool: "bash", input: { command: boundCommand } });
1850
1969
  }
1851
- await (recordToolCall ?? ((data) => this.recordEntry("tool_call", data)))({
1970
+ const toolCallEntry = await (recordToolCall ?? ((data) => this.recordEntry("tool_call", data)))({
1852
1971
  tool: call.tool,
1853
1972
  input: call.input,
1854
1973
  inputDigest: approvalInputDigest(call.input),
1855
1974
  policyDigest: approvalInputDigest(policy ?? null),
1975
+ // Harness-set from the resolution-time classification: recovery settles
1976
+ // a trailing dangling call carrying it as unknown and does not run it
1977
+ // again. A call hidden behind a later turn boundary (a signal, say)
1978
+ // is outside the trailing window and is not settled by recovery.
1979
+ ...(proposal ? { proposal: { actionId: proposal.runner.actionId } } : {}),
1856
1980
  ...(executingPrincipal
1857
1981
  ? { executingPrincipal: executingPrincipal }
1858
1982
  : {}),
1859
1983
  ...(approvalGrant ? { approval: approvalGrantToJson(approvalGrant) } : {}),
1984
+ ...(approvalGrants.length > 0
1985
+ ? { approvals: approvalGrants.map(approvalGrantToJson) }
1986
+ : {}),
1860
1987
  ...(tool?.metadata?.effect ? { effect: tool.metadata.effect } : {}),
1861
1988
  ...(tool?.durable ? { durable: true } : {}),
1989
+ // Recovery grants a scoped command only if it still renders this command.
1990
+ ...(tool?.durable && boundCommand !== undefined ? { renderedCommand: boundCommand } : {}),
1862
1991
  toolCallId,
1863
1992
  ...(attribution ? { attribution: attribution } : {}),
1864
1993
  });
@@ -1871,6 +2000,18 @@ export class StubFabricSession {
1871
2000
  ...(effectiveInput !== undefined ? { input: effectiveInput } : {}),
1872
2001
  ...(attribution ? { attribution: attribution } : {}),
1873
2002
  });
2003
+ if (proposal) {
2004
+ await this.executeProposalCall({
2005
+ call,
2006
+ proposal,
2007
+ toolCallId,
2008
+ sandbox,
2009
+ results,
2010
+ ...(signal ? { signal } : {}),
2011
+ ...(attribution ? { attribution: attribution } : {}),
2012
+ });
2013
+ continue;
2014
+ }
1874
2015
  if (!tool?.execute) {
1875
2016
  const error = `Tool is not available: ${call.tool}`;
1876
2017
  results.push({
@@ -1900,6 +2041,7 @@ export class StubFabricSession {
1900
2041
  const agentName = this.agent.name ?? submission?.agent;
1901
2042
  const execute = () => Promise.resolve(executeTool(tool, input, {
1902
2043
  sandbox,
2044
+ ...(renderedCommand !== undefined ? { __fabricScopedCommand: renderedCommand } : {}),
1903
2045
  toolCallId,
1904
2046
  ...(signal ? { signal } : {}),
1905
2047
  onOrphanSettled: (settlement) => this.recordSandboxOrphanSettlement(call.tool, toolCallId, settlement),
@@ -2174,9 +2316,22 @@ export class StubFabricSession {
2174
2316
  onCredentialMissing: this.options.autonomy?.onCredentialMissing ?? "fail",
2175
2317
  };
2176
2318
  }
2177
- evaluateScopedCommandToolCall(tool, input, policy) {
2319
+ evaluateScopedCommandToolCall(tool, input, policy, rendered) {
2320
+ if (hasScopedCommandRenderer(tool)) {
2321
+ if (rendered === undefined) {
2322
+ return {
2323
+ allowed: false,
2324
+ reason: `Failed to render command for tool: ${tool?.name ?? "unknown"}`,
2325
+ };
2326
+ }
2327
+ return evaluateCommandPolicy(rendered, policy);
2328
+ }
2178
2329
  if (tool?.metadata?.kind !== "command" || typeof tool.metadata.command !== "string")
2179
2330
  return { allowed: true };
2331
+ // The exact command the tool will run (executable, default arguments,
2332
+ // buildArgs, quoting), as the sandbox layer will judge it.
2333
+ if (rendered !== undefined)
2334
+ return evaluateCommandPolicy(rendered, policy);
2180
2335
  const args = typeof input === "object" &&
2181
2336
  input !== null &&
2182
2337
  Array.isArray(input.args)
@@ -2193,7 +2348,8 @@ export class StubFabricSession {
2193
2348
  Array.isArray(input.args)
2194
2349
  ? input.args.filter((value) => typeof value === "string")
2195
2350
  : [];
2196
- return [tool.metadata.command, ...args].join(" ");
2351
+ // Quoted as evaluateScopedCommandToolCall judges it and the tool runs it.
2352
+ return [tool.metadata.command, ...args.map(shellQuote)].join(" ");
2197
2353
  }
2198
2354
  clampBashToolInput(input, policy) {
2199
2355
  if (!policy?.maxCommandTimeoutMs || typeof input !== "object" || input === null)
@@ -2202,29 +2358,63 @@ export class StubFabricSession {
2202
2358
  const timeout = typeof record.timeout === "number" ? record.timeout : undefined;
2203
2359
  return { ...record, timeout: clampCommandTimeout(timeout, policy) };
2204
2360
  }
2205
- resolveTools(sandbox, promptTools = [], promptCommands = []) {
2206
- const tools = new Map();
2361
+ /**
2362
+ * Combine the session's and the prompt's tools. Later definitions replace
2363
+ * earlier ones of the same name. `policy` is the effective policy the tools
2364
+ * will run under: proposal tools are checked against it here. Each tool is
2365
+ * classified here, once, and the proposal tools are kept with the returned
2366
+ * map for dispatch and recovery (#274).
2367
+ */
2368
+ resolveTools(promptTools, promptCommands, policy) {
2369
+ const ordered = [];
2207
2370
  const commandToolOptions = this.options.resolveSecret
2208
2371
  ? { resolveSecret: this.options.resolveSecret }
2209
2372
  : {};
2210
- for (const tool of createBuiltinTools(sandbox, this.effectivePackagedSkills()))
2211
- tools.set(tool.name, tool);
2212
- for (const tool of createCommandTools(this.options.commands ?? [], commandToolOptions))
2213
- tools.set(tool.name, tool);
2214
- for (const tool of this.options.tools ?? [])
2215
- tools.set(tool.name, tool);
2216
- for (const tool of createCommandTools(promptCommands ?? [], commandToolOptions))
2217
- tools.set(tool.name, tool);
2218
- for (const tool of promptTools)
2219
- tools.set(tool.name, tool);
2373
+ // Built-ins run on the sandbox each call is handed (`context.sandbox`),
2374
+ // which carries that call's effective policy, not one captured here.
2375
+ // One push per tool: a spread argument list has an engine limit, and the
2376
+ // base resolved lists of any length.
2377
+ for (const list of [
2378
+ createBuiltinTools(undefined, this.effectivePackagedSkills()),
2379
+ createCommandTools(this.options.commands ?? [], commandToolOptions),
2380
+ this.options.tools ?? [],
2381
+ createCommandTools(promptCommands ?? [], commandToolOptions),
2382
+ promptTools ?? [],
2383
+ ]) {
2384
+ for (const tool of list)
2385
+ ordered.push(tool);
2386
+ }
2220
2387
  const skills = this.options.skills ?? [];
2221
2388
  if (skills.length > 0) {
2222
2389
  const skillNames = skills.map((skill) => skill.name);
2223
- const activateSkillTool = createActivateSkillTool(skillNames, (name) => this.activateSkillForTool(name));
2224
- tools.set(activateSkillTool.name, activateSkillTool);
2390
+ ordered.push(createActivateSkillTool(skillNames, (name) => this.activateSkillForTool(name)));
2225
2391
  }
2392
+ const classified = classifyTools(ordered);
2393
+ const authority = this.options.proposalAuthority;
2394
+ assertProposalToolConfiguration({ tools: classified, policy, authority });
2395
+ const tools = new Map();
2396
+ for (const tool of ordered)
2397
+ tools.set(tool.name, tool);
2398
+ const proposals = new Map();
2399
+ for (const { tool, runner } of classified) {
2400
+ // The configuration check above refused a proposal tool without an
2401
+ // authority or sharing its name, so each one is its name's only tool.
2402
+ if (runner && authority)
2403
+ proposals.set(tool.name, { tool, runner, authority });
2404
+ }
2405
+ if (proposals.size > 0)
2406
+ this.resolvedProposals.set(tools, proposals);
2226
2407
  return tools;
2227
2408
  }
2409
+ /**
2410
+ * The resolution-time classification of `tool`, found in `tools` under
2411
+ * `name`, if it was classified a proposal tool. A definition that replaced
2412
+ * the classified one in the map afterwards is not a proposal tool.
2413
+ */
2414
+ resolvedProposal(tools, name, tool) {
2415
+ const resolved = this.resolvedProposals.get(tools)?.get(name);
2416
+ return resolved !== undefined && resolved.tool === tool ? resolved : undefined;
2417
+ }
2228
2418
  async activateSkillForTool(name) {
2229
2419
  const cached = this.skillCache.get(name);
2230
2420
  if (cached !== undefined)
@@ -2370,10 +2560,11 @@ export class StubFabricSession {
2370
2560
  * appends one advisory `signal` entry so the model knows the previous turn
2371
2561
  * was cut short. Idempotent: a repaired window has no dangling calls.
2372
2562
  */
2373
- async repairDanglingToolCalls(tools, sandbox, signal,
2563
+ async repairDanglingToolCalls(tools, sessionSandbox, signal,
2374
2564
  /** The resuming prompt's policy; the session's applies when absent. */
2375
2565
  promptPolicy) {
2376
2566
  const recoveryPolicy = promptPolicy ?? this.options.policy;
2567
+ const sandbox = this.sandboxUnderPolicy(sessionSandbox, recoveryPolicy);
2377
2568
  for (let attempt = 0; attempt < 8; attempt += 1) {
2378
2569
  let data = await this.history();
2379
2570
  let path = SessionHistory.fromData(data).getActivePath();
@@ -2381,12 +2572,23 @@ export class StubFabricSession {
2381
2572
  for (const call of dangling) {
2382
2573
  const toolName = typeof call.data?.tool === "string" ? call.data.tool : undefined;
2383
2574
  const toolCallId = typeof call.data?.toolCallId === "string" ? call.data.toolCallId : undefined;
2575
+ // A proposal call carries the harness's marker on its tool_call entry.
2576
+ // It is settled as unknown, from the marker alone: it is never run
2577
+ // again, the port is not called, and the current tool of that name,
2578
+ // if any, is not consulted.
2579
+ if (call.data?.proposal !== undefined && toolName && toolCallId) {
2580
+ await this.settleRecoveredProposal(call, toolName, toolCallId);
2581
+ continue;
2582
+ }
2384
2583
  const tool = toolName ? tools.get(toolName) : undefined;
2385
2584
  if (call.data?.durable !== true ||
2386
2585
  !tool?.durable ||
2387
2586
  !tool.execute ||
2388
2587
  !toolCallId ||
2389
- !toolName) {
2588
+ !toolName ||
2589
+ // An unmarked call never runs through a tool that is now a proposal
2590
+ // tool; it is settled below like any call that cannot be re-entered.
2591
+ this.resolvedProposal(tools, toolName, tool) !== undefined) {
2390
2592
  continue;
2391
2593
  }
2392
2594
  await this.emit("tool_start", {
@@ -2397,11 +2599,18 @@ export class StubFabricSession {
2397
2599
  });
2398
2600
  const recoveryStartedAt = performance.now();
2399
2601
  try {
2400
- const authorization = await this.authorizeRecoveredToolCall(call, toolName, tool, toolCallId, recoveryPolicy);
2602
+ // Rendered once: authorised, compared with the recorded command, run.
2603
+ const scoped = renderScopedCommand(tool, call.data?.input);
2604
+ // A metadata-only command tool runs the command its approval described.
2605
+ const rendered = hasScopedCommandRenderer(tool)
2606
+ ? scoped
2607
+ : (scoped ?? this.commandTextForApproval(tool, call.data?.input));
2608
+ const authorization = await this.authorizeRecoveredToolCall(call, toolName, tool, toolCallId, recoveryPolicy, sandbox, scoped, rendered);
2401
2609
  const submission = currentSubmissionContext();
2402
2610
  const agentName = this.agent.name ?? submission?.agent;
2403
2611
  const execute = () => Promise.resolve(executeTool(tool, call.data?.input, {
2404
2612
  sandbox,
2613
+ ...(scoped !== undefined ? { __fabricScopedCommand: scoped } : {}),
2405
2614
  toolCallId,
2406
2615
  ...(signal ? { signal } : {}),
2407
2616
  onOrphanSettled: (settlement) => this.recordSandboxOrphanSettlement(toolName, toolCallId, settlement),
@@ -2425,10 +2634,15 @@ export class StubFabricSession {
2425
2634
  }
2426
2635
  : {}),
2427
2636
  }));
2428
- const approvedCall = authorization.approvedCall;
2429
- const rawOutput = await abandonToolOnAbort(approvedCall
2430
- ? () => runWithSandboxPolicyApproval(sandbox, approvedCall, execute)
2431
- : execute, signal);
2637
+ // Only re-grant the sandbox gate(s) whose persisted approvals were
2638
+ // verified against the active policy and recorded command.
2639
+ const approvedCalls = [
2640
+ ...(authorization.approvedToolCall ? [authorization.approvedToolCall] : []),
2641
+ ...(authorization.approvedCommand !== undefined
2642
+ ? [{ tool: "bash", input: { command: authorization.approvedCommand } }]
2643
+ : []),
2644
+ ];
2645
+ const rawOutput = await abandonToolOnAbort(approvedCalls.reduceRight((next, granted) => () => runWithSandboxPolicyApproval(sandbox, granted, next), execute), signal);
2432
2646
  const dynamicOutput = unwrapDynamicToolResult(rawOutput);
2433
2647
  const hookOutput = unwrapHookToolRunResult(dynamicOutput.output);
2434
2648
  const recoveryDurationMs = Math.max(0, Math.round(performance.now() - recoveryStartedAt));
@@ -2550,7 +2764,7 @@ export class StubFabricSession {
2550
2764
  }
2551
2765
  throw new Error(`Could not repair interrupted session ${this.id}: session leaf kept changing.`);
2552
2766
  }
2553
- async authorizeRecoveredToolCall(call, toolName, tool, toolCallId, policy) {
2767
+ async authorizeRecoveredToolCall(call, toolName, tool, toolCallId, policy, sandbox, scopedCommand, expectedCommand) {
2554
2768
  const input = call.data?.input;
2555
2769
  const inputDigest = approvalInputDigest(input);
2556
2770
  if (call.data?.inputDigest !== inputDigest) {
@@ -2572,11 +2786,10 @@ export class StubFabricSession {
2572
2786
  input,
2573
2787
  id: toolCallId,
2574
2788
  };
2575
- const decisions = [
2576
- this.checkMountWriteAccess({ tool: toolName, input, id: toolCallId }) ??
2577
- evaluateToolCallPolicy(policyCall, policy),
2578
- this.evaluateScopedCommandToolCall(tool, input, policy),
2579
- ];
2789
+ const toolDecision = this.checkMountWriteAccess({ tool: toolName, input, id: toolCallId }) ??
2790
+ evaluateToolCallPolicyInSandbox(policyCall, policy, sandbox);
2791
+ const commandDecision = this.evaluateScopedCommandToolCall(tool, input, policy, scopedCommand);
2792
+ const decisions = [toolDecision, commandDecision];
2580
2793
  const denied = decisions.find((decision) => !decision.allowed && !decision.approvalRequired);
2581
2794
  if (denied) {
2582
2795
  throw new FabricError({
@@ -2584,12 +2797,28 @@ export class StubFabricSession {
2584
2797
  message: denied.reason ?? `Recovered tool ${toolName} is denied by the current policy.`,
2585
2798
  });
2586
2799
  }
2800
+ if ((expectedCommand !== undefined || call.data?.renderedCommand !== undefined) &&
2801
+ call.data?.renderedCommand !== expectedCommand) {
2802
+ throw new FabricError({
2803
+ code: "POLICY_DENIED",
2804
+ message: `Recovered tool ${toolName} renders a different command than the recorded call.`,
2805
+ });
2806
+ }
2587
2807
  const requiresApproval = decisions.some((decision) => decision.approvalRequired);
2588
2808
  if (!requiresApproval)
2589
2809
  return { inputDigest, policyDigest };
2590
- const grant = approvalGrantFromJson(call.data?.approval);
2810
+ const rawApprovals = Array.isArray(call.data?.approvals)
2811
+ ? call.data.approvals
2812
+ : call.data?.approval !== undefined
2813
+ ? [call.data.approval]
2814
+ : [];
2815
+ const grants = rawApprovals
2816
+ .map((item) => approvalGrantFromJson(item))
2817
+ .filter((item) => item !== undefined);
2591
2818
  const principal = toolExecutingPrincipal(tool) ?? this.approvalPrincipal();
2592
- if (!grant || !sameApprovalOperation(grant, { toolCallId, toolInput: input, principal })) {
2819
+ if (grants.length === 0 ||
2820
+ rawApprovals.length !== grants.length ||
2821
+ grants.some((grant) => !sameApprovalOperation(grant, { toolCallId, toolInput: input, principal }))) {
2593
2822
  throw new FabricError({
2594
2823
  code: "POLICY_DENIED",
2595
2824
  message: `Recovered tool ${toolName} requires a current approval bound to this call and principal.`,
@@ -2598,22 +2827,41 @@ export class StubFabricSession {
2598
2827
  if (!this.store.getApprovalState) {
2599
2828
  throw new FabricError({
2600
2829
  code: "POLICY_DENIED",
2601
- message: `Recovered tool ${toolName} cannot prove that approval ${grant.approvalId} remains valid.`,
2830
+ message: `Recovered tool ${toolName} cannot prove that approval ${grants[0]?.approvalId ?? ""} remains valid.`,
2602
2831
  });
2603
2832
  }
2604
- const state = await this.store.getApprovalState(this.id, grant.approvalId);
2605
- const currentGrant = state
2606
- ? approvalGrantFromState(state, input, principal, toolCallId)
2607
- : undefined;
2608
- if (!currentGrant) {
2833
+ const verifiedStates = [];
2834
+ const verifiedGrants = [];
2835
+ for (const grant of grants) {
2836
+ const state = await this.store.getApprovalState(this.id, grant.approvalId);
2837
+ const currentGrant = state
2838
+ ? approvalGrantFromState(state, input, principal, toolCallId)
2839
+ : undefined;
2840
+ if (!state || !currentGrant) {
2841
+ throw new FabricError({
2842
+ code: "POLICY_DENIED",
2843
+ message: `Recovered tool ${toolName} approval is expired, denied, revoked, or unavailable.`,
2844
+ });
2845
+ }
2846
+ verifiedStates.push(state);
2847
+ verifiedGrants.push(currentGrant);
2848
+ }
2849
+ const hasToolApproval = verifiedStates.some((state) => state.request.kind === "tool");
2850
+ const hasCommandApproval = verifiedStates.some((state) => state.request.kind === "command");
2851
+ if ((toolDecision.approvalRequired && !hasToolApproval) ||
2852
+ (commandDecision.approvalRequired && !hasCommandApproval)) {
2609
2853
  throw new FabricError({
2610
2854
  code: "POLICY_DENIED",
2611
- message: `Recovered tool ${toolName} approval is expired, denied, revoked, or unavailable.`,
2855
+ message: `Recovered tool ${toolName} does not have an approval covering the active policy gate.`,
2612
2856
  });
2613
2857
  }
2858
+ const latestGrant = verifiedGrants.at(-1);
2614
2859
  return {
2615
- approval: currentGrant,
2616
- approvedCall: policyCall,
2860
+ ...(latestGrant ? { approval: latestGrant } : {}),
2861
+ ...(hasToolApproval ? { approvedToolCall: policyCall } : {}),
2862
+ ...(hasCommandApproval && expectedCommand !== undefined
2863
+ ? { approvedCommand: expectedCommand }
2864
+ : {}),
2617
2865
  inputDigest,
2618
2866
  policyDigest,
2619
2867
  };
@@ -2729,6 +2977,145 @@ export class StubFabricSession {
2729
2977
  }
2730
2978
  return { value, continued: appended.length > 0 };
2731
2979
  }
2980
+ /**
2981
+ * Run one proposal call through the SDK-owned runner kept with the resolved
2982
+ * tool, and settle it once. On the normal path this code writes no entry of
2983
+ * its own between the call's tool_call entry and its tool_result. A failure
2984
+ * after the port was called settles as a non-error `unknown` result; a
2985
+ * failure before it is an ordinary error. This path attempts the result
2986
+ * write once, unconditionally, as an ordinary tool does: if it fails, the
2987
+ * error propagates, and a later prompt that finds the call trailing and
2988
+ * dangling settles it as unknown. If a second prompt starts while the
2989
+ * proposal is still in flight, that prompt can settle the call as unknown
2990
+ * first and this path then appends the real result, so the call ends with
2991
+ * two results; the port is still called at most once. Known and tracked in
2992
+ * https://github.com/Fabric-Pro/fabric-harness/issues/335.
2993
+ */
2994
+ async executeProposalCall(input) {
2995
+ const { call, proposal, toolCallId, results, attribution } = input;
2996
+ const tracker = createProposalCallTracker({
2997
+ sessionId: this.id,
2998
+ ...(this.options.tenantId !== undefined ? { tenantId: this.options.tenantId } : {}),
2999
+ ...(this.options.actor !== undefined ? { actor: this.options.actor } : {}),
3000
+ authority: proposal.authority,
3001
+ });
3002
+ const startedAt = performance.now();
3003
+ let result;
3004
+ let failure;
3005
+ try {
3006
+ // No progress logger: it writes transcript entries of its own, which
3007
+ // would land between this call's tool_call and its tool_result.
3008
+ await executeTool(proposalDispatchTool(proposal, tracker.binding), call.input, {
3009
+ sandbox: input.sandbox,
3010
+ toolCallId,
3011
+ ...(input.signal ? { signal: input.signal } : {}),
3012
+ });
3013
+ result = tracker.outcome()?.result;
3014
+ }
3015
+ catch (error) {
3016
+ failure = error;
3017
+ }
3018
+ const durationMs = Math.max(0, Math.round(performance.now() - startedAt));
3019
+ // An abort before submission reaches here from the shared abort helper,
3020
+ // which copies the abort reason's text into an AbortError. That text is
3021
+ // not this tool's to publish: replace it with a fixed message. Errors
3022
+ // proposal-tool.ts itself throws are not AbortErrors and keep their text.
3023
+ // Matched by name: the looser isAbortError() also matches message text, and
3024
+ // a validation error that mentions "cancelled" must keep its message.
3025
+ if (failure instanceof Error &&
3026
+ failure.name === "AbortError" &&
3027
+ tracker.submittedKey() === undefined) {
3028
+ failure = new Error(`Proposal tool "${call.tool}" was cancelled before submission; nothing was submitted.`);
3029
+ }
3030
+ // A failure after the port was called (an answer that could not be read,
3031
+ // say) may still have landed: unknown, not an error.
3032
+ const submittedKey = tracker.submittedKey();
3033
+ if (result === undefined && submittedKey !== undefined)
3034
+ result = unknownResult(submittedKey);
3035
+ if (result === undefined) {
3036
+ const message = failure instanceof Error ? failure.message : String(failure);
3037
+ results.push({
3038
+ tool: call.tool,
3039
+ input: call.input,
3040
+ error: message,
3041
+ ...(call.id ? { id: toolCallId } : {}),
3042
+ });
3043
+ await this.recordEntry("error", { tool: call.tool, toolCallId, error: message });
3044
+ await deliverAfterSettlement(call.tool, () => this.emit("tool_end", {
3045
+ tool: call.tool,
3046
+ toolCallId,
3047
+ durationMs,
3048
+ error: message,
3049
+ ...(attribution ? { attribution } : {}),
3050
+ }));
3051
+ return;
3052
+ }
3053
+ const output = result;
3054
+ await this.recordToolResult({
3055
+ tool: call.tool,
3056
+ output,
3057
+ durationMs,
3058
+ toolCallId,
3059
+ // Harness-set: only the SDK-owned runner's outcome produces it.
3060
+ proposal: proposalTranscriptRecord({ actionId: proposal.runner.actionId, result }),
3061
+ ...(attribution ? { attribution } : {}),
3062
+ }, []);
3063
+ results.push({
3064
+ tool: call.tool,
3065
+ input: call.input,
3066
+ output: result,
3067
+ ...(call.id ? { id: toolCallId } : {}),
3068
+ });
3069
+ await deliverAfterSettlement(call.tool, () => this.emit("tool_end", {
3070
+ tool: call.tool,
3071
+ toolCallId,
3072
+ durationMs,
3073
+ output,
3074
+ ...(attribution ? { attribution } : {}),
3075
+ }));
3076
+ }
3077
+ /**
3078
+ * Settle a dangling proposal call after a crash, as a non-error `unknown`
3079
+ * result: the harness cannot tell whether the port was called, and it does
3080
+ * not call it again. Only the tool_call entry's marker is read.
3081
+ */
3082
+ async settleRecoveredProposal(call, toolName, toolCallId) {
3083
+ const marker = call.data?.proposal;
3084
+ const markedAction = typeof marker === "object" && marker !== null && !Array.isArray(marker)
3085
+ ? marker.actionId
3086
+ : undefined;
3087
+ const result = unknownResult();
3088
+ const output = result;
3089
+ await this.recordToolResult({
3090
+ tool: toolName,
3091
+ toolCallId,
3092
+ output,
3093
+ durationMs: 0,
3094
+ proposal: proposalTranscriptRecord({
3095
+ actionId: typeof markedAction === "string" ? markedAction : "",
3096
+ result,
3097
+ }),
3098
+ recovered: true,
3099
+ }, []);
3100
+ await deliverAfterSettlement(toolName, () => this.emit("tool_end", { tool: toolName, recovery: true, toolCallId, durationMs: 0, output }));
3101
+ }
3102
+ /** Refuse a proposal call with its configuration error; nothing is submitted. */
3103
+ async refuseProposalCall(call, toolCallId, reason, results) {
3104
+ const error = proposalConfigurationError(call.tool, reason).message;
3105
+ results.push({
3106
+ tool: call.tool,
3107
+ input: call.input,
3108
+ error,
3109
+ ...(call.id ? { id: call.id } : {}),
3110
+ });
3111
+ await this.recordEntry("error", {
3112
+ tool: call.tool,
3113
+ toolCallId,
3114
+ error,
3115
+ approvalRequired: false,
3116
+ });
3117
+ await this.emit("error", { tool: call.tool, error, approvalRequired: false });
3118
+ }
2732
3119
  createToolStep(toolCallId) {
2733
3120
  const used = new Set();
2734
3121
  return {
@@ -2887,11 +3274,28 @@ function normalizeSkillReference(value) {
2887
3274
  function stripMarkdownExtension(value) {
2888
3275
  return value.endsWith(".md") ? value.slice(0, -3) : value;
2889
3276
  }
2890
- function affectedPathsFromInput(input) {
3277
+ const SINGLE_PATH_TOOLS = new Set([
3278
+ "read",
3279
+ "read_buffer",
3280
+ "stat",
3281
+ "readdir",
3282
+ "exists",
3283
+ "grep",
3284
+ "write",
3285
+ "edit",
3286
+ "mkdir",
3287
+ "rm",
3288
+ ]);
3289
+ function affectedPathsFromInput(input, toolName) {
2891
3290
  if (typeof input !== "object" || input === null)
2892
3291
  return [];
2893
3292
  const record = input;
2894
- const paths = [record.path, record.cwd].filter((value) => typeof value === "string");
3293
+ const candidates = toolName === "glob"
3294
+ ? [record.cwd]
3295
+ : toolName !== undefined && SINGLE_PATH_TOOLS.has(toolName)
3296
+ ? [record.path]
3297
+ : [record.path, record.cwd];
3298
+ const paths = candidates.filter((value) => typeof value === "string");
2895
3299
  return [...new Set(paths)];
2896
3300
  }
2897
3301
  function commandEnvKeys(tool) {
@@ -3198,6 +3602,32 @@ function isAbortError(error) {
3198
3602
  function sameFabricActor(a, b) {
3199
3603
  return approvalInputDigest(a ?? null) === approvalInputDigest(b ?? null);
3200
3604
  }
3605
+ /** The tool the session dispatches for a proposal call: the stored SDK-owned runner, never `tool.execute`. */
3606
+ function proposalDispatchTool(proposal, binding) {
3607
+ const timeoutMs = proposal.tool.timeoutMs;
3608
+ return {
3609
+ name: proposal.tool.name,
3610
+ ...(timeoutMs !== undefined ? { timeoutMs } : {}),
3611
+ execute: (input, context) => proposal.runner.run(input, context, binding),
3612
+ };
3613
+ }
3614
+ /**
3615
+ * Run event delivery after a proposal call settled. A failing subscriber is
3616
+ * logged with a fixed label and cannot re-enter settlement.
3617
+ */
3618
+ async function deliverAfterSettlement(tool, deliver) {
3619
+ try {
3620
+ await deliver();
3621
+ }
3622
+ catch {
3623
+ try {
3624
+ getLogger().warn("tool_end delivery failed after a proposal call settled", { tool });
3625
+ }
3626
+ catch {
3627
+ // Diagnostics never decide the outcome.
3628
+ }
3629
+ }
3630
+ }
3201
3631
  function toolStepEntryId(toolCallId, name) {
3202
3632
  return `tool-step:${encodeURIComponent(toolCallId)}:${encodeURIComponent(name)}`;
3203
3633
  }