@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/dist/backend/pi/index.js
CHANGED
|
@@ -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
|
-
|
|
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
|
-
|
|
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:
|
|
600
|
+
permissions: true,
|
|
581
601
|
};
|
|
582
602
|
}
|
|
583
603
|
export function describeModel(model) {
|
package/dist/backend/registry.js
CHANGED
|
@@ -1,34 +1,9 @@
|
|
|
1
|
-
import {
|
|
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.
|
|
32
|
-
|
|
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,61 @@
|
|
|
1
|
+
import { copyFileSync, existsSync, lstatSync, mkdirSync, mkdtempSync, realpathSync, rmSync, statSync, symlinkSync } from "node:fs";
|
|
2
|
+
import { homedir, tmpdir } from "node:os";
|
|
3
|
+
import { join, resolve } from "node:path";
|
|
4
|
+
/**
|
|
5
|
+
* Keep projects durable in the Backend Session's state. CLAUDE_SECURESTORAGE_CONFIG_DIR
|
|
6
|
+
* separates Claude's auth root (credential storage AND refresh/write locks) from its config /
|
|
7
|
+
* transcript root on Linux and macOS. Unrestricted launches keep the ordinary shared auth root;
|
|
8
|
+
* restricted launches already bind projects into a narrowly staged config root and must NEVER
|
|
9
|
+
* receive the host auth override.
|
|
10
|
+
*/
|
|
11
|
+
export function prepareClaudeState(stateDir, inherited = process.env, scope = process.cwd()) {
|
|
12
|
+
if (!stateDir)
|
|
13
|
+
return { env: inherited, cleanup() { } };
|
|
14
|
+
const backend = realpathSync(stateDir);
|
|
15
|
+
const projects = join(backend, "claude-projects");
|
|
16
|
+
if (!existsSync(projects))
|
|
17
|
+
mkdirSync(projects, { mode: 0o700 });
|
|
18
|
+
if (!lstatSync(projects).isDirectory() || realpathSync(projects) !== projects) {
|
|
19
|
+
throw new Error("Unsafe Claude backend transcript directory");
|
|
20
|
+
}
|
|
21
|
+
const home = inherited.HOME ?? homedir();
|
|
22
|
+
// Match the CLI: relative config roots are Scope-relative, and literal ~ is not
|
|
23
|
+
// expanded. Restricted callers reject nonabsolute host roots before reaching here.
|
|
24
|
+
const source = resolve(scope, inherited.CLAUDE_CONFIG_DIR || join(home, ".claude"));
|
|
25
|
+
const currentProjects = join(source, "projects");
|
|
26
|
+
if (existsSync(currentProjects)) {
|
|
27
|
+
// Bind mounts have different realpath strings, but identify the same owned directory.
|
|
28
|
+
const current = statSync(currentProjects), owned = statSync(projects);
|
|
29
|
+
if (current.dev === owned.dev && current.ino === owned.ino)
|
|
30
|
+
return { env: inherited, cleanup() { } };
|
|
31
|
+
}
|
|
32
|
+
// Unrestricted config view. Do not alter the user's global projects link, copy any global
|
|
33
|
+
// transcripts, or persist credentials in backend state (which restricted workers can read).
|
|
34
|
+
const config = mkdtempSync(join(tmpdir(), "flow-claude-config-"));
|
|
35
|
+
const cleanup = () => rmSync(config, { recursive: true, force: true });
|
|
36
|
+
try {
|
|
37
|
+
symlinkSync(projects, join(config, "projects"), "dir");
|
|
38
|
+
for (const name of [".config.json", ".claude.json"]) {
|
|
39
|
+
const from = name === ".claude.json" && !existsSync(join(source, name)) ? join(home, name) : join(source, name);
|
|
40
|
+
if (existsSync(from) && statSync(from).isFile())
|
|
41
|
+
copyFileSync(from, join(config, name));
|
|
42
|
+
}
|
|
43
|
+
for (const name of ["CLAUDE.md", "settings.json", "commands", "skills", "agents", "rules", "plugins"]) {
|
|
44
|
+
const from = join(source, name);
|
|
45
|
+
if (existsSync(from))
|
|
46
|
+
symlinkSync(from, join(config, name), statSync(from).isDirectory() ? "dir" : "file");
|
|
47
|
+
}
|
|
48
|
+
const env = { ...inherited, CLAUDE_CONFIG_DIR: config,
|
|
49
|
+
// Use the original spelling, including the empty default: macOS hashes this string for
|
|
50
|
+
// its keychain service identity. Linux resolves it to the original credential directory.
|
|
51
|
+
// Both the atomic credential replacement and all refresh/write locks use this ROOT, not
|
|
52
|
+
// a credential-file link or a copy that would lose token rotation on worker disposal.
|
|
53
|
+
CLAUDE_SECURESTORAGE_CONFIG_DIR: inherited.CLAUDE_SECURESTORAGE_CONFIG_DIR ?? inherited.CLAUDE_CONFIG_DIR ?? "",
|
|
54
|
+
};
|
|
55
|
+
return { env, cleanup };
|
|
56
|
+
}
|
|
57
|
+
catch (error) {
|
|
58
|
+
cleanup();
|
|
59
|
+
throw error;
|
|
60
|
+
}
|
|
61
|
+
}
|
|
@@ -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();
|