@nathanstephenson/flow 0.1.7 → 0.1.8
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 +122 -640
- package/build/backend-worker-chunks/chunk-J2DBNTL7.mjs +94 -0
- package/build/backend-worker-chunks/chunk-MLOUI3ZM.mjs +19752 -0
- package/build/backend-worker-chunks/chunk-UQDH2COY.mjs +15296 -0
- package/build/backend-worker-chunks/claude-GTW5KHY5.mjs +30778 -0
- package/build/backend-worker-chunks/pi-M4OA2FGL.mjs +5730 -0
- package/build/backend-worker.mjs +4401 -0
- package/dist/backend/fake/index.js +2 -0
- package/dist/backend/mcp.js +34 -15
- package/dist/backend/pi/state.js +18 -0
- package/dist/backend/registry.js +2 -1
- package/dist/backend/worker/claude-state.js +24 -3
- package/dist/backend/worker/entry.js +70 -13
- package/dist/backend/worker/frames.js +34 -0
- package/dist/backend/worker/index.js +139 -16
- package/dist/backend/worker/launcher.js +22 -3
- package/dist/backend/worker/sandbox-mcp.js +86 -0
- package/dist/build-id +1 -1
- package/dist/cli/bootstrap.js +7 -6
- package/dist/cli/install-guard.js +1 -1
- package/dist/cli/main.js +3 -6
- package/dist/cli/update.js +3 -3
- package/dist/cli/web-update.js +9 -6
- package/dist/client/connection.js +5 -2
- package/dist/client/diff.js +6 -9
- package/dist/client/reduce.js +19 -0
- package/dist/client/tool-chains.js +12 -4
- package/dist/daemon/config-store.js +21 -14
- package/dist/daemon/config.js +48 -5
- package/dist/daemon/git.js +47 -0
- package/dist/daemon/host.js +208 -29
- package/dist/daemon/models.js +27 -24
- package/dist/daemon/release-checker.js +48 -34
- package/dist/daemon/runtime.js +10 -4
- package/dist/daemon/server.js +13 -1
- package/dist/daemon/shell.js +2 -1
- package/dist/daemon/skills.js +34 -31
- package/dist/daemon/summariser.js +33 -14
- package/dist/daemon/timings.js +14 -0
- package/dist/daemon/workflow-authoring-scope-checks.js +5 -8
- package/dist/daemon/workflow-authoring-scope-reader.js +20 -9
- package/dist/daemon/workflow-builder-files.js +5 -5
- package/dist/daemon/workflow-builder-guidance.js +3 -3
- package/dist/daemon/workflow-builder-reader.js +21 -10
- package/dist/daemon/workflow-builder.js +66 -8
- package/dist/daemon/workflow-executions.js +10 -10
- package/dist/daemon/workflow-mcp-authoring-routes.js +18 -6
- package/dist/daemon/workflow-mcp-authoring.js +44 -20
- package/dist/isolation/filesystem.js +8 -9
- package/dist/isolation/sandbox-supervisor.js +50 -0
- package/dist/isolation/sandbox.js +165 -0
- package/dist/isolation/shared-sandbox.js +77 -0
- package/dist/workflows/executors.js +16 -4
- package/dist/workflows/json-schema.js +14 -4
- package/package.json +7 -4
- package/web/dist/assets/index-CiEgCpiO.js +40 -0
- package/web/dist/assets/index-ClwLFMZN.css +2 -0
- package/web/dist/assets/settings-mcp-CoRWT-D_.js +1 -0
- package/web/dist/assets/settings-secrets-BIO_hXZ1.js +1 -0
- package/web/dist/assets/settings-workflows-BXbj0TKs.js +23 -0
- package/web/dist/assets/switch-DIogWclb.js +1 -0
- package/web/dist/assets/workflow-api-BfExddae.js +6 -0
- package/web/dist/assets/workflow-editors-CsbVx4WJ.js +139 -0
- package/web/dist/assets/workflows-Bv0sj7d0.js +7 -0
- package/web/dist/assets/workflows-pane-C_Yg4pgr.js +1 -0
- package/web/dist/index.html +5 -5
- package/web/dist/assets/index-DxTV-TYZ.js +0 -38
- package/web/dist/assets/index-jwsr3cpu.css +0 -2
- package/web/dist/assets/input-BOuBzJVY.js +0 -6
- package/web/dist/assets/settings-mcp-D-jWezcS.js +0 -1
- package/web/dist/assets/settings-secrets-DdQ0eujd.js +0 -1
- package/web/dist/assets/settings-workflows-BCzYKkOk.js +0 -23
- package/web/dist/assets/switch-B0hMd_dH.js +0 -1
- package/web/dist/assets/workflow-editors-CDZqnDvT.js +0 -137
- package/web/dist/assets/workflows-BpPNiK-H.js +0 -7
- package/web/dist/assets/workflows-pane-N3Vf30Cb.js +0 -1
|
@@ -45,6 +45,7 @@ export class FakeSession {
|
|
|
45
45
|
workflow;
|
|
46
46
|
/** Whether this session was created as a one-shot text call, for asserting the Summary Model's. */
|
|
47
47
|
toolless;
|
|
48
|
+
scope;
|
|
48
49
|
/** Every Subagent begun in this session, in the style of `prompts`. */
|
|
49
50
|
subagents = [];
|
|
50
51
|
workflowSubagents = [];
|
|
@@ -116,6 +117,7 @@ export class FakeSession {
|
|
|
116
117
|
this.standingAuthorisations = options.standingAuthorisations ?? [];
|
|
117
118
|
this.workflow = options.workflow;
|
|
118
119
|
this.toolless = options.tools === "none";
|
|
120
|
+
this.scope = options.scope;
|
|
119
121
|
this.backendAutoReply = backendAutoReply;
|
|
120
122
|
if (this.capabilities.enquiries) {
|
|
121
123
|
this.answerEnquiry = async (askId, answers) => {
|
package/dist/backend/mcp.js
CHANGED
|
@@ -2,6 +2,7 @@ import { createHash } from "node:crypto";
|
|
|
2
2
|
import { closeSync, constants, existsSync, fstatSync, openSync, realpathSync, statSync } from "node:fs";
|
|
3
3
|
import { dirname, join, resolve } from "node:path";
|
|
4
4
|
import { prepareFilesystemIsolation } from "../isolation/filesystem.js";
|
|
5
|
+
import { sandboxUnavailable } from "../isolation/sandbox.js";
|
|
5
6
|
import { SupervisedStdioTransport } from "./mcp-stdio-supervisor.js";
|
|
6
7
|
import { nodeExecutionAssets } from "../isolation/node-assets.js";
|
|
7
8
|
import { Client } from "@modelcontextprotocol/sdk/client/index.js";
|
|
@@ -57,9 +58,14 @@ export class McpSession {
|
|
|
57
58
|
resolveSecret;
|
|
58
59
|
protectedPaths;
|
|
59
60
|
stateRoot;
|
|
60
|
-
|
|
61
|
+
isolationMode;
|
|
61
62
|
expectedScopeIdentity;
|
|
62
|
-
|
|
63
|
+
/** Sandbox workers: the host owns OAuth, refreshes on request and returns only access tokens. */
|
|
64
|
+
hostToken;
|
|
65
|
+
/** Sandbox workers start local servers from host paths over the VM's shared file system. */
|
|
66
|
+
connectTimeoutMs = 10_000;
|
|
67
|
+
constructor(connections, scope, auth, direct = false, resolveSecret, protectedPaths, stateRoot, isolationMode = "bubblewrap", expectedScopeIdentity, hostToken) {
|
|
68
|
+
this.hostToken = hostToken;
|
|
63
69
|
this.connections = structuredClone(connections);
|
|
64
70
|
this.scope = scope;
|
|
65
71
|
this.auth = auth;
|
|
@@ -67,7 +73,7 @@ export class McpSession {
|
|
|
67
73
|
this.resolveSecret = resolveSecret;
|
|
68
74
|
this.protectedPaths = protectedPaths;
|
|
69
75
|
this.stateRoot = stateRoot;
|
|
70
|
-
this.
|
|
76
|
+
this.isolationMode = isolationMode;
|
|
71
77
|
this.expectedScopeIdentity = expectedScopeIdentity;
|
|
72
78
|
}
|
|
73
79
|
registrationFailed() {
|
|
@@ -147,7 +153,9 @@ export class McpSession {
|
|
|
147
153
|
return;
|
|
148
154
|
}
|
|
149
155
|
const configured = connection.transport === "http" ? this.configuredHeaders(connection.headers) : {};
|
|
150
|
-
if (connection.transport === "stdio" &&
|
|
156
|
+
if (connection.transport === "stdio" && this.isolationMode === "sandbox")
|
|
157
|
+
throw sandboxUnavailable();
|
|
158
|
+
if (connection.transport === "stdio" && this.isolationMode === "none") {
|
|
151
159
|
// Refuse unsupported authoring before touching a potentially stalled Scope path.
|
|
152
160
|
if (this.expectedScopeIdentity !== undefined && process.platform !== "linux")
|
|
153
161
|
throw new Error("Descriptor-bound MCP authoring requires Linux");
|
|
@@ -211,18 +219,29 @@ export class McpSession {
|
|
|
211
219
|
: {}),
|
|
212
220
|
// A Headers object rather than a spread, because header names are case-insensitive: a
|
|
213
221
|
// configured `Authorization` must lose to the OAuth token, not travel beside it.
|
|
214
|
-
fetch: (input, init) => {
|
|
222
|
+
fetch: async (input, init) => {
|
|
215
223
|
const headers = new Headers(configured);
|
|
216
224
|
new Headers(init?.headers).forEach((value, name) => headers.set(name, value));
|
|
217
225
|
if (tokens)
|
|
218
226
|
headers.set("Authorization", `Bearer ${tokens.access_token}`);
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
227
|
+
const send = async (refresh) => {
|
|
228
|
+
if (refresh !== undefined)
|
|
229
|
+
headers.set("Authorization", `Bearer ${await this.hostToken(id, refresh)}`);
|
|
230
|
+
return fetch(input, {
|
|
231
|
+
...init,
|
|
232
|
+
headers,
|
|
233
|
+
signal: this.direct ? init?.signal ?? null : init?.signal
|
|
234
|
+
? AbortSignal.any([init.signal, AbortSignal.timeout(10_000)])
|
|
235
|
+
: AbortSignal.timeout(10_000),
|
|
236
|
+
});
|
|
237
|
+
};
|
|
238
|
+
if (!connection.oauth || !this.hostToken)
|
|
239
|
+
return send();
|
|
240
|
+
const response = await send(false);
|
|
241
|
+
if (response.status !== 401)
|
|
242
|
+
return response;
|
|
243
|
+
await response.body?.cancel();
|
|
244
|
+
return send(true);
|
|
226
245
|
},
|
|
227
246
|
});
|
|
228
247
|
}
|
|
@@ -236,15 +255,15 @@ export class McpSession {
|
|
|
236
255
|
await stop();
|
|
237
256
|
return;
|
|
238
257
|
}
|
|
239
|
-
const signal = AbortSignal.timeout(
|
|
240
|
-
await client.connect(transport, { timeout:
|
|
258
|
+
const signal = AbortSignal.timeout(this.connectTimeoutMs);
|
|
259
|
+
await client.connect(transport, { timeout: this.connectTimeoutMs, signal });
|
|
241
260
|
const serverIdentity = createHash("sha256").update(JSON.stringify(client.getServerVersion() ?? null)).digest("hex");
|
|
242
261
|
const tools = [];
|
|
243
262
|
let cursor;
|
|
244
263
|
const seen = new Set();
|
|
245
264
|
do {
|
|
246
265
|
const result = await client.listTools(cursor ? { cursor } : {}, {
|
|
247
|
-
timeout:
|
|
266
|
+
timeout: this.connectTimeoutMs,
|
|
248
267
|
signal,
|
|
249
268
|
});
|
|
250
269
|
for (const definition of result.tools) {
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
import { readdirSync, readFileSync, renameSync, writeFileSync } from "node:fs";
|
|
2
|
+
import { join } from "node:path";
|
|
3
|
+
/** Point pi session files in `stateDir` from Scope `from` to Scope `to`. pi reopens a session only when its header `cwd` matches. */
|
|
4
|
+
export function relocatePiState(stateDir, from, to) {
|
|
5
|
+
for (const entry of readdirSync(stateDir, { withFileTypes: true })) {
|
|
6
|
+
if (!entry.isFile() || !entry.name.endsWith(".jsonl"))
|
|
7
|
+
continue;
|
|
8
|
+
const path = join(stateDir, entry.name);
|
|
9
|
+
const content = readFileSync(path, "utf8");
|
|
10
|
+
const end = content.indexOf("\n");
|
|
11
|
+
const header = JSON.parse(end < 0 ? content : content.slice(0, end));
|
|
12
|
+
if (header.type !== "session" || header.cwd !== from)
|
|
13
|
+
continue;
|
|
14
|
+
const temporary = `${path}.relocate`;
|
|
15
|
+
writeFileSync(temporary, JSON.stringify({ ...header, cwd: to }) + (end < 0 ? "" : content.slice(end)), { mode: 0o600 });
|
|
16
|
+
renameSync(temporary, path);
|
|
17
|
+
}
|
|
18
|
+
}
|
package/dist/backend/registry.js
CHANGED
|
@@ -2,7 +2,8 @@ import { WorkerBackend } from "./worker/index.js";
|
|
|
2
2
|
import { FakeBackend } from "./fake/index.js";
|
|
3
3
|
export function registerBackends(host) {
|
|
4
4
|
const stateRoot = host.filesystemStateRoot();
|
|
5
|
-
const policy = { ...(stateRoot ? { stateRoot } : {}),
|
|
5
|
+
const policy = { ...(stateRoot ? { stateRoot } : {}), isolationMode: () => host.filesystemIsolationMode(), sandbox: () => host.sandboxSupport(),
|
|
6
|
+
sharedSandbox: () => host.sharedSandbox() };
|
|
6
7
|
host.registerBackend(new WorkerBackend({ backend: "claude", ...policy }));
|
|
7
8
|
host.registerBackend(new WorkerBackend({ backend: "pi", ...policy }));
|
|
8
9
|
host.registerBackend(new FakeBackend());
|
|
@@ -12,7 +12,7 @@ function ownedProjects(stateDir) {
|
|
|
12
12
|
return projects;
|
|
13
13
|
}
|
|
14
14
|
/** Claude's Scope key, including the CLI's suffix for paths longer than 200 characters. */
|
|
15
|
-
function projectKey(scope) {
|
|
15
|
+
export function projectKey(scope) {
|
|
16
16
|
const key = scope.replace(/[^a-zA-Z0-9]/g, "-");
|
|
17
17
|
if (key.length <= 200)
|
|
18
18
|
return key;
|
|
@@ -21,6 +21,19 @@ function projectKey(scope) {
|
|
|
21
21
|
hash = ((hash << 5) - hash + scope.charCodeAt(i)) | 0;
|
|
22
22
|
return `${key.slice(0, 200)}-${Math.abs(hash).toString(36)}`;
|
|
23
23
|
}
|
|
24
|
+
/** Move the owned records of Scope `from` to Scope `to`. Does nothing when there is no record. */
|
|
25
|
+
export function relocateClaudeState(stateDir, from, to) {
|
|
26
|
+
if (!existsSync(join(stateDir, "claude-projects")))
|
|
27
|
+
return;
|
|
28
|
+
const projects = ownedProjects(stateDir);
|
|
29
|
+
const source = join(projects, projectKey(from));
|
|
30
|
+
const destination = join(projects, projectKey(to));
|
|
31
|
+
if (!existsSync(source) || source === destination)
|
|
32
|
+
return;
|
|
33
|
+
if (existsSync(destination))
|
|
34
|
+
throw new Error(`A Claude record for ${to} already exists`);
|
|
35
|
+
renameSync(source, destination);
|
|
36
|
+
}
|
|
24
37
|
/** Copy only regular, unlinked records; never follow a link into other host state. */
|
|
25
38
|
function copyRecord(source, destination, from = source) {
|
|
26
39
|
const before = lstatSync(from);
|
|
@@ -135,7 +148,7 @@ export function migrateLegacyClaudeState(stateDir, inherited, scope, resume) {
|
|
|
135
148
|
* restricted launches already bind projects into a narrowly staged config root and must NEVER
|
|
136
149
|
* receive the host auth override.
|
|
137
150
|
*/
|
|
138
|
-
export function prepareClaudeState(stateDir, inherited = process.env, scope = process.cwd(), resume) {
|
|
151
|
+
export function prepareClaudeState(stateDir, inherited = process.env, scope = process.cwd(), resume, options = {}) {
|
|
139
152
|
if (!stateDir)
|
|
140
153
|
return { env: inherited, cleanup() { } };
|
|
141
154
|
migrateLegacyClaudeState(stateDir, inherited, scope, resume);
|
|
@@ -153,7 +166,11 @@ export function prepareClaudeState(stateDir, inherited = process.env, scope = pr
|
|
|
153
166
|
}
|
|
154
167
|
// Unrestricted config view. Do not alter the user's global projects link, copy any global
|
|
155
168
|
// transcripts, or persist credentials in backend state (which restricted workers can read).
|
|
156
|
-
const config = mkdtempSync(join(tmpdir(), "flow-claude-config-"));
|
|
169
|
+
const config = options.viewRoot ? join(options.viewRoot, "claude-config") : mkdtempSync(join(tmpdir(), "flow-claude-config-"));
|
|
170
|
+
if (options.viewRoot) {
|
|
171
|
+
rmSync(config, { recursive: true, force: true });
|
|
172
|
+
mkdirSync(config, { mode: 0o700 });
|
|
173
|
+
}
|
|
157
174
|
const cleanup = () => rmSync(config, { recursive: true, force: true });
|
|
158
175
|
try {
|
|
159
176
|
symlinkSync(projects, join(config, "projects"), "dir");
|
|
@@ -167,6 +184,10 @@ export function prepareClaudeState(stateDir, inherited = process.env, scope = pr
|
|
|
167
184
|
if (existsSync(from))
|
|
168
185
|
symlinkSync(from, join(config, name), statSync(from).isDirectory() ? "dir" : "file");
|
|
169
186
|
}
|
|
187
|
+
if (options.secureStorage !== undefined) {
|
|
188
|
+
const { CLAUDE_SECURESTORAGE_CONFIG_DIR: _, ...rest } = inherited;
|
|
189
|
+
return { env: { ...rest, CLAUDE_CONFIG_DIR: config, ...(options.secureStorage === null ? {} : { CLAUDE_SECURESTORAGE_CONFIG_DIR: options.secureStorage }) }, cleanup };
|
|
190
|
+
}
|
|
170
191
|
const env = { ...inherited, CLAUDE_CONFIG_DIR: config,
|
|
171
192
|
// Use the original spelling, including the empty default: macOS hashes this string for
|
|
172
193
|
// its keychain service identity. Linux resolves it to the original credential directory.
|
|
@@ -6,9 +6,11 @@ var __rewriteRelativeImportExtension = (this && this.__rewriteRelativeImportExte
|
|
|
6
6
|
}
|
|
7
7
|
return path;
|
|
8
8
|
};
|
|
9
|
+
import { McpSession } from "../mcp.js";
|
|
9
10
|
import { WorkerRpc, errorText } from "./rpc.js";
|
|
10
11
|
import { snapshot } from "./protocol.js";
|
|
11
12
|
import { killWorkerTree } from "./launcher.js";
|
|
13
|
+
import { encodeFrame, frameDecoder } from "./frames.js";
|
|
12
14
|
import { createRequire } from "node:module";
|
|
13
15
|
import { isSea } from "node:sea";
|
|
14
16
|
import { fileURLToPath, pathToFileURL } from "node:url";
|
|
@@ -22,8 +24,8 @@ export function runWorker() {
|
|
|
22
24
|
});
|
|
23
25
|
return;
|
|
24
26
|
}
|
|
25
|
-
|
|
26
|
-
|
|
27
|
+
const writeFrame = process.stdout.write.bind(process.stdout);
|
|
28
|
+
process.stdout.write = process.stderr.write.bind(process.stderr);
|
|
27
29
|
let session;
|
|
28
30
|
let published;
|
|
29
31
|
const publishSnapshot = () => (published = snapshot(session));
|
|
@@ -31,19 +33,22 @@ export function runWorker() {
|
|
|
31
33
|
let closing = false;
|
|
32
34
|
let shutdown;
|
|
33
35
|
let tools = [];
|
|
36
|
+
let localMcp;
|
|
37
|
+
let localMcpOpening;
|
|
34
38
|
const workflows = new Map();
|
|
35
39
|
const send = (message) => {
|
|
36
|
-
if (!process.
|
|
40
|
+
if (!process.stdout.writable)
|
|
37
41
|
throw new Error("Backend worker disconnected");
|
|
38
|
-
|
|
42
|
+
writeFrame(encodeFrame(message), (error) => { if (error)
|
|
39
43
|
void stop(); });
|
|
40
44
|
};
|
|
41
|
-
const rpc = new WorkerRpc(send, async (method, args) => {
|
|
45
|
+
const rpc = new WorkerRpc(send, async (method, args, signal) => {
|
|
42
46
|
if (method === "create") {
|
|
47
|
+
const ready = performance.now();
|
|
43
48
|
if (creating || closing)
|
|
44
49
|
throw new Error("Backend worker already initialized");
|
|
45
50
|
creating = true;
|
|
46
|
-
const { mcpTools, mcpConnectionIds, workflowEnabled, workflowBuilderInstructions, backendModule, backend: backendName = "pi", ...options } = args[0];
|
|
51
|
+
const { mcpTools, mcpConnectionIds, mcpSandbox, workflowEnabled, workflowBuilderInstructions, backendModule, backend: backendName = "pi", ...options } = args[0];
|
|
47
52
|
const workflowBuilder = workflowBuilderInstructions === undefined ? undefined : {
|
|
48
53
|
instructions: workflowBuilderInstructions,
|
|
49
54
|
read: (path) => rpc.call("workflowBuilder.read", [path]),
|
|
@@ -51,6 +56,13 @@ export function runWorker() {
|
|
|
51
56
|
write: (content) => rpc.call("workflowBuilder.write", [content]),
|
|
52
57
|
};
|
|
53
58
|
updateTools(mcpTools ?? []);
|
|
59
|
+
if (mcpSandbox)
|
|
60
|
+
localMcp = new McpSession(mcpSandbox, options.scope, undefined, false, undefined, undefined, undefined, "none", undefined, (connectionId, refresh) => rpc.call("mcp.token", [connectionId, refresh]));
|
|
61
|
+
if (localMcp) {
|
|
62
|
+
localMcp.connectTimeoutMs = 120_000;
|
|
63
|
+
localMcpOpening = localMcp.open();
|
|
64
|
+
localMcpOpening.catch(() => { });
|
|
65
|
+
}
|
|
54
66
|
const workflow = {
|
|
55
67
|
inspect: (input) => rpc.call("workflow.inspect", [input]),
|
|
56
68
|
recover: (input, signal) => rpc.call("workflow.recover", [input], signal),
|
|
@@ -58,6 +70,7 @@ export function runWorker() {
|
|
|
58
70
|
relayPermission: (input, signal) => rpc.call("workflow.relayPermission", [input], signal),
|
|
59
71
|
};
|
|
60
72
|
let backend;
|
|
73
|
+
const importing = performance.now();
|
|
61
74
|
try {
|
|
62
75
|
backend = backendModule
|
|
63
76
|
? (isSea()
|
|
@@ -69,10 +82,12 @@ export function runWorker() {
|
|
|
69
82
|
catch (error) {
|
|
70
83
|
throw new Error(`Backend "${backendName}" is not available in this build: ${errorText(error)}`);
|
|
71
84
|
}
|
|
85
|
+
const imported = performance.now();
|
|
72
86
|
session = await backend.create({
|
|
73
87
|
...options,
|
|
74
88
|
...(workflowBuilder ? { workflowBuilder } : {
|
|
75
|
-
...(
|
|
89
|
+
...(localMcp ? { mcp: localMcp }
|
|
90
|
+
: mcpTools ? { mcp: { connections: (mcpConnectionIds ?? []).map((id) => ({ id })), tools: () => tools } } : {}),
|
|
76
91
|
...(workflowEnabled ? { workflow } : {}),
|
|
77
92
|
}),
|
|
78
93
|
emit: (event) => {
|
|
@@ -86,13 +101,12 @@ export function runWorker() {
|
|
|
86
101
|
await session.dispose();
|
|
87
102
|
throw new Error("Backend worker stopped during initialization");
|
|
88
103
|
}
|
|
89
|
-
return publishSnapshot();
|
|
104
|
+
return { ...publishSnapshot(), startup: { ready, import: imported - importing, create: performance.now() - imported } };
|
|
90
105
|
}
|
|
91
106
|
if (method === "dispose") {
|
|
92
107
|
await disposeSession();
|
|
93
108
|
// The RPC reply must be queued before disconnecting and exiting.
|
|
94
|
-
setImmediate(() =>
|
|
95
|
-
process.disconnect(); process.exit(0); });
|
|
109
|
+
setImmediate(() => process.stdout.end(() => process.exit(0)));
|
|
96
110
|
return;
|
|
97
111
|
}
|
|
98
112
|
if (!session || closing)
|
|
@@ -133,9 +147,42 @@ export function runWorker() {
|
|
|
133
147
|
result = await session.answerPermission?.(args[0], args[1]) ?? false;
|
|
134
148
|
break;
|
|
135
149
|
case "refreshMcp":
|
|
136
|
-
|
|
150
|
+
if (!localMcp)
|
|
151
|
+
updateTools(args[0]);
|
|
137
152
|
result = await session.refreshMcp?.();
|
|
138
153
|
break;
|
|
154
|
+
case "mcp.open": {
|
|
155
|
+
if (!localMcp)
|
|
156
|
+
throw new Error("No sandbox MCP clients");
|
|
157
|
+
const opening = localMcpOpening ?? localMcp.open();
|
|
158
|
+
localMcpOpening = undefined;
|
|
159
|
+
await opening;
|
|
160
|
+
result = localMcp.status();
|
|
161
|
+
break;
|
|
162
|
+
}
|
|
163
|
+
case "mcp.retry":
|
|
164
|
+
if (!localMcp)
|
|
165
|
+
throw new Error("No sandbox MCP clients");
|
|
166
|
+
await localMcp.retry(args[0]);
|
|
167
|
+
result = localMcp.status();
|
|
168
|
+
break;
|
|
169
|
+
case "mcp.direct": {
|
|
170
|
+
if (!localMcp)
|
|
171
|
+
throw new Error("No sandbox MCP clients");
|
|
172
|
+
const id = args[0];
|
|
173
|
+
if (localMcp.status().find((state) => state.id === id)?.state !== "connected")
|
|
174
|
+
await localMcp.retry(id).catch(() => { });
|
|
175
|
+
result = { status: localMcp.status().find((state) => state.id === id) ?? { id, state: "failed", tools: 0 },
|
|
176
|
+
tools: localMcp.tools().filter((tool) => tool.connectionId === id).map(({ call: _, ...tool }) => tool) };
|
|
177
|
+
break;
|
|
178
|
+
}
|
|
179
|
+
case "mcp.callTool": {
|
|
180
|
+
const tool = localMcp?.tools().find((entry) => entry.name === args[0]);
|
|
181
|
+
if (!tool)
|
|
182
|
+
throw new Error("Unknown MCP tool");
|
|
183
|
+
result = await tool.call(args[1], signal, args[2]);
|
|
184
|
+
break;
|
|
185
|
+
}
|
|
139
186
|
case "workflow.start": {
|
|
140
187
|
if (!session.startWorkflowSubagent)
|
|
141
188
|
throw new Error("Workflow Subagents are not supported");
|
|
@@ -168,6 +215,7 @@ export function runWorker() {
|
|
|
168
215
|
closing = true;
|
|
169
216
|
await Promise.allSettled([...workflows.values()].map((handle) => handle.cancel()));
|
|
170
217
|
await session?.dispose();
|
|
218
|
+
await localMcp?.dispose({ waitForExit: true });
|
|
171
219
|
}
|
|
172
220
|
function stop() {
|
|
173
221
|
return shutdown ??= (async () => {
|
|
@@ -185,8 +233,17 @@ export function runWorker() {
|
|
|
185
233
|
}
|
|
186
234
|
})();
|
|
187
235
|
}
|
|
188
|
-
|
|
189
|
-
process.
|
|
236
|
+
const decode = frameDecoder((message) => rpc.receive(message));
|
|
237
|
+
process.stdin.on("data", (chunk) => {
|
|
238
|
+
try {
|
|
239
|
+
decode(chunk);
|
|
240
|
+
}
|
|
241
|
+
catch {
|
|
242
|
+
void stop();
|
|
243
|
+
}
|
|
244
|
+
});
|
|
245
|
+
process.stdin.once("end", () => { void stop(); });
|
|
246
|
+
process.stdout.on("error", () => { void stop(); });
|
|
190
247
|
process.once("SIGTERM", () => { void stop(); });
|
|
191
248
|
process.once("SIGINT", () => { void stop(); });
|
|
192
249
|
}
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
import { deserialize, serialize } from "node:v8";
|
|
2
|
+
export function encodeFrame(message) {
|
|
3
|
+
const body = serialize(message);
|
|
4
|
+
const frame = Buffer.allocUnsafe(4 + body.length);
|
|
5
|
+
frame.writeUInt32BE(body.length, 0);
|
|
6
|
+
body.copy(frame, 4);
|
|
7
|
+
return frame;
|
|
8
|
+
}
|
|
9
|
+
export function frameDecoder(onMessage) {
|
|
10
|
+
let chunks = [];
|
|
11
|
+
let size = 0;
|
|
12
|
+
let need = 4;
|
|
13
|
+
let header = true;
|
|
14
|
+
return (chunk) => {
|
|
15
|
+
chunks.push(chunk);
|
|
16
|
+
size += chunk.length;
|
|
17
|
+
while (size >= need) {
|
|
18
|
+
const data = chunks.length === 1 ? chunks[0] : Buffer.concat(chunks, size);
|
|
19
|
+
chunks = [data];
|
|
20
|
+
if (header) {
|
|
21
|
+
need = 4 + data.readUInt32BE(0);
|
|
22
|
+
header = false;
|
|
23
|
+
continue;
|
|
24
|
+
}
|
|
25
|
+
const message = deserialize(data.subarray(4, need));
|
|
26
|
+
const rest = data.subarray(need);
|
|
27
|
+
chunks = rest.length ? [rest] : [];
|
|
28
|
+
size = rest.length;
|
|
29
|
+
need = 4;
|
|
30
|
+
header = true;
|
|
31
|
+
onMessage(message);
|
|
32
|
+
}
|
|
33
|
+
};
|
|
34
|
+
}
|