@nathanstephenson/flow 0.1.2 → 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 +135 -39
- package/dist/backend/claude/mcp.js +3 -1
- package/dist/backend/claude/permissions.js +26 -15
- package/dist/backend/claude/subagents.js +4 -0
- package/dist/backend/claude/workflow-parent.js +4 -1
- package/dist/backend/claude/workflow-subagent.js +2 -2
- 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/auto-compaction.js +1 -3
- package/dist/backend/pi/compaction-model.js +38 -0
- package/dist/backend/pi/index.js +71 -24
- package/dist/backend/pi/work.js +1 -1
- package/dist/backend/pi/workflow-subagent.js +11 -2
- 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 +38 -2
- package/dist/daemon/config.js +110 -51
- package/dist/daemon/host.js +301 -30
- 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 +72 -27
- 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 +5 -4
- 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-BlZBshi8.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-ZMIfuuZU.js +0 -1
- package/web/dist/assets/settings-secrets-CgTrBpi2.js +0 -1
- package/web/dist/assets/settings-workflows-1DMYfZtn.js +0 -23
- package/web/dist/assets/switch-ftZleVB8.js +0 -6
- package/web/dist/assets/workflows-CBuB_bva.js +0 -7
- package/web/dist/assets/workflows-pane-DPXGg0na.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
|
*
|
|
@@ -158,6 +161,7 @@ class ClaudeSession {
|
|
|
158
161
|
emit;
|
|
159
162
|
stream;
|
|
160
163
|
pump;
|
|
164
|
+
modelsReady;
|
|
161
165
|
sdkSessionId = "";
|
|
162
166
|
turnId;
|
|
163
167
|
/** Set between asking the CLI for a compaction and the `result` that closes it. See `compact`. */
|
|
@@ -184,6 +188,9 @@ class ClaudeSession {
|
|
|
184
188
|
calls = new BackgroundCalls();
|
|
185
189
|
enquiries = new PendingEnquiries();
|
|
186
190
|
permissions = new PendingPermissions();
|
|
191
|
+
/** Spawning call id for each parked ordinary-Subagent permission, through its terminal event. */
|
|
192
|
+
permissionProducers = new Map();
|
|
193
|
+
permissionMode;
|
|
187
194
|
/**
|
|
188
195
|
* What runs without being asked about: the pre-approved set, plus the Standing Authorisations this
|
|
189
196
|
* Backend Session was created with.
|
|
@@ -206,11 +213,14 @@ class ClaudeSession {
|
|
|
206
213
|
options;
|
|
207
214
|
backendOptions;
|
|
208
215
|
workflowAutoCompaction;
|
|
209
|
-
|
|
216
|
+
claudeState;
|
|
217
|
+
constructor(options, backendOptions, claudeState) {
|
|
218
|
+
this.claudeState = claudeState;
|
|
210
219
|
this.parentWorkflow = workflowParentServer(options.tools === "none" ? undefined : options.workflow);
|
|
211
220
|
this.options = options;
|
|
221
|
+
this.permissionMode = options.permissionMode ?? "ask";
|
|
212
222
|
this.backendOptions = backendOptions;
|
|
213
|
-
this.workflowAutoCompaction = structuredClone(options.autoCompaction
|
|
223
|
+
this.workflowAutoCompaction = structuredClone(options.autoCompaction);
|
|
214
224
|
this.emit = options.emit;
|
|
215
225
|
this.workflowGrants = new Set(options.standingAuthorisations ?? []);
|
|
216
226
|
this.modelId = options.modelId;
|
|
@@ -227,10 +237,10 @@ class ClaudeSession {
|
|
|
227
237
|
// pre-approved set. A Standing Authorisation is honoured in `canUseTool` instead, so that
|
|
228
238
|
// `disallowedTools` — which an operator meant — still outranks a grant a human clicked.
|
|
229
239
|
const startingEffort = sdkEffort(options.effort);
|
|
230
|
-
const env = claudeAutoCompactionEnv(
|
|
240
|
+
const env = claudeAutoCompactionEnv(this.workflowAutoCompaction, claudeState.env) ?? claudeState.env;
|
|
231
241
|
const queryOptions = {
|
|
232
242
|
cwd: options.scope,
|
|
233
|
-
|
|
243
|
+
env,
|
|
234
244
|
includePartialMessages: true,
|
|
235
245
|
mcpServers: toolless ? {} : { ...claudeMcpServers(options.mcp), ...this.parentWorkflow },
|
|
236
246
|
strictMcpConfig: true,
|
|
@@ -267,16 +277,23 @@ class ClaudeSession {
|
|
|
267
277
|
// the turn open until the caller gave up on it.
|
|
268
278
|
if (toolless)
|
|
269
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.` };
|
|
270
282
|
if (toolName === ASK_TOOL)
|
|
271
283
|
return await this.ask(extra.toolUseID, input);
|
|
272
|
-
if (this.allowed.has(toolName) || this.workflowGrants.has(toolName))
|
|
284
|
+
if (this.permissionMode === "always" || this.allowed.has(toolName) || this.workflowGrants.has(toolName))
|
|
273
285
|
return { behavior: "allow", updatedInput: input };
|
|
274
|
-
|
|
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);
|
|
275
292
|
},
|
|
276
293
|
};
|
|
277
294
|
this.stream = (backendOptions.query ?? query)({ prompt: this.inbox, options: queryOptions });
|
|
278
295
|
this.pump = this.consume();
|
|
279
|
-
|
|
296
|
+
this.modelsReady = this.loadModels();
|
|
280
297
|
// A meter that only fills once a turn ends reads as "no window" when it is really just early.
|
|
281
298
|
// Occupancy is already meaningful here: system prompt, tools and memory files are loaded
|
|
282
299
|
// before anything is sent.
|
|
@@ -466,29 +483,43 @@ class ClaudeSession {
|
|
|
466
483
|
/**
|
|
467
484
|
* Hold the permission callback for a tool nobody has authorised until a human decides.
|
|
468
485
|
*
|
|
469
|
-
* The returned promise
|
|
470
|
-
* throw and no path may drop it. Deliberately has no timeout, the rule ADR 0016
|
|
471
|
-
* — a timer that gave up on a prompt someone was still reading would be worse
|
|
472
|
-
* 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.
|
|
473
490
|
*
|
|
474
|
-
* A tool already refused this
|
|
491
|
+
* A tool already refused in this producer's work is answered here rather than asked again, with the
|
|
475
492
|
* adapter's own neutral message. That is not a shortcut: a model that wanted a tool wants it
|
|
476
493
|
* several times, and re-asking the moment someone says no pins the composer on the same question
|
|
477
494
|
* while the model rephrases around it.
|
|
478
495
|
*/
|
|
479
|
-
async authorise(callId, tool, input) {
|
|
480
|
-
if (this.permissions.isRefused(tool)) {
|
|
496
|
+
async authorise(callId, tool, input, producer, signal) {
|
|
497
|
+
if (this.permissions.isRefused(tool, producer)) {
|
|
481
498
|
return { behavior: "deny", message: `${tool} is not enabled for this session. Continue without it.` };
|
|
482
499
|
}
|
|
483
500
|
return await new Promise((resolve) => {
|
|
484
|
-
|
|
485
|
-
|
|
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();
|
|
486
515
|
});
|
|
487
516
|
}
|
|
488
517
|
async answerPermission(callId, decision) {
|
|
489
518
|
const tool = this.permissions.describe(callId);
|
|
490
519
|
if (tool === undefined || !this.permissions.decide(callId, decision))
|
|
491
520
|
return false;
|
|
521
|
+
const producer = this.permissionProducers.get(callId) ?? "";
|
|
522
|
+
this.permissionProducers.delete(callId);
|
|
492
523
|
// Before the snapshot, so nothing can observe a decided Always against a session still asking.
|
|
493
524
|
// The Standing Authorisation itself is the host's to persist; this is only this session honouring
|
|
494
525
|
// it, which it must do itself because the list it was created with is a snapshot.
|
|
@@ -496,22 +527,33 @@ class ClaudeSession {
|
|
|
496
527
|
this.allowed.add(tool);
|
|
497
528
|
this.workflowGrants.add(tool);
|
|
498
529
|
}
|
|
499
|
-
this.emit({ type: "permission", callId, tool, state: "decided", decision });
|
|
530
|
+
this.emit({ type: "permission", callId, tool, ...attribution(producer), state: "decided", decision });
|
|
500
531
|
return true;
|
|
501
532
|
}
|
|
502
533
|
/**
|
|
503
534
|
* Settle every open Permission Prompt as unauthorised, and say so in the transcript.
|
|
504
535
|
*
|
|
505
|
-
*
|
|
506
|
-
*
|
|
507
|
-
* 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.
|
|
508
538
|
*/
|
|
509
|
-
abandonPermissions(why) {
|
|
510
|
-
for (const { callId, tool } of this.permissions.abandonAll(why)) {
|
|
511
|
-
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" });
|
|
512
544
|
}
|
|
513
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
|
+
}
|
|
514
555
|
async abort() {
|
|
556
|
+
// Keep the existing all-prompts semantics: this interrupts the shared CLI, not a single producer.
|
|
515
557
|
// Before the interrupt, not after: the CLI is blocked on this callback, and an interrupt that
|
|
516
558
|
// waits on the outstanding permission request would be waiting on something only this releases.
|
|
517
559
|
this.abandonEnquiries("the turn was aborted");
|
|
@@ -523,6 +565,10 @@ class ClaudeSession {
|
|
|
523
565
|
this.emit({ type: "notice", level: "warn", text: `Interrupt failed: ${message(error)}` });
|
|
524
566
|
}
|
|
525
567
|
}
|
|
568
|
+
async setPermissionMode(mode) {
|
|
569
|
+
await this.stream.setPermissionMode(mode === "auto" ? "auto" : "default");
|
|
570
|
+
this.permissionMode = mode;
|
|
571
|
+
}
|
|
526
572
|
async setModel(modelId) {
|
|
527
573
|
await this.stream.setModel(modelId);
|
|
528
574
|
this.announceModel(modelId);
|
|
@@ -581,7 +627,13 @@ class ClaudeSession {
|
|
|
581
627
|
...(this.backendOptions.pathToClaudeCodeExecutable ? { pathToClaudeCodeExecutable: this.backendOptions.pathToClaudeCodeExecutable } : {}),
|
|
582
628
|
}, options, this.workflowGrants, {
|
|
583
629
|
...(this.backendOptions.query ? { query: this.backendOptions.query } : {}),
|
|
584
|
-
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
|
+
}),
|
|
585
637
|
}, this.workflowAutoCompaction);
|
|
586
638
|
this.workflowSubagents.add(handle);
|
|
587
639
|
void handle.done.finally(() => this.workflowSubagents.delete(handle)).catch(() => { });
|
|
@@ -598,6 +650,7 @@ class ClaudeSession {
|
|
|
598
650
|
// belongs to is going Dormant — so that record is exactly what the next Revive resumes onto.
|
|
599
651
|
this.abandonEnquiries("the session stopped");
|
|
600
652
|
this.abandonPermissions("the session stopped");
|
|
653
|
+
this.permissions.clearRefusals();
|
|
601
654
|
// Detached Subagents die with the CLI process, so nothing will ever notify them closed. The
|
|
602
655
|
// Session Host records that from the transcript, the way it does a torn turn.
|
|
603
656
|
this.subagents.abandon();
|
|
@@ -610,8 +663,13 @@ class ClaudeSession {
|
|
|
610
663
|
catch {
|
|
611
664
|
// Closing a stream that already ended is not an error worth surfacing.
|
|
612
665
|
}
|
|
613
|
-
|
|
614
|
-
|
|
666
|
+
try {
|
|
667
|
+
await this.pump.catch(() => undefined);
|
|
668
|
+
await workflowsStopped;
|
|
669
|
+
}
|
|
670
|
+
finally {
|
|
671
|
+
this.claudeState.cleanup();
|
|
672
|
+
}
|
|
615
673
|
}
|
|
616
674
|
async consume() {
|
|
617
675
|
try {
|
|
@@ -630,6 +688,7 @@ class ClaudeSession {
|
|
|
630
688
|
// session that has stopped is a question the human can answer into nothing.
|
|
631
689
|
this.abandonEnquiries("the session failed");
|
|
632
690
|
this.abandonPermissions("the session failed");
|
|
691
|
+
this.permissions.clearRefusals();
|
|
633
692
|
this.emit({ type: "notice", level: "error", text: message(error) });
|
|
634
693
|
this.endTurn("error");
|
|
635
694
|
}
|
|
@@ -848,6 +907,8 @@ class ClaudeSession {
|
|
|
848
907
|
this.endTurn(reason);
|
|
849
908
|
}
|
|
850
909
|
closeSubagent(callId) {
|
|
910
|
+
this.abandonPermissions("the Subagent stopped", (producer) => producer === callId);
|
|
911
|
+
this.permissions.clearRefusals((producer) => producer === callId);
|
|
851
912
|
const released = this.subagents.returned(callId);
|
|
852
913
|
if (released)
|
|
853
914
|
this.endTurn(released);
|
|
@@ -930,22 +991,20 @@ class ClaudeSession {
|
|
|
930
991
|
endTurn(reason) {
|
|
931
992
|
const turnId = this.turnId;
|
|
932
993
|
/*
|
|
933
|
-
* Defensive
|
|
934
|
-
*
|
|
935
|
-
*
|
|
936
|
-
* 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).
|
|
937
997
|
*/
|
|
938
998
|
this.abandonEnquiries("the turn ended");
|
|
939
|
-
this.
|
|
940
|
-
|
|
941
|
-
|
|
942
|
-
//
|
|
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.
|
|
943
1003
|
this.subagents.clear();
|
|
944
1004
|
// Drops the calls this turn announced. Open Background Calls survive — one outlives the turn
|
|
945
1005
|
// that made it, which is the whole of ADR 0021.
|
|
946
1006
|
this.calls.clear();
|
|
947
1007
|
this.enquiries.clear();
|
|
948
|
-
this.permissions.clear();
|
|
949
1008
|
if (!turnId)
|
|
950
1009
|
return;
|
|
951
1010
|
this.turnId = undefined;
|
|
@@ -960,10 +1019,47 @@ export class ClaudeBackend {
|
|
|
960
1019
|
this.options = { ...options, ...(resolved ? { pathToClaudeCodeExecutable: resolved } : {}) };
|
|
961
1020
|
}
|
|
962
1021
|
async create(options) {
|
|
963
|
-
//
|
|
964
|
-
//
|
|
965
|
-
//
|
|
966
|
-
|
|
1022
|
+
// Do not await the init message: streaming input yields none until the first prompt. The
|
|
1023
|
+
// supportedModels control request does answer before that prompt, however. Returning while it
|
|
1024
|
+
// is still in flight lets the first send race the empty provisional capabilities.
|
|
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
|
+
}
|
|
1034
|
+
let timer;
|
|
1035
|
+
try {
|
|
1036
|
+
await Promise.race([
|
|
1037
|
+
session.modelsReady,
|
|
1038
|
+
new Promise((_, reject) => {
|
|
1039
|
+
timer = setTimeout(() => reject(new Error("Model capability discovery timed out")), 45_000);
|
|
1040
|
+
}),
|
|
1041
|
+
]);
|
|
1042
|
+
if (session.capabilities.models.length === 0) {
|
|
1043
|
+
throw new Error("Claude model capabilities are unavailable; check the CLI and try again");
|
|
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
|
+
}
|
|
1053
|
+
return session;
|
|
1054
|
+
}
|
|
1055
|
+
catch (error) {
|
|
1056
|
+
await session.dispose();
|
|
1057
|
+
throw error;
|
|
1058
|
+
}
|
|
1059
|
+
finally {
|
|
1060
|
+
if (timer)
|
|
1061
|
+
clearTimeout(timer);
|
|
1062
|
+
}
|
|
967
1063
|
}
|
|
968
1064
|
}
|
|
969
1065
|
/** Claude reports one Provider, and per-model effort: haiku carries no supportedEffortLevels. */
|
|
@@ -26,7 +26,9 @@ export async function refreshClaudeMcp(stream, mcp, additional = {}) {
|
|
|
26
26
|
break;
|
|
27
27
|
await new Promise((resolve) => setTimeout(resolve, 25));
|
|
28
28
|
}
|
|
29
|
-
|
|
29
|
+
// A failed external refresh must not remove the parent workflow controls. They are owned by
|
|
30
|
+
// this Backend Session, not by the external connection being retried.
|
|
31
|
+
await stream.setMcpServers(additional);
|
|
30
32
|
throw new Error("MCP tools could not be registered");
|
|
31
33
|
}
|
|
32
34
|
export function claudeMcpServers(mcp) {
|
|
@@ -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)
|
|
@@ -3,7 +3,10 @@ import { workflowInspectInput, workflowRecoverInput, workflowRelayInput, inspect
|
|
|
3
3
|
export function workflowParentServer(parent) {
|
|
4
4
|
if (!parent)
|
|
5
5
|
return {};
|
|
6
|
-
|
|
6
|
+
// The parent is woken with a request to call a specific relay tool. Newer Claude models
|
|
7
|
+
// defer MCP tools behind tool search by default, which can leave that tool unavailable
|
|
8
|
+
// in the relay turn. Keep these host-owned controls in the prompt from turn one.
|
|
9
|
+
return { flow_workflow: createSdkMcpServer({ name: 'flow_workflow', alwaysLoad: true, tools: [
|
|
7
10
|
tool('workflow_inspect', inspectDescription, workflowInspectInput.shape, async (input) => ({ content: [{ type: 'text', text: JSON.stringify(await parent.inspect(input)) }] })),
|
|
8
11
|
tool('workflow_recover', recoverDescription, workflowRecoverInput.shape, async (input, extra) => ({ content: [{ type: 'text', text: JSON.stringify(await parent.recover(input, extra?.signal)) }] })),
|
|
9
12
|
tool('workflow_relay_enquiry', relayEnquiryDescription, workflowRelayInput.shape, async (input, extra) => ({ content: [{ type: 'text', text: JSON.stringify(await parent.relayEnquiry(input, extra?.signal)) }] })),
|
|
@@ -21,7 +21,7 @@ export class ClaudeWorkflowSubagent {
|
|
|
21
21
|
launch;
|
|
22
22
|
dependencies;
|
|
23
23
|
autoCompaction;
|
|
24
|
-
constructor(launch, options, grants, dependencies = {}, autoCompaction
|
|
24
|
+
constructor(launch, options, grants, dependencies = {}, autoCompaction) {
|
|
25
25
|
this.launch = launch;
|
|
26
26
|
this.dependencies = dependencies;
|
|
27
27
|
this.options = { ...options, input: structuredClone(options.input) };
|
|
@@ -105,7 +105,7 @@ export class ClaudeWorkflowSubagent {
|
|
|
105
105
|
const skillContext = options.skill
|
|
106
106
|
? `You are workflow Subagent ${options.name}. The leading Skill invocation is expanded as the user prompt. Follow it together with the mapped workflow input below.\n\nMapped workflow input (JSON):\n${JSON.stringify(options.input)}\n\nWorkflow constraints:${options.instructions.slice(options.skill.invocation.length)}`
|
|
107
107
|
: options.instructions;
|
|
108
|
-
const compactionEnv = claudeAutoCompactionEnv(this.autoCompaction
|
|
108
|
+
const compactionEnv = claudeAutoCompactionEnv(this.autoCompaction) ?? process.env;
|
|
109
109
|
const stream = (this.dependencies.query ?? query)({ prompt: this.inbox, options: {
|
|
110
110
|
...this.launch, model: options.modelId,
|
|
111
111
|
...(options.effort === "off" ? {} : { effort: options.effort }),
|