@nathanstephenson/flow 0.1.3 → 0.1.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (67) hide show
  1. package/README.md +46 -2
  2. package/build/workflow-runtime.cjs +1 -46
  3. package/dist/backend/claude/index.js +109 -35
  4. package/dist/backend/claude/permissions.js +26 -15
  5. package/dist/backend/claude/subagents.js +4 -0
  6. package/dist/backend/mcp-stdio-supervisor.js +196 -0
  7. package/dist/backend/mcp.js +146 -51
  8. package/dist/backend/permission-errors.js +3 -0
  9. package/dist/backend/pi/agent-permissions.js +74 -0
  10. package/dist/backend/pi/index.js +29 -9
  11. package/dist/backend/registry.js +5 -30
  12. package/dist/backend/worker/assets.js +16 -0
  13. package/dist/backend/worker/claude-state.js +183 -0
  14. package/dist/backend/worker/entry.js +186 -0
  15. package/dist/backend/worker/index.js +257 -0
  16. package/dist/backend/worker/launcher.js +67 -0
  17. package/dist/backend/worker/protocol.js +11 -0
  18. package/dist/backend/worker/rpc.js +108 -0
  19. package/dist/build-id +1 -1
  20. package/dist/cli/bootstrap.js +1 -1
  21. package/dist/cli/main.js +9 -1
  22. package/dist/client/connection.js +107 -2
  23. package/dist/client/diff.js +43 -0
  24. package/dist/client/reduce.js +3 -0
  25. package/dist/daemon/config-store.js +36 -1
  26. package/dist/daemon/config.js +54 -18
  27. package/dist/daemon/host.js +279 -29
  28. package/dist/daemon/log.js +98 -0
  29. package/dist/daemon/runtime.js +10 -1
  30. package/dist/daemon/server.js +67 -1
  31. package/dist/daemon/workflow-execution-routes.js +1 -1
  32. package/dist/daemon/workflow-executions.js +63 -25
  33. package/dist/daemon/workflow-mcp.js +2 -4
  34. package/dist/daemon/workflow-routes.js +4 -3
  35. package/dist/isolation/filesystem.js +382 -0
  36. package/dist/isolation/launcher.js +40 -0
  37. package/dist/isolation/node-assets.js +84 -0
  38. package/dist/isolation/support.js +40 -0
  39. package/dist/isolation/toolchain-assets.js +62 -0
  40. package/dist/protocol/presentation.js +230 -0
  41. package/dist/protocol/settings.js +1 -4
  42. package/dist/workflows/executors.js +118 -62
  43. package/dist/workflows/graph.js +3 -6
  44. package/dist/workflows/json-schema.js +8 -3
  45. package/dist/workflows/mcp.js +15 -1
  46. package/dist/workflows/runtime-settings.js +7 -7
  47. package/dist/workflows/runtime.js +1 -34
  48. package/package.json +1 -1
  49. package/web/dist/assets/index-2oJWC9JF.css +2 -0
  50. package/web/dist/assets/index-6BD3ul5N.js +174 -0
  51. package/web/dist/assets/input-CqyJUgIE.js +6 -0
  52. package/web/dist/assets/settings-mcp-DOQOULdG.js +1 -0
  53. package/web/dist/assets/settings-secrets-D3zCO2H1.js +1 -0
  54. package/web/dist/assets/settings-workflows-BSVIqm4R.js +23 -0
  55. package/web/dist/assets/switch-ehZe7Kr5.js +1 -0
  56. package/web/dist/assets/workflows-DC1k1O8g.js +7 -0
  57. package/web/dist/assets/workflows-pane-B0hL69SD.js +1 -0
  58. package/web/dist/index.html +4 -4
  59. package/web/dist/assets/index-BmX_AxCZ.js +0 -170
  60. package/web/dist/assets/index-DWF4-3Fh.css +0 -2
  61. package/web/dist/assets/select-6i3wxovH.js +0 -1
  62. package/web/dist/assets/settings-mcp-CSLXJftV.js +0 -1
  63. package/web/dist/assets/settings-secrets-DpEwZLL4.js +0 -1
  64. package/web/dist/assets/settings-workflows-Dt-GaRtX.js +0 -23
  65. package/web/dist/assets/switch-ftZleVB8.js +0 -6
  66. package/web/dist/assets/workflows-DDRfFnAE.js +0 -7
  67. package/web/dist/assets/workflows-pane-g5njqean.js +0 -1
@@ -10,6 +10,7 @@ import { compactionExtensionError, compactionModelExtension } from "./compaction
10
10
  import { ASK_TOOL, PiEnquiries } from "./enquiries.js";
