@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
|
@@ -0,0 +1,255 @@
|
|
|
1
|
+
import { randomUUID } from "node:crypto";
|
|
2
|
+
import { realpathSync, statSync } from "node:fs";
|
|
3
|
+
import { dirname, resolve } from "node:path";
|
|
4
|
+
import { isSea } from "node:sea";
|
|
5
|
+
import { fileURLToPath } from "node:url";
|
|
6
|
+
import { prepareFilesystemIsolation } from "../../isolation/filesystem.js";
|
|
7
|
+
import { nodeExecutionAssets } from "../../isolation/node-assets.js";
|
|
8
|
+
import { launchWorker, workerCommand } from "./launcher.js";
|
|
9
|
+
import { seaSdkExecutionAssets } from "./assets.js";
|
|
10
|
+
import { WorkerRpc } from "./rpc.js";
|
|
11
|
+
import { mcpMetadata } from "./protocol.js";
|
|
12
|
+
import { workflowInspectInput, workflowRecoverInput, workflowRelayInput } from "../workflow-tools.js";
|
|
13
|
+
import { prepareClaudeState } from "./claude-state.js";
|
|
14
|
+
/** One owned worker per Backend Session, optionally enforcing a filesystem boundary. */
|
|
15
|
+
export class WorkerBackend {
|
|
16
|
+
name;
|
|
17
|
+
options;
|
|
18
|
+
constructor(options = {}) { this.options = options; this.name = options.backend ?? "pi"; }
|
|
19
|
+
async create(options) {
|
|
20
|
+
const isolationEnabled = this.options.isolationEnabled?.() ?? true;
|
|
21
|
+
if (!isolationEnabled) {
|
|
22
|
+
const scope = realpathSync(options.scope);
|
|
23
|
+
if (!statSync(scope).isDirectory())
|
|
24
|
+
throw new Error("Scope must be a directory");
|
|
25
|
+
// Pi retains its ordinary full environment. Claude needs an owned projects tree in both
|
|
26
|
+
// modes; prepare its private config view on the host so Workflow children inherit it too.
|
|
27
|
+
const claude = this.name === "claude" ? prepareClaudeState(options.stateDir, { ...process.env, ...this.options.env }, scope) : undefined;
|
|
28
|
+
let proxy;
|
|
29
|
+
try {
|
|
30
|
+
proxy = new WorkerSession({ ...options, scope }, claude ? { ...this.options, env: claude.env } : this.options, claude?.cleanup ?? (() => { }));
|
|
31
|
+
await proxy.open();
|
|
32
|
+
return proxy;
|
|
33
|
+
}
|
|
34
|
+
catch (error) {
|
|
35
|
+
if (proxy)
|
|
36
|
+
await proxy.dispose();
|
|
37
|
+
else
|
|
38
|
+
claude?.cleanup();
|
|
39
|
+
throw error;
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
const plan = workerCommand(this.options);
|
|
43
|
+
const packageRoot = isSea() ? dirname(process.execPath) : fileURLToPath(new URL("../../..", import.meta.url));
|
|
44
|
+
const assets = [packageRoot, ...(this.options.readablePaths ?? [])];
|
|
45
|
+
if (isSea())
|
|
46
|
+
assets.push(...seaSdkExecutionAssets());
|
|
47
|
+
if (this.options.backendModule)
|
|
48
|
+
assets.push(fileURLToPath(this.options.backendModule));
|
|
49
|
+
if (this.options.entry) {
|
|
50
|
+
assets.push(this.options.entry);
|
|
51
|
+
if (dirname(this.options.entry).endsWith("/backend/worker"))
|
|
52
|
+
assets.push(resolve(dirname(this.options.entry), "../../.."));
|
|
53
|
+
}
|
|
54
|
+
// Both npm workers and SEAs can resolve hoisted or linked dependencies outside the
|
|
55
|
+
// package root. Restore only those trees/targets; the policy validates all mounts.
|
|
56
|
+
assets.push(...nodeExecutionAssets(assets));
|
|
57
|
+
const isolation = await prepareFilesystemIsolation({ ...plan, scope: options.scope, expectedScope: resolve(options.scope),
|
|
58
|
+
...(options.stateDir ? { stateDir: options.stateDir } : {}),
|
|
59
|
+
...(this.options.stateRoot ? { stateRoot: this.options.stateRoot } : {}),
|
|
60
|
+
env: this.options.env ?? {}, credentials: this.name, ipc: true, readablePaths: assets });
|
|
61
|
+
let proxy;
|
|
62
|
+
try {
|
|
63
|
+
proxy = new WorkerSession({ ...options, scope: isolation.scope, stateDir: isolation.stateDir }, { ...this.options, command: isolation.command, args: isolation.args, env: isolation.env, stdioFds: isolation.stdioFds }, isolation.cleanup);
|
|
64
|
+
await proxy.open();
|
|
65
|
+
return proxy;
|
|
66
|
+
}
|
|
67
|
+
catch (error) {
|
|
68
|
+
if (proxy)
|
|
69
|
+
await proxy.dispose();
|
|
70
|
+
else
|
|
71
|
+
isolation.cleanup();
|
|
72
|
+
throw error;
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
class WorkerSession {
|
|
77
|
+
capabilities;
|
|
78
|
+
resume;
|
|
79
|
+
worker;
|
|
80
|
+
rpc;
|
|
81
|
+
failed;
|
|
82
|
+
disposing = false;
|
|
83
|
+
disposal;
|
|
84
|
+
workflows = new Map();
|
|
85
|
+
refreshMcp;
|
|
86
|
+
startWorkflowSubagent;
|
|
87
|
+
compact;
|
|
88
|
+
skills;
|
|
89
|
+
answerEnquiry;
|
|
90
|
+
answerPermission;
|
|
91
|
+
setPermissionMode;
|
|
92
|
+
options;
|
|
93
|
+
launchOptions;
|
|
94
|
+
cleanup;
|
|
95
|
+
constructor(options, launchOptions, cleanup) {
|
|
96
|
+
this.cleanup = cleanup;
|
|
97
|
+
this.options = options;
|
|
98
|
+
this.launchOptions = launchOptions;
|
|
99
|
+
this.worker = launchWorker(launchOptions);
|
|
100
|
+
const child = this.worker.child;
|
|
101
|
+
this.rpc = new WorkerRpc((message) => {
|
|
102
|
+
if (!child.connected)
|
|
103
|
+
throw new Error("Backend worker disconnected");
|
|
104
|
+
child.send(message, (error) => { if (error)
|
|
105
|
+
this.fail(error); });
|
|
106
|
+
}, async (method, args, signal) => {
|
|
107
|
+
if (this.disposing || this.failed)
|
|
108
|
+
throw new Error("Backend Session stopped");
|
|
109
|
+
// Never look up host functions by a worker-supplied property name.
|
|
110
|
+
switch (method) {
|
|
111
|
+
case "mcp.call": {
|
|
112
|
+
const tool = this.options.mcp?.tools().find((tool) => tool.name === args[0]);
|
|
113
|
+
if (!tool)
|
|
114
|
+
throw new Error("Unknown MCP tool");
|
|
115
|
+
const input = args[1];
|
|
116
|
+
const timeout = args[2];
|
|
117
|
+
if (!input || typeof input !== "object" || Array.isArray(input))
|
|
118
|
+
throw new Error("Invalid MCP input");
|
|
119
|
+
if (timeout !== undefined && (typeof timeout !== "number" || !Number.isFinite(timeout) || timeout <= 0))
|
|
120
|
+
throw new Error("Invalid MCP timeout");
|
|
121
|
+
return tool.call(input, signal, timeout);
|
|
122
|
+
}
|
|
123
|
+
case "workflow.inspect": return this.requireWorkflow().inspect(workflowInspectInput.parse(args[0]));
|
|
124
|
+
case "workflow.recover": return this.requireWorkflow().recover(workflowRecoverInput.parse(args[0]), signal);
|
|
125
|
+
case "workflow.relayEnquiry": return this.requireWorkflow().relayEnquiry(workflowRelayInput.parse(args[0]), signal);
|
|
126
|
+
case "workflow.relayPermission": return this.requireWorkflow().relayPermission(workflowRelayInput.parse(args[0]), signal);
|
|
127
|
+
default: throw new Error(`Unknown host method: ${method}`);
|
|
128
|
+
}
|
|
129
|
+
}, (name, value) => this.notify(name, value));
|
|
130
|
+
child.on("message", (message) => this.rpc.receive(message));
|
|
131
|
+
child.once("error", (error) => this.fail(error));
|
|
132
|
+
child.once("disconnect", () => this.fail(new Error("Backend worker disconnected")));
|
|
133
|
+
child.once("exit", (code, signal) => this.fail(new Error(`Backend worker exited (${signal ?? code ?? "unknown"})${this.worker.diagnostics() ? `: ${this.worker.diagnostics()}` : ""}`)));
|
|
134
|
+
}
|
|
135
|
+
requireWorkflow() {
|
|
136
|
+
if (!this.options.workflow)
|
|
137
|
+
throw new Error("Workflow tools are not enabled");
|
|
138
|
+
return this.options.workflow;
|
|
139
|
+
}
|
|
140
|
+
async open() {
|
|
141
|
+
const { emit: _emit, onFailure: _onFailure, mcp, workflow, ...options } = this.options;
|
|
142
|
+
const controller = new AbortController();
|
|
143
|
+
const timer = setTimeout(() => controller.abort(), this.launchOptions.startupTimeoutMs ?? 60_000);
|
|
144
|
+
try {
|
|
145
|
+
const state = await this.rpc.call("create", [{ ...options, backend: this.launchOptions.backend ?? "pi",
|
|
146
|
+
workflowEnabled: !!workflow,
|
|
147
|
+
...(mcp ? { mcpTools: mcpMetadata(mcp) } : {}),
|
|
148
|
+
...(this.launchOptions.backendModule ? { backendModule: this.launchOptions.backendModule } : {}),
|
|
149
|
+
}], controller.signal);
|
|
150
|
+
this.updateSnapshot(state);
|
|
151
|
+
const methods = new Set(state.methods);
|
|
152
|
+
if (methods.has("refreshMcp"))
|
|
153
|
+
this.refreshMcp = () => this.rpc.call("refreshMcp", [mcpMetadata(this.options.mcp)]);
|
|
154
|
+
if (methods.has("compact"))
|
|
155
|
+
this.compact = (instructions) => this.rpc.call("compact", [instructions]);
|
|
156
|
+
if (methods.has("skills"))
|
|
157
|
+
this.skills = () => this.rpc.call("skills");
|
|
158
|
+
if (methods.has("answerEnquiry"))
|
|
159
|
+
this.answerEnquiry = (id, answers) => this.rpc.call("answerEnquiry", [id, answers]);
|
|
160
|
+
if (methods.has("answerPermission"))
|
|
161
|
+
this.answerPermission = (id, decision) => this.rpc.call("answerPermission", [id, decision]);
|
|
162
|
+
if (methods.has("setPermissionMode"))
|
|
163
|
+
this.setPermissionMode = (mode) => this.rpc.call("setPermissionMode", [mode]);
|
|
164
|
+
if (methods.has("startWorkflowSubagent"))
|
|
165
|
+
this.startWorkflowSubagent = (options) => this.startWorkflow(options);
|
|
166
|
+
}
|
|
167
|
+
finally {
|
|
168
|
+
clearTimeout(timer);
|
|
169
|
+
}
|
|
170
|
+
}
|
|
171
|
+
updateSnapshot(state) {
|
|
172
|
+
this.capabilities = state.capabilities;
|
|
173
|
+
this.resume = state.resume;
|
|
174
|
+
}
|
|
175
|
+
notify(name, value) {
|
|
176
|
+
switch (name) {
|
|
177
|
+
case "snapshot":
|
|
178
|
+
this.updateSnapshot(value);
|
|
179
|
+
break;
|
|
180
|
+
case "event": {
|
|
181
|
+
const { event, snapshot } = value;
|
|
182
|
+
if (snapshot)
|
|
183
|
+
this.updateSnapshot(snapshot);
|
|
184
|
+
if (event.type === "capabilities_changed")
|
|
185
|
+
this.capabilities = event.capabilities;
|
|
186
|
+
this.options.emit(event);
|
|
187
|
+
break;
|
|
188
|
+
}
|
|
189
|
+
case "workflow.event": {
|
|
190
|
+
const { id, activity } = value;
|
|
191
|
+
this.workflows.get(id)?.emit(activity);
|
|
192
|
+
break;
|
|
193
|
+
}
|
|
194
|
+
case "workflow.done": {
|
|
195
|
+
const { id, value: result, error } = value;
|
|
196
|
+
const handle = this.workflows.get(id);
|
|
197
|
+
this.workflows.delete(id);
|
|
198
|
+
if (error !== undefined)
|
|
199
|
+
handle?.reject(new Error(error));
|
|
200
|
+
else
|
|
201
|
+
handle?.resolve(result);
|
|
202
|
+
break;
|
|
203
|
+
}
|
|
204
|
+
}
|
|
205
|
+
}
|
|
206
|
+
startWorkflow(options) {
|
|
207
|
+
if (this.failed || this.disposing)
|
|
208
|
+
throw this.failed ?? new Error("Backend Session stopped");
|
|
209
|
+
const id = randomUUID();
|
|
210
|
+
const { emit, ...metadata } = options;
|
|
211
|
+
const done = new Promise((resolve, reject) => { this.workflows.set(id, { emit, resolve, reject }); });
|
|
212
|
+
// A caller may attach its rejection handler after the synchronous handle has returned.
|
|
213
|
+
void done.catch(() => { });
|
|
214
|
+
const started = this.rpc.call("workflow.start", [id, metadata]);
|
|
215
|
+
void started.catch((error) => { this.workflows.get(id)?.reject(error); this.workflows.delete(id); });
|
|
216
|
+
return {
|
|
217
|
+
done,
|
|
218
|
+
answerEnquiry: async (askId, answers) => { await started; return this.rpc.call("workflow.answerEnquiry", [id, askId, answers]); },
|
|
219
|
+
answerPermission: async (callId, decision) => { await started; return this.rpc.call("workflow.answerPermission", [id, callId, decision]); },
|
|
220
|
+
cancel: async () => { await started; await this.rpc.call("workflow.cancel", [id]); },
|
|
221
|
+
};
|
|
222
|
+
}
|
|
223
|
+
fail(error) {
|
|
224
|
+
if (this.failed)
|
|
225
|
+
return;
|
|
226
|
+
this.failed = error;
|
|
227
|
+
this.rpc.close(error);
|
|
228
|
+
for (const handle of this.workflows.values())
|
|
229
|
+
handle.reject(error);
|
|
230
|
+
this.workflows.clear();
|
|
231
|
+
// A backend loss interrupts workflow work. Do not replay commands or start a replacement.
|
|
232
|
+
if (!this.disposing) {
|
|
233
|
+
this.options.emit({ type: "notice", level: "error", text: error.message });
|
|
234
|
+
this.options.onFailure?.(error);
|
|
235
|
+
}
|
|
236
|
+
void this.worker.stop(async () => { }).then(this.cleanup).catch(() => { });
|
|
237
|
+
}
|
|
238
|
+
resumeToken() { return this.resume; }
|
|
239
|
+
prompt(text, attachments) { return this.rpc.call("prompt", [text, attachments]); }
|
|
240
|
+
abort() { return this.rpc.call("abort"); }
|
|
241
|
+
setModel(modelId) { return this.rpc.call("setModel", [modelId]); }
|
|
242
|
+
setEffort(effort) { return this.rpc.call("setEffort", [effort]); }
|
|
243
|
+
dispose() {
|
|
244
|
+
return this.disposal ??= (async () => {
|
|
245
|
+
this.disposing = true;
|
|
246
|
+
try {
|
|
247
|
+
await this.worker.stop(() => this.rpc.call("dispose"));
|
|
248
|
+
}
|
|
249
|
+
finally {
|
|
250
|
+
this.fail(new Error("Backend Session stopped"));
|
|
251
|
+
this.cleanup();
|
|
252
|
+
}
|
|
253
|
+
})();
|
|
254
|
+
}
|
|
255
|
+
}
|
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
import { spawn } from "node:child_process";
|
|
2
|
+
import { isSea } from "node:sea";
|
|
3
|
+
import { fileURLToPath } from "node:url";
|
|
4
|
+
export function workerCommand(options = {}) {
|
|
5
|
+
const source = import.meta.url.endsWith(".ts");
|
|
6
|
+
const entry = options.entry ?? fileURLToPath(new URL(source ? "./entry.ts" : "./entry.js", import.meta.url));
|
|
7
|
+
const args = options.args ?? (isSea() && !options.entry
|
|
8
|
+
? ["--flow-backend-worker"]
|
|
9
|
+
: [...(options.execArgv ?? (source ? ["--experimental-strip-types"] : [])), entry]);
|
|
10
|
+
return { command: options.command ?? process.execPath, args };
|
|
11
|
+
}
|
|
12
|
+
export function launchWorker(options = {}) {
|
|
13
|
+
const { command, args } = workerCommand(options);
|
|
14
|
+
const child = spawn(command, args, {
|
|
15
|
+
env: { ...process.env, ...options.env, FLOW_BACKEND_WORKER: "1" },
|
|
16
|
+
detached: process.platform !== "win32",
|
|
17
|
+
stdio: ["ignore", "ignore", "pipe", "ipc", ...(options.stdioFds ?? [])],
|
|
18
|
+
serialization: "advanced",
|
|
19
|
+
});
|
|
20
|
+
// Drain diagnostics so a chatty SDK cannot block on stderr. Keep only a bounded failure tail.
|
|
21
|
+
let diagnostics = "";
|
|
22
|
+
child.stderr?.on("data", (chunk) => { diagnostics = (diagnostics + chunk.toString()).slice(-8192); });
|
|
23
|
+
const exited = new Promise((resolve) => {
|
|
24
|
+
child.once("close", () => resolve());
|
|
25
|
+
});
|
|
26
|
+
let stopping;
|
|
27
|
+
return {
|
|
28
|
+
child,
|
|
29
|
+
exited,
|
|
30
|
+
diagnostics: () => diagnostics.trim(),
|
|
31
|
+
/** Await the process, then kill its entire process group if cooperative disposal stalled. */
|
|
32
|
+
stop: (graceful) => stopping ??= (async () => {
|
|
33
|
+
let timer;
|
|
34
|
+
try {
|
|
35
|
+
const cooperative = Promise.resolve().then(graceful).catch(() => { }).then(() => exited);
|
|
36
|
+
const timeout = new Promise((resolve) => { timer = setTimeout(resolve, options.shutdownTimeoutMs ?? 5000); });
|
|
37
|
+
await Promise.race([cooperative, exited, timeout]);
|
|
38
|
+
// Also clean up detached descendants after an unexpected exit of their leader.
|
|
39
|
+
await killWorkerTree(child);
|
|
40
|
+
await exited;
|
|
41
|
+
}
|
|
42
|
+
finally {
|
|
43
|
+
clearTimeout(timer);
|
|
44
|
+
}
|
|
45
|
+
})(),
|
|
46
|
+
};
|
|
47
|
+
}
|
|
48
|
+
export async function killWorkerTree(child) {
|
|
49
|
+
if (!child.pid)
|
|
50
|
+
return;
|
|
51
|
+
if (process.platform === "win32") {
|
|
52
|
+
await new Promise((resolve) => {
|
|
53
|
+
const killer = spawn("taskkill", ["/pid", String(child.pid), "/T", "/F"], { stdio: "ignore" });
|
|
54
|
+
killer.once("error", () => resolve());
|
|
55
|
+
killer.once("close", () => resolve());
|
|
56
|
+
});
|
|
57
|
+
}
|
|
58
|
+
else {
|
|
59
|
+
try {
|
|
60
|
+
process.kill(-child.pid, "SIGKILL");
|
|
61
|
+
}
|
|
62
|
+
catch (error) {
|
|
63
|
+
if (error.code !== "ESRCH")
|
|
64
|
+
throw error;
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
}
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
export function snapshot(session) {
|
|
2
|
+
return {
|
|
3
|
+
capabilities: session.capabilities,
|
|
4
|
+
resume: session.resumeToken(),
|
|
5
|
+
methods: ["refreshMcp", "startWorkflowSubagent", "compact", "skills", "answerEnquiry", "answerPermission", "setPermissionMode"]
|
|
6
|
+
.filter((method) => typeof session[method] === "function"),
|
|
7
|
+
};
|
|
8
|
+
}
|
|
9
|
+
export function mcpMetadata(mcp) {
|
|
10
|
+
return (mcp?.tools() ?? []).map(({ name, connectionId, definition, serverIdentity }) => ({ name, connectionId, definition, serverIdentity }));
|
|
11
|
+
}
|
|
@@ -0,0 +1,108 @@
|
|
|
1
|
+
import { AutoPermissionUnavailable } from "../permission-errors.js";
|
|
2
|
+
export function errorText(error) {
|
|
3
|
+
return error instanceof Error ? error.message : String(error);
|
|
4
|
+
}
|
|
5
|
+
/** Concurrent, bidirectional RPC. Inbound dispatchers must explicitly allowlist their methods. */
|
|
6
|
+
export class WorkerRpc {
|
|
7
|
+
nextId = 0;
|
|
8
|
+
failure;
|
|
9
|
+
pending = new Map();
|
|
10
|
+
incoming = new Map();
|
|
11
|
+
send;
|
|
12
|
+
dispatch;
|
|
13
|
+
notification;
|
|
14
|
+
constructor(send, dispatch, notification) {
|
|
15
|
+
this.send = send;
|
|
16
|
+
this.dispatch = dispatch;
|
|
17
|
+
this.notification = notification;
|
|
18
|
+
}
|
|
19
|
+
call(method, args = [], signal) {
|
|
20
|
+
if (this.failure)
|
|
21
|
+
return Promise.reject(this.failure);
|
|
22
|
+
if (signal?.aborted)
|
|
23
|
+
return Promise.reject(new Error("Worker call cancelled"));
|
|
24
|
+
const id = ++this.nextId;
|
|
25
|
+
return new Promise((resolve, reject) => {
|
|
26
|
+
const abort = () => {
|
|
27
|
+
this.pending.delete(id);
|
|
28
|
+
try {
|
|
29
|
+
this.send({ kind: "cancel", id });
|
|
30
|
+
}
|
|
31
|
+
catch { }
|
|
32
|
+
reject(new Error("Worker call cancelled"));
|
|
33
|
+
};
|
|
34
|
+
const cleanup = () => signal?.removeEventListener("abort", abort);
|
|
35
|
+
this.pending.set(id, {
|
|
36
|
+
resolve: (value) => { cleanup(); resolve(value); },
|
|
37
|
+
reject: (error) => { cleanup(); reject(error); },
|
|
38
|
+
});
|
|
39
|
+
signal?.addEventListener("abort", abort, { once: true });
|
|
40
|
+
try {
|
|
41
|
+
this.send({ kind: "call", id, method, args });
|
|
42
|
+
}
|
|
43
|
+
catch (error) {
|
|
44
|
+
this.pending.delete(id);
|
|
45
|
+
cleanup();
|
|
46
|
+
reject(error);
|
|
47
|
+
}
|
|
48
|
+
});
|
|
49
|
+
}
|
|
50
|
+
notify(name, value) {
|
|
51
|
+
if (!this.failure)
|
|
52
|
+
this.send({ kind: "notification", name, value });
|
|
53
|
+
}
|
|
54
|
+
receive(raw) {
|
|
55
|
+
if (this.failure || !raw || typeof raw !== "object")
|
|
56
|
+
return;
|
|
57
|
+
const message = raw;
|
|
58
|
+
switch (message.kind) {
|
|
59
|
+
case "reply": {
|
|
60
|
+
const pending = this.pending.get(message.id);
|
|
61
|
+
this.pending.delete(message.id);
|
|
62
|
+
if (message.error !== undefined)
|
|
63
|
+
pending?.reject(message.errorCode === "auto_permission_unavailable"
|
|
64
|
+
? new AutoPermissionUnavailable(message.error) : new Error(message.error));
|
|
65
|
+
else
|
|
66
|
+
pending?.resolve(message.value);
|
|
67
|
+
break;
|
|
68
|
+
}
|
|
69
|
+
case "cancel":
|
|
70
|
+
this.incoming.get(message.id)?.abort();
|
|
71
|
+
break;
|
|
72
|
+
case "notification":
|
|
73
|
+
this.notification(message.name, message.value);
|
|
74
|
+
break;
|
|
75
|
+
case "call": {
|
|
76
|
+
if (!Number.isSafeInteger(message.id) || typeof message.method !== "string" || !Array.isArray(message.args) || this.incoming.has(message.id))
|
|
77
|
+
return;
|
|
78
|
+
const controller = new AbortController();
|
|
79
|
+
this.incoming.set(message.id, controller);
|
|
80
|
+
// Deliberately do not queue: prompt may be awaiting an answer from another RPC.
|
|
81
|
+
void Promise.resolve().then(() => this.dispatch(message.method, message.args, controller.signal)).then((value) => this.reply({ kind: "reply", id: message.id, value }), (error) => this.reply({ kind: "reply", id: message.id, error: errorText(error),
|
|
82
|
+
...(error instanceof AutoPermissionUnavailable ? { errorCode: "auto_permission_unavailable" } : {}) })).finally(() => this.incoming.delete(message.id));
|
|
83
|
+
break;
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
reply(message) {
|
|
88
|
+
if (this.failure)
|
|
89
|
+
return;
|
|
90
|
+
try {
|
|
91
|
+
this.send(message);
|
|
92
|
+
}
|
|
93
|
+
catch (error) {
|
|
94
|
+
this.close(new Error(errorText(error)));
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
close(error) {
|
|
98
|
+
if (this.failure)
|
|
99
|
+
return;
|
|
100
|
+
this.failure = error;
|
|
101
|
+
for (const pending of this.pending.values())
|
|
102
|
+
pending.reject(error);
|
|
103
|
+
this.pending.clear();
|
|
104
|
+
for (const controller of this.incoming.values())
|
|
105
|
+
controller.abort();
|
|
106
|
+
this.incoming.clear();
|
|
107
|
+
}
|
|
108
|
+
}
|
package/dist/build-id
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
|
|
1
|
+
e5b65913-9f67-4248-8f84-d7d8187c41ee
|
package/dist/cli/bootstrap.js
CHANGED
|
@@ -883,7 +883,7 @@ async function bootstrap() {
|
|
|
883
883
|
if (!managed) throw new Error("Missing systemd update configuration");
|
|
884
884
|
await assertSystemdOwner(managed, managed.updater, process.pid);
|
|
885
885
|
}
|
|
886
|
-
const lease = await install.register("
|
|
886
|
+
const lease = await install.register("e5b65913-9f67-4248-8f84-d7d8187c41ee", root, args, process.env.FLOW_UPDATE_CAPABILITY ?? systemdCapability(root));
|
|
887
887
|
delete process.env.FLOW_UPDATE_CAPABILITY;
|
|
888
888
|
process.on("exit", lease.release);
|
|
889
889
|
if (args[0] === "update") {
|
package/dist/cli/main.js
CHANGED
|
@@ -1,6 +1,14 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
import { isSea } from 'node:sea';
|
|
3
|
-
if (
|
|
3
|
+
if (process.argv[2] === '--flow-isolation-launch' ||
|
|
4
|
+
(process.argv[2] === '--flow-backend-worker' && process.send && process.env.FLOW_BACKEND_WORKER === '1')) {
|
|
5
|
+
void import("../backend/worker/entry.js").catch(error => {
|
|
6
|
+
console.error(error instanceof Error ? error.message : error);
|
|
7
|
+
process.exitCode = 1;
|
|
8
|
+
process.disconnect?.();
|
|
9
|
+
});
|
|
10
|
+
}
|
|
11
|
+
else if (!isSea() && import.meta.url.endsWith('.js')) {
|
|
4
12
|
console.error('Use the flow executable, not the internal CLI entry');
|
|
5
13
|
process.exitCode = 1;
|
|
6
14
|
}
|
|
@@ -45,6 +45,82 @@ export function connect(options) {
|
|
|
45
45
|
await requireOk(response, options.token, options.authenticationRequired);
|
|
46
46
|
return (await response.json());
|
|
47
47
|
},
|
|
48
|
+
async readPresentation(sessionId, before, signal) {
|
|
49
|
+
const response = await fetch(`${options.url}/api/sessions/${encodeURIComponent(sessionId)}/presentation?before=${before}&limit=400`, {
|
|
50
|
+
headers, ...credentials, ...(signal ? { signal } : {}),
|
|
51
|
+
});
|
|
52
|
+
await requireOk(response, options.token, options.authenticationRequired);
|
|
53
|
+
return await response.json();
|
|
54
|
+
},
|
|
55
|
+
subscribePresentation({ sessionId, start, onSnapshot, onUpdate, onError, onLink, silenceMs }) {
|
|
56
|
+
const events = `${options.url}/api/sessions/${encodeURIComponent(sessionId)}/presentation/events`;
|
|
57
|
+
let stopped = false;
|
|
58
|
+
let stream;
|
|
59
|
+
let wake;
|
|
60
|
+
let attempt = 0;
|
|
61
|
+
void (async () => {
|
|
62
|
+
while (!stopped) {
|
|
63
|
+
onLink?.("connecting");
|
|
64
|
+
const controller = new AbortController();
|
|
65
|
+
stream = controller;
|
|
66
|
+
let silent = false;
|
|
67
|
+
const arm = () => setTimeout(() => { silent = true; controller.abort(); }, silenceMs ?? SILENCE_MS);
|
|
68
|
+
let watchdog = arm();
|
|
69
|
+
const receivedChunk = () => { clearTimeout(watchdog); watchdog = arm(); };
|
|
70
|
+
const openedAt = Date.now();
|
|
71
|
+
try {
|
|
72
|
+
const from = start();
|
|
73
|
+
const response = await fetch(`${events}?limit=400${from === undefined ? "" : `&start=${from}`}`, {
|
|
74
|
+
headers, ...credentials, signal: controller.signal,
|
|
75
|
+
});
|
|
76
|
+
if (!response.ok || !response.body) {
|
|
77
|
+
const error = await responseError(response, options.token, options.authenticationRequired);
|
|
78
|
+
if (FATAL_STATUS.has(response.status)) {
|
|
79
|
+
onLink?.("gone");
|
|
80
|
+
onError?.(error);
|
|
81
|
+
return;
|
|
82
|
+
}
|
|
83
|
+
throw error;
|
|
84
|
+
}
|
|
85
|
+
let ready = false;
|
|
86
|
+
for await (const frame of readEventStream(response.body, receivedChunk)) {
|
|
87
|
+
if (stopped)
|
|
88
|
+
return;
|
|
89
|
+
if (frame.type === "snapshot") {
|
|
90
|
+
onSnapshot(frame);
|
|
91
|
+
ready = true;
|
|
92
|
+
// A 200 response is not current activity until its snapshot has actually arrived.
|
|
93
|
+
onLink?.("live");
|
|
94
|
+
}
|
|
95
|
+
else {
|
|
96
|
+
if (!ready)
|
|
97
|
+
throw new Error("Presentation stream did not begin with a snapshot");
|
|
98
|
+
onUpdate(frame);
|
|
99
|
+
}
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
catch (error) {
|
|
103
|
+
if (stopped)
|
|
104
|
+
return;
|
|
105
|
+
if (!silent)
|
|
106
|
+
onError?.(error instanceof Error ? error : new Error(String(error)));
|
|
107
|
+
}
|
|
108
|
+
finally {
|
|
109
|
+
clearTimeout(watchdog);
|
|
110
|
+
}
|
|
111
|
+
if (stopped)
|
|
112
|
+
return;
|
|
113
|
+
attempt = Date.now() - openedAt >= BACKOFF_MIN_MS ? 1 : attempt + 1;
|
|
114
|
+
onLink?.("retrying");
|
|
115
|
+
await new Promise(resolve => {
|
|
116
|
+
const timer = setTimeout(resolve, backoffMs(attempt));
|
|
117
|
+
wake = () => { clearTimeout(timer); resolve(); };
|
|
118
|
+
});
|
|
119
|
+
wake = undefined;
|
|
120
|
+
}
|
|
121
|
+
})();
|
|
122
|
+
return () => { stopped = true; stream?.abort(); wake?.(); };
|
|
123
|
+
},
|
|
48
124
|
subscribe({ sessionId, since, onEntry, onError, onLink, silenceMs }) {
|
|
49
125
|
const events = `${options.url}/api/sessions/${encodeURIComponent(sessionId)}/events`;
|
|
50
126
|
const silence = silenceMs ?? SILENCE_MS;
|
|
@@ -143,10 +219,11 @@ function backoffMs(attempt) {
|
|
|
143
219
|
return Math.round(ceiling * (0.5 + Math.random() / 2));
|
|
144
220
|
}
|
|
145
221
|
/** Minimal SSE reader: enough for `id:`/`data:` frames, which is all the host emits. */
|
|
146
|
-
async function* readEventStream(body) {
|
|
222
|
+
async function* readEventStream(body, onChunk) {
|
|
147
223
|
const decoder = new TextDecoder();
|
|
148
224
|
let buffer = "";
|
|
149
225
|
for await (const chunk of body) {
|
|
226
|
+
onChunk?.();
|
|
150
227
|
buffer += decoder.decode(chunk, { stream: true });
|
|
151
228
|
let split = buffer.indexOf("\n\n");
|
|
152
229
|
while (split !== -1) {
|
|
@@ -179,5 +256,33 @@ async function responseError(response, token, authenticationRequired) {
|
|
|
179
256
|
}
|
|
180
257
|
async function describe(response) {
|
|
181
258
|
const body = await response.text().catch(() => "");
|
|
182
|
-
|
|
259
|
+
// A proxy timeout says nothing about whether the host accepted or finished a command.
|
|
260
|
+
if (response.status === 524) {
|
|
261
|
+
return "524 Proxy timed out. Accepted commands may still be running. Check their status before retrying.";
|
|
262
|
+
}
|
|
263
|
+
const status = `${response.status} ${safeErrorText(response.statusText)}`.trim();
|
|
264
|
+
const contentType = response.headers.get("content-type")?.split(";", 1)[0]?.trim().toLowerCase();
|
|
265
|
+
if (contentType === "text/html" || contentType === "application/xhtml+xml")
|
|
266
|
+
return status;
|
|
267
|
+
let detail = "";
|
|
268
|
+
try {
|
|
269
|
+
const parsed = JSON.parse(body);
|
|
270
|
+
if (parsed && typeof parsed === "object" && "error" in parsed && typeof parsed.error === "string") {
|
|
271
|
+
detail = safeErrorText(parsed.error);
|
|
272
|
+
}
|
|
273
|
+
}
|
|
274
|
+
catch {
|
|
275
|
+
// Only plain text (or an untyped response) is useful without a JSON error envelope.
|
|
276
|
+
if (!contentType || contentType === "text/plain")
|
|
277
|
+
detail = safeErrorText(body);
|
|
278
|
+
}
|
|
279
|
+
return detail ? `${status}: ${detail}` : status;
|
|
280
|
+
}
|
|
281
|
+
/** Keep toasts single-line and short; never show markup, even from a mislabeled proxy response. */
|
|
282
|
+
function safeErrorText(text) {
|
|
283
|
+
if (/[<>]/.test(text))
|
|
284
|
+
return "";
|
|
285
|
+
const normalized = text.replace(/[\u0000-\u001f\u007f]/g, " ").replace(/\s+/g, " ").trim();
|
|
286
|
+
const limit = 240;
|
|
287
|
+
return normalized.length > limit ? `${normalized.slice(0, limit - 1)}…` : normalized;
|
|
183
288
|
}
|
package/dist/client/diff.js
CHANGED
|
@@ -26,6 +26,49 @@ export function editDiff(input) {
|
|
|
26
26
|
added: lines(after),
|
|
27
27
|
};
|
|
28
28
|
}
|
|
29
|
+
/**
|
|
30
|
+
* Explicit diff/patch fences may contain just +/- fragments. Without that hint, require a unified
|
|
31
|
+
* file header and hunk, so ordinary code and tool output are not mistaken for changes. Keep every
|
|
32
|
+
* byte, including newlines, for copying and search highlighting.
|
|
33
|
+
*/
|
|
34
|
+
export function textDiff(text, lang) {
|
|
35
|
+
const language = lang?.trim().split(/\s+/, 1)[0]?.toLowerCase();
|
|
36
|
+
const explicit = language === "diff" || language === "patch";
|
|
37
|
+
if (language && !explicit)
|
|
38
|
+
return undefined;
|
|
39
|
+
if (!explicit) {
|
|
40
|
+
const fileHeader = /^--- [^\n]*\n\+\+\+ [^\n]*\n/m.test(text);
|
|
41
|
+
const hunkHeader = /^@@ -\d+(?:,\d+)? \+\d+(?:,\d+)? @@/m.test(text);
|
|
42
|
+
if (!fileHeader || !hunkHeader)
|
|
43
|
+
return undefined;
|
|
44
|
+
}
|
|
45
|
+
let remainingOld = 0;
|
|
46
|
+
let remainingNew = 0;
|
|
47
|
+
return (text.match(/[^\n]*\n|[^\n]+$/g) ?? []).map((line) => {
|
|
48
|
+
const hunk = /^@@ -\d+(?:,(\d+))? \+\d+(?:,(\d+))? @@/.exec(line);
|
|
49
|
+
if (hunk) {
|
|
50
|
+
remainingOld = Number(hunk[1] ?? 1);
|
|
51
|
+
remainingNew = Number(hunk[2] ?? 1);
|
|
52
|
+
return { text: line, kind: "context" };
|
|
53
|
+
}
|
|
54
|
+
const inHunk = remainingOld > 0 || remainingNew > 0;
|
|
55
|
+
let kind = "context";
|
|
56
|
+
if (inHunk || explicit) {
|
|
57
|
+
// ---/+++ are file headers outside a hunk, but valid removed/added content inside one.
|
|
58
|
+
if (line.startsWith("-") && (inHunk || !line.startsWith("--- ")))
|
|
59
|
+
kind = "removed";
|
|
60
|
+
if (line.startsWith("+") && (inHunk || !line.startsWith("+++ ")))
|
|
61
|
+
kind = "added";
|
|
62
|
+
}
|
|
63
|
+
if (inHunk) {
|
|
64
|
+
if (kind === "removed" || line.startsWith(" "))
|
|
65
|
+
remainingOld = Math.max(0, remainingOld - 1);
|
|
66
|
+
if (kind === "added" || line.startsWith(" "))
|
|
67
|
+
remainingNew = Math.max(0, remainingNew - 1);
|
|
68
|
+
}
|
|
69
|
+
return { text: line, kind };
|
|
70
|
+
});
|
|
71
|
+
}
|
|
29
72
|
function lines(text) {
|
|
30
73
|
if (!text)
|
|
31
74
|
return [];
|
package/dist/client/reduce.js
CHANGED
|
@@ -86,6 +86,7 @@ function applyEvent(state, event, at) {
|
|
|
86
86
|
backend: event.backend,
|
|
87
87
|
scope: event.scope,
|
|
88
88
|
capabilities: event.capabilities,
|
|
89
|
+
...(event.permissionMode ? { permissionMode: event.permissionMode } : {}),
|
|
89
90
|
...(event.worktree === undefined ? {} : { worktree: event.worktree }),
|
|
90
91
|
};
|
|
91
92
|
case "capabilities_changed":
|
|
@@ -307,6 +308,8 @@ function applyEvent(state, event, at) {
|
|
|
307
308
|
}
|
|
308
309
|
case "model_changed":
|
|
309
310
|
return { ...state, model: event.model };
|
|
311
|
+
case "permission_mode_changed":
|
|
312
|
+
return { ...state, permissionMode: event.mode };
|
|
310
313
|
case "effort_changed":
|
|
311
314
|
return { ...state, effort: event.effort };
|
|
312
315
|
case "branch_changed":
|