@fabric-harness/sdk 6.8.0 → 6.9.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.
- package/dist/agent.d.ts +5 -4
- package/dist/agent.d.ts.map +1 -1
- package/dist/agent.js +37 -18
- package/dist/agent.js.map +1 -1
- package/dist/dynamic-agent.d.ts +24 -19
- package/dist/dynamic-agent.d.ts.map +1 -1
- package/dist/dynamic-agent.js +402 -239
- package/dist/dynamic-agent.js.map +1 -1
- package/dist/error.d.ts +1 -1
- package/dist/error.d.ts.map +1 -1
- package/dist/error.js.map +1 -1
- package/dist/events.d.ts +5 -0
- package/dist/events.d.ts.map +1 -1
- package/dist/events.js.map +1 -1
- package/dist/experimental.d.ts +6 -5
- package/dist/experimental.d.ts.map +1 -1
- package/dist/experimental.js +5 -3
- package/dist/experimental.js.map +1 -1
- package/dist/index.d.ts +1 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +1 -1
- package/dist/index.js.map +1 -1
- package/dist/local-process.d.ts +8 -0
- package/dist/local-process.d.ts.map +1 -0
- package/dist/local-process.js +61 -0
- package/dist/local-process.js.map +1 -0
- package/dist/loop.d.ts +5 -0
- package/dist/loop.d.ts.map +1 -1
- package/dist/loop.js +18 -3
- package/dist/loop.js.map +1 -1
- package/dist/model-id.d.ts +3 -0
- package/dist/model-id.d.ts.map +1 -0
- package/dist/model-id.js +5 -0
- package/dist/model-id.js.map +1 -0
- package/dist/model-pricing.d.ts.map +1 -1
- package/dist/model-pricing.js +18 -1
- package/dist/model-pricing.js.map +1 -1
- package/dist/model.d.ts.map +1 -1
- package/dist/model.js +39 -14
- package/dist/model.js.map +1 -1
- package/dist/observability.d.ts +3 -2
- package/dist/observability.d.ts.map +1 -1
- package/dist/observability.js +42 -17
- package/dist/observability.js.map +1 -1
- package/dist/otel-observer.d.ts +2 -2
- package/dist/otel-observer.d.ts.map +1 -1
- package/dist/otel-observer.js +109 -26
- package/dist/otel-observer.js.map +1 -1
- package/dist/otel.d.ts +4 -4
- package/dist/otel.d.ts.map +1 -1
- package/dist/otel.js +28 -24
- package/dist/otel.js.map +1 -1
- package/dist/persistent-agent.d.ts +6 -6
- package/dist/persistent-agent.d.ts.map +1 -1
- package/dist/persistent-agent.js +79 -47
- package/dist/persistent-agent.js.map +1 -1
- package/dist/pi-loop-runtime.d.ts +6 -0
- package/dist/pi-loop-runtime.d.ts.map +1 -1
- package/dist/pi-loop-runtime.js +44 -22
- package/dist/pi-loop-runtime.js.map +1 -1
- package/dist/policied-sandbox.d.ts +9 -3
- package/dist/policied-sandbox.d.ts.map +1 -1
- package/dist/policied-sandbox.js +276 -53
- package/dist/policied-sandbox.js.map +1 -1
- package/dist/policy.d.ts +6 -4
- package/dist/policy.d.ts.map +1 -1
- package/dist/policy.js +123 -60
- package/dist/policy.js.map +1 -1
- package/dist/sandbox-ref.d.ts +2 -2
- package/dist/sandbox-ref.d.ts.map +1 -1
- package/dist/sandbox-ref.js +143 -70
- package/dist/sandbox-ref.js.map +1 -1
- package/dist/sandbox.d.ts +20 -12
- package/dist/sandbox.d.ts.map +1 -1
- package/dist/sandbox.js +429 -246
- package/dist/sandbox.js.map +1 -1
- package/dist/session-stream-recovery.d.ts +21 -0
- package/dist/session-stream-recovery.d.ts.map +1 -0
- package/dist/session-stream-recovery.js +115 -0
- package/dist/session-stream-recovery.js.map +1 -0
- package/dist/session.d.ts +17 -3
- package/dist/session.d.ts.map +1 -1
- package/dist/session.js +417 -182
- package/dist/session.js.map +1 -1
- package/dist/skills.d.ts +3 -1
- package/dist/skills.d.ts.map +1 -1
- package/dist/skills.js +7 -2
- package/dist/skills.js.map +1 -1
- package/dist/strict.d.ts +1 -1
- package/dist/strict.d.ts.map +1 -1
- package/dist/strict.js +1 -1
- package/dist/strict.js.map +1 -1
- package/dist/suspending-sandbox.d.ts +2 -2
- package/dist/suspending-sandbox.d.ts.map +1 -1
- package/dist/suspending-sandbox.js +65 -26
- package/dist/suspending-sandbox.js.map +1 -1
- package/dist/telemetry.d.ts +1 -1
- package/dist/telemetry.d.ts.map +1 -1
- package/dist/telemetry.js +30 -26
- package/dist/telemetry.js.map +1 -1
- package/dist/tools.d.ts +19 -3
- package/dist/tools.d.ts.map +1 -1
- package/dist/tools.js +100 -49
- package/dist/tools.js.map +1 -1
- package/dist/types.d.ts +14 -0
- package/dist/types.d.ts.map +1 -1
- package/dist/types.js.map +1 -1
- package/package.json +7 -23
package/dist/session.js
CHANGED
|
@@ -1,31 +1,32 @@
|
|
|
1
1
|
import { createHash, randomUUID } from "node:crypto";
|
|
2
|
-
import
|
|
3
|
-
import { inMemorySessionMemory } from "./session-memory.js";
|
|
4
|
-
import { FabricError } from "./error.js";
|
|
2
|
+
import path from "node:path";
|
|
5
3
|
import { abandonToolOnAbort } from "./abort.js";
|
|
6
|
-
import { executeTool } from "./tool-execution.js";
|
|
7
|
-
import { openGovernedVoice } from "./governed-voice.js";
|
|
8
|
-
import { dynamicStateEntriesForTool, unwrapDynamicToolResult } from "./dynamic-agent.js";
|
|
9
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";
|
|
7
|
+
import { CostBudgetTracker } from "./cost-budget.js";
|
|
8
|
+
import { deliveredSignalToEntryData, renderDeliveredMessage } from "./delivered-message.js";
|
|
9
|
+
import { dynamicStateEntriesForTool, unwrapDynamicToolResult } from "./dynamic-agent.js";
|
|
10
|
+
import { FabricError } from "./error.js";
|
|
11
|
+
import { createFabricFs } from "./filesystem.js";
|
|
12
|
+
import { openGovernedVoice, } from "./governed-voice.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
16
|
import { defaultModelProvider, generateWithRuntime } from "./model.js";
|
|
14
|
-
import {
|
|
15
|
-
import {
|
|
16
|
-
import { estimateSessionEntryTokens, evaluateContextBudget, isContextOverflowError, } from "./context-budget.js";
|
|
17
|
-
import { policiedSandboxEnv, runWithSandboxPolicyApproval } from "./policied-sandbox.js";
|
|
18
|
-
import { currentSubmissionContext } from "./submission-context.js";
|
|
19
|
-
import { deliveredSignalToEntryData, renderDeliveredMessage } from "./delivered-message.js";
|
|
20
|
-
import { BoundedInMemoryAttachmentStore } from "./attachment-store.js";
|
|
17
|
+
import { evaluateToolCallPolicyInSandbox, policiedSandboxEnv, runWithSandboxPolicyApproval, } from "./policied-sandbox.js";
|
|
18
|
+
import { canonicalizeToolCall, clampCommandTimeout, evaluateCommandPolicy } from "./policy.js";
|
|
21
19
|
import { createAttachmentHydrationBudget, hydrateModelMessageAttachments, preparePromptAttachments, recordsToModelAttachments, validatePromptAttachments, } from "./prompt-attachments.js";
|
|
22
|
-
import {
|
|
23
|
-
import { createFabricFs } from "./filesystem.js";
|
|
20
|
+
import { buildResultRetryPrompt, validateResult } from "./result.js";
|
|
24
21
|
import { registerSandbox, serializeSandboxRef, unregisterSandbox } from "./sandbox-ref.js";
|
|
25
|
-
import
|
|
26
|
-
import {
|
|
27
|
-
import {
|
|
22
|
+
import { createSandboxEnv, createScopedSandboxEnv, execSandboxCommand } from "./sandbox.js";
|
|
23
|
+
import { inMemorySessionMemory } from "./session-memory.js";
|
|
24
|
+
import { SessionStreamRecovery } from "./session-stream-recovery.js";
|
|
28
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 { createActivateSkillTool, createBuiltinTools, createCommandTools, hasScopedCommandRenderer, renderScopedCommand, shellQuote, unwrapHookToolRunResult, } from "./tools.js";
|
|
29
30
|
import { MAX_TASK_DEPTH } from "./types.js";
|
|
30
31
|
let nextTaskId = 0;
|
|
31
32
|
const CROCKFORD_ALPHABET = "0123456789ABCDEFGHJKMNPQRSTVWXYZ";
|
|
@@ -209,24 +210,24 @@ export class StubFabricSession {
|
|
|
209
210
|
}
|
|
210
211
|
async voice(options) {
|
|
211
212
|
if (this.options.sessionRuntime)
|
|
212
|
-
throw new Error(
|
|
213
|
+
throw new Error("Open voice in an activity or server runtime, not a durable workflow");
|
|
213
214
|
await this.ensureData();
|
|
214
215
|
const sandbox = await this.sandbox;
|
|
215
216
|
return openGovernedVoice(options, {
|
|
216
217
|
sessionId: this.id,
|
|
217
|
-
tenantId: this.options.tenantId ??
|
|
218
|
-
actorId: this.options.actor?.principal?.id ??
|
|
218
|
+
tenantId: this.options.tenantId ?? "",
|
|
219
|
+
actorId: this.options.actor?.principal?.id ?? "",
|
|
219
220
|
store: this.store,
|
|
220
221
|
execute: async (call, tools, signal) => {
|
|
221
|
-
const result = await this.executeToolCalls([call], new Map(tools.map(tool => [tool.name, tool])), sandbox, undefined, this.options.approvalTimeoutMs, this.options.onApproval, undefined, signal, async (name, output) => {
|
|
222
|
+
const result = await this.executeToolCalls([call], new Map(tools.map((tool) => [tool.name, tool])), sandbox, undefined, this.options.approvalTimeoutMs, this.options.onApproval, undefined, signal, async (name, output) => {
|
|
222
223
|
const safe = await options.prepareToolOutput(name, output);
|
|
223
224
|
const json = JSON.stringify(safe ?? null);
|
|
224
225
|
if (json.length > 65_536)
|
|
225
|
-
throw new Error(
|
|
226
|
+
throw new Error("Voice tool output too large");
|
|
226
227
|
return JSON.parse(json);
|
|
227
228
|
});
|
|
228
229
|
if (!result[0])
|
|
229
|
-
throw new Error(
|
|
230
|
+
throw new Error("Voice tool did not settle");
|
|
230
231
|
return result[0];
|
|
231
232
|
},
|
|
232
233
|
});
|
|
@@ -247,6 +248,17 @@ export class StubFabricSession {
|
|
|
247
248
|
}
|
|
248
249
|
const inlineAttachments = validatePromptAttachments(options.images, options.documents);
|
|
249
250
|
const durable = await this.getDurableRuntime();
|
|
251
|
+
if (this.options.streamRecovery !== undefined &&
|
|
252
|
+
(this.options.streamRecovery !== "replace" ||
|
|
253
|
+
durable ||
|
|
254
|
+
!this.store.appendEntry ||
|
|
255
|
+
(options.loopRuntime ?? this.options.loopRuntime ?? defaultLoopRuntime)
|
|
256
|
+
.supportsStreamRecovery !== true)) {
|
|
257
|
+
throw new FabricError({
|
|
258
|
+
code: "INVALID_CONFIG",
|
|
259
|
+
message: "streamRecovery: 'replace' requires an inline loop with supportsStreamRecovery: true and SessionStore.appendEntry. Delegated durable runtimes own their recovery contract.",
|
|
260
|
+
});
|
|
261
|
+
}
|
|
250
262
|
if (durable) {
|
|
251
263
|
if (this.options.dynamic && durable.supportsDynamicAgents !== true) {
|
|
252
264
|
throw new FabricError({
|
|
@@ -270,9 +282,10 @@ export class StubFabricSession {
|
|
|
270
282
|
// local prompt_start/end pair so local subscribers see activity.
|
|
271
283
|
await this.emit("prompt_start", { text });
|
|
272
284
|
try {
|
|
285
|
+
const forwardedPolicy = this.durablePolicy(options.policy);
|
|
273
286
|
const result = await durable.prompt({
|
|
274
287
|
text,
|
|
275
|
-
|
|
288
|
+
options: forwardedPolicy !== undefined ? { ...options, policy: forwardedPolicy } : options,
|
|
276
289
|
...(this.options.dynamic ? { dynamic: this.options.dynamic.executionDescriptor() } : {}),
|
|
277
290
|
});
|
|
278
291
|
await this.emit("prompt_end", { text });
|
|
@@ -288,9 +301,10 @@ export class StubFabricSession {
|
|
|
288
301
|
if (promptSubscriber)
|
|
289
302
|
this.eventSubscribers.add(promptSubscriber);
|
|
290
303
|
let dynamic = this.options.dynamic;
|
|
304
|
+
const lifecycleSignal = options.signal ?? new AbortController().signal;
|
|
291
305
|
try {
|
|
292
306
|
let sandbox = createScopedSandboxEnv(await this.sandbox, options.cwd);
|
|
293
|
-
let tools = this.resolveTools(
|
|
307
|
+
let tools = this.resolveTools(options.tools, options.commands);
|
|
294
308
|
let joinedRenderReady = false;
|
|
295
309
|
const currentTurnConfiguration = () => ({
|
|
296
310
|
...(typeof this.options.model === "string" ? { model: this.options.model } : {}),
|
|
@@ -379,17 +393,29 @@ export class StubFabricSession {
|
|
|
379
393
|
}
|
|
380
394
|
role = this.resolveRole(this.options.role);
|
|
381
395
|
}
|
|
382
|
-
tools = this.resolveTools(
|
|
396
|
+
tools = this.resolveTools(options.tools, options.commands);
|
|
383
397
|
if (!config.dynamic) {
|
|
384
398
|
throw new Error("[fabric-harness] A dynamic-agent refresh did not return its runtime.");
|
|
385
399
|
}
|
|
386
400
|
dynamic = config.dynamic;
|
|
387
401
|
this.options.dynamic = config.dynamic;
|
|
402
|
+
dynamic.bindLifecycleContext({ signal: lifecycleSignal, sandbox });
|
|
388
403
|
if (prior !== dynamic)
|
|
389
404
|
await prior.close();
|
|
390
405
|
return currentTurnConfiguration();
|
|
391
406
|
};
|
|
392
407
|
const activeSubmission = currentSubmissionContext();
|
|
408
|
+
const streamRecovery = this.options.streamRecovery === "replace"
|
|
409
|
+
? new SessionStreamRecovery((type, data) => this.recordEntry(type, data), (type, data) => this.emit(type, data))
|
|
410
|
+
: undefined;
|
|
411
|
+
if (streamRecovery) {
|
|
412
|
+
if (options.signal?.aborted)
|
|
413
|
+
throw promptAbortError(options.signal);
|
|
414
|
+
const path = SessionHistory.fromData(await this.history()).getActivePath();
|
|
415
|
+
await streamRecovery.recover(path.filter((entry) => entry.tenantId === this.options.tenantId &&
|
|
416
|
+
sameFabricActor(entry.actor, this.options.actor)));
|
|
417
|
+
}
|
|
418
|
+
dynamic?.bindLifecycleContext({ signal: lifecycleSignal, sandbox });
|
|
393
419
|
const submissionCorrelation = activeSubmission
|
|
394
420
|
? {
|
|
395
421
|
submissionId: activeSubmission.submissionId,
|
|
@@ -500,7 +526,7 @@ export class StubFabricSession {
|
|
|
500
526
|
await this.recordEntry("result", { result: results });
|
|
501
527
|
await this.emit("prompt_end", { text, result: results });
|
|
502
528
|
const value = await validateResult(results, options.result, options.resultExtraction);
|
|
503
|
-
const finalized = await this.finalizeDynamicResult(value, responseStartLeafId);
|
|
529
|
+
const finalized = await this.finalizeDynamicResult(value, responseStartLeafId, undefined, submissionCorrelation);
|
|
504
530
|
if (finalized.continued) {
|
|
505
531
|
throw new Error("useAgentFinish().append() cannot continue a prompt that uses PromptOptions.toolCalls; run the normal model loop instead.");
|
|
506
532
|
}
|
|
@@ -512,6 +538,7 @@ export class StubFabricSession {
|
|
|
512
538
|
const runtime = options.loopRuntime ?? this.options.loopRuntime ?? defaultLoopRuntime;
|
|
513
539
|
const runRuntime = () => runtime.runPrompt({
|
|
514
540
|
sessionId: this.id,
|
|
541
|
+
...(streamRecovery ? { streamRecovery: "replace" } : {}),
|
|
515
542
|
...(sessionData.affinityKey !== undefined
|
|
516
543
|
? { affinityKey: sessionData.affinityKey }
|
|
517
544
|
: {}),
|
|
@@ -597,7 +624,9 @@ export class StubFabricSession {
|
|
|
597
624
|
role: "user",
|
|
598
625
|
content: input.text,
|
|
599
626
|
...(joinedAttachments.records.length > 0
|
|
600
|
-
? {
|
|
627
|
+
? {
|
|
628
|
+
attachments: recordsToModelAttachments(joinedAttachments.records),
|
|
629
|
+
}
|
|
601
630
|
: {}),
|
|
602
631
|
},
|
|
603
632
|
], {
|
|
@@ -646,7 +675,7 @@ export class StubFabricSession {
|
|
|
646
675
|
executeToolCalls: (calls, policy, approvalTimeoutMs, attribution) => this.executeToolCalls(calls, tools, sandbox,
|
|
647
676
|
// The prompt's policy wins (call over session over agent). A loop may pass none for
|
|
648
677
|
// model-issued calls, and a dynamic agent's turn refresh passes its rendered agent policy.
|
|
649
|
-
options.policy ?? policy, approvalTimeoutMs, options.onApproval, attribution, options.signal),
|
|
678
|
+
options.policy ?? policy, approvalTimeoutMs, options.onApproval, attribution, options.signal, undefined, streamRecovery ? (data) => streamRecovery.record("tool_call", data) : undefined),
|
|
650
679
|
recordToolAdditions: async (toolCallId, names) => {
|
|
651
680
|
if (names.length === 0)
|
|
652
681
|
return;
|
|
@@ -657,8 +686,8 @@ export class StubFabricSession {
|
|
|
657
686
|
names,
|
|
658
687
|
});
|
|
659
688
|
},
|
|
660
|
-
recordEntry: (type, data) => this.recordEntry(type, data),
|
|
661
|
-
emit: (type, data) => this.emit(type, data),
|
|
689
|
+
recordEntry: (type, data) => streamRecovery ? streamRecovery.record(type, data) : this.recordEntry(type, data),
|
|
690
|
+
emit: (type, data) => streamRecovery ? streamRecovery.emit(type, data) : this.emit(type, data),
|
|
662
691
|
});
|
|
663
692
|
let result;
|
|
664
693
|
try {
|
|
@@ -740,7 +769,7 @@ export class StubFabricSession {
|
|
|
740
769
|
}
|
|
741
770
|
}
|
|
742
771
|
}
|
|
743
|
-
const finalized = await this.finalizeDynamicResult(value, responseStartLeafId, result.usage);
|
|
772
|
+
const finalized = await this.finalizeDynamicResult(value, responseStartLeafId, result.usage, submissionCorrelation);
|
|
744
773
|
if (!finalized.continued) {
|
|
745
774
|
if (result.terminatedByTool)
|
|
746
775
|
await this.compactAfterTermination(role, options);
|
|
@@ -848,7 +877,11 @@ export class StubFabricSession {
|
|
|
848
877
|
const taskId = options.id ?? `${this.id}:task-${++nextTaskId}`;
|
|
849
878
|
await this.emit("task_start", { taskId, depth: 1, parentSessionId: this.id });
|
|
850
879
|
try {
|
|
851
|
-
const { id: _id, ...
|
|
880
|
+
const { id: _id, ...requestedTaskOptions } = options;
|
|
881
|
+
const forwardedPolicy = this.durablePolicy(options.policy);
|
|
882
|
+
const taskOptions = forwardedPolicy !== undefined
|
|
883
|
+
? { ...requestedTaskOptions, policy: forwardedPolicy }
|
|
884
|
+
: requestedTaskOptions;
|
|
852
885
|
const result = await durable.task({
|
|
853
886
|
text,
|
|
854
887
|
taskId,
|
|
@@ -969,6 +1002,13 @@ export class StubFabricSession {
|
|
|
969
1002
|
// instructions, model, and capabilities.
|
|
970
1003
|
if (delegatedRole)
|
|
971
1004
|
Reflect.deleteProperty(childOptions, "dynamic");
|
|
1005
|
+
// A policy the caller set on this session, or on the task itself, stays
|
|
1006
|
+
// explicit for the child, so the child's dynamic refresh cannot replace it.
|
|
1007
|
+
const childExplicitPolicy = options.policy ?? explicitSessionPolicies.get(this.options);
|
|
1008
|
+
if (childExplicitPolicy !== undefined) {
|
|
1009
|
+
childOptions.policy = childExplicitPolicy;
|
|
1010
|
+
markExplicitSessionPolicy(childOptions, childExplicitPolicy);
|
|
1011
|
+
}
|
|
972
1012
|
const child = new StubFabricSession(this.agent, taskId, childOptions);
|
|
973
1013
|
const result = await child.prompt(text, {
|
|
974
1014
|
...childPromptOptions,
|
|
@@ -1066,7 +1106,11 @@ export class StubFabricSession {
|
|
|
1066
1106
|
const durable = await this.getDurableRuntime();
|
|
1067
1107
|
if (durable) {
|
|
1068
1108
|
await this.emit("command_start", { command });
|
|
1069
|
-
const
|
|
1109
|
+
const forwardedPolicy = this.durablePolicy(options.policy, false);
|
|
1110
|
+
const result = await durable.shell({
|
|
1111
|
+
command,
|
|
1112
|
+
options: forwardedPolicy !== undefined ? { ...options, policy: forwardedPolicy } : options,
|
|
1113
|
+
});
|
|
1070
1114
|
await this.emit("command_end", { command, exitCode: result.exitCode });
|
|
1071
1115
|
return result;
|
|
1072
1116
|
}
|
|
@@ -1264,6 +1308,7 @@ export class StubFabricSession {
|
|
|
1264
1308
|
const sandboxFork = sandbox.fork;
|
|
1265
1309
|
const agent = this.agent;
|
|
1266
1310
|
const baseOptions = this.options;
|
|
1311
|
+
const baseExplicitPolicy = explicitSessionPolicies.get(this.options);
|
|
1267
1312
|
await this.recordEntry("checkpoint_created", {
|
|
1268
1313
|
label: label ?? `fork:${snapshot.id}`,
|
|
1269
1314
|
...(label ? { metadata: { fork: true } } : { metadata: { fork: true } }),
|
|
@@ -1292,6 +1337,13 @@ export class StubFabricSession {
|
|
|
1292
1337
|
...(label !== undefined ? { forkLabel: label } : {}),
|
|
1293
1338
|
},
|
|
1294
1339
|
};
|
|
1340
|
+
// attach() creates a session like agent.session() does: a policy passed
|
|
1341
|
+
// here, else the origin's explicit one, outranks a dynamic agent's render.
|
|
1342
|
+
const explicitPolicy = attachOptions.policy ?? baseExplicitPolicy;
|
|
1343
|
+
if (explicitPolicy !== undefined) {
|
|
1344
|
+
merged.policy = explicitPolicy;
|
|
1345
|
+
markExplicitSessionPolicy(merged, explicitPolicy);
|
|
1346
|
+
}
|
|
1295
1347
|
return new StubFabricSession(agent, newId, merged);
|
|
1296
1348
|
},
|
|
1297
1349
|
};
|
|
@@ -1495,9 +1547,11 @@ export class StubFabricSession {
|
|
|
1495
1547
|
* `AbortError`.
|
|
1496
1548
|
*/
|
|
1497
1549
|
async summarizeEntrySet(entries, prefixPrompt, control) {
|
|
1498
|
-
|
|
1499
|
-
|
|
1500
|
-
|
|
1550
|
+
// Recovery output is presentation-only even when history is compacted.
|
|
1551
|
+
const canonicalEntries = entries.filter((entry) => entry.type !== "model_attempt" || entry.data?.kind !== "stream_recovery");
|
|
1552
|
+
if (canonicalEntries.length === 0)
|
|
1553
|
+
return summarizeEntries(canonicalEntries);
|
|
1554
|
+
const deterministic = summarizeEntries(canonicalEntries);
|
|
1501
1555
|
const provider = this.options.modelProvider ?? defaultModelProvider;
|
|
1502
1556
|
const timeoutMs = control.timeoutMs !== undefined && control.timeoutMs > 0
|
|
1503
1557
|
? control.timeoutMs
|
|
@@ -1520,11 +1574,11 @@ export class StubFabricSession {
|
|
|
1520
1574
|
const onDeadline = () => stop?.(deadline.signal.reason);
|
|
1521
1575
|
deadline.signal.addEventListener("abort", onDeadline, { once: true });
|
|
1522
1576
|
try {
|
|
1523
|
-
const serialized = JSON.stringify(
|
|
1577
|
+
const serialized = JSON.stringify(canonicalEntries
|
|
1524
1578
|
.map((entry) => ({
|
|
1525
1579
|
type: entry.type,
|
|
1526
1580
|
timestamp: entry.timestamp,
|
|
1527
|
-
data: entry.data ?? {},
|
|
1581
|
+
data: Object.fromEntries(Object.entries(entry.data ?? {}).filter(([key]) => key !== "streamRecoveryKeys")),
|
|
1528
1582
|
}))
|
|
1529
1583
|
.slice(0, 200));
|
|
1530
1584
|
const userContent = prefixPrompt ? `${serialized}\n\n${prefixPrompt}` : serialized;
|
|
@@ -1649,6 +1703,30 @@ export class StubFabricSession {
|
|
|
1649
1703
|
...(isSnapshot(snapshot) ? { snapshotId: snapshot.id } : {}),
|
|
1650
1704
|
};
|
|
1651
1705
|
}
|
|
1706
|
+
/**
|
|
1707
|
+
* The sandbox a tool sees under `policy`. The session's sandbox already
|
|
1708
|
+
* enforces the policy it was created with; this layers the call's effective
|
|
1709
|
+
* policy on top, so the two intersect and a call can narrow, never widen.
|
|
1710
|
+
*/
|
|
1711
|
+
sandboxUnderPolicy(sandbox, policy) {
|
|
1712
|
+
return wrapWithPolicy(sandbox, policy, this.options.bypassPolicyEnforcement);
|
|
1713
|
+
}
|
|
1714
|
+
/**
|
|
1715
|
+
* The policy forwarded to a durable runtime: the call's, else the session's
|
|
1716
|
+
* (which `agent.session()` fills from the agent's), so the worker enforces
|
|
1717
|
+
* call over session over agent rather than its own default. A dynamic
|
|
1718
|
+
* agent's rendered policy is re-rendered by the runtime, so for one only a
|
|
1719
|
+
* policy the caller set on the session is forwarded.
|
|
1720
|
+
*/
|
|
1721
|
+
durablePolicy(callPolicy, reRendered = true) {
|
|
1722
|
+
if (callPolicy !== undefined)
|
|
1723
|
+
return callPolicy;
|
|
1724
|
+
// Only prompts and tasks re-render a dynamic agent on the worker; a
|
|
1725
|
+
// shell call does not, so it carries the rendered policy itself.
|
|
1726
|
+
if (this.options.dynamic && reRendered)
|
|
1727
|
+
return explicitSessionPolicies.get(this.options);
|
|
1728
|
+
return this.options.policy;
|
|
1729
|
+
}
|
|
1652
1730
|
async createSandbox() {
|
|
1653
1731
|
const sandbox = this.options.sandbox;
|
|
1654
1732
|
let env;
|
|
@@ -1668,10 +1746,19 @@ export class StubFabricSession {
|
|
|
1668
1746
|
const scoped = createScopedSandboxEnv(env, this.options.cwd);
|
|
1669
1747
|
return wrapWithPolicy(scoped, this.options.policy, this.options.bypassPolicyEnforcement);
|
|
1670
1748
|
}
|
|
1671
|
-
async executeToolCalls(calls, tools,
|
|
1749
|
+
async executeToolCalls(calls, tools, sessionSandbox, callPolicy, approvalTimeoutMs, approvalHandler, attribution, signal, prepareOutput, recordToolCall) {
|
|
1672
1750
|
const results = [];
|
|
1673
1751
|
const policy = callPolicy ?? this.options.policy;
|
|
1674
|
-
|
|
1752
|
+
// Tools get the sandbox under the call's effective policy, layered over
|
|
1753
|
+
// the session's, so a narrower prompt policy reaches `context.sandbox`.
|
|
1754
|
+
const sandbox = this.sandboxUnderPolicy(sessionSandbox, policy);
|
|
1755
|
+
for (const requestedCall of calls) {
|
|
1756
|
+
const tool = tools.get(requestedCall.tool);
|
|
1757
|
+
const canonical = canonicalizeToolCall({
|
|
1758
|
+
...requestedCall,
|
|
1759
|
+
tool: tool?.policyAlias ?? requestedCall.tool,
|
|
1760
|
+
});
|
|
1761
|
+
const call = { ...requestedCall, input: canonical.input };
|
|
1675
1762
|
// Providers are allowed to omit a call id. Mint one once at the session
|
|
1676
1763
|
// boundary so approvals, lineage, history, and tool execution all refer
|
|
1677
1764
|
// to the same unique logical operation.
|
|
@@ -1681,57 +1768,84 @@ export class StubFabricSession {
|
|
|
1681
1768
|
// outcomes; calls that never started are settled as interrupted (and
|
|
1682
1769
|
// never executed, approved, or policy-evaluated) so the transcript
|
|
1683
1770
|
// keeps every requested call paired with an outcome.
|
|
1684
|
-
results.push(await this.recordUnexecutedInterruptedToolCall(call, toolCallId));
|
|
1771
|
+
results.push(await this.recordUnexecutedInterruptedToolCall(call, toolCallId, recordToolCall));
|
|
1685
1772
|
continue;
|
|
1686
1773
|
}
|
|
1687
1774
|
const approvedSandboxCalls = [];
|
|
1688
1775
|
let approvalGrant;
|
|
1689
|
-
const
|
|
1776
|
+
const approvalGrants = [];
|
|
1777
|
+
// A scoped command tool's command, rendered once: the same command is
|
|
1778
|
+
// judged, shown to the approver, recorded and granted to the sandbox.
|
|
1779
|
+
const renderedCommand = renderScopedCommand(tool, call.input);
|
|
1780
|
+
const boundCommand = hasScopedCommandRenderer(tool)
|
|
1781
|
+
? renderedCommand
|
|
1782
|
+
: (renderedCommand ?? this.commandTextForApproval(tool, call.input));
|
|
1690
1783
|
const executingPrincipal = toolExecutingPrincipal(tool);
|
|
1691
1784
|
const mountDecision = this.checkMountWriteAccess(call);
|
|
1692
1785
|
const policyCall = tool?.policyAlias ? { ...call, tool: tool.policyAlias } : call;
|
|
1693
|
-
|
|
1694
|
-
|
|
1695
|
-
|
|
1696
|
-
|
|
1697
|
-
|
|
1698
|
-
|
|
1699
|
-
|
|
1700
|
-
|
|
1701
|
-
|
|
1702
|
-
|
|
1703
|
-
|
|
1704
|
-
|
|
1705
|
-
|
|
1706
|
-
|
|
1707
|
-
|
|
1708
|
-
|
|
1709
|
-
|
|
1710
|
-
|
|
1711
|
-
|
|
1712
|
-
|
|
1713
|
-
|
|
1714
|
-
|
|
1715
|
-
|
|
1716
|
-
|
|
1717
|
-
|
|
1718
|
-
|
|
1719
|
-
|
|
1720
|
-
|
|
1721
|
-
|
|
1722
|
-
|
|
1723
|
-
|
|
1724
|
-
|
|
1725
|
-
|
|
1726
|
-
|
|
1727
|
-
|
|
1728
|
-
|
|
1729
|
-
|
|
1730
|
-
|
|
1731
|
-
|
|
1786
|
+
// File paths are judged in every form the sandbox reaches, as its layer
|
|
1787
|
+
// judges them, so an approval is asked for here when one is needed there.
|
|
1788
|
+
const decision = mountDecision ?? evaluateToolCallPolicyInSandbox(policyCall, policy, sandbox);
|
|
1789
|
+
const commandDecision = this.evaluateScopedCommandToolCall(tool, call.input, policy, renderedCommand);
|
|
1790
|
+
if (!decision.allowed && !decision.approvalRequired) {
|
|
1791
|
+
const error = decision.reason ?? `Tool call denied by policy: ${call.tool}`;
|
|
1792
|
+
results.push({
|
|
1793
|
+
tool: call.tool,
|
|
1794
|
+
input: call.input,
|
|
1795
|
+
error,
|
|
1796
|
+
...(call.id ? { id: call.id } : {}),
|
|
1797
|
+
});
|
|
1798
|
+
await this.recordEntry("error", {
|
|
1799
|
+
tool: call.tool,
|
|
1800
|
+
toolCallId,
|
|
1801
|
+
error,
|
|
1802
|
+
approvalRequired: false,
|
|
1803
|
+
});
|
|
1804
|
+
await this.emit("error", { tool: call.tool, error, approvalRequired: false });
|
|
1805
|
+
continue;
|
|
1806
|
+
}
|
|
1807
|
+
if (!commandDecision.allowed && !commandDecision.approvalRequired) {
|
|
1808
|
+
const error = commandDecision.reason ?? `Command denied by policy: ${call.tool}`;
|
|
1809
|
+
results.push({
|
|
1810
|
+
tool: call.tool,
|
|
1811
|
+
input: call.input,
|
|
1812
|
+
error,
|
|
1813
|
+
...(call.id ? { id: call.id } : {}),
|
|
1814
|
+
});
|
|
1815
|
+
await this.recordEntry("error", {
|
|
1816
|
+
tool: call.tool,
|
|
1817
|
+
toolCallId,
|
|
1818
|
+
error,
|
|
1819
|
+
approvalRequired: false,
|
|
1820
|
+
});
|
|
1821
|
+
await this.emit("error", { tool: call.tool, error, approvalRequired: false });
|
|
1822
|
+
continue;
|
|
1823
|
+
}
|
|
1824
|
+
if (!decision.allowed && decision.approvalRequired) {
|
|
1825
|
+
const grant = await this.requestApproval({
|
|
1826
|
+
kind: "tool",
|
|
1827
|
+
tool: call.tool,
|
|
1828
|
+
subject: call.tool,
|
|
1829
|
+
toolCallId,
|
|
1830
|
+
...(executingPrincipal ? { executingPrincipal } : {}),
|
|
1831
|
+
...(boundCommand !== undefined ? { command: boundCommand } : {}),
|
|
1832
|
+
input: call.input,
|
|
1833
|
+
reason: decision.reason ?? `Approval required for tool: ${call.tool}`,
|
|
1834
|
+
...(decision.risk ? { risk: decision.risk } : {}),
|
|
1835
|
+
...(decision.matchedPattern ? { matchedPattern: decision.matchedPattern } : {}),
|
|
1836
|
+
...(decision.approvalAudience ? { audience: decision.approvalAudience } : {}),
|
|
1837
|
+
...(decision.approvalTtlSeconds !== undefined
|
|
1838
|
+
? { ttlSeconds: decision.approvalTtlSeconds }
|
|
1839
|
+
: {}),
|
|
1840
|
+
affectedPaths: affectedPathsFromInput(call.input, call.tool),
|
|
1841
|
+
}, policy, approvalTimeoutMs, approvalHandler);
|
|
1842
|
+
if (grant) {
|
|
1843
|
+
approvalGrant = grant;
|
|
1844
|
+
approvalGrants.push(grant);
|
|
1845
|
+
approvedSandboxCalls.push(policyCall);
|
|
1732
1846
|
}
|
|
1733
1847
|
else {
|
|
1734
|
-
const error = decision.reason ?? `
|
|
1848
|
+
const error = decision.reason ?? `Approval required for tool call: ${call.tool}`;
|
|
1735
1849
|
results.push({
|
|
1736
1850
|
tool: call.tool,
|
|
1737
1851
|
input: call.input,
|
|
@@ -1742,61 +1856,37 @@ export class StubFabricSession {
|
|
|
1742
1856
|
tool: call.tool,
|
|
1743
1857
|
toolCallId,
|
|
1744
1858
|
error,
|
|
1745
|
-
approvalRequired:
|
|
1859
|
+
approvalRequired: true,
|
|
1746
1860
|
});
|
|
1747
|
-
await this.emit("error", { tool: call.tool, error, approvalRequired:
|
|
1861
|
+
await this.emit("error", { tool: call.tool, error, approvalRequired: true });
|
|
1748
1862
|
continue;
|
|
1749
1863
|
}
|
|
1750
1864
|
}
|
|
1751
|
-
|
|
1752
|
-
|
|
1753
|
-
|
|
1754
|
-
|
|
1755
|
-
|
|
1756
|
-
|
|
1757
|
-
|
|
1758
|
-
|
|
1759
|
-
|
|
1760
|
-
|
|
1761
|
-
|
|
1762
|
-
|
|
1763
|
-
|
|
1764
|
-
|
|
1765
|
-
|
|
1766
|
-
|
|
1767
|
-
|
|
1768
|
-
|
|
1769
|
-
|
|
1770
|
-
|
|
1771
|
-
|
|
1772
|
-
|
|
1773
|
-
|
|
1774
|
-
|
|
1775
|
-
|
|
1776
|
-
if (!grant) {
|
|
1777
|
-
const error = commandDecision.reason ?? `Approval required for command: ${call.tool}`;
|
|
1778
|
-
results.push({
|
|
1779
|
-
tool: call.tool,
|
|
1780
|
-
input: call.input,
|
|
1781
|
-
error,
|
|
1782
|
-
...(call.id ? { id: call.id } : {}),
|
|
1783
|
-
});
|
|
1784
|
-
await this.recordEntry("error", {
|
|
1785
|
-
tool: call.tool,
|
|
1786
|
-
toolCallId,
|
|
1787
|
-
error,
|
|
1788
|
-
approvalRequired: true,
|
|
1789
|
-
});
|
|
1790
|
-
await this.emit("error", { tool: call.tool, error, approvalRequired: true });
|
|
1791
|
-
continue;
|
|
1792
|
-
}
|
|
1793
|
-
approvalGrant = grant;
|
|
1794
|
-
const approvedCommand = this.commandTextForApproval(tool, call.input);
|
|
1795
|
-
if (approvedCommand)
|
|
1796
|
-
approvedSandboxCalls.push({ tool: "bash", input: { command: approvedCommand } });
|
|
1797
|
-
}
|
|
1798
|
-
else {
|
|
1799
|
-
const error = commandDecision.reason ?? `Command denied by policy: ${call.tool}`;
|
|
1865
|
+
if (!commandDecision.allowed && commandDecision.approvalRequired) {
|
|
1866
|
+
// The approval names the exact command the tool will run.
|
|
1867
|
+
const grant = await this.requestApproval({
|
|
1868
|
+
kind: "command",
|
|
1869
|
+
tool: call.tool,
|
|
1870
|
+
toolCallId,
|
|
1871
|
+
...(executingPrincipal ? { executingPrincipal } : {}),
|
|
1872
|
+
...(boundCommand !== undefined ? { command: boundCommand } : {}),
|
|
1873
|
+
input: call.input,
|
|
1874
|
+
reason: commandDecision.reason ?? `Approval required for command: ${call.tool}`,
|
|
1875
|
+
...(commandDecision.risk ? { risk: commandDecision.risk } : {}),
|
|
1876
|
+
...(commandDecision.matchedPattern
|
|
1877
|
+
? { matchedPattern: commandDecision.matchedPattern }
|
|
1878
|
+
: {}),
|
|
1879
|
+
...(commandDecision.approvalAudience
|
|
1880
|
+
? { audience: commandDecision.approvalAudience }
|
|
1881
|
+
: {}),
|
|
1882
|
+
...(commandDecision.approvalTtlSeconds !== undefined
|
|
1883
|
+
? { ttlSeconds: commandDecision.approvalTtlSeconds }
|
|
1884
|
+
: {}),
|
|
1885
|
+
envKeys: commandEnvKeys(tool),
|
|
1886
|
+
affectedPaths: affectedPathsFromInput(call.input, call.tool),
|
|
1887
|
+
}, policy, approvalTimeoutMs, approvalHandler);
|
|
1888
|
+
if (!grant) {
|
|
1889
|
+
const error = commandDecision.reason ?? `Approval required for command: ${call.tool}`;
|
|
1800
1890
|
results.push({
|
|
1801
1891
|
tool: call.tool,
|
|
1802
1892
|
input: call.input,
|
|
@@ -1807,13 +1897,20 @@ export class StubFabricSession {
|
|
|
1807
1897
|
tool: call.tool,
|
|
1808
1898
|
toolCallId,
|
|
1809
1899
|
error,
|
|
1810
|
-
approvalRequired:
|
|
1900
|
+
approvalRequired: true,
|
|
1811
1901
|
});
|
|
1812
|
-
await this.emit("error", { tool: call.tool, error, approvalRequired:
|
|
1902
|
+
await this.emit("error", { tool: call.tool, error, approvalRequired: true });
|
|
1813
1903
|
continue;
|
|
1814
1904
|
}
|
|
1905
|
+
approvalGrant = grant;
|
|
1906
|
+
approvalGrants.push(grant);
|
|
1907
|
+
// The sandbox grant names the exact command the tool will run.
|
|
1908
|
+
// A metadata-only command tool runs its command itself; the grant
|
|
1909
|
+
// names the command its approval described.
|
|
1910
|
+
if (boundCommand !== undefined)
|
|
1911
|
+
approvedSandboxCalls.push({ tool: "bash", input: { command: boundCommand } });
|
|
1815
1912
|
}
|
|
1816
|
-
await this.recordEntry("tool_call", {
|
|
1913
|
+
await (recordToolCall ?? ((data) => this.recordEntry("tool_call", data)))({
|
|
1817
1914
|
tool: call.tool,
|
|
1818
1915
|
input: call.input,
|
|
1819
1916
|
inputDigest: approvalInputDigest(call.input),
|
|
@@ -1822,13 +1919,23 @@ export class StubFabricSession {
|
|
|
1822
1919
|
? { executingPrincipal: executingPrincipal }
|
|
1823
1920
|
: {}),
|
|
1824
1921
|
...(approvalGrant ? { approval: approvalGrantToJson(approvalGrant) } : {}),
|
|
1922
|
+
...(approvalGrants.length > 0
|
|
1923
|
+
? { approvals: approvalGrants.map(approvalGrantToJson) }
|
|
1924
|
+
: {}),
|
|
1825
1925
|
...(tool?.metadata?.effect ? { effect: tool.metadata.effect } : {}),
|
|
1826
1926
|
...(tool?.durable ? { durable: true } : {}),
|
|
1927
|
+
// Recovery grants a scoped command only if it still renders this command.
|
|
1928
|
+
...(tool?.durable && boundCommand !== undefined ? { renderedCommand: boundCommand } : {}),
|
|
1827
1929
|
toolCallId,
|
|
1828
1930
|
...(attribution ? { attribution: attribution } : {}),
|
|
1829
1931
|
});
|
|
1932
|
+
const effectiveInput = tool?.execute && call.tool === "bash"
|
|
1933
|
+
? this.clampBashToolInput(call.input, policy)
|
|
1934
|
+
: call.input;
|
|
1830
1935
|
await this.emit("tool_start", {
|
|
1831
1936
|
tool: call.tool,
|
|
1937
|
+
toolCallId,
|
|
1938
|
+
...(effectiveInput !== undefined ? { input: effectiveInput } : {}),
|
|
1832
1939
|
...(attribution ? { attribution: attribution } : {}),
|
|
1833
1940
|
});
|
|
1834
1941
|
if (!tool?.execute) {
|
|
@@ -1847,23 +1954,28 @@ export class StubFabricSession {
|
|
|
1847
1954
|
});
|
|
1848
1955
|
await this.emit("tool_end", {
|
|
1849
1956
|
tool: call.tool,
|
|
1957
|
+
toolCallId,
|
|
1850
1958
|
error,
|
|
1851
1959
|
...(attribution ? { attribution: attribution } : {}),
|
|
1852
1960
|
});
|
|
1853
1961
|
continue;
|
|
1854
1962
|
}
|
|
1963
|
+
const startedAt = performance.now();
|
|
1855
1964
|
try {
|
|
1856
|
-
const input =
|
|
1857
|
-
const startedAt = Date.now();
|
|
1965
|
+
const input = effectiveInput;
|
|
1858
1966
|
const submission = currentSubmissionContext();
|
|
1967
|
+
const agentName = this.agent.name ?? submission?.agent;
|
|
1859
1968
|
const execute = () => Promise.resolve(executeTool(tool, input, {
|
|
1860
1969
|
sandbox,
|
|
1970
|
+
...(renderedCommand !== undefined ? { __fabricScopedCommand: renderedCommand } : {}),
|
|
1861
1971
|
toolCallId,
|
|
1862
1972
|
...(signal ? { signal } : {}),
|
|
1863
1973
|
onOrphanSettled: (settlement) => this.recordSandboxOrphanSettlement(call.tool, toolCallId, settlement),
|
|
1864
1974
|
...(approvalGrant ? { approval: approvalGrant } : {}),
|
|
1865
1975
|
...(this.options.actor ? { actor: this.options.actor } : {}),
|
|
1866
1976
|
...(this.options.tenantId ? { tenantId: this.options.tenantId } : {}),
|
|
1977
|
+
...(this.agent.id ? { agentId: this.agent.id } : {}),
|
|
1978
|
+
...(agentName ? { agentName } : {}),
|
|
1867
1979
|
policyVersion: approvalInputDigest(policy ?? null),
|
|
1868
1980
|
...(policy ? { policy } : {}),
|
|
1869
1981
|
inputDigest: approvalInputDigest(input),
|
|
@@ -1883,12 +1995,12 @@ export class StubFabricSession {
|
|
|
1883
1995
|
const dynamicOutput = unwrapDynamicToolResult(rawOutput);
|
|
1884
1996
|
const hookOutput = unwrapHookToolRunResult(dynamicOutput.output);
|
|
1885
1997
|
if (prepareOutput && dynamicOutput.stateWrites.length) {
|
|
1886
|
-
throw new Error(
|
|
1998
|
+
throw new Error("Voice tools must commit domain state through governed application actions");
|
|
1887
1999
|
}
|
|
1888
2000
|
const output = prepareOutput
|
|
1889
2001
|
? await abandonToolOnAbort(() => prepareOutput(call.tool, hookOutput.output), signal)
|
|
1890
2002
|
: hookOutput.output;
|
|
1891
|
-
const durationMs =
|
|
2003
|
+
const durationMs = Math.max(0, Math.round(performance.now() - startedAt));
|
|
1892
2004
|
await this.recordToolResult({
|
|
1893
2005
|
tool: call.tool,
|
|
1894
2006
|
output: output,
|
|
@@ -1906,12 +2018,19 @@ export class StubFabricSession {
|
|
|
1906
2018
|
});
|
|
1907
2019
|
await this.emit("tool_end", {
|
|
1908
2020
|
tool: call.tool,
|
|
2021
|
+
toolCallId,
|
|
1909
2022
|
durationMs,
|
|
2023
|
+
...(output !== undefined ? { output: output } : {}),
|
|
1910
2024
|
...(attribution ? { attribution: attribution } : {}),
|
|
1911
2025
|
});
|
|
1912
2026
|
}
|
|
1913
2027
|
catch (error) {
|
|
1914
|
-
const
|
|
2028
|
+
const durationMs = Math.max(0, Math.round(performance.now() - startedAt));
|
|
2029
|
+
const message = prepareOutput
|
|
2030
|
+
? "Voice tool rejected or failed"
|
|
2031
|
+
: error instanceof Error
|
|
2032
|
+
? error.message
|
|
2033
|
+
: String(error);
|
|
1915
2034
|
results.push({
|
|
1916
2035
|
tool: call.tool,
|
|
1917
2036
|
input: call.input,
|
|
@@ -1921,6 +2040,8 @@ export class StubFabricSession {
|
|
|
1921
2040
|
await this.recordEntry("error", { tool: call.tool, toolCallId, error: message });
|
|
1922
2041
|
await this.emit("tool_end", {
|
|
1923
2042
|
tool: call.tool,
|
|
2043
|
+
toolCallId,
|
|
2044
|
+
durationMs,
|
|
1924
2045
|
error: message,
|
|
1925
2046
|
...(attribution ? { attribution: attribution } : {}),
|
|
1926
2047
|
});
|
|
@@ -1928,9 +2049,9 @@ export class StubFabricSession {
|
|
|
1928
2049
|
}
|
|
1929
2050
|
return results;
|
|
1930
2051
|
}
|
|
1931
|
-
async recordUnexecutedInterruptedToolCall(call, toolCallId) {
|
|
2052
|
+
async recordUnexecutedInterruptedToolCall(call, toolCallId, recordToolCall) {
|
|
1932
2053
|
const message = "Tool call was not executed: the prompt was aborted before this call started.";
|
|
1933
|
-
await this.recordEntry("tool_call", {
|
|
2054
|
+
await (recordToolCall ?? ((data) => this.recordEntry("tool_call", data)))({
|
|
1934
2055
|
tool: call.tool,
|
|
1935
2056
|
input: call.input,
|
|
1936
2057
|
inputDigest: approvalInputDigest(call.input),
|
|
@@ -2121,9 +2242,22 @@ export class StubFabricSession {
|
|
|
2121
2242
|
onCredentialMissing: this.options.autonomy?.onCredentialMissing ?? "fail",
|
|
2122
2243
|
};
|
|
2123
2244
|
}
|
|
2124
|
-
evaluateScopedCommandToolCall(tool, input, policy) {
|
|
2245
|
+
evaluateScopedCommandToolCall(tool, input, policy, rendered) {
|
|
2246
|
+
if (hasScopedCommandRenderer(tool)) {
|
|
2247
|
+
if (rendered === undefined) {
|
|
2248
|
+
return {
|
|
2249
|
+
allowed: false,
|
|
2250
|
+
reason: `Failed to render command for tool: ${tool?.name ?? "unknown"}`,
|
|
2251
|
+
};
|
|
2252
|
+
}
|
|
2253
|
+
return evaluateCommandPolicy(rendered, policy);
|
|
2254
|
+
}
|
|
2125
2255
|
if (tool?.metadata?.kind !== "command" || typeof tool.metadata.command !== "string")
|
|
2126
2256
|
return { allowed: true };
|
|
2257
|
+
// The exact command the tool will run (executable, default arguments,
|
|
2258
|
+
// buildArgs, quoting), as the sandbox layer will judge it.
|
|
2259
|
+
if (rendered !== undefined)
|
|
2260
|
+
return evaluateCommandPolicy(rendered, policy);
|
|
2127
2261
|
const args = typeof input === "object" &&
|
|
2128
2262
|
input !== null &&
|
|
2129
2263
|
Array.isArray(input.args)
|
|
@@ -2140,7 +2274,8 @@ export class StubFabricSession {
|
|
|
2140
2274
|
Array.isArray(input.args)
|
|
2141
2275
|
? input.args.filter((value) => typeof value === "string")
|
|
2142
2276
|
: [];
|
|
2143
|
-
|
|
2277
|
+
// Quoted as evaluateScopedCommandToolCall judges it and the tool runs it.
|
|
2278
|
+
return [tool.metadata.command, ...args.map(shellQuote)].join(" ");
|
|
2144
2279
|
}
|
|
2145
2280
|
clampBashToolInput(input, policy) {
|
|
2146
2281
|
if (!policy?.maxCommandTimeoutMs || typeof input !== "object" || input === null)
|
|
@@ -2149,12 +2284,14 @@ export class StubFabricSession {
|
|
|
2149
2284
|
const timeout = typeof record.timeout === "number" ? record.timeout : undefined;
|
|
2150
2285
|
return { ...record, timeout: clampCommandTimeout(timeout, policy) };
|
|
2151
2286
|
}
|
|
2152
|
-
resolveTools(
|
|
2287
|
+
resolveTools(promptTools = [], promptCommands = []) {
|
|
2153
2288
|
const tools = new Map();
|
|
2154
2289
|
const commandToolOptions = this.options.resolveSecret
|
|
2155
2290
|
? { resolveSecret: this.options.resolveSecret }
|
|
2156
2291
|
: {};
|
|
2157
|
-
|
|
2292
|
+
// Built-ins run on the sandbox each call is handed (`context.sandbox`),
|
|
2293
|
+
// which carries that call's effective policy, not one captured here.
|
|
2294
|
+
for (const tool of createBuiltinTools(undefined, this.effectivePackagedSkills()))
|
|
2158
2295
|
tools.set(tool.name, tool);
|
|
2159
2296
|
for (const tool of createCommandTools(this.options.commands ?? [], commandToolOptions))
|
|
2160
2297
|
tools.set(tool.name, tool);
|
|
@@ -2317,10 +2454,11 @@ export class StubFabricSession {
|
|
|
2317
2454
|
* appends one advisory `signal` entry so the model knows the previous turn
|
|
2318
2455
|
* was cut short. Idempotent: a repaired window has no dangling calls.
|
|
2319
2456
|
*/
|
|
2320
|
-
async repairDanglingToolCalls(tools,
|
|
2457
|
+
async repairDanglingToolCalls(tools, sessionSandbox, signal,
|
|
2321
2458
|
/** The resuming prompt's policy; the session's applies when absent. */
|
|
2322
2459
|
promptPolicy) {
|
|
2323
2460
|
const recoveryPolicy = promptPolicy ?? this.options.policy;
|
|
2461
|
+
const sandbox = this.sandboxUnderPolicy(sessionSandbox, recoveryPolicy);
|
|
2324
2462
|
for (let attempt = 0; attempt < 8; attempt += 1) {
|
|
2325
2463
|
let data = await this.history();
|
|
2326
2464
|
let path = SessionHistory.fromData(data).getActivePath();
|
|
@@ -2336,18 +2474,34 @@ export class StubFabricSession {
|
|
|
2336
2474
|
!toolName) {
|
|
2337
2475
|
continue;
|
|
2338
2476
|
}
|
|
2339
|
-
await this.emit("tool_start", {
|
|
2477
|
+
await this.emit("tool_start", {
|
|
2478
|
+
tool: toolName,
|
|
2479
|
+
recovery: true,
|
|
2480
|
+
toolCallId,
|
|
2481
|
+
...(call.data?.input !== undefined ? { input: call.data.input } : {}),
|
|
2482
|
+
});
|
|
2483
|
+
const recoveryStartedAt = performance.now();
|
|
2340
2484
|
try {
|
|
2341
|
-
|
|
2485
|
+
// Rendered once: authorised, compared with the recorded command, run.
|
|
2486
|
+
const scoped = renderScopedCommand(tool, call.data?.input);
|
|
2487
|
+
// A metadata-only command tool runs the command its approval described.
|
|
2488
|
+
const rendered = hasScopedCommandRenderer(tool)
|
|
2489
|
+
? scoped
|
|
2490
|
+
: (scoped ?? this.commandTextForApproval(tool, call.data?.input));
|
|
2491
|
+
const authorization = await this.authorizeRecoveredToolCall(call, toolName, tool, toolCallId, recoveryPolicy, sandbox, scoped, rendered);
|
|
2342
2492
|
const submission = currentSubmissionContext();
|
|
2493
|
+
const agentName = this.agent.name ?? submission?.agent;
|
|
2343
2494
|
const execute = () => Promise.resolve(executeTool(tool, call.data?.input, {
|
|
2344
2495
|
sandbox,
|
|
2496
|
+
...(scoped !== undefined ? { __fabricScopedCommand: scoped } : {}),
|
|
2345
2497
|
toolCallId,
|
|
2346
2498
|
...(signal ? { signal } : {}),
|
|
2347
2499
|
onOrphanSettled: (settlement) => this.recordSandboxOrphanSettlement(toolName, toolCallId, settlement),
|
|
2348
2500
|
...(authorization.approval ? { approval: authorization.approval } : {}),
|
|
2349
2501
|
...(this.options.actor ? { actor: this.options.actor } : {}),
|
|
2350
2502
|
...(this.options.tenantId ? { tenantId: this.options.tenantId } : {}),
|
|
2503
|
+
...(this.agent.id ? { agentId: this.agent.id } : {}),
|
|
2504
|
+
...(agentName ? { agentName } : {}),
|
|
2351
2505
|
policyVersion: authorization.policyDigest,
|
|
2352
2506
|
...(recoveryPolicy ? { policy: recoveryPolicy } : {}),
|
|
2353
2507
|
inputDigest: authorization.inputDigest,
|
|
@@ -2363,22 +2517,36 @@ export class StubFabricSession {
|
|
|
2363
2517
|
}
|
|
2364
2518
|
: {}),
|
|
2365
2519
|
}));
|
|
2366
|
-
|
|
2367
|
-
|
|
2368
|
-
|
|
2369
|
-
:
|
|
2520
|
+
// Only re-grant the sandbox gate(s) whose persisted approvals were
|
|
2521
|
+
// verified against the active policy and recorded command.
|
|
2522
|
+
const approvedCalls = [
|
|
2523
|
+
...(authorization.approvedToolCall ? [authorization.approvedToolCall] : []),
|
|
2524
|
+
...(authorization.approvedCommand !== undefined
|
|
2525
|
+
? [{ tool: "bash", input: { command: authorization.approvedCommand } }]
|
|
2526
|
+
: []),
|
|
2527
|
+
];
|
|
2528
|
+
const rawOutput = await abandonToolOnAbort(approvedCalls.reduceRight((next, granted) => () => runWithSandboxPolicyApproval(sandbox, granted, next), execute), signal);
|
|
2370
2529
|
const dynamicOutput = unwrapDynamicToolResult(rawOutput);
|
|
2371
2530
|
const hookOutput = unwrapHookToolRunResult(dynamicOutput.output);
|
|
2531
|
+
const recoveryDurationMs = Math.max(0, Math.round(performance.now() - recoveryStartedAt));
|
|
2372
2532
|
await this.recordToolResult({
|
|
2373
2533
|
tool: toolName,
|
|
2374
2534
|
toolCallId,
|
|
2375
2535
|
output: hookOutput.output,
|
|
2536
|
+
durationMs: recoveryDurationMs,
|
|
2376
2537
|
...(hookOutput.terminate ? { terminate: true } : {}),
|
|
2377
2538
|
recovered: true,
|
|
2378
2539
|
}, dynamicOutput.stateWrites);
|
|
2379
|
-
await this.emit("tool_end", {
|
|
2540
|
+
await this.emit("tool_end", {
|
|
2541
|
+
tool: toolName,
|
|
2542
|
+
recovery: true,
|
|
2543
|
+
toolCallId,
|
|
2544
|
+
durationMs: recoveryDurationMs,
|
|
2545
|
+
...(hookOutput.output !== undefined ? { output: hookOutput.output } : {}),
|
|
2546
|
+
});
|
|
2380
2547
|
}
|
|
2381
2548
|
catch (error) {
|
|
2549
|
+
const recoveryDurationMs = Math.max(0, Math.round(performance.now() - recoveryStartedAt));
|
|
2382
2550
|
const message = error instanceof Error ? error.message : String(error);
|
|
2383
2551
|
await this.recordEntry("error", {
|
|
2384
2552
|
tool: toolName,
|
|
@@ -2390,6 +2558,7 @@ export class StubFabricSession {
|
|
|
2390
2558
|
tool: toolName,
|
|
2391
2559
|
recovery: true,
|
|
2392
2560
|
toolCallId,
|
|
2561
|
+
durationMs: recoveryDurationMs,
|
|
2393
2562
|
error: message,
|
|
2394
2563
|
});
|
|
2395
2564
|
}
|
|
@@ -2466,13 +2635,19 @@ export class StubFabricSession {
|
|
|
2466
2635
|
}
|
|
2467
2636
|
for (const call of dangling) {
|
|
2468
2637
|
const tool = typeof call.data?.tool === "string" ? call.data.tool : "unknown";
|
|
2469
|
-
|
|
2638
|
+
const toolCallId = typeof call.data?.toolCallId === "string" ? call.data.toolCallId : undefined;
|
|
2639
|
+
await this.emit("tool_end", {
|
|
2640
|
+
tool,
|
|
2641
|
+
...(toolCallId ? { toolCallId } : {}),
|
|
2642
|
+
error: "interrupted",
|
|
2643
|
+
synthetic: true,
|
|
2644
|
+
});
|
|
2470
2645
|
}
|
|
2471
2646
|
return;
|
|
2472
2647
|
}
|
|
2473
2648
|
throw new Error(`Could not repair interrupted session ${this.id}: session leaf kept changing.`);
|
|
2474
2649
|
}
|
|
2475
|
-
async authorizeRecoveredToolCall(call, toolName, tool, toolCallId, policy) {
|
|
2650
|
+
async authorizeRecoveredToolCall(call, toolName, tool, toolCallId, policy, sandbox, scopedCommand, expectedCommand) {
|
|
2476
2651
|
const input = call.data?.input;
|
|
2477
2652
|
const inputDigest = approvalInputDigest(input);
|
|
2478
2653
|
if (call.data?.inputDigest !== inputDigest) {
|
|
@@ -2494,11 +2669,10 @@ export class StubFabricSession {
|
|
|
2494
2669
|
input,
|
|
2495
2670
|
id: toolCallId,
|
|
2496
2671
|
};
|
|
2497
|
-
const
|
|
2498
|
-
|
|
2499
|
-
|
|
2500
|
-
|
|
2501
|
-
];
|
|
2672
|
+
const toolDecision = this.checkMountWriteAccess({ tool: toolName, input, id: toolCallId }) ??
|
|
2673
|
+
evaluateToolCallPolicyInSandbox(policyCall, policy, sandbox);
|
|
2674
|
+
const commandDecision = this.evaluateScopedCommandToolCall(tool, input, policy, scopedCommand);
|
|
2675
|
+
const decisions = [toolDecision, commandDecision];
|
|
2502
2676
|
const denied = decisions.find((decision) => !decision.allowed && !decision.approvalRequired);
|
|
2503
2677
|
if (denied) {
|
|
2504
2678
|
throw new FabricError({
|
|
@@ -2506,12 +2680,28 @@ export class StubFabricSession {
|
|
|
2506
2680
|
message: denied.reason ?? `Recovered tool ${toolName} is denied by the current policy.`,
|
|
2507
2681
|
});
|
|
2508
2682
|
}
|
|
2683
|
+
if ((expectedCommand !== undefined || call.data?.renderedCommand !== undefined) &&
|
|
2684
|
+
call.data?.renderedCommand !== expectedCommand) {
|
|
2685
|
+
throw new FabricError({
|
|
2686
|
+
code: "POLICY_DENIED",
|
|
2687
|
+
message: `Recovered tool ${toolName} renders a different command than the recorded call.`,
|
|
2688
|
+
});
|
|
2689
|
+
}
|
|
2509
2690
|
const requiresApproval = decisions.some((decision) => decision.approvalRequired);
|
|
2510
2691
|
if (!requiresApproval)
|
|
2511
2692
|
return { inputDigest, policyDigest };
|
|
2512
|
-
const
|
|
2693
|
+
const rawApprovals = Array.isArray(call.data?.approvals)
|
|
2694
|
+
? call.data.approvals
|
|
2695
|
+
: call.data?.approval !== undefined
|
|
2696
|
+
? [call.data.approval]
|
|
2697
|
+
: [];
|
|
2698
|
+
const grants = rawApprovals
|
|
2699
|
+
.map((item) => approvalGrantFromJson(item))
|
|
2700
|
+
.filter((item) => item !== undefined);
|
|
2513
2701
|
const principal = toolExecutingPrincipal(tool) ?? this.approvalPrincipal();
|
|
2514
|
-
if (
|
|
2702
|
+
if (grants.length === 0 ||
|
|
2703
|
+
rawApprovals.length !== grants.length ||
|
|
2704
|
+
grants.some((grant) => !sameApprovalOperation(grant, { toolCallId, toolInput: input, principal }))) {
|
|
2515
2705
|
throw new FabricError({
|
|
2516
2706
|
code: "POLICY_DENIED",
|
|
2517
2707
|
message: `Recovered tool ${toolName} requires a current approval bound to this call and principal.`,
|
|
@@ -2520,22 +2710,41 @@ export class StubFabricSession {
|
|
|
2520
2710
|
if (!this.store.getApprovalState) {
|
|
2521
2711
|
throw new FabricError({
|
|
2522
2712
|
code: "POLICY_DENIED",
|
|
2523
|
-
message: `Recovered tool ${toolName} cannot prove that approval ${
|
|
2713
|
+
message: `Recovered tool ${toolName} cannot prove that approval ${grants[0]?.approvalId ?? ""} remains valid.`,
|
|
2524
2714
|
});
|
|
2525
2715
|
}
|
|
2526
|
-
const
|
|
2527
|
-
const
|
|
2528
|
-
|
|
2529
|
-
|
|
2530
|
-
|
|
2716
|
+
const verifiedStates = [];
|
|
2717
|
+
const verifiedGrants = [];
|
|
2718
|
+
for (const grant of grants) {
|
|
2719
|
+
const state = await this.store.getApprovalState(this.id, grant.approvalId);
|
|
2720
|
+
const currentGrant = state
|
|
2721
|
+
? approvalGrantFromState(state, input, principal, toolCallId)
|
|
2722
|
+
: undefined;
|
|
2723
|
+
if (!state || !currentGrant) {
|
|
2724
|
+
throw new FabricError({
|
|
2725
|
+
code: "POLICY_DENIED",
|
|
2726
|
+
message: `Recovered tool ${toolName} approval is expired, denied, revoked, or unavailable.`,
|
|
2727
|
+
});
|
|
2728
|
+
}
|
|
2729
|
+
verifiedStates.push(state);
|
|
2730
|
+
verifiedGrants.push(currentGrant);
|
|
2731
|
+
}
|
|
2732
|
+
const hasToolApproval = verifiedStates.some((state) => state.request.kind === "tool");
|
|
2733
|
+
const hasCommandApproval = verifiedStates.some((state) => state.request.kind === "command");
|
|
2734
|
+
if ((toolDecision.approvalRequired && !hasToolApproval) ||
|
|
2735
|
+
(commandDecision.approvalRequired && !hasCommandApproval)) {
|
|
2531
2736
|
throw new FabricError({
|
|
2532
2737
|
code: "POLICY_DENIED",
|
|
2533
|
-
message: `Recovered tool ${toolName} approval
|
|
2738
|
+
message: `Recovered tool ${toolName} does not have an approval covering the active policy gate.`,
|
|
2534
2739
|
});
|
|
2535
2740
|
}
|
|
2741
|
+
const latestGrant = verifiedGrants.at(-1);
|
|
2536
2742
|
return {
|
|
2537
|
-
approval:
|
|
2538
|
-
|
|
2743
|
+
...(latestGrant ? { approval: latestGrant } : {}),
|
|
2744
|
+
...(hasToolApproval ? { approvedToolCall: policyCall } : {}),
|
|
2745
|
+
...(hasCommandApproval && expectedCommand !== undefined
|
|
2746
|
+
? { approvedCommand: expectedCommand }
|
|
2747
|
+
: {}),
|
|
2539
2748
|
inputDigest,
|
|
2540
2749
|
policyDigest,
|
|
2541
2750
|
};
|
|
@@ -2565,14 +2774,15 @@ export class StubFabricSession {
|
|
|
2565
2774
|
await this.store.appendEntry?.(this.id, entry);
|
|
2566
2775
|
return entry;
|
|
2567
2776
|
}
|
|
2568
|
-
async finalizeDynamicResult(value, responseStartLeafId, usage) {
|
|
2777
|
+
async finalizeDynamicResult(value, responseStartLeafId, usage, correlationOverride) {
|
|
2569
2778
|
const dynamic = this.options.dynamic;
|
|
2570
2779
|
if (!dynamic)
|
|
2571
2780
|
return { value, continued: false };
|
|
2572
2781
|
const submission = currentSubmissionContext();
|
|
2573
|
-
const submissionCorrelation =
|
|
2574
|
-
|
|
2575
|
-
|
|
2782
|
+
const submissionCorrelation = correlationOverride ??
|
|
2783
|
+
(submission
|
|
2784
|
+
? { submissionId: submission.submissionId, attemptId: submission.attemptId }
|
|
2785
|
+
: undefined);
|
|
2576
2786
|
const history = SessionHistory.fromData(await this.history());
|
|
2577
2787
|
const path = responseStartLeafId
|
|
2578
2788
|
? history.getActivePathSince(responseStartLeafId)
|
|
@@ -2590,7 +2800,10 @@ export class StubFabricSession {
|
|
|
2590
2800
|
}
|
|
2591
2801
|
const responseId = path.findLast((entry) => entry.type === "assistant_message" ||
|
|
2592
2802
|
entry.type === "tool_result" ||
|
|
2593
|
-
entry.type === "error"
|
|
2803
|
+
entry.type === "error" ||
|
|
2804
|
+
entry.type === "result")?.id ??
|
|
2805
|
+
path.at(-1)?.id ??
|
|
2806
|
+
responseStartLeafId;
|
|
2594
2807
|
const response = {
|
|
2595
2808
|
...(responseId ? { responseId } : {}),
|
|
2596
2809
|
result: value,
|
|
@@ -2775,11 +2988,16 @@ export class StubFabricSession {
|
|
|
2775
2988
|
}
|
|
2776
2989
|
async emit(type, data) {
|
|
2777
2990
|
await this.ensureData();
|
|
2991
|
+
const submission = currentSubmissionContext();
|
|
2992
|
+
const agentName = this.agent.name ?? submission?.agent;
|
|
2778
2993
|
const event = {
|
|
2779
2994
|
id: `${this.id}-${Date.now()}-${Math.random().toString(16).slice(2)}`,
|
|
2780
2995
|
type,
|
|
2781
2996
|
timestamp: new Date().toISOString(),
|
|
2782
2997
|
sessionId: this.id,
|
|
2998
|
+
...(this.agent.id ? { agentId: this.agent.id } : {}),
|
|
2999
|
+
...(agentName ? { agentName } : {}),
|
|
3000
|
+
...(submission?.submissionId ? { submissionId: submission.submissionId } : {}),
|
|
2783
3001
|
...(this.options.tenantId ? { tenantId: this.options.tenantId } : {}),
|
|
2784
3002
|
...(data ? { data } : {}),
|
|
2785
3003
|
};
|
|
@@ -2800,11 +3018,28 @@ function normalizeSkillReference(value) {
|
|
|
2800
3018
|
function stripMarkdownExtension(value) {
|
|
2801
3019
|
return value.endsWith(".md") ? value.slice(0, -3) : value;
|
|
2802
3020
|
}
|
|
2803
|
-
|
|
3021
|
+
const SINGLE_PATH_TOOLS = new Set([
|
|
3022
|
+
"read",
|
|
3023
|
+
"read_buffer",
|
|
3024
|
+
"stat",
|
|
3025
|
+
"readdir",
|
|
3026
|
+
"exists",
|
|
3027
|
+
"grep",
|
|
3028
|
+
"write",
|
|
3029
|
+
"edit",
|
|
3030
|
+
"mkdir",
|
|
3031
|
+
"rm",
|
|
3032
|
+
]);
|
|
3033
|
+
function affectedPathsFromInput(input, toolName) {
|
|
2804
3034
|
if (typeof input !== "object" || input === null)
|
|
2805
3035
|
return [];
|
|
2806
3036
|
const record = input;
|
|
2807
|
-
const
|
|
3037
|
+
const candidates = toolName === "glob"
|
|
3038
|
+
? [record.cwd]
|
|
3039
|
+
: toolName !== undefined && SINGLE_PATH_TOOLS.has(toolName)
|
|
3040
|
+
? [record.path]
|
|
3041
|
+
: [record.path, record.cwd];
|
|
3042
|
+
const paths = candidates.filter((value) => typeof value === "string");
|
|
2808
3043
|
return [...new Set(paths)];
|
|
2809
3044
|
}
|
|
2810
3045
|
function commandEnvKeys(tool) {
|