@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/dist/backend/pi/index.js
CHANGED
|
@@ -6,9 +6,11 @@ import { PiWorkflowSubagent } from "./workflow-subagent.js";
|
|
|
6
6
|
import { piEffortLevels } from "./effort-capabilities.js";
|
|
7
7
|
import { clampEffort } from "../effort.js";
|
|
8
8
|
import { piAutoCompaction } from "./auto-compaction.js";
|
|
9
|
+
import { compactionExtensionError, compactionModelExtension } from "./compaction-model.js";
|
|
9
10
|
import { ASK_TOOL, PiEnquiries } from "./enquiries.js";
|
|
10
11
|
import { backgroundTools } from "./background-calls.js";
|
|
11
12
|
import { SUBAGENT_TOOL, subagentTool } from "./subagents.js";
|
|
13
|
+
import { PiAgentPermissions } from "./agent-permissions.js";
|
|
12
14
|
import { PiWork, callIdFor, resultText, textResult } from "./work.js";
|
|
13
15
|
export class PiSession {
|
|
14
16
|
capabilities;
|
|
@@ -18,16 +20,27 @@ export class PiSession {
|
|
|
18
20
|
completions = [];
|
|
19
21
|
workflows = new Map();
|
|
20
22
|
mcp;
|
|
23
|
+
recreate;
|
|
21
24
|
async refreshMcp() {
|
|
22
|
-
|
|
25
|
+
if (!this.recreate)
|
|
26
|
+
return;
|
|
27
|
+
const current = this.session;
|
|
28
|
+
this.unsubscribe();
|
|
29
|
+
current.dispose();
|
|
30
|
+
this.session = await this.recreate(current);
|
|
31
|
+
this.unsubscribe = this.session.subscribe((event) => this.translate(event));
|
|
23
32
|
}
|
|
24
33
|
standingAuthorisations;
|
|
34
|
+
agentPermissions;
|
|
35
|
+
permissionProducer;
|
|
36
|
+
answerPermission;
|
|
25
37
|
disposed = false;
|
|
26
38
|
disposal;
|
|
27
39
|
turnReason = "complete";
|
|
28
40
|
session;
|
|
29
41
|
applyAutoCompaction;
|
|
30
42
|
workflowAutoCompaction;
|
|
43
|
+
workflowCompactionModelId;
|
|
31
44
|
emit;
|
|
32
45
|
unsubscribe;
|
|
33
46
|
sessionDir;
|
|
@@ -46,16 +59,23 @@ export class PiSession {
|
|
|
46
59
|
currentMessageId;
|
|
47
60
|
constructor(session, emit, sessionDir, support = {}) {
|
|
48
61
|
this.mcp = support.mcp;
|
|
62
|
+
this.recreate = support.recreate;
|
|
49
63
|
this.standingAuthorisations = [...(support.standingAuthorisations ?? [])];
|
|
64
|
+
this.agentPermissions = support.agentPermissions;
|
|
65
|
+
if (support.permissionProducer)
|
|
66
|
+
this.permissionProducer = support.permissionProducer;
|
|
50
67
|
this.session = session;
|
|
51
68
|
this.applyAutoCompaction = support.autoCompaction;
|
|
52
|
-
this.workflowAutoCompaction = support.workflowAutoCompaction
|
|
69
|
+
this.workflowAutoCompaction = support.workflowAutoCompaction;
|
|
70
|
+
this.workflowCompactionModelId = support.workflowCompactionModelId;
|
|
53
71
|
this.applyAutoCompaction?.(session.model);
|
|
54
72
|
this.emit = emit;
|
|
55
73
|
this.sessionDir = sessionDir;
|
|
56
74
|
this.enquiries = support.enquiries;
|
|
57
75
|
this.work = support.work;
|
|
58
76
|
const enquiries = support.enquiries;
|
|
77
|
+
if (this.agentPermissions)
|
|
78
|
+
this.answerPermission = async (callId, decision) => this.agentPermissions.answer(callId, decision);
|
|
59
79
|
if (enquiries)
|
|
60
80
|
this.answerEnquiry = async (askId, answers) => enquiries.answer(askId, answers);
|
|
61
81
|
this.capabilities = capabilitiesOf(session, support.enquiries !== undefined, support.subagents ?? false);
|
|
@@ -66,7 +86,7 @@ export class PiSession {
|
|
|
66
86
|
throw new Error("Backend Session stopped");
|
|
67
87
|
if (this.workflows.has(options.id))
|
|
68
88
|
throw new Error(`Duplicate workflow Subagent: ${options.id}`);
|
|
69
|
-
const handle = new PiWorkflowSubagent(this.session, options, this.standingAuthorisations, this.mcp, this.workflowAutoCompaction);
|
|
89
|
+
const handle = new PiWorkflowSubagent(this.session, options, this.standingAuthorisations, this.mcp, this.workflowAutoCompaction, this.workflowCompactionModelId);
|
|
70
90
|
this.workflows.set(options.id, handle);
|
|
71
91
|
void handle.done.finally(() => this.workflows.delete(options.id)).catch(() => { });
|
|
72
92
|
return handle;
|
|
@@ -88,9 +108,11 @@ export class PiSession {
|
|
|
88
108
|
});
|
|
89
109
|
}
|
|
90
110
|
async abort() {
|
|
111
|
+
this.agentPermissions?.cancel(this.permissionProducer ?? { subagentId: "" });
|
|
91
112
|
this.aborting = this.turnId !== undefined;
|
|
92
113
|
await this.session.abort();
|
|
93
114
|
}
|
|
115
|
+
async setPermissionMode(mode) { this.agentPermissions?.setMode(mode); }
|
|
94
116
|
async setModel(modelId) {
|
|
95
117
|
const available = await this.session.modelRuntime.getAvailable();
|
|
96
118
|
const qualified = available.find((candidate) => describeModel(candidate).id === modelId);
|
|
@@ -219,6 +241,7 @@ export class PiSession {
|
|
|
219
241
|
}
|
|
220
242
|
async disposeOnce() {
|
|
221
243
|
this.disposed = true;
|
|
244
|
+
this.agentPermissions?.cancel(this.permissionProducer);
|
|
222
245
|
this.completions.length = 0;
|
|
223
246
|
try {
|
|
224
247
|
await Promise.all([this.abort(), this.work?.dispose(), ...[...this.workflows.values()].map((handle) => handle.cancel())]);
|
|
@@ -389,11 +412,16 @@ export class PiBackend {
|
|
|
389
412
|
// Extensions are not loaded: they expect pi's own UI surface, and a background session that
|
|
390
413
|
// registers UI hooks has nowhere to render them.
|
|
391
414
|
const settingsManager = SettingsManager.create(options.scope, agentDir);
|
|
415
|
+
const agentPermissions = options.tools === "none" ? undefined : new PiAgentPermissions(options.permissionMode ?? "always", options.standingAuthorisations ?? [], options.emit);
|
|
392
416
|
const resourceLoader = new DefaultResourceLoader({
|
|
393
417
|
cwd: options.scope,
|
|
394
418
|
agentDir,
|
|
395
419
|
settingsManager,
|
|
396
420
|
noExtensions: true,
|
|
421
|
+
extensionFactories: [
|
|
422
|
+
...(agentPermissions ? [agentPermissions.extension()] : []),
|
|
423
|
+
...(options.compactionModelId ? [compactionModelExtension(options.compactionModelId, (text) => options.emit({ type: "notice", level: "error", text }))] : []),
|
|
424
|
+
],
|
|
397
425
|
});
|
|
398
426
|
await resourceLoader.reload();
|
|
399
427
|
// Reviving reopens the most recent pi session in the directory we gave this Agent Session;
|
|
@@ -410,30 +438,39 @@ export class PiBackend {
|
|
|
410
438
|
])];
|
|
411
439
|
const mcp = options.tools === "none" ? undefined : options.mcp;
|
|
412
440
|
const workflowTools = workflowParentTools(options.tools === "none" ? undefined : options.workflow);
|
|
413
|
-
tools.push(...workflowTools.map(tool => tool.name)
|
|
441
|
+
tools.push(...workflowTools.map(tool => tool.name));
|
|
414
442
|
const enabled = (name) => tools.includes(name);
|
|
415
443
|
const enquiries = enabled(ASK_TOOL) ? new PiEnquiries(options.emit) : undefined;
|
|
416
444
|
const work = new PiWork(options.emit, (completion) => piSession.completed(completion));
|
|
417
445
|
const subagents = enabled(SUBAGENT_TOOL);
|
|
418
446
|
const customTools = [
|
|
419
447
|
...workflowTools,
|
|
420
|
-
...piMcpTools(mcp),
|
|
421
448
|
...backgroundTools(options.scope, settingsManager, work).filter((tool) => enabled(tool.name)),
|
|
422
449
|
...(enquiries ? [enquiries.tool] : []),
|
|
423
|
-
...(subagents ? [subagentTool(work, (id, input, signal) => runSubagent(session, options.scope, agentDir, work, id, input, signal, options.emit, mcp))] : []),
|
|
450
|
+
...(subagents ? [subagentTool(work, (id, input, signal) => runSubagent(session, options.scope, agentDir, work, id, input, signal, options.emit, mcp, options.compactionModelId, agentPermissions))] : []),
|
|
424
451
|
];
|
|
425
|
-
const
|
|
426
|
-
|
|
427
|
-
|
|
428
|
-
|
|
429
|
-
|
|
430
|
-
|
|
431
|
-
|
|
432
|
-
|
|
433
|
-
|
|
434
|
-
|
|
435
|
-
|
|
436
|
-
|
|
452
|
+
const start = (current) => {
|
|
453
|
+
const mcpTools = piMcpTools(mcp);
|
|
454
|
+
return createAgentSession({
|
|
455
|
+
cwd: options.scope,
|
|
456
|
+
agentDir,
|
|
457
|
+
resourceLoader,
|
|
458
|
+
settingsManager,
|
|
459
|
+
customTools: [...customTools, ...mcpTools],
|
|
460
|
+
tools: [...tools, ...mcpTools.map((tool) => tool.name)],
|
|
461
|
+
...(current ? { sessionManager: current.sessionManager, modelRuntime: current.modelRuntime, thinkingLevel: current.thinkingLevel, ...(current.model ? { model: current.model } : {}) }
|
|
462
|
+
: sessionManager ? { sessionManager } : {}),
|
|
463
|
+
...(tools.length === 0 ? { noTools: "all" } : {}),
|
|
464
|
+
});
|
|
465
|
+
};
|
|
466
|
+
let { session, extensionsResult } = await start();
|
|
467
|
+
const extensionError = options.compactionModelId && compactionExtensionError(extensionsResult.errors);
|
|
468
|
+
if (extensionError) {
|
|
469
|
+
session.dispose();
|
|
470
|
+
throw new Error(`Could not load the Pi compaction model hook: ${extensionError}`);
|
|
471
|
+
}
|
|
472
|
+
const autoCompaction = structuredClone(options.autoCompaction);
|
|
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) } : {}) });
|
|
437
474
|
if (options.modelId) {
|
|
438
475
|
try {
|
|
439
476
|
await piSession.setModel(options.modelId);
|
|
@@ -471,7 +508,7 @@ export class PiBackend {
|
|
|
471
508
|
return piSession;
|
|
472
509
|
}
|
|
473
510
|
}
|
|
474
|
-
async function runSubagent(parent, scope, agentDir, work, id, input, signal, emit, mcp) {
|
|
511
|
+
async function runSubagent(parent, scope, agentDir, work, id, input, signal, emit, mcp, compactionModelId, agentPermissions) {
|
|
475
512
|
const available = parent.modelRuntime.getAvailableSnapshot();
|
|
476
513
|
const model = input.model ? available.find((model) => describeModel(model).id === input.model) : parent.model;
|
|
477
514
|
if (!model)
|
|
@@ -479,15 +516,24 @@ async function runSubagent(parent, scope, agentDir, work, id, input, signal, emi
|
|
|
479
516
|
const effort = (input.effort ?? parent.thinkingLevel);
|
|
480
517
|
const tools = [...new Set([...parent.getActiveToolNames(), ...piMcpTools(mcp).map((tool) => tool.name)])].filter((name) => name !== ASK_TOOL && name !== SUBAGENT_TOOL && !name.startsWith("workflow_"));
|
|
481
518
|
const settingsManager = SettingsManager.create(scope, agentDir);
|
|
519
|
+
const producer = { subagentId: id };
|
|
482
520
|
const resourceLoader = new DefaultResourceLoader({ cwd: scope, agentDir, settingsManager, noExtensions: true,
|
|
521
|
+
extensionFactories: [
|
|
522
|
+
...(agentPermissions ? [agentPermissions.extension(producer)] : []),
|
|
523
|
+
...(compactionModelId ? [compactionModelExtension(compactionModelId, (text) => emit({ type: "notice", level: "error", text }))] : []),
|
|
524
|
+
],
|
|
483
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."] });
|
|
484
526
|
await resourceLoader.reload();
|
|
485
527
|
signal.throwIfAborted();
|
|
486
|
-
const
|
|
487
|
-
const { session: child } = await createAgentSession({ cwd: scope, agentDir, model, modelRuntime: parent.modelRuntime,
|
|
528
|
+
const { session: child, extensionsResult } = await createAgentSession({ cwd: scope, agentDir, model, modelRuntime: parent.modelRuntime,
|
|
488
529
|
resourceLoader, settingsManager, sessionManager: SessionManager.inMemory(scope), tools,
|
|
489
530
|
customTools: [...piMcpTools(mcp), ...backgroundTools(scope, settingsManager, work, producer, input.run_in_background === false).filter((tool) => tools.includes(tool.name))],
|
|
490
531
|
});
|
|
532
|
+
const extensionError = compactionModelId && compactionExtensionError(extensionsResult.errors);
|
|
533
|
+
if (extensionError) {
|
|
534
|
+
child.dispose();
|
|
535
|
+
throw new Error(`Could not load the Pi compaction model hook: ${extensionError}`);
|
|
536
|
+
}
|
|
491
537
|
let output = "";
|
|
492
538
|
let failure;
|
|
493
539
|
let reason = "complete";
|
|
@@ -518,8 +564,8 @@ async function runSubagent(parent, scope, agentDir, work, id, input, signal, emi
|
|
|
518
564
|
reason = event.reason;
|
|
519
565
|
break;
|
|
520
566
|
}
|
|
521
|
-
});
|
|
522
|
-
const abort = () => { void adapter.abort(); };
|
|
567
|
+
}, undefined, agentPermissions ? { agentPermissions, permissionProducer: producer } : {});
|
|
568
|
+
const abort = () => { agentPermissions?.cancel(producer); void adapter.abort(); };
|
|
523
569
|
signal.addEventListener("abort", abort, { once: true });
|
|
524
570
|
try {
|
|
525
571
|
signal.throwIfAborted();
|
|
@@ -532,6 +578,7 @@ async function runSubagent(parent, scope, agentDir, work, id, input, signal, emi
|
|
|
532
578
|
}
|
|
533
579
|
finally {
|
|
534
580
|
signal.removeEventListener("abort", abort);
|
|
581
|
+
agentPermissions?.cancel(producer);
|
|
535
582
|
await adapter.dispose();
|
|
536
583
|
if (input.run_in_background === false)
|
|
537
584
|
await work.stopOwnedCalls(id);
|
|
@@ -550,7 +597,7 @@ function capabilitiesOf(session, enquiries, subagents) {
|
|
|
550
597
|
fork: false,
|
|
551
598
|
subagents,
|
|
552
599
|
enquiries,
|
|
553
|
-
permissions:
|
|
600
|
+
permissions: true,
|
|
554
601
|
};
|
|
555
602
|
}
|
|
556
603
|
export function describeModel(model) {
|
package/dist/backend/pi/work.js
CHANGED
|
@@ -28,7 +28,7 @@ export class PiWork {
|
|
|
28
28
|
try {
|
|
29
29
|
signal.throwIfAborted();
|
|
30
30
|
const result = await execute(signal, (result) => { work.result = result; });
|
|
31
|
-
return { brief, state: signal.aborted ? "aborted" : "complete", result };
|
|
31
|
+
return { brief, state: signal.aborted ? "aborted" : result.isError ? "error" : "complete", result };
|
|
32
32
|
}
|
|
33
33
|
catch (error) {
|
|
34
34
|
return { brief, state: signal.aborted ? "aborted" : "error", result: textResult(error instanceof Error ? error.message : String(error)) };
|
|
@@ -3,6 +3,7 @@ import { createAgentSession, DefaultPackageManager, DefaultResourceLoader, getAg
|
|
|
3
3
|
import { PiSession } from "./index.js";
|
|
4
4
|
import { piAcceptsWorkflowEffort, piEffortLevels } from "./effort-capabilities.js";
|
|
5
5
|
import { piAutoCompaction } from "./auto-compaction.js";
|
|
6
|
+
import { compactionExtensionError, compactionModelExtension } from "./compaction-model.js";
|
|
6
7
|
import { PiEnquiries } from "./enquiries.js";
|
|
7
8
|
import { backgroundTools } from "./background-calls.js";
|
|
8
9
|
import { PiWork } from "./work.js";
|
|
@@ -16,11 +17,13 @@ export class PiWorkflowSubagent {
|
|
|
16
17
|
permissions = new Map();
|
|
17
18
|
options;
|
|
18
19
|
autoCompaction;
|
|
20
|
+
compactionModelId;
|
|
19
21
|
mcp;
|
|
20
|
-
constructor(parent, options, grants, mcp, autoCompaction
|
|
22
|
+
constructor(parent, options, grants, mcp, autoCompaction, compactionModelId) {
|
|
21
23
|
this.mcp = mcp;
|
|
22
24
|
this.options = { ...options, input: structuredClone(options.input) };
|
|
23
25
|
this.autoCompaction = autoCompaction;
|
|
26
|
+
this.compactionModelId = compactionModelId;
|
|
24
27
|
this.grants = new Set(grants);
|
|
25
28
|
this.enquiries = new PiEnquiries((event) => this.emit(event));
|
|
26
29
|
this.work = new PiWork((event) => this.emit(event), () => { });
|
|
@@ -95,6 +98,7 @@ export class PiWorkflowSubagent {
|
|
|
95
98
|
}).resolve(async () => "skip") : undefined;
|
|
96
99
|
const resourceLoader = new DefaultResourceLoader({ cwd: scope, agentDir: getAgentDir(), settingsManager,
|
|
97
100
|
noExtensions: true, noSkills: true, noPromptTemplates: true, noThemes: true,
|
|
101
|
+
...(this.compactionModelId ? { extensionFactories: [compactionModelExtension(this.compactionModelId, (text) => this.emit({ type: "notice", level: "error", text }))] } : {}),
|
|
98
102
|
additionalSkillPaths: resources?.skills.filter(resource => resource.enabled).map(resource => resource.path) ?? [],
|
|
99
103
|
additionalPromptTemplatePaths: resources?.prompts.filter(resource => resource.enabled).map(resource => resource.path) ?? [],
|
|
100
104
|
...(options.skill ? {
|
|
@@ -136,10 +140,15 @@ export class PiWorkflowSubagent {
|
|
|
136
140
|
...backgroundTools(scope, settingsManager, this.work, undefined, false, true)];
|
|
137
141
|
const customTools = definitions.filter((tool) => names.includes(tool.name)).map((tool) => this.wrap(tool));
|
|
138
142
|
customTools.push(this.enquiries.tool);
|
|
139
|
-
const { session } = await createAgentSession({ cwd: scope, model, modelRuntime: parent.modelRuntime,
|
|
143
|
+
const { session, extensionsResult } = await createAgentSession({ cwd: scope, model, modelRuntime: parent.modelRuntime,
|
|
140
144
|
resourceLoader, settingsManager, sessionManager: SessionManager.inMemory(scope),
|
|
141
145
|
tools: customTools.map((tool) => tool.name), customTools,
|
|
142
146
|
});
|
|
147
|
+
const extensionError = this.compactionModelId && compactionExtensionError(extensionsResult.errors);
|
|
148
|
+
if (extensionError) {
|
|
149
|
+
session.dispose();
|
|
150
|
+
throw new Error(`Could not load the Pi compaction model hook: ${extensionError}`);
|
|
151
|
+
}
|
|
143
152
|
// Session creation initializes SDK settings after resource loading, so apply the immutable
|
|
144
153
|
// Flow policy at the same boundary PiSession uses for a parent model selection.
|
|
145
154
|
piAutoCompaction(settingsManager, this.autoCompaction)(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();
|