11
11
  import { backgroundTools } from "./background-calls.js";
12
12
  import { SUBAGENT_TOOL, subagentTool } from "./subagents.js";
13
+ import { PiAgentPermissions } from "./agent-permissions.js";
13
14
  import { PiWork, callIdFor, resultText, textResult } from "./work.js";
14
15
  export class PiSession {
15
16
  capabilities;
@@ -30,6 +31,9 @@ export class PiSession {
30
31
  this.unsubscribe = this.session.subscribe((event) => this.translate(event));
31
32
  }
32
33
  standingAuthorisations;
34
+ agentPermissions;
35
+ permissionProducer;
36
+ answerPermission;
33
37
  disposed = false;
34
38
  disposal;
35
39
  turnReason = "complete";
@@ -57,6 +61,9 @@ export class PiSession {
57
61
  this.mcp = support.mcp;
58
62
  this.recreate = support.recreate;
59
63
  this.standingAuthorisations = [...(support.standingAuthorisations ?? [])];
64
+ this.agentPermissions = support.agentPermissions;
65
+ if (support.permissionProducer)
66
+ this.permissionProducer = support.permissionProducer;
60
67
  this.session = session;
61
68
  this.applyAutoCompaction = support.autoCompaction;
62
69
  this.workflowAutoCompaction = support.workflowAutoCompaction;
@@ -67,6 +74,8 @@ export class PiSession {
67
74
  this.enquiries = support.enquiries;
68
75
  this.work = support.work;
69
76
  const enquiries = support.enquiries;
77
+ if (this.agentPermissions)
78
+ this.answerPermission = async (callId, decision) => this.agentPermissions.answer(callId, decision);
70
79
  if (enquiries)
71
80
  this.answerEnquiry = async (askId, answers) => enquiries.answer(askId, answers);
72
81
  this.capabilities = capabilitiesOf(session, support.enquiries !== undefined, support.subagents ?? false);
@@ -99,9 +108,11 @@ export class PiSession {
99
108
  });
100
109
  }
101
110
  async abort() {
111
+ this.agentPermissions?.cancel(this.permissionProducer ?? { subagentId: "" });
102
112
  this.aborting = this.turnId !== undefined;
103
113
  await this.session.abort();
104
114
  }
115
+ async setPermissionMode(mode) { this.agentPermissions?.setMode(mode); }
105
116
  async setModel(modelId) {
106
117
  const available = await this.session.modelRuntime.getAvailable();
107
118
  const qualified = available.find((candidate) => describeModel(candidate).id === modelId);
@@ -230,6 +241,7 @@ export class PiSession {
230
241
  }
231
242
  async disposeOnce() {
232
243
  this.disposed = true;
244
+ this.agentPermissions?.cancel(this.permissionProducer);
233
245
  this.completions.length = 0;
234
246
  try {
235
247
  await Promise.all([this.abort(), this.work?.dispose(), ...[...this.workflows.values()].map((handle) => handle.cancel())]);
@@ -400,12 +412,16 @@ export class PiBackend {
400
412
  // Extensions are not loaded: they expect pi's own UI surface, and a background session that
401
413
  // registers UI hooks has nowhere to render them.
402
414
  const settingsManager = SettingsManager.create(options.scope, agentDir);
415
+ const agentPermissions = options.tools === "none" ? undefined : new PiAgentPermissions(options.permissionMode ?? "always", options.standingAuthorisations ?? [], options.emit);
403
416
  const resourceLoader = new DefaultResourceLoader({
404
417
  cwd: options.scope,
405
418
  agentDir,
406
419
  settingsManager,
407
420
  noExtensions: true,
408
- ...(options.compactionModelId ? { extensionFactories: [compactionModelExtension(options.compactionModelId, (text) => options.emit({ type: "notice", level: "error", text }))] } : {}),
421
+ extensionFactories: [
422
+ ...(agentPermissions ? [agentPermissions.extension()] : []),
423
+ ...(options.compactionModelId ? [compactionModelExtension(options.compactionModelId, (text) => options.emit({ type: "notice", level: "error", text }))] : []),
424
+ ],
409
425
  });
410
426
  await resourceLoader.reload();
411
427
  // Reviving reopens the most recent pi session in the directory we gave this Agent Session;
@@ -431,7 +447,7 @@ export class PiBackend {
431
447
  ...workflowTools,
432
448
  ...backgroundTools(options.scope, settingsManager, work).filter((tool) => enabled(tool.name)),
433
449
  ...(enquiries ? [enquiries.tool] : []),
434
- ...(subagents ? [subagentTool(work, (id, input, signal) => runSubagent(session, options.scope, agentDir, work, id, input, signal, options.emit, mcp, options.compactionModelId))] : []),
450
+ ...(subagents ? [subagentTool(work, (id, input, signal) => runSubagent(session, options.scope, agentDir, work, id, input, signal, options.emit, mcp, options.compactionModelId, agentPermissions))] : []),
435
451
  ];
436
452
  const start = (current) => {
437
453
  const mcpTools = piMcpTools(mcp);
@@ -454,7 +470,7 @@ export class PiBackend {
454
470
  throw new Error(`Could not load the Pi compaction model hook: ${extensionError}`);
455
471
  }
456
472
  const autoCompaction = structuredClone(options.autoCompaction);
457
- const piSession = new PiSession(session, options.emit, sessionDir, { ...(mcp ? { mcp } : {}), work, subagents, standingAuthorisations: options.standingAuthorisations ?? [], autoCompaction: piAutoCompaction(settingsManager, autoCompaction), ...(autoCompaction ? { workflowAutoCompaction: autoCompaction } : {}), ...(options.compactionModelId ? { workflowCompactionModelId: options.compactionModelId } : {}), ...(enquiries ? { enquiries } : {}), ...(mcp ? { recreate: async (current) => (session = (await start(current)).session) } : {}) });
473
+ const piSession = new PiSession(session, options.emit, sessionDir, { ...(mcp ? { mcp } : {}), work, subagents, standingAuthorisations: options.standingAuthorisations ?? [], ...(agentPermissions ? { agentPermissions } : {}), autoCompaction: piAutoCompaction(settingsManager, autoCompaction), ...(autoCompaction ? { workflowAutoCompaction: autoCompaction } : {}), ...(options.compactionModelId ? { workflowCompactionModelId: options.compactionModelId } : {}), ...(enquiries ? { enquiries } : {}), ...(mcp ? { recreate: async (current) => (session = (await start(current)).session) } : {}) });
458
474
  if (options.modelId) {
459
475
  try {
460
476
  await piSession.setModel(options.modelId);
@@ -492,7 +508,7 @@ export class PiBackend {
492
508
  return piSession;
493
509
  }
494
510
  }
495
- async function runSubagent(parent, scope, agentDir, work, id, input, signal, emit, mcp, compactionModelId) {
511
+ async function runSubagent(parent, scope, agentDir, work, id, input, signal, emit, mcp, compactionModelId, agentPermissions) {
496
512
  const available = parent.modelRuntime.getAvailableSnapshot();
497
513
  const model = input.model ? available.find((model) => describeModel(model).id === input.model) : parent.model;
498
514
  if (!model)
@@ -500,12 +516,15 @@ async function runSubagent(parent, scope, agentDir, work, id, input, signal, emi
500
516
  const effort = (input.effort ?? parent.thinkingLevel);
501
517
  const tools = [...new Set([...parent.getActiveToolNames(), ...piMcpTools(mcp).map((tool) => tool.name)])].filter((name) => name !== ASK_TOOL && name !== SUBAGENT_TOOL && !name.startsWith("workflow_"));
502
518
  const settingsManager = SettingsManager.create(scope, agentDir);
519
+ const producer = { subagentId: id };
503
520
  const resourceLoader = new DefaultResourceLoader({ cwd: scope, agentDir, settingsManager, noExtensions: true,
504
- ...(compactionModelId ? { extensionFactories: [compactionModelExtension(compactionModelId, (text) => emit({ type: "notice", level: "error", text }))] } : {}),
521
+ extensionFactories: [
522
+ ...(agentPermissions ? [agentPermissions.extension(producer)] : []),
523
+ ...(compactionModelId ? [compactionModelExtension(compactionModelId, (text) => emit({ type: "notice", level: "error", text }))] : []),
524
+ ],
505
525
  appendSystemPrompt: ["You are a Subagent. Complete the delegated work and return the result. If human input is needed, return that request to the parent. You cannot ask the human or create further Subagents."] });
506
526
  await resourceLoader.reload();
507
527
  signal.throwIfAborted();
508
- const producer = { subagentId: id };
509
528
  const { session: child, extensionsResult } = await createAgentSession({ cwd: scope, agentDir, model, modelRuntime: parent.modelRuntime,
510
529
  resourceLoader, settingsManager, sessionManager: SessionManager.inMemory(scope), tools,
511
530
  customTools: [...piMcpTools(mcp), ...backgroundTools(scope, settingsManager, work, producer, input.run_in_background === false).filter((tool) => tools.includes(tool.name))],
@@ -545,8 +564,8 @@ async function runSubagent(parent, scope, agentDir, work, id, input, signal, emi
545
564
  reason = event.reason;
546
565
  break;
547
566
  }
548
- });
549
- const abort = () => { void adapter.abort(); };
567
+ }, undefined, agentPermissions ? { agentPermissions, permissionProducer: producer } : {});
568
+ const abort = () => { agentPermissions?.cancel(producer); void adapter.abort(); };
550
569
  signal.addEventListener("abort", abort, { once: true });
551
570
  try {
552
571
  signal.throwIfAborted();
@@ -559,6 +578,7 @@ async function runSubagent(parent, scope, agentDir, work, id, input, signal, emi
559
578
  }
560
579
  finally {
561
580
  signal.removeEventListener("abort", abort);
581
+ agentPermissions?.cancel(producer);
562
582
  await adapter.dispose();
563
583
  if (input.run_in_background === false)
564
584
  await work.stopOwnedCalls(id);
@@ -577,7 +597,7 @@ function capabilitiesOf(session, enquiries, subagents) {
577
597
  fork: false,
578
598
  subagents,
579
599
  enquiries,
580
- permissions: false,
600
+ permissions: true,
581
601
  };
582
602
  }
583
603
  export function describeModel(model) {
@@ -1,34 +1,9 @@
1
- import { ClaudeBackend } from "./claude/index.js";
1
+ import { WorkerBackend } from "./worker/index.js";
2
2
  import { FakeBackend } from "./fake/index.js";
3
- /**
4
- * A Backend Adapter whose module is only loaded when a session actually uses it.
5
- *
6
- * pi is ESM-only and pulls in native and wasm packages, so a bundled build cannot require it at
7
- * startup. Loading it on demand keeps it optional: the binary runs without it, and asking for a pi
8
- * session when it is missing fails with something a person can act on.
9
- */
10
- class LazyBackend {
11
- name;
12
- load;
13
- loaded;
14
- constructor(name, load) {
15
- this.name = name;
16
- this.load = load;
17
- }
18
- async create(options) {
19
- if (!this.loaded) {
20
- try {
21
- this.loaded = await this.load();
22
- }
23
- catch (error) {
24
- throw new Error(`Backend "${this.name}" is not available in this build: ${error instanceof Error ? error.message : String(error)}`);
25
- }
26
- }
27
- return this.loaded.create(options);
28
- }
29
- }
30
3
  export function registerBackends(host) {
31
- host.registerBackend(new ClaudeBackend());
32
- host.registerBackend(new LazyBackend("pi", async () => new (await import("./pi/index.js")).PiBackend()));
4
+ const stateRoot = host.filesystemStateRoot();
5
+ const policy = { ...(stateRoot ? { stateRoot } : {}), isolationEnabled: () => host.filesystemIsolationEnabled() };
6
+ host.registerBackend(new WorkerBackend({ backend: "claude", ...policy }));
7
+ host.registerBackend(new WorkerBackend({ backend: "pi", ...policy }));
33
8
  host.registerBackend(new FakeBackend());
34
9
  }
@@ -0,0 +1,16 @@
1
+ import { existsSync } from 'node:fs';
2
+ import { createRequire } from 'node:module';
3
+ import { join } from 'node:path';
4
+ /** Match the SEA optional-SDK loader, including Node's default $PREFIX/lib/node lookup.
5
+ * These are candidates only: all trees and linked package targets still pass the mount policy.
6
+ */
7
+ export function seaSdkExecutionAssets() {
8
+ const sdk = '@earendil-works/pi-coding-agent';
9
+ const assets = [];
10
+ for (const root of createRequire(process.execPath).resolve.paths(sdk) ?? []) {
11
+ const pkg = join(root, sdk);
12
+ if (existsSync(join(pkg, 'package.json')))
13
+ assets.push(root, pkg);
14
+ }
15
+ return assets;
16
+ }
@@ -0,0 +1,183 @@
1
+ import { createHash } from "node:crypto";
2
+ import { closeSync, constants, copyFileSync, existsSync, fstatSync, linkSync, lstatSync, mkdirSync, mkdtempSync, openSync, readFileSync, readdirSync, realpathSync, renameSync, rmSync, statSync, symlinkSync, writeFileSync } from "node:fs";
3
+ import { homedir, tmpdir } from "node:os";
4
+ import { join, resolve } from "node:path";
5
+ function ownedProjects(stateDir) {
6
+ const projects = join(realpathSync(stateDir), "claude-projects");
7
+ if (!existsSync(projects))
8
+ mkdirSync(projects, { mode: 0o700 });
9
+ if (!lstatSync(projects).isDirectory() || realpathSync(projects) !== projects) {
10
+ throw new Error("Unsafe Claude backend transcript directory");
11
+ }
12
+ return projects;
13
+ }
14
+ /** Claude's Scope key, including the CLI's suffix for paths longer than 200 characters. */
15
+ function projectKey(scope) {
16
+ const key = scope.replace(/[^a-zA-Z0-9]/g, "-");
17
+ if (key.length <= 200)
18
+ return key;
19
+ let hash = 0;
20
+ for (let i = 0; i < scope.length; i++)
21
+ hash = ((hash << 5) - hash + scope.charCodeAt(i)) | 0;
22
+ return `${key.slice(0, 200)}-${Math.abs(hash).toString(36)}`;
23
+ }
24
+ /** Copy only regular, unlinked records; never follow a link into other host state. */
25
+ function copyRecord(source, destination, from = source) {
26
+ const before = lstatSync(from);
27
+ if (realpathSync(source) !== source || (!before.isDirectory() && (!before.isFile() || before.nlink !== 1))) {
28
+ throw new Error("Unsafe legacy Claude conversation record");
29
+ }
30
+ const fd = openSync(from, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK);
31
+ try {
32
+ const pinned = fstatSync(fd);
33
+ const descriptor = process.platform === "linux" ? `/proc/self/fd/${fd}` : source;
34
+ if (pinned.dev !== before.dev || pinned.ino !== before.ino || realpathSync(descriptor) !== source) {
35
+ throw new Error("Legacy Claude conversation record changed during migration");
36
+ }
37
+ const hash = createHash("sha256");
38
+ if (before.isDirectory()) {
39
+ mkdirSync(destination, { mode: 0o700 });
40
+ hash.update("directory\0");
41
+ // Linux copies through pinned directories, never through mutable ancestors. Elsewhere,
42
+ // no-follow opens and a post-copy identity check refuse a changed tree before publication.
43
+ for (const name of readdirSync(descriptor).sort()) {
44
+ hash.update(JSON.stringify([name, copyRecord(join(source, name), join(destination, name), join(descriptor, name))]));
45
+ }
46
+ }
47
+ else {
48
+ const content = readFileSync(fd);
49
+ writeFileSync(destination, content, { mode: 0o600, flag: "wx" });
50
+ hash.update("file\0").update(content);
51
+ }
52
+ const after = lstatSync(source);
53
+ if (after.dev !== pinned.dev || after.ino !== pinned.ino || realpathSync(source) !== source) {
54
+ throw new Error("Legacy Claude conversation record changed during migration");
55
+ }
56
+ return hash.digest("hex");
57
+ }
58
+ finally {
59
+ closeSync(fd);
60
+ }
61
+ }
62
+ /**
63
+ * Pre-isolation Claude wrote Conversation Context into the global projects tree. On Revive,
64
+ * import only the saved UUID under this Scope, plus its UUID-owned sidecars (Subagents and tool
65
+ * results). Never import another conversation, credentials, or overwrite a newer owned record.
66
+ * This runs on the host before restricted launch: workers must not gain access to global state.
67
+ */
68
+ export function migrateLegacyClaudeState(stateDir, inherited, scope, resume) {
69
+ if (!stateDir || !resume)
70
+ return;
71
+ if (!/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(resume)) {
72
+ throw new Error("Invalid Claude resume ID");
73
+ }
74
+ const projects = ownedProjects(stateDir);
75
+ const key = projectKey(scope);
76
+ const destination = join(projects, key);
77
+ const record = `${resume}.jsonl`;
78
+ if (existsSync(destination) && (!lstatSync(destination).isDirectory() || realpathSync(destination) !== destination)) {
79
+ throw new Error("Unsafe Claude backend project directory");
80
+ }
81
+ // Do not consult global storage at all once the owned copy exists.
82
+ const owned = join(destination, record);
83
+ if (existsSync(owned)) {
84
+ if (!lstatSync(owned).isFile() || realpathSync(owned) !== owned)
85
+ throw new Error("Unsafe Claude backend conversation record");
86
+ return;
87
+ }
88
+ const config = resolve(scope, inherited.CLAUDE_CONFIG_DIR || join(inherited.HOME ?? homedir(), ".claude"));
89
+ if (!existsSync(config))
90
+ return;
91
+ const source = join(realpathSync(config), "projects", key);
92
+ if (!existsSync(join(source, record)))
93
+ return;
94
+ if (realpathSync(source) !== source)
95
+ throw new Error("Unsafe legacy Claude project directory");
96
+ const staged = mkdtempSync(join(projects, ".migrate-"));
97
+ let movedSidecars = false;
98
+ try {
99
+ copyRecord(join(source, record), join(staged, record));
100
+ const sidecars = existsSync(join(source, resume)) ? copyRecord(join(source, resume), join(staged, resume)) : undefined;
101
+ if (!existsSync(destination)) {
102
+ // The ordinary legacy case publishes the transcript and all sidecars together.
103
+ renameSync(staged, destination);
104
+ return;
105
+ }
106
+ if (sidecars !== undefined) {
107
+ if (existsSync(join(destination, resume))) {
108
+ // A restart between sidecar publication and the atomic main-record link is retryable.
109
+ // Reuse only an exact match; never discard or overwrite potentially newer owned state.
110
+ if (copyRecord(join(destination, resume), join(staged, ".existing-sidecars")) !== sidecars) {
111
+ throw new Error("Claude conversation sidecars differ from the legacy record without their transcript");
112
+ }
113
+ }
114
+ else {
115
+ renameSync(join(staged, resume), join(destination, resume));
116
+ movedSidecars = true;
117
+ }
118
+ }
119
+ // Publish a complete main record last, atomically and without replacing an existing one.
120
+ linkSync(join(staged, record), join(destination, record));
121
+ }
122
+ catch (error) {
123
+ if (movedSidecars)
124
+ rmSync(join(destination, resume), { recursive: true, force: true });
125
+ throw error;
126
+ }
127
+ finally {
128
+ rmSync(staged, { recursive: true, force: true });
129
+ }
130
+ }
131
+ /**
132
+ * Keep projects durable in the Backend Session's state. CLAUDE_SECURESTORAGE_CONFIG_DIR
133
+ * separates Claude's auth root (credential storage AND refresh/write locks) from its config /
134
+ * transcript root on Linux and macOS. Unrestricted launches keep the ordinary shared auth root;
135
+ * restricted launches already bind projects into a narrowly staged config root and must NEVER
136
+ * receive the host auth override.
137
+ */
138
+ export function prepareClaudeState(stateDir, inherited = process.env, scope = process.cwd(), resume) {
139
+ if (!stateDir)
140
+ return { env: inherited, cleanup() { } };
141
+ migrateLegacyClaudeState(stateDir, inherited, scope, resume);
142
+ const projects = ownedProjects(stateDir);
143
+ const home = inherited.HOME ?? homedir();
144
+ // Match the CLI: relative config roots are Scope-relative, and literal ~ is not
145
+ // expanded. Restricted callers reject nonabsolute host roots before reaching here.
146
+ const source = resolve(scope, inherited.CLAUDE_CONFIG_DIR || join(home, ".claude"));
147
+ const currentProjects = join(source, "projects");
148
+ if (existsSync(currentProjects)) {
149
+ // Bind mounts have different realpath strings, but identify the same owned directory.
150
+ const current = statSync(currentProjects), owned = statSync(projects);
151
+ if (current.dev === owned.dev && current.ino === owned.ino)
152
+ return { env: inherited, cleanup() { } };
153
+ }
154
+ // Unrestricted config view. Do not alter the user's global projects link, copy any global
155
+ // transcripts, or persist credentials in backend state (which restricted workers can read).
156
+ const config = mkdtempSync(join(tmpdir(), "flow-claude-config-"));
157
+ const cleanup = () => rmSync(config, { recursive: true, force: true });
158
+ try {
159
+ symlinkSync(projects, join(config, "projects"), "dir");
160
+ for (const name of [".config.json", ".claude.json"]) {
161
+ const from = name === ".claude.json" && !existsSync(join(source, name)) ? join(home, name) : join(source, name);
162
+ if (existsSync(from) && statSync(from).isFile())
163
+ copyFileSync(from, join(config, name));
164
+ }
165
+ for (const name of ["CLAUDE.md", "settings.json", "commands", "skills", "agents", "rules", "plugins"]) {
166
+ const from = join(source, name);
167
+ if (existsSync(from))
168
+ symlinkSync(from, join(config, name), statSync(from).isDirectory() ? "dir" : "file");
169
+ }
170
+ const env = { ...inherited, CLAUDE_CONFIG_DIR: config,
171
+ // Use the original spelling, including the empty default: macOS hashes this string for
172
+ // its keychain service identity. Linux resolves it to the original credential directory.
173
+ // Both the atomic credential replacement and all refresh/write locks use this ROOT, not
174
+ // a credential-file link or a copy that would lose token rotation on worker disposal.
175
+ CLAUDE_SECURESTORAGE_CONFIG_DIR: inherited.CLAUDE_SECURESTORAGE_CONFIG_DIR ?? inherited.CLAUDE_CONFIG_DIR ?? "",
176
+ };
177
+ return { env, cleanup };
178
+ }
179
+ catch (error) {
180
+ cleanup();
181
+ throw error;
182
+ }
183
+ }
@@ -0,0 +1,186 @@
1
+ var __rewriteRelativeImportExtension = (this && this.__rewriteRelativeImportExtension) || function (path, preserveJsx) {
2
+ if (typeof path === "string" && /^\.\.?\//.test(path)) {
3
+ return path.replace(/\.(tsx)$|((?:\.d)?)((?:\.[^./]+?)?)\.([cm]?)ts$/i, function (m, tsx, d, ext, cm) {
4
+ return tsx ? preserveJsx ? ".jsx" : ".js" : d && (!ext || !cm) ? m : (d + ext + "." + cm.toLowerCase() + "js");
5
+ });
6
+ }
7
+ return path;
8
+ };
9
+ import { WorkerRpc, errorText } from "./rpc.js";
10
+ import { snapshot } from "./protocol.js";
11
+ import { killWorkerTree } from "./launcher.js";
12
+ import { createRequire } from "node:module";
13
+ import { isSea } from "node:sea";
14
+ import { fileURLToPath, pathToFileURL } from "node:url";
15
+ import { isFilesystemLauncher, runFilesystemLauncher } from "../../isolation/launcher.js";
16
+ /** Private executable entry; no host/state initialization takes place in this process. */
17
+ export function runWorker() {
18
+ if (isFilesystemLauncher()) {
19
+ void runFilesystemLauncher().catch((error) => {
20
+ console.error(errorText(error));
21
+ process.exitCode = 1;
22
+ });
23
+ return;
24
+ }
25
+ if (!process.send)
26
+ throw new Error("Backend worker requires an IPC channel");
27
+ let session;
28
+ let published;
29
+ const publishSnapshot = () => (published = snapshot(session));
30
+ let creating = false;
31
+ let closing = false;
32
+ let shutdown;
33
+ let tools = [];
34
+ const workflows = new Map();
35
+ const send = (message) => {
36
+ if (!process.connected)
37
+ throw new Error("Backend worker disconnected");
38
+ process.send(message, (error) => { if (error)
39
+ void stop(); });
40
+ };
41
+ const rpc = new WorkerRpc(send, async (method, args) => {
42
+ if (method === "create") {
43
+ if (creating || closing)
44
+ throw new Error("Backend worker already initialized");
45
+ creating = true;
46
+ const { mcpTools, workflowEnabled, backendModule, backend: backendName = "pi", ...options } = args[0];
47
+ updateTools(mcpTools ?? []);
48
+ const workflow = {
49
+ inspect: (input) => rpc.call("workflow.inspect", [input]),
50
+ recover: (input, signal) => rpc.call("workflow.recover", [input], signal),
51
+ relayEnquiry: (input, signal) => rpc.call("workflow.relayEnquiry", [input], signal),
52
+ relayPermission: (input, signal) => rpc.call("workflow.relayPermission", [input], signal),
53
+ };
54
+ let backend;
55
+ try {
56
+ backend = backendModule
57
+ ? (isSea()
58
+ ? createRequire(pathToFileURL(process.execPath))(fileURLToPath(backendModule)).default
59
+ : (await import(__rewriteRelativeImportExtension(backendModule))).default)
60
+ : backendName === "claude" ? new (await import("../claude/index.js")).ClaudeBackend()
61
+ : new (await import("../pi/index.js")).PiBackend();
62
+ }
63
+ catch (error) {
64
+ throw new Error(`Backend "${backendName}" is not available in this build: ${errorText(error)}`);
65
+ }
66
+ session = await backend.create({
67
+ ...options,
68
+ ...(mcpTools ? { mcp: { tools: () => tools } } : {}),
69
+ ...(workflowEnabled ? { workflow } : {}),
70
+ emit: (event) => {
71
+ // Models can be a large catalogue. Do not resend it for every text/tool delta, but do
72
+ // mirror any changed state before the event that exposes it to the Session Host.
73
+ const changed = session && (session.capabilities !== published?.capabilities || session.resumeToken() !== published?.resume);
74
+ rpc.notify("event", { event, ...(changed ? { snapshot: publishSnapshot() } : {}) });
75
+ },
76
+ });
77
+ if (closing) {
78
+ await session.dispose();
79
+ throw new Error("Backend worker stopped during initialization");
80
+ }
81
+ return publishSnapshot();
82
+ }
83
+ if (method === "dispose") {
84
+ await disposeSession();
85
+ // The RPC reply must be queued before disconnecting and exiting.
86
+ setImmediate(() => { if (process.connected)
87
+ process.disconnect(); process.exit(0); });
88
+ return;
89
+ }
90
+ if (!session || closing)
91
+ throw new Error("Backend worker is not running");
92
+ let result;
93
+ switch (method) {
94
+ case "prompt":
95
+ result = await session.prompt(args[0], args[1]);
96
+ break;
97
+ case "abort":
98
+ result = await session.abort();
99
+ break;
100
+ case "setModel":
101
+ result = await session.setModel(args[0]);
102
+ break;
103
+ case "setEffort":
104
+ result = await session.setEffort(args[0]);
105
+ break;
106
+ case "setPermissionMode": {
107
+ const mode = args[0];
108
+ if (mode !== "ask" && mode !== "auto" && mode !== "always")
109
+ throw new Error("Invalid permission mode");
110
+ if (!session.setPermissionMode)
111
+ throw new Error("Permission mode changes are not supported");
112
+ result = await session.setPermissionMode(mode);
113
+ break;
114
+ }
115
+ case "compact":
116
+ result = await session.compact?.(args[0]);
117
+ break;
118
+ case "skills":
119
+ result = await session.skills?.();
120
+ break;
121
+ case "answerEnquiry":
122
+ result = await session.answerEnquiry?.(args[0], args[1]) ?? false;
123
+ break;
124
+ case "answerPermission":
125
+ result = await session.answerPermission?.(args[0], args[1]) ?? false;
126
+ break;
127
+ case "refreshMcp":
128
+ updateTools(args[0]);
129
+ result = await session.refreshMcp?.();
130
+ break;
131
+ case "workflow.start": {
132
+ if (!session.startWorkflowSubagent)
133
+ throw new Error("Workflow Subagents are not supported");
134
+ const id = args[0];
135
+ if (workflows.has(id))
136
+ throw new Error("Duplicate workflow handle");
137
+ const handle = session.startWorkflowSubagent({ ...args[1], emit: (activity) => rpc.notify("workflow.event", { id, activity }) });
138
+ workflows.set(id, handle);
139
+ void handle.done.then((value) => rpc.notify("workflow.done", { id, value }), (error) => rpc.notify("workflow.done", { id, error: errorText(error) })).finally(() => workflows.delete(id)).catch(() => { });
140
+ break;
141
+ }
142
+ case "workflow.answerEnquiry":
143
+ result = await workflows.get(args[0])?.answerEnquiry(args[1], args[2]) ?? false;
144
+ break;
145
+ case "workflow.answerPermission":
146
+ result = await workflows.get(args[0])?.answerPermission(args[1], args[2]) ?? false;
147
+ break;
148
+ case "workflow.cancel":
149
+ result = await workflows.get(args[0])?.cancel();
150
+ break;
151
+ default: throw new Error(`Unknown worker method: ${method}`);
152
+ }
153
+ rpc.notify("snapshot", publishSnapshot());
154
+ return result;
155
+ }, () => { });
156
+ function updateTools(metadata) {
157
+ tools = metadata.map((tool) => ({ ...tool, call: (input, signal, timeoutMs) => rpc.call("mcp.call", [tool.name, input, timeoutMs], signal) }));
158
+ }
159
+ async function disposeSession() {
160
+ closing = true;
161
+ await Promise.allSettled([...workflows.values()].map((handle) => handle.cancel()));
162
+ await session?.dispose();
163
+ }
164
+ function stop() {
165
+ return shutdown ??= (async () => {
166
+ rpc.close(new Error("Backend worker disconnected"));
167
+ const timer = setTimeout(() => {
168
+ // The host may itself have died: retain the tree-kill fallback on this side too.
169
+ void killWorkerTree({ pid: process.pid }).finally(() => process.exit(1));
170
+ }, 5000);
171
+ try {
172
+ await disposeSession();
173
+ }
174
+ finally {
175
+ clearTimeout(timer);
176
+ process.exit(0);
177
+ }
178
+ })();
179
+ }
180
+ process.on("message", (message) => rpc.receive(message));
181
+ process.once("disconnect", () => { void stop(); });
182
+ process.once("SIGTERM", () => { void stop(); });
183
+ process.once("SIGINT", () => { void stop(); });
184
+ }
185
+ if (process.env.FLOW_BACKEND_WORKER === "1" || isFilesystemLauncher())
186
+ runWorker();