@nathanstephenson/flow 0.1.3 → 0.1.4
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/README.md +46 -2
- package/build/workflow-runtime.cjs +1 -46
- package/dist/backend/claude/index.js +108 -34
- package/dist/backend/claude/permissions.js +26 -15
- package/dist/backend/claude/subagents.js +4 -0
- package/dist/backend/mcp-stdio-supervisor.js +196 -0
- package/dist/backend/mcp.js +146 -51
- package/dist/backend/permission-errors.js +3 -0
- package/dist/backend/pi/agent-permissions.js +74 -0
- package/dist/backend/pi/index.js +29 -9
- package/dist/backend/registry.js +5 -30
- package/dist/backend/worker/assets.js +16 -0
- package/dist/backend/worker/claude-state.js +61 -0
- package/dist/backend/worker/entry.js +186 -0
- package/dist/backend/worker/index.js +255 -0
- package/dist/backend/worker/launcher.js +67 -0
- package/dist/backend/worker/protocol.js +11 -0
- package/dist/backend/worker/rpc.js +108 -0
- package/dist/build-id +1 -1
- package/dist/cli/bootstrap.js +1 -1
- package/dist/cli/main.js +9 -1
- package/dist/client/connection.js +107 -2
- package/dist/client/diff.js +43 -0
- package/dist/client/reduce.js +3 -0
- package/dist/daemon/config-store.js +36 -1
- package/dist/daemon/config.js +54 -18
- package/dist/daemon/host.js +279 -29
- package/dist/daemon/log.js +98 -0
- package/dist/daemon/runtime.js +10 -1
- package/dist/daemon/server.js +67 -1
- package/dist/daemon/workflow-execution-routes.js +1 -1
- package/dist/daemon/workflow-executions.js +63 -25
- package/dist/daemon/workflow-mcp.js +2 -4
- package/dist/daemon/workflow-routes.js +4 -3
- package/dist/isolation/filesystem.js +382 -0
- package/dist/isolation/launcher.js +40 -0
- package/dist/isolation/node-assets.js +84 -0
- package/dist/isolation/support.js +40 -0
- package/dist/isolation/toolchain-assets.js +62 -0
- package/dist/protocol/presentation.js +230 -0
- package/dist/protocol/settings.js +1 -4
- package/dist/workflows/executors.js +118 -62
- package/dist/workflows/graph.js +3 -6
- package/dist/workflows/json-schema.js +8 -3
- package/dist/workflows/mcp.js +15 -1
- package/dist/workflows/runtime-settings.js +7 -7
- package/dist/workflows/runtime.js +1 -34
- package/package.json +1 -1
- package/web/dist/assets/index-Bn-ECZ7w.js +174 -0
- package/web/dist/assets/index-DL0CGVaN.css +2 -0
- package/web/dist/assets/input-NIrLDFaS.js +6 -0
- package/web/dist/assets/settings-mcp-B60T2XUv.js +1 -0
- package/web/dist/assets/settings-secrets-BtQwc-w4.js +1 -0
- package/web/dist/assets/settings-workflows-BZ4W0Ja8.js +23 -0
- package/web/dist/assets/switch-DyYU6B5T.js +1 -0
- package/web/dist/assets/workflows-BAdf2yKH.js +7 -0
- package/web/dist/assets/workflows-pane-MSSNIrgu.js +1 -0
- package/web/dist/index.html +4 -4
- package/web/dist/assets/index-BmX_AxCZ.js +0 -170
- package/web/dist/assets/index-DWF4-3Fh.css +0 -2
- package/web/dist/assets/select-6i3wxovH.js +0 -1
- package/web/dist/assets/settings-mcp-CSLXJftV.js +0 -1
- package/web/dist/assets/settings-secrets-DpEwZLL4.js +0 -1
- package/web/dist/assets/settings-workflows-Dt-GaRtX.js +0 -23
- package/web/dist/assets/switch-ftZleVB8.js +0 -6
- package/web/dist/assets/workflows-DDRfFnAE.js +0 -7
- package/web/dist/assets/workflows-pane-g5njqean.js +0 -1
package/README.md
CHANGED
|
@@ -36,6 +36,36 @@ do not start another host against that state directory. Inspect the log and reso
|
|
|
36
36
|
operation before attempting recovery.
|
|
37
37
|
Configure credentials for the Backend Adapter you use.
|
|
38
38
|
|
|
39
|
+
Claude and Pi Backend Sessions run in owned workers in **both** filesystem modes. Machine-wide
|
|
40
|
+
**Settings → General → Filesystem isolation** defaults to ON when a real Linux Bubblewrap launch
|
|
41
|
+
check succeeds, and **UNRESTRICTED** when enforcement is unsupported or unavailable (including on
|
|
42
|
+
macOS, missing Bubblewrap or unavailable namespaces). Settings shows the support reason and a
|
|
43
|
+
clear unrestricted warning. The initial automatic choice is latched for the Session Host's lifetime.
|
|
44
|
+
|
|
45
|
+
When isolation is enabled, Bubblewrap makes the host filesystem read-only, with writable mounts
|
|
46
|
+
only for the selected Scope, dedicated backend state and private scratch. Subagents and Background
|
|
47
|
+
Calls inherit that boundary. Local Workflow Shell and TypeScript steps and local stdio MCP servers
|
|
48
|
+
receive the policy too. One boundary covers the local supervisor, QuickJS worker and all Shell
|
|
49
|
+
descendants; its inherited PID namespace enforces cleanup even for detached processes. Local code
|
|
50
|
+
steps require host Node 22 or later; `workflowRuntime` Settings contain only an optional absolute
|
|
51
|
+
`nodePath` override. HTTP MCP and network access are unchanged in either mode.
|
|
52
|
+
|
|
53
|
+
For Linux enforcement, install Bubblewrap (for example, `sudo apt install bubblewrap`) with
|
|
54
|
+
descriptor-backed bind mounts (`--bind-fd` and `--ro-bind-fd`) to pin mount sources, and working
|
|
55
|
+
user, mount and PID namespaces. **Explicit enable fails closed**: unavailable enforcement, unsafe
|
|
56
|
+
Scopes and failed restricted launches refuse work, never silently downgrading to unrestricted.
|
|
57
|
+
After installing or fixing enforcement, restart the Session Host to refresh its automatic choice.
|
|
58
|
+
|
|
59
|
+
With isolation off, Scope is only a working directory. Agent tools, Shell commands and local stdio
|
|
60
|
+
MCP servers can read, write or delete elsewhere as the host user, including credentials and Flow
|
|
61
|
+
state. Detached processes lack PID-namespace containment. QuickJS, closed compilation and scoped
|
|
62
|
+
filesystem APIs still restrict direct TypeScript guest access, but Shell and the trusted Node
|
|
63
|
+
supervisor have unrestricted host authority, not an OS-enforced boundary.
|
|
64
|
+
|
|
65
|
+
The Session Host retains transcripts and authorisation; worker failure interrupts rather than replays
|
|
66
|
+
work. Neither mode protects Scope from damage or fully mediates pre-existing hard links and data
|
|
67
|
+
aliases. See [the policy and its limits](docs/adr/0028-local-model-work-has-a-fail-closed-filesystem-boundary.md).
|
|
68
|
+
|
|
39
69
|
To check a release from source, run `npm ci` and `npm run test:package`.
|
|
40
70
|
This builds, packs, and installs the archive into a temporary prefix, then checks it
|
|
41
71
|
from an unrelated directory. Build outputs are not tracked in Git.
|
|
@@ -477,6 +507,7 @@ Settings are machine-wide: they govern every Agent Session on the machine, not o
|
|
|
477
507
|
|
|
478
508
|
| Setting | Meaning | Default |
|
|
479
509
|
| --- | --- | --- |
|
|
510
|
+
| `filesystemIsolation` | Machine-wide filesystem enforcement: `true` requires isolation; `false` selects unrestricted execution. | automatic: ON when actual Linux Bubblewrap enforcement is available, otherwise UNRESTRICTED |
|
|
480
511
|
| `retention.settled` | How long a Settled Agent Session survives before it is reaped. A duration — `90m`, `36h`, `1d` — or `never`. | `1d` |
|
|
481
512
|
| `fonts.chrome` | The interface typeface: labels, transcript prose, buttons. | `'Inter Variable', sans-serif` |
|
|
482
513
|
| `fonts.monospace` | The Shell's terminal, and the chrome that aligns character by character. | a Nerd Font stack (below) |
|
|
@@ -491,6 +522,17 @@ it. The Session Host reads the file through one owner (`src/daemon/config-store.
|
|
|
491
522
|
copying values at startup, so an edit applies to the running daemon: retention takes effect at the
|
|
492
523
|
next hourly sweep, and a typeface immediately.
|
|
493
524
|
|
|
525
|
+
The **General → Filesystem isolation** group shows support status/reason and warns clearly when
|
|
526
|
+
execution is unrestricted. The optional stored key is `filesystemIsolation?: boolean`; leaving it
|
|
527
|
+
out selects automatic mode, and PUT `/api/config` with `filesystemIsolation: null` resets to that
|
|
528
|
+
mode. Omitting the key in a PUT leaves the current override unchanged. The config view reports
|
|
529
|
+
isolation status with `supported`, `enabled`, `automatic`, `checking` and `reason`. The initial
|
|
530
|
+
capability-dependent automatic choice remains fixed until the Session Host restarts; a failed
|
|
531
|
+
enabled launch never changes it to unrestricted. Checking must finish before automatic work launches.
|
|
532
|
+
Settings changes apply to new Backend Sessions (including Revive), new Workflow Executions and new
|
|
533
|
+
local stdio MCP clients, not existing work. Agent Workflow Steps inherit their Backend Session's
|
|
534
|
+
policy. Worker process separation stays on in both modes; HTTP MCP and network access do not change.
|
|
535
|
+
|
|
494
536
|
Shortening `retention.settled` arms a delete. Nothing is removed on save — the sweep does it, within
|
|
495
537
|
the hour — but the Settings page counts the Agent Sessions the new window newly reaches and makes you
|
|
496
538
|
confirm before saving. Only Settled Agent Sessions are ever reaped; an Ended one stays on disk.
|
|
@@ -625,8 +667,10 @@ explicitly; no constraint is silently discarded. Supported dialects are draft-07
|
|
|
625
667
|
2020-12 (the MCP default).
|
|
626
668
|
|
|
627
669
|
Direct steps support both stdio and Streamable HTTP, including existing OAuth sign-in. They make
|
|
628
|
-
no model call, create no Subagent and add no model tokens.
|
|
629
|
-
|
|
670
|
+
no model call, create no Subagent and add no model tokens. New local stdio clients capture the
|
|
671
|
+
machine-wide filesystem isolation policy: servers are restricted when enabled and otherwise run
|
|
672
|
+
with unrestricted host-user filesystem authority. Existing clients retain their policy; HTTP calls
|
|
673
|
+
use the configured remote service unchanged.
|
|
630
674
|
Credentials belong in MCP Settings, never in workflow arguments. Expired/missing authentication
|
|
631
675
|
requires signing in there and a manual Retry; executions never launch a login flow or replay an
|
|
632
676
|
HTTP tool request after a 401.
|
|
@@ -213597,57 +213597,12 @@ lines.on("line", (line) => {
|
|
|
213597
213597
|
lease = setTimeout(() => stop(), 3e3);
|
|
213598
213598
|
if (started) return;
|
|
213599
213599
|
started = true;
|
|
213600
|
-
void
|
|
213600
|
+
void run(JSON.parse(line)).then((output) => finish({ output }), (error) => finish({ error: error instanceof Error ? error.message : String(error) }));
|
|
213601
213601
|
});
|
|
213602
213602
|
function finish(result) {
|
|
213603
213603
|
clearTimeout(lease);
|
|
213604
213604
|
process.stdout.write(JSON.stringify(result) + "\n", () => process.exit(0));
|
|
213605
213605
|
}
|
|
213606
|
-
async function dockerSupervisor(config) {
|
|
213607
|
-
const child = (0, import_node_child_process.spawn)(config.docker, config.args, { stdio: ["pipe", "pipe", "pipe"] });
|
|
213608
|
-
let output = "", error = "", stopped = false;
|
|
213609
|
-
stop = () => {
|
|
213610
|
-
stopped = true;
|
|
213611
|
-
controller.abort();
|
|
213612
|
-
child.kill("SIGKILL");
|
|
213613
|
-
};
|
|
213614
|
-
const deadline = setTimeout(stop, config.request.timeout);
|
|
213615
|
-
child.stdin.on("error", () => {
|
|
213616
|
-
});
|
|
213617
|
-
child.stdin.write(JSON.stringify(config.request) + "\n");
|
|
213618
|
-
const heartbeat = setInterval(() => {
|
|
213619
|
-
if (!stopped) child.stdin.write("\n");
|
|
213620
|
-
}, 500);
|
|
213621
|
-
child.stdout.setEncoding("utf8").on("data", (chunk) => {
|
|
213622
|
-
output += chunk;
|
|
213623
|
-
});
|
|
213624
|
-
child.stderr.setEncoding("utf8").on("data", (chunk) => {
|
|
213625
|
-
error = (error + chunk).slice(-1e3);
|
|
213626
|
-
});
|
|
213627
|
-
try {
|
|
213628
|
-
const code = await new Promise((resolve2, reject) => {
|
|
213629
|
-
child.once("error", reject);
|
|
213630
|
-
child.once("close", resolve2);
|
|
213631
|
-
});
|
|
213632
|
-
if (stopped || code !== 0) throw new Error(`Docker runtime stopped (${code}): ${error}`);
|
|
213633
|
-
const result = JSON.parse(output);
|
|
213634
|
-
if (Object.hasOwn(result, "error")) throw new Error(result.error);
|
|
213635
|
-
return result.output;
|
|
213636
|
-
} finally {
|
|
213637
|
-
clearInterval(heartbeat);
|
|
213638
|
-
clearTimeout(deadline);
|
|
213639
|
-
clearTimeout(lease);
|
|
213640
|
-
await new Promise((resolve2, reject) => {
|
|
213641
|
-
const cleanup = (0, import_node_child_process.spawn)(config.docker, ["--host", "unix:///var/run/docker.sock", "rm", "--force", config.name], { stdio: ["ignore", "ignore", "pipe"], timeout: 5e3, killSignal: "SIGKILL" });
|
|
213642
|
-
let error2 = "";
|
|
213643
|
-
cleanup.stderr.on("data", (chunk) => {
|
|
213644
|
-
error2 = (error2 + chunk.toString()).slice(-1e3);
|
|
213645
|
-
});
|
|
213646
|
-
cleanup.once("error", reject);
|
|
213647
|
-
cleanup.once("close", (code) => code === 0 || error2.includes("No such container") ? resolve2() : reject(new Error(`Docker container cleanup failed: ${error2}`)));
|
|
213648
|
-
});
|
|
213649
|
-
}
|
|
213650
|
-
}
|
|
213651
213606
|
async function run(request) {
|
|
213652
213607
|
const timer = setTimeout(() => stop(), request.timeout);
|
|
213653
213608
|
try {
|
|
@@ -12,6 +12,9 @@ import { PendingPermissions } from "./permissions.js";
|
|
|
12
12
|
import { StreamedMessages } from "./streamed-message.js";
|
|
13
13
|
import { Subagents } from "./subagents.js";
|
|
14
14
|
import { BackgroundCalls } from "./background-calls.js";
|
|
15
|
+
import { prepareClaudeState } from "../worker/claude-state.js";
|
|
16
|
+
import { AutoPermissionUnavailable } from "../permission-errors.js";
|
|
17
|
+
export { AutoPermissionUnavailable } from "../permission-errors.js";
|
|
15
18
|
/**
|
|
16
19
|
* Locate the Claude Code CLI.
|
|
17
20
|
*
|
|
@@ -185,6 +188,9 @@ class ClaudeSession {
|
|
|
185
188
|
calls = new BackgroundCalls();
|
|
186
189
|
enquiries = new PendingEnquiries();
|
|
187
190
|
permissions = new PendingPermissions();
|
|
191
|
+
/** Spawning call id for each parked ordinary-Subagent permission, through its terminal event. */
|
|
192
|
+
permissionProducers = new Map();
|
|
193
|
+
permissionMode;
|
|
188
194
|
/**
|
|
189
195
|
* What runs without being asked about: the pre-approved set, plus the Standing Authorisations this
|
|
190
196
|
* Backend Session was created with.
|
|
@@ -207,9 +213,12 @@ class ClaudeSession {
|
|
|
207
213
|
options;
|
|
208
214
|
backendOptions;
|
|
209
215
|
workflowAutoCompaction;
|
|
210
|
-
|
|
216
|
+
claudeState;
|
|
217
|
+
constructor(options, backendOptions, claudeState) {
|
|
218
|
+
this.claudeState = claudeState;
|
|
211
219
|
this.parentWorkflow = workflowParentServer(options.tools === "none" ? undefined : options.workflow);
|
|
212
220
|
this.options = options;
|
|
221
|
+
this.permissionMode = options.permissionMode ?? "ask";
|
|
213
222
|
this.backendOptions = backendOptions;
|
|
214
223
|
this.workflowAutoCompaction = structuredClone(options.autoCompaction);
|
|
215
224
|
this.emit = options.emit;
|
|
@@ -228,10 +237,10 @@ class ClaudeSession {
|
|
|
228
237
|
// pre-approved set. A Standing Authorisation is honoured in `canUseTool` instead, so that
|
|
229
238
|
// `disallowedTools` — which an operator meant — still outranks a grant a human clicked.
|
|
230
239
|
const startingEffort = sdkEffort(options.effort);
|
|
231
|
-
const env = claudeAutoCompactionEnv(this.workflowAutoCompaction);
|
|
240
|
+
const env = claudeAutoCompactionEnv(this.workflowAutoCompaction, claudeState.env) ?? claudeState.env;
|
|
232
241
|
const queryOptions = {
|
|
233
242
|
cwd: options.scope,
|
|
234
|
-
|
|
243
|
+
env,
|
|
235
244
|
includePartialMessages: true,
|
|
236
245
|
mcpServers: toolless ? {} : { ...claudeMcpServers(options.mcp), ...this.parentWorkflow },
|
|
237
246
|
strictMcpConfig: true,
|
|
@@ -268,11 +277,18 @@ class ClaudeSession {
|
|
|
268
277
|
// the turn open until the caller gave up on it.
|
|
269
278
|
if (toolless)
|
|
270
279
|
return { behavior: "deny", message: "This session runs no tools" };
|
|
280
|
+
if (extra.signal.aborted || this.disposed)
|
|
281
|
+
return { behavior: "deny", message: `${toolName} was not authorised: the permission request was cancelled. Continue without it.` };
|
|
271
282
|
if (toolName === ASK_TOOL)
|
|
272
283
|
return await this.ask(extra.toolUseID, input);
|
|
273
|
-
if (this.allowed.has(toolName) || this.workflowGrants.has(toolName))
|
|
284
|
+
if (this.permissionMode === "always" || this.allowed.has(toolName) || this.workflowGrants.has(toolName))
|
|
274
285
|
return { behavior: "allow", updatedInput: input };
|
|
275
|
-
|
|
286
|
+
// The SDK calls this field agentID, but for an ordinary Agent it is the task id announced by
|
|
287
|
+
// task_started, not the Agent tool-use id carried as parent_tool_use_id on transcript events.
|
|
288
|
+
// Resolve through the same task map used by task notifications so the permission belongs to
|
|
289
|
+
// the Subagent card clients can actually answer, rather than to an otherwise unknown id.
|
|
290
|
+
const producer = extra.agentID ? (this.subagents.callIdOf(extra.agentID) ?? extra.agentID) : "";
|
|
291
|
+
return await this.authorise(extra.toolUseID, toolName, input, producer, extra.signal);
|
|
276
292
|
},
|
|
277
293
|
};
|
|
278
294
|
this.stream = (backendOptions.query ?? query)({ prompt: this.inbox, options: queryOptions });
|
|
@@ -467,29 +483,43 @@ class ClaudeSession {
|
|
|
467
483
|
/**
|
|
468
484
|
* Hold the permission callback for a tool nobody has authorised until a human decides.
|
|
469
485
|
*
|
|
470
|
-
* The returned promise
|
|
471
|
-
* throw and no path may drop it. Deliberately has no timeout, the rule ADR 0016
|
|
472
|
-
* — a timer that gave up on a prompt someone was still reading would be worse
|
|
473
|
-
* and Abort is the escape.
|
|
486
|
+
* The returned promise holds the tool call: its producer cannot continue until it settles, so
|
|
487
|
+
* nothing here may throw and no path may drop it. Deliberately has no timeout, the rule ADR 0016
|
|
488
|
+
* set for an Enquiry — a timer that gave up on a prompt someone was still reading would be worse
|
|
489
|
+
* than one that waits, and Abort is the escape.
|
|
474
490
|
*
|
|
475
|
-
* A tool already refused this
|
|
491
|
+
* A tool already refused in this producer's work is answered here rather than asked again, with the
|
|
476
492
|
* adapter's own neutral message. That is not a shortcut: a model that wanted a tool wants it
|
|
477
493
|
* several times, and re-asking the moment someone says no pins the composer on the same question
|
|
478
494
|
* while the model rephrases around it.
|
|
479
495
|
*/
|
|
480
|
-
async authorise(callId, tool, input) {
|
|
481
|
-
if (this.permissions.isRefused(tool)) {
|
|
496
|
+
async authorise(callId, tool, input, producer, signal) {
|
|
497
|
+
if (this.permissions.isRefused(tool, producer)) {
|
|
482
498
|
return { behavior: "deny", message: `${tool} is not enabled for this session. Continue without it.` };
|
|
483
499
|
}
|
|
484
500
|
return await new Promise((resolve) => {
|
|
485
|
-
|
|
486
|
-
|
|
501
|
+
// The SDK cancels individual requests independently of the parent turn (for example when a
|
|
502
|
+
// background Subagent stops). Remove the listener on *every* settlement path, and remove the
|
|
503
|
+
// pending callback before emitting its terminal event so a stale Always cannot grant a tool.
|
|
504
|
+
const onAbort = () => this.abandonPermission(callId, "the permission request was cancelled");
|
|
505
|
+
this.permissions.hold(callId, tool, input, (result) => {
|
|
506
|
+
signal.removeEventListener("abort", onAbort);
|
|
507
|
+
resolve(result);
|
|
508
|
+
}, producer);
|
|
509
|
+
if (producer !== "")
|
|
510
|
+
this.permissionProducers.set(callId, producer);
|
|
511
|
+
signal.addEventListener("abort", onAbort, { once: true });
|
|
512
|
+
this.emit({ type: "permission", callId, tool, ...attribution(producer), state: "asked" });
|
|
513
|
+
if (signal.aborted)
|
|
514
|
+
onAbort();
|
|
487
515
|
});
|
|
488
516
|
}
|
|
489
517
|
async answerPermission(callId, decision) {
|
|
490
518
|
const tool = this.permissions.describe(callId);
|
|
491
519
|
if (tool === undefined || !this.permissions.decide(callId, decision))
|
|
492
520
|
return false;
|
|
521
|
+
const producer = this.permissionProducers.get(callId) ?? "";
|
|
522
|
+
this.permissionProducers.delete(callId);
|
|
493
523
|
// Before the snapshot, so nothing can observe a decided Always against a session still asking.
|
|
494
524
|
// The Standing Authorisation itself is the host's to persist; this is only this session honouring
|
|
495
525
|
// it, which it must do itself because the list it was created with is a snapshot.
|
|
@@ -497,22 +527,33 @@ class ClaudeSession {
|
|
|
497
527
|
this.allowed.add(tool);
|
|
498
528
|
this.workflowGrants.add(tool);
|
|
499
529
|
}
|
|
500
|
-
this.emit({ type: "permission", callId, tool, state: "decided", decision });
|
|
530
|
+
this.emit({ type: "permission", callId, tool, ...attribution(producer), state: "decided", decision });
|
|
501
531
|
return true;
|
|
502
532
|
}
|
|
503
533
|
/**
|
|
504
534
|
* Settle every open Permission Prompt as unauthorised, and say so in the transcript.
|
|
505
535
|
*
|
|
506
|
-
*
|
|
507
|
-
*
|
|
508
|
-
* Revive resumes onto a turn with no dangling `tool_use`.
|
|
536
|
+
* Parent turn cleanup preserves detached producers; termination and Backend Session shutdown do
|
|
537
|
+
* not. Denying rather than dropping leaves the CLI's own conversation record complete.
|
|
509
538
|
*/
|
|
510
|
-
abandonPermissions(why) {
|
|
511
|
-
for (const { callId, tool } of this.permissions.abandonAll(why)) {
|
|
512
|
-
this.
|
|
539
|
+
abandonPermissions(why, matches = () => true) {
|
|
540
|
+
for (const { callId, tool } of this.permissions.abandonAll(why, matches)) {
|
|
541
|
+
const producer = this.permissionProducers.get(callId) ?? "";
|
|
542
|
+
this.permissionProducers.delete(callId);
|
|
543
|
+
this.emit({ type: "permission", callId, tool, ...attribution(producer), state: "aborted" });
|
|
513
544
|
}
|
|
514
545
|
}
|
|
546
|
+
/** Cancel one SDK request, idempotently with human answers and lifecycle cleanup. */
|
|
547
|
+
abandonPermission(callId, why) {
|
|
548
|
+
const tool = this.permissions.abandon(callId, why);
|
|
549
|
+
if (tool === undefined)
|
|
550
|
+
return;
|
|
551
|
+
const producer = this.permissionProducers.get(callId) ?? "";
|
|
552
|
+
this.permissionProducers.delete(callId);
|
|
553
|
+
this.emit({ type: "permission", callId, tool, ...attribution(producer), state: "aborted" });
|
|
554
|
+
}
|
|
515
555
|
async abort() {
|
|
556
|
+
// Keep the existing all-prompts semantics: this interrupts the shared CLI, not a single producer.
|
|
516
557
|
// Before the interrupt, not after: the CLI is blocked on this callback, and an interrupt that
|
|
517
558
|
// waits on the outstanding permission request would be waiting on something only this releases.
|
|
518
559
|
this.abandonEnquiries("the turn was aborted");
|
|
@@ -524,6 +565,10 @@ class ClaudeSession {
|
|
|
524
565
|
this.emit({ type: "notice", level: "warn", text: `Interrupt failed: ${message(error)}` });
|
|
525
566
|
}
|
|
526
567
|
}
|
|
568
|
+
async setPermissionMode(mode) {
|
|
569
|
+
await this.stream.setPermissionMode(mode === "auto" ? "auto" : "default");
|
|
570
|
+
this.permissionMode = mode;
|
|
571
|
+
}
|
|
527
572
|
async setModel(modelId) {
|
|
528
573
|
await this.stream.setModel(modelId);
|
|
529
574
|
this.announceModel(modelId);
|
|
@@ -582,7 +627,13 @@ class ClaudeSession {
|
|
|
582
627
|
...(this.backendOptions.pathToClaudeCodeExecutable ? { pathToClaudeCodeExecutable: this.backendOptions.pathToClaudeCodeExecutable } : {}),
|
|
583
628
|
}, options, this.workflowGrants, {
|
|
584
629
|
...(this.backendOptions.query ? { query: this.backendOptions.query } : {}),
|
|
585
|
-
spawn: (options) => spawnWorkflowProcess(
|
|
630
|
+
spawn: (options) => spawnWorkflowProcess({ ...options,
|
|
631
|
+
...(isSingleExecutable() ? seaSpawnTarget(options) : {}),
|
|
632
|
+
// Worker launches inherit this view already; direct embeddings must pass it to owned
|
|
633
|
+
// Workflow children too, without replacing their toolless/compaction environment.
|
|
634
|
+
env: { ...options.env, CLAUDE_CONFIG_DIR: this.claudeState.env.CLAUDE_CONFIG_DIR,
|
|
635
|
+
CLAUDE_SECURESTORAGE_CONFIG_DIR: this.claudeState.env.CLAUDE_SECURESTORAGE_CONFIG_DIR },
|
|
636
|
+
}),
|
|
586
637
|
}, this.workflowAutoCompaction);
|
|
587
638
|
this.workflowSubagents.add(handle);
|
|
588
639
|
void handle.done.finally(() => this.workflowSubagents.delete(handle)).catch(() => { });
|
|
@@ -599,6 +650,7 @@ class ClaudeSession {
|
|
|
599
650
|
// belongs to is going Dormant — so that record is exactly what the next Revive resumes onto.
|
|
600
651
|
this.abandonEnquiries("the session stopped");
|
|
601
652
|
this.abandonPermissions("the session stopped");
|
|
653
|
+
this.permissions.clearRefusals();
|
|
602
654
|
// Detached Subagents die with the CLI process, so nothing will ever notify them closed. The
|
|
603
655
|
// Session Host records that from the transcript, the way it does a torn turn.
|
|
604
656
|
this.subagents.abandon();
|
|
@@ -611,8 +663,13 @@ class ClaudeSession {
|
|
|
611
663
|
catch {
|
|
612
664
|
// Closing a stream that already ended is not an error worth surfacing.
|
|
613
665
|
}
|
|
614
|
-
|
|
615
|
-
|
|
666
|
+
try {
|
|
667
|
+
await this.pump.catch(() => undefined);
|
|
668
|
+
await workflowsStopped;
|
|
669
|
+
}
|
|
670
|
+
finally {
|
|
671
|
+
this.claudeState.cleanup();
|
|
672
|
+
}
|
|
616
673
|
}
|
|
617
674
|
async consume() {
|
|
618
675
|
try {
|
|
@@ -631,6 +688,7 @@ class ClaudeSession {
|
|
|
631
688
|
// session that has stopped is a question the human can answer into nothing.
|
|
632
689
|
this.abandonEnquiries("the session failed");
|
|
633
690
|
this.abandonPermissions("the session failed");
|
|
691
|
+
this.permissions.clearRefusals();
|
|
634
692
|
this.emit({ type: "notice", level: "error", text: message(error) });
|
|
635
693
|
this.endTurn("error");
|
|
636
694
|
}
|
|
@@ -849,6 +907,8 @@ class ClaudeSession {
|
|
|
849
907
|
this.endTurn(reason);
|
|
850
908
|
}
|
|
851
909
|
closeSubagent(callId) {
|
|
910
|
+
this.abandonPermissions("the Subagent stopped", (producer) => producer === callId);
|
|
911
|
+
this.permissions.clearRefusals((producer) => producer === callId);
|
|
852
912
|
const released = this.subagents.returned(callId);
|
|
853
913
|
if (released)
|
|
854
914
|
this.endTurn(released);
|
|
@@ -931,22 +991,20 @@ class ClaudeSession {
|
|
|
931
991
|
endTurn(reason) {
|
|
932
992
|
const turnId = this.turnId;
|
|
933
993
|
/*
|
|
934
|
-
* Defensive
|
|
935
|
-
*
|
|
936
|
-
*
|
|
937
|
-
* ended — a question with no way to answer it and no way to dismiss it.
|
|
994
|
+
* Defensive for the parent and foreground work: an ended turn cannot answer their callbacks.
|
|
995
|
+
* Detached Subagents hold no parent turn and keep their prompts until their own termination,
|
|
996
|
+
* SDK request cancellation, or Backend Session shutdown (ADR 0016).
|
|
938
997
|
*/
|
|
939
998
|
this.abandonEnquiries("the turn ended");
|
|
940
|
-
this.
|
|
941
|
-
|
|
942
|
-
|
|
943
|
-
//
|
|
999
|
+
const ended = (producer) => !this.subagents.isDetached(producer);
|
|
1000
|
+
this.abandonPermissions("the turn ended", ended);
|
|
1001
|
+
this.permissions.clearRefusals(ended);
|
|
1002
|
+
// Cleared whatever the outcome, so a held end cannot reach the turn after this one.
|
|
944
1003
|
this.subagents.clear();
|
|
945
1004
|
// Drops the calls this turn announced. Open Background Calls survive — one outlives the turn
|
|
946
1005
|
// that made it, which is the whole of ADR 0021.
|
|
947
1006
|
this.calls.clear();
|
|
948
1007
|
this.enquiries.clear();
|
|
949
|
-
this.permissions.clear();
|
|
950
1008
|
if (!turnId)
|
|
951
1009
|
return;
|
|
952
1010
|
this.turnId = undefined;
|
|
@@ -964,7 +1022,15 @@ export class ClaudeBackend {
|
|
|
964
1022
|
// Do not await the init message: streaming input yields none until the first prompt. The
|
|
965
1023
|
// supportedModels control request does answer before that prompt, however. Returning while it
|
|
966
1024
|
// is still in flight lets the first send race the empty provisional capabilities.
|
|
967
|
-
const
|
|
1025
|
+
const claudeState = prepareClaudeState(options.stateDir, process.env, options.scope);
|
|
1026
|
+
let session;
|
|
1027
|
+
try {
|
|
1028
|
+
session = new ClaudeSession(options, this.options, claudeState);
|
|
1029
|
+
}
|
|
1030
|
+
catch (error) {
|
|
1031
|
+
claudeState.cleanup();
|
|
1032
|
+
throw error;
|
|
1033
|
+
}
|
|
968
1034
|
let timer;
|
|
969
1035
|
try {
|
|
970
1036
|
await Promise.race([
|
|
@@ -976,6 +1042,14 @@ export class ClaudeBackend {
|
|
|
976
1042
|
if (session.capabilities.models.length === 0) {
|
|
977
1043
|
throw new Error("Claude model capabilities are unavailable; check the CLI and try again");
|
|
978
1044
|
}
|
|
1045
|
+
if (options.permissionMode === "auto") {
|
|
1046
|
+
try {
|
|
1047
|
+
await session.setPermissionMode("auto");
|
|
1048
|
+
}
|
|
1049
|
+
catch (error) {
|
|
1050
|
+
throw new AutoPermissionUnavailable(`SDK rejected Auto: ${String(error)}`);
|
|
1051
|
+
}
|
|
1052
|
+
}
|
|
979
1053
|
return session;
|
|
980
1054
|
}
|
|
981
1055
|
catch (error) {
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* The Permission Prompts open in
|
|
3
|
-
* already refused.
|
|
2
|
+
* The Permission Prompts open in a Backend Session, the callbacks held for them, and what the human
|
|
3
|
+
* has already refused in each producer's work. Detached Subagents outlive the parent turn.
|
|
4
4
|
*
|
|
5
5
|
* A sibling of `PendingEnquiries`, and the rule is the same one: the Claude SDK does not continue
|
|
6
6
|
* until `canUseTool` settles, so **every path must settle it**. A rejected or dropped callback leaves
|
|
@@ -15,27 +15,27 @@
|
|
|
15
15
|
* than "the human declined", because the model is being unblocked, not corrected, and one told a
|
|
16
16
|
* person refused it will spend the turn negotiating.
|
|
17
17
|
*
|
|
18
|
-
*
|
|
19
|
-
*
|
|
20
|
-
*
|
|
18
|
+
* Producer-scoped and no wider. A no was about what was being attempted, not about the tool forever;
|
|
19
|
+
* the parent forgets its refusals at turn end, a Subagent at termination. Neither can refuse a tool
|
|
20
|
+
* on the other's behalf. Always remains a Backend Session-wide grant.
|
|
21
21
|
*
|
|
22
22
|
* Its own module rather than fields on ClaudeSession because that session cannot be constructed
|
|
23
23
|
* without spawning a Claude process, so none of this would be reachable from a test there.
|
|
24
24
|
*/
|
|
25
25
|
export class PendingPermissions {
|
|
26
26
|
open = new Map();
|
|
27
|
-
refused = new
|
|
27
|
+
refused = new Map();
|
|
28
28
|
/** Park a callback against the call awaiting authorisation. `callId` is the SDK's `toolUseID`. */
|
|
29
|
-
hold(callId, tool, input, settle) {
|
|
30
|
-
this.open.set(callId, { tool, input, settle });
|
|
29
|
+
hold(callId, tool, input, settle, producer = "") {
|
|
30
|
+
this.open.set(callId, { tool, input, settle, producer });
|
|
31
31
|
}
|
|
32
32
|
/** Which tool an open prompt is about, or undefined for one already settled. */
|
|
33
33
|
describe(callId) {
|
|
34
34
|
return this.open.get(callId)?.tool;
|
|
35
35
|
}
|
|
36
|
-
/** Whether this
|
|
37
|
-
isRefused(tool) {
|
|
38
|
-
return this.refused.has(tool);
|
|
36
|
+
/** Whether this producer's work has already refused the tool, so it must not be asked again. */
|
|
37
|
+
isRefused(tool, producer = "") {
|
|
38
|
+
return this.refused.get(producer)?.has(tool) ?? false;
|
|
39
39
|
}
|
|
40
40
|
/**
|
|
41
41
|
* Settle an open prompt with a human's decision.
|
|
@@ -50,7 +50,9 @@ export class PendingPermissions {
|
|
|
50
50
|
return false;
|
|
51
51
|
this.open.delete(callId);
|
|
52
52
|
if (decision === "deny") {
|
|
53
|
-
this.refused.
|
|
53
|
+
const refused = this.refused.get(pending.producer) ?? new Set();
|
|
54
|
+
refused.add(pending.tool);
|
|
55
|
+
this.refused.set(pending.producer, refused);
|
|
54
56
|
pending.settle({ behavior: "deny", message: refusal(pending.tool) });
|
|
55
57
|
return true;
|
|
56
58
|
}
|
|
@@ -69,13 +71,22 @@ export class PendingPermissions {
|
|
|
69
71
|
pending.settle({ behavior: "deny", message: abandonment(pending.tool, why) });
|
|
70
72
|
return pending.tool;
|
|
71
73
|
}
|
|
72
|
-
/** Abandon
|
|
73
|
-
abandonAll(why) {
|
|
74
|
-
return [...this.open
|
|
74
|
+
/** Abandon matching prompts, and name each one for its terminal snapshot. */
|
|
75
|
+
abandonAll(why, matches = () => true) {
|
|
76
|
+
return [...this.open].flatMap(([callId, pending]) => {
|
|
77
|
+
if (!matches(pending.producer))
|
|
78
|
+
return [];
|
|
75
79
|
const tool = this.abandon(callId, why);
|
|
76
80
|
return tool ? [{ callId, tool }] : [];
|
|
77
81
|
});
|
|
78
82
|
}
|
|
83
|
+
/** Forget refusals only for work that ended; pending callbacks must be settled separately. */
|
|
84
|
+
clearRefusals(matches = () => true) {
|
|
85
|
+
for (const producer of this.refused.keys()) {
|
|
86
|
+
if (matches(producer))
|
|
87
|
+
this.refused.delete(producer);
|
|
88
|
+
}
|
|
89
|
+
}
|
|
79
90
|
/**
|
|
80
91
|
* Forget everything without settling anything, and forget what was refused.
|
|
81
92
|
*
|
|
@@ -56,6 +56,10 @@ export class Subagents {
|
|
|
56
56
|
this.detached.set(callId, brief);
|
|
57
57
|
return this.release();
|
|
58
58
|
}
|
|
59
|
+
/** Whether this Subagent's work survives the parent turn ending. */
|
|
60
|
+
isDetached(callId) {
|
|
61
|
+
return this.detached.has(callId);
|
|
62
|
+
}
|
|
59
63
|
/** Remember which Subagent a task id belongs to. Ignores a task that is not one's. */
|
|
60
64
|
noteTask(taskId, callId) {
|
|
61
65
|
if (this.describe(callId) === undefined)
|