@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,196 @@
|
|
|
1
|
+
import { spawn } from "node:child_process";
|
|
2
|
+
import { ReadBuffer, serializeMessage } from "@modelcontextprotocol/sdk/shared/stdio.js";
|
|
3
|
+
/** Lifecycle ownership is independent of filesystem isolation. Use the SDK's public framing,
|
|
4
|
+
* not its private subprocess fields. This code is statically loaded in npm and SEA builds;
|
|
5
|
+
* there is no executable helper in a writable Scope or source-relative runtime asset.
|
|
6
|
+
*
|
|
7
|
+
* POSIX groups cover ordinary children, not deliberately detached unrestricted descendants.
|
|
8
|
+
* Pipe closure is therefore separate from process exit: an escaped pipe holder must never
|
|
9
|
+
* hold Retry/disposal open. Windows uses bounded, best-effort taskkill tree cleanup.
|
|
10
|
+
*/
|
|
11
|
+
export class SupervisedStdioTransport {
|
|
12
|
+
onclose;
|
|
13
|
+
onerror;
|
|
14
|
+
onmessage;
|
|
15
|
+
buffer = new ReadBuffer();
|
|
16
|
+
child;
|
|
17
|
+
started = false;
|
|
18
|
+
closed = false;
|
|
19
|
+
notified = false;
|
|
20
|
+
closing;
|
|
21
|
+
finishing;
|
|
22
|
+
leaderExited = false;
|
|
23
|
+
treeCleanup;
|
|
24
|
+
resolveExit;
|
|
25
|
+
/** Actual leader exit (not stdio 'close'), plus group cleanup. State must outlive this. */
|
|
26
|
+
exited = new Promise((resolve) => { this.resolveExit = resolve; });
|
|
27
|
+
launch;
|
|
28
|
+
constructor(launch) { this.launch = launch; }
|
|
29
|
+
async start() {
|
|
30
|
+
if (this.started || this.closed)
|
|
31
|
+
throw new Error("MCP transport already started or closed");
|
|
32
|
+
this.started = true;
|
|
33
|
+
try {
|
|
34
|
+
const child = this.child = spawn(this.launch.command, this.launch.args, {
|
|
35
|
+
env: this.launch.env,
|
|
36
|
+
cwd: this.launch.cwd,
|
|
37
|
+
detached: process.platform !== "win32",
|
|
38
|
+
windowsHide: true,
|
|
39
|
+
stdio: ["pipe", "pipe", "pipe", ...(this.launch.stdioFds ?? [])],
|
|
40
|
+
});
|
|
41
|
+
child.stdin.on("error", error => this.onerror?.(error));
|
|
42
|
+
child.stdout.on("error", error => this.onerror?.(error));
|
|
43
|
+
// Drain, but do not retain server diagnostics or host secrets.
|
|
44
|
+
child.stderr.on("error", error => this.onerror?.(error));
|
|
45
|
+
child.stderr.resume();
|
|
46
|
+
child.stdout.on("data", (chunk) => {
|
|
47
|
+
try {
|
|
48
|
+
this.buffer.append(chunk);
|
|
49
|
+
}
|
|
50
|
+
catch (error) {
|
|
51
|
+
this.onerror?.(error);
|
|
52
|
+
void this.close();
|
|
53
|
+
return;
|
|
54
|
+
}
|
|
55
|
+
while (!this.closed) {
|
|
56
|
+
try {
|
|
57
|
+
const message = this.buffer.readMessage();
|
|
58
|
+
if (message === null)
|
|
59
|
+
break;
|
|
60
|
+
this.onmessage?.(message);
|
|
61
|
+
}
|
|
62
|
+
catch (error) {
|
|
63
|
+
this.onerror?.(error);
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
});
|
|
67
|
+
// 'close' can wait forever for a descendant's inherited stdout/stderr. 'exit' cannot.
|
|
68
|
+
child.once("exit", () => { void this.finishExit(); });
|
|
69
|
+
child.once("error", error => {
|
|
70
|
+
this.onerror?.(error);
|
|
71
|
+
if (!child.pid)
|
|
72
|
+
void this.finishExit();
|
|
73
|
+
});
|
|
74
|
+
await new Promise((resolve, reject) => {
|
|
75
|
+
child.once("spawn", resolve);
|
|
76
|
+
child.once("error", reject);
|
|
77
|
+
});
|
|
78
|
+
}
|
|
79
|
+
catch (error) {
|
|
80
|
+
if (!this.child?.pid)
|
|
81
|
+
await this.finishExit();
|
|
82
|
+
throw error;
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
closePipes() {
|
|
86
|
+
this.closed = true;
|
|
87
|
+
this.child?.stdin?.destroy();
|
|
88
|
+
this.child?.stdout?.destroy();
|
|
89
|
+
this.child?.stderr?.destroy();
|
|
90
|
+
this.buffer.clear();
|
|
91
|
+
}
|
|
92
|
+
killTree() {
|
|
93
|
+
return this.treeCleanup ??= (async () => {
|
|
94
|
+
const child = this.child;
|
|
95
|
+
if (!child?.pid)
|
|
96
|
+
return;
|
|
97
|
+
if (process.platform !== "win32") {
|
|
98
|
+
try {
|
|
99
|
+
process.kill(-child.pid, "SIGKILL");
|
|
100
|
+
}
|
|
101
|
+
catch (error) {
|
|
102
|
+
if (error.code !== "ESRCH") {
|
|
103
|
+
// Retain the error, but still try to stop the leader and close its pipes.
|
|
104
|
+
this.onerror?.(error);
|
|
105
|
+
child.kill("SIGKILL");
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
else {
|
|
110
|
+
const killer = spawn("taskkill", ["/pid", String(child.pid), "/T", "/F"], { stdio: "ignore", windowsHide: true });
|
|
111
|
+
await bounded(new Promise(resolve => {
|
|
112
|
+
killer.once("error", () => resolve());
|
|
113
|
+
killer.once("exit", () => resolve());
|
|
114
|
+
}), 1000);
|
|
115
|
+
killer.kill();
|
|
116
|
+
killer.unref();
|
|
117
|
+
child.kill("SIGKILL");
|
|
118
|
+
}
|
|
119
|
+
})();
|
|
120
|
+
}
|
|
121
|
+
drainStdout() {
|
|
122
|
+
const stdout = this.child?.stdout;
|
|
123
|
+
if (this.closed || !stdout || stdout.destroyed || stdout.readableEnded)
|
|
124
|
+
return Promise.resolve();
|
|
125
|
+
return new Promise(resolve => {
|
|
126
|
+
const done = () => {
|
|
127
|
+
clearTimeout(timer);
|
|
128
|
+
stdout.off("end", done);
|
|
129
|
+
stdout.off("close", done);
|
|
130
|
+
stdout.off("error", done);
|
|
131
|
+
resolve();
|
|
132
|
+
};
|
|
133
|
+
const timer = setTimeout(done, 1000);
|
|
134
|
+
stdout.once("end", done);
|
|
135
|
+
stdout.once("close", done);
|
|
136
|
+
stdout.once("error", done);
|
|
137
|
+
stdout.resume();
|
|
138
|
+
});
|
|
139
|
+
}
|
|
140
|
+
finishExit() {
|
|
141
|
+
return this.finishing ??= (async () => {
|
|
142
|
+
this.leaderExited = true;
|
|
143
|
+
// Kill ordinary pipe holders first, but retain stdout until its already-written
|
|
144
|
+
// final reply drains. 'exit' can precede those data events. A detached holder
|
|
145
|
+
// cannot force an unbounded EOF wait; explicit disposal may discard replies.
|
|
146
|
+
await this.killTree();
|
|
147
|
+
await this.drainStdout();
|
|
148
|
+
this.closePipes();
|
|
149
|
+
this.resolveExit();
|
|
150
|
+
this.notifyClose();
|
|
151
|
+
})();
|
|
152
|
+
}
|
|
153
|
+
notifyClose() {
|
|
154
|
+
if (this.notified)
|
|
155
|
+
return;
|
|
156
|
+
this.notified = true;
|
|
157
|
+
this.onclose?.();
|
|
158
|
+
}
|
|
159
|
+
close() {
|
|
160
|
+
return this.closing ??= (async () => {
|
|
161
|
+
this.closed = true;
|
|
162
|
+
if (!this.started) {
|
|
163
|
+
await this.finishExit();
|
|
164
|
+
return;
|
|
165
|
+
}
|
|
166
|
+
// Give a well-behaved server EOF, then always kill the group, even if its leader
|
|
167
|
+
// exited cooperatively. A SIGTERM-ignoring child must not outlive its client.
|
|
168
|
+
this.child?.stdin?.end();
|
|
169
|
+
await bounded(this.exited, 500);
|
|
170
|
+
await this.killTree();
|
|
171
|
+
this.closePipes();
|
|
172
|
+
// A kernel-stalled leader need not block host shutdown. Its mount state is retained
|
|
173
|
+
// until the actual exit event; do not pretend this bounded wait means it has exited.
|
|
174
|
+
await bounded(this.exited, 1000);
|
|
175
|
+
this.child?.unref();
|
|
176
|
+
this.notifyClose();
|
|
177
|
+
})();
|
|
178
|
+
}
|
|
179
|
+
async send(message) {
|
|
180
|
+
const stdin = this.child?.stdin;
|
|
181
|
+
if (this.closed || this.leaderExited || !stdin || stdin.destroyed)
|
|
182
|
+
throw new Error("MCP transport not connected");
|
|
183
|
+
await new Promise((resolve, reject) => {
|
|
184
|
+
stdin.write(serializeMessage(message), error => error ? reject(error) : resolve());
|
|
185
|
+
});
|
|
186
|
+
}
|
|
187
|
+
}
|
|
188
|
+
async function bounded(promise, milliseconds) {
|
|
189
|
+
let timer;
|
|
190
|
+
try {
|
|
191
|
+
await Promise.race([promise, new Promise(resolve => { timer = setTimeout(resolve, milliseconds); })]);
|
|
192
|
+
}
|
|
193
|
+
finally {
|
|
194
|
+
clearTimeout(timer);
|
|
195
|
+
}
|
|
196
|
+
}
|
package/dist/backend/mcp.js
CHANGED
|
@@ -1,9 +1,49 @@
|
|
|
1
1
|
import { createHash } from "node:crypto";
|
|
2
|
+
import { existsSync, realpathSync, statSync } from "node:fs";
|
|
3
|
+
import { dirname, join, resolve } from "node:path";
|
|
4
|
+
import { prepareFilesystemIsolation } from "../isolation/filesystem.js";
|
|
5
|
+
import { SupervisedStdioTransport } from "./mcp-stdio-supervisor.js";
|
|
6
|
+
import { nodeExecutionAssets } from "../isolation/node-assets.js";
|
|
2
7
|
import { Client } from "@modelcontextprotocol/sdk/client/index.js";
|
|
3
|
-
import {
|
|
8
|
+
import { getDefaultEnvironment } from "@modelcontextprotocol/sdk/client/stdio.js";
|
|
4
9
|
import { StreamableHTTPClientTransport } from "@modelcontextprotocol/sdk/client/streamableHttp.js";
|
|
10
|
+
/** Execution assets, not a general grant to the directories named in server arguments.
|
|
11
|
+
* The policy canonicalises and rejects broad/protected mounts before launching anything.
|
|
12
|
+
* Package roots keep relative imports and dependencies available when /tmp is masked.
|
|
13
|
+
*/
|
|
14
|
+
function executionAssets(connection, scope) {
|
|
15
|
+
const paths = [];
|
|
16
|
+
const command = connection.command.includes("/") ? resolve(scope, connection.command)
|
|
17
|
+
: (process.env.PATH ?? "/usr/bin:/bin").split(":").map((directory) => resolve(directory, connection.command)).find((path) => existsSync(path));
|
|
18
|
+
for (const argument of [...(command ? [command] : []), ...connection.args]) {
|
|
19
|
+
if (argument.startsWith("-"))
|
|
20
|
+
continue;
|
|
21
|
+
const path = resolve(scope, argument);
|
|
22
|
+
if (!existsSync(path))
|
|
23
|
+
continue;
|
|
24
|
+
const canonical = realpathSync(path);
|
|
25
|
+
if (statSync(canonical).isDirectory()) {
|
|
26
|
+
paths.push(canonical);
|
|
27
|
+
continue;
|
|
28
|
+
}
|
|
29
|
+
let root = dirname(canonical);
|
|
30
|
+
for (let ancestor = root; ancestor !== dirname(ancestor); ancestor = dirname(ancestor)) {
|
|
31
|
+
if (existsSync(join(ancestor, "package.json"))) {
|
|
32
|
+
root = ancestor;
|
|
33
|
+
break;
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
// Never widen a lone file in /tmp into a mount of all /tmp. Other unsafe roots
|
|
37
|
+
// (home, protected state, and runtime sockets) are rejected by the policy.
|
|
38
|
+
paths.push(root === "/tmp" ? canonical : root);
|
|
39
|
+
}
|
|
40
|
+
// A private ancestor mask can hide symlinked or hoisted Node dependencies even when the
|
|
41
|
+
// package itself remains visible. Restore dependency trees explicitly, still policy-checked.
|
|
42
|
+
return [...new Set([...paths, ...nodeExecutionAssets(paths)])];
|
|
43
|
+
}
|
|
5
44
|
export class McpSession {
|
|
6
45
|
clients = new Map();
|
|
46
|
+
stops = new Map();
|
|
7
47
|
entries = new Map();
|
|
8
48
|
states = new Map();
|
|
9
49
|
pending = new Map();
|
|
@@ -14,12 +54,18 @@ export class McpSession {
|
|
|
14
54
|
scope;
|
|
15
55
|
auth;
|
|
16
56
|
resolveSecret;
|
|
17
|
-
|
|
57
|
+
protectedPaths;
|
|
58
|
+
stateRoot;
|
|
59
|
+
isolationEnabled;
|
|
60
|
+
constructor(connections, scope, auth, direct = false, resolveSecret, protectedPaths, stateRoot, isolationEnabled = true) {
|
|
18
61
|
this.connections = structuredClone(connections);
|
|
19
62
|
this.scope = scope;
|
|
20
63
|
this.auth = auth;
|
|
21
64
|
this.direct = direct;
|
|
22
65
|
this.resolveSecret = resolveSecret;
|
|
66
|
+
this.protectedPaths = protectedPaths;
|
|
67
|
+
this.stateRoot = stateRoot;
|
|
68
|
+
this.isolationEnabled = isolationEnabled;
|
|
23
69
|
}
|
|
24
70
|
registrationFailed() {
|
|
25
71
|
for (const [id] of this.states)
|
|
@@ -62,59 +108,103 @@ export class McpSession {
|
|
|
62
108
|
const { id } = connection;
|
|
63
109
|
this.states.set(id, { id, state: "connecting", tools: 0 });
|
|
64
110
|
this.entries.delete(id);
|
|
65
|
-
await this.
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
.catch(() => { });
|
|
111
|
+
await this.stops.get(id)?.();
|
|
112
|
+
this.clients.delete(id);
|
|
113
|
+
this.stops.delete(id);
|
|
69
114
|
if (this.disposed)
|
|
70
115
|
return;
|
|
71
116
|
const client = new Client({ name: "Flow", version: "1.0.0" }, { capabilities: {} });
|
|
72
117
|
this.clients.set(id, client);
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
118
|
+
let isolation;
|
|
119
|
+
let transport;
|
|
120
|
+
let stopping;
|
|
121
|
+
const stop = () => stopping ??= (async () => {
|
|
122
|
+
await client.close().catch(() => { });
|
|
123
|
+
// Client may already have detached a transport after an error or spontaneous exit.
|
|
124
|
+
await transport?.close();
|
|
125
|
+
// A bounded stdio close may return before a kernel-stalled process exits. Its pinned
|
|
126
|
+
// mount state is released only by the actual-exit hook registered below.
|
|
127
|
+
if (!(transport instanceof SupervisedStdioTransport))
|
|
128
|
+
isolation?.cleanup();
|
|
129
|
+
})();
|
|
130
|
+
this.stops.set(id, stop);
|
|
131
|
+
try {
|
|
132
|
+
// Direct workflow sessions never initiate login or replay a POST after a 401.
|
|
133
|
+
const tokens = this.direct && connection.transport === 'http' && connection.oauth ? await this.auth?.(connection).tokens() : undefined;
|
|
134
|
+
if (this.direct && connection.transport === 'http' && connection.oauth && !tokens?.access_token) {
|
|
135
|
+
this.states.set(id, { id, state: 'failed', tools: 0 });
|
|
136
|
+
return;
|
|
137
|
+
}
|
|
138
|
+
const configured = connection.transport === "http" ? this.configuredHeaders(connection.headers) : {};
|
|
139
|
+
if (connection.transport === "stdio" && !this.isolationEnabled) {
|
|
140
|
+
const scope = realpathSync(this.scope);
|
|
141
|
+
if (!statSync(scope).isDirectory())
|
|
142
|
+
throw new Error("Scope must be a directory");
|
|
143
|
+
transport = new SupervisedStdioTransport({
|
|
144
|
+
command: connection.command,
|
|
145
|
+
args: connection.args,
|
|
146
|
+
env: getDefaultEnvironment(),
|
|
147
|
+
cwd: scope,
|
|
148
|
+
});
|
|
83
149
|
}
|
|
84
|
-
|
|
85
|
-
|
|
150
|
+
else if (connection.transport === "stdio") {
|
|
151
|
+
isolation = await prepareFilesystemIsolation({
|
|
152
|
+
scope: this.scope, expectedScope: resolve(this.scope),
|
|
153
|
+
command: connection.command.includes("/") ? resolve(this.scope, connection.command) : connection.command,
|
|
154
|
+
args: connection.args,
|
|
155
|
+
readablePaths: executionAssets(connection, this.scope),
|
|
156
|
+
// Match the SDK's pre-isolation minimal environment, not all host/provider secrets.
|
|
157
|
+
env: { ...Object.fromEntries(Object.keys(process.env).map((key) => [key, undefined])), ...getDefaultEnvironment(),
|
|
158
|
+
FLOW_BWRAP_PATH: process.env.FLOW_BWRAP_PATH, PI_CODING_AGENT_DIR: process.env.PI_CODING_AGENT_DIR,
|
|
159
|
+
CLAUDE_CONFIG_DIR: process.env.CLAUDE_CONFIG_DIR },
|
|
160
|
+
...(this.protectedPaths ? { protectedPaths: this.protectedPaths } : {}),
|
|
161
|
+
...(this.stateRoot ? { stateRoot: this.stateRoot } : {}),
|
|
162
|
+
credentials: "none",
|
|
163
|
+
});
|
|
164
|
+
// Disposal can arrive while the mount/namespace probe is in flight. No spawn may
|
|
165
|
+
// follow it, even when preparation succeeds after dispose() has closed the client.
|
|
166
|
+
if (this.disposed) {
|
|
167
|
+
isolation.cleanup();
|
|
168
|
+
return;
|
|
169
|
+
}
|
|
170
|
+
transport = new SupervisedStdioTransport({
|
|
171
|
+
command: isolation.command,
|
|
172
|
+
args: isolation.args,
|
|
173
|
+
stdioFds: isolation.stdioFds,
|
|
174
|
+
env: isolation.env,
|
|
175
|
+
cwd: isolation.scope,
|
|
176
|
+
});
|
|
177
|
+
const prepared = isolation;
|
|
178
|
+
void transport.exited.then(() => prepared.cleanup());
|
|
179
|
+
}
|
|
180
|
+
else {
|
|
181
|
+
// HTTP MCP deliberately retains its external/network authority.
|
|
182
|
+
transport = new StreamableHTTPClientTransport(new URL(connection.url), {
|
|
183
|
+
...(connection.oauth && this.auth && !this.direct
|
|
184
|
+
? { authProvider: this.auth(connection) }
|
|
185
|
+
: {}),
|
|
186
|
+
// A Headers object rather than a spread, because header names are case-insensitive: a
|
|
187
|
+
// configured `Authorization` must lose to the OAuth token, not travel beside it.
|
|
188
|
+
fetch: (input, init) => {
|
|
189
|
+
const headers = new Headers(configured);
|
|
190
|
+
new Headers(init?.headers).forEach((value, name) => headers.set(name, value));
|
|
191
|
+
if (tokens)
|
|
192
|
+
headers.set("Authorization", `Bearer ${tokens.access_token}`);
|
|
193
|
+
return fetch(input, {
|
|
194
|
+
...init,
|
|
195
|
+
headers,
|
|
196
|
+
signal: this.direct ? init?.signal ?? null : init?.signal
|
|
197
|
+
? AbortSignal.any([init.signal, AbortSignal.timeout(10_000)])
|
|
198
|
+
: AbortSignal.timeout(10_000),
|
|
199
|
+
});
|
|
200
|
+
},
|
|
201
|
+
});
|
|
202
|
+
}
|
|
203
|
+
if (this.disposed) {
|
|
204
|
+
await stop();
|
|
86
205
|
return;
|
|
87
206
|
}
|
|
88
|
-
|
|
89
|
-
const transport = connection.transport === "stdio"
|
|
90
|
-
? new StdioClientTransport({
|
|
91
|
-
command: connection.command,
|
|
92
|
-
args: connection.args,
|
|
93
|
-
cwd: this.scope,
|
|
94
|
-
stderr: "ignore",
|
|
95
|
-
})
|
|
96
|
-
: new StreamableHTTPClientTransport(new URL(connection.url), {
|
|
97
|
-
...(connection.oauth && this.auth && !this.direct
|
|
98
|
-
? { authProvider: this.auth(connection) }
|
|
99
|
-
: {}),
|
|
100
|
-
// A Headers object rather than a spread, because header names are case-insensitive: a
|
|
101
|
-
// configured `Authorization` must lose to the OAuth token, not travel beside it.
|
|
102
|
-
fetch: (input, init) => {
|
|
103
|
-
const headers = new Headers(configured);
|
|
104
|
-
new Headers(init?.headers).forEach((value, name) => headers.set(name, value));
|
|
105
|
-
if (tokens)
|
|
106
|
-
headers.set("Authorization", `Bearer ${tokens.access_token}`);
|
|
107
|
-
return fetch(input, {
|
|
108
|
-
...init,
|
|
109
|
-
headers,
|
|
110
|
-
signal: this.direct ? init?.signal ?? null : init?.signal
|
|
111
|
-
? AbortSignal.any([init.signal, AbortSignal.timeout(10_000)])
|
|
112
|
-
: AbortSignal.timeout(10_000),
|
|
113
|
-
});
|
|
114
|
-
},
|
|
115
|
-
});
|
|
116
|
-
const signal = AbortSignal.timeout(10_000);
|
|
117
|
-
try {
|
|
207
|
+
const signal = AbortSignal.timeout(10_000);
|
|
118
208
|
await client.connect(transport, { timeout: 10_000, signal });
|
|
119
209
|
const serverIdentity = createHash("sha256").update(JSON.stringify(client.getServerVersion() ?? null)).digest("hex");
|
|
120
210
|
const tools = [];
|
|
@@ -167,24 +257,29 @@ export class McpSession {
|
|
|
167
257
|
seen.add(cursor);
|
|
168
258
|
} while (cursor);
|
|
169
259
|
if (this.disposed) {
|
|
170
|
-
await
|
|
260
|
+
await stop();
|
|
171
261
|
return;
|
|
172
262
|
}
|
|
173
263
|
this.entries.set(id, tools);
|
|
174
264
|
this.states.set(id, { id, state: "connected", tools: tools.length });
|
|
175
265
|
client.onclose = () => {
|
|
266
|
+
this.entries.delete(id);
|
|
176
267
|
if (!this.disposed)
|
|
177
268
|
this.states.set(id, { id, state: "failed", tools: 0 });
|
|
178
269
|
};
|
|
179
270
|
}
|
|
180
271
|
catch {
|
|
181
|
-
await
|
|
272
|
+
await stop();
|
|
273
|
+
this.entries.delete(id);
|
|
182
274
|
this.states.set(id, { id, state: "failed", tools: 0 });
|
|
183
275
|
}
|
|
184
276
|
}
|
|
185
277
|
async dispose() {
|
|
186
278
|
this.disposed = true;
|
|
187
|
-
|
|
279
|
+
this.entries.clear();
|
|
280
|
+
await Promise.all([...this.stops.values()].map((stop) => stop()));
|
|
188
281
|
await Promise.allSettled(this.pending.values());
|
|
282
|
+
// A connect may have been waiting for the previous connection's teardown.
|
|
283
|
+
await Promise.all([...this.stops.values()].map((stop) => stop()));
|
|
189
284
|
}
|
|
190
285
|
}
|
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
import { callIdFor } from "./work.js";
|
|
2
|
+
/** A single decision register shared by the parent and ordinary Subagents. Workflow Steps do not use it. */
|
|
3
|
+
export class PiAgentPermissions {
|
|
4
|
+
mode;
|
|
5
|
+
emit;
|
|
6
|
+
pending = new Map();
|
|
7
|
+
grants;
|
|
8
|
+
refused = new Set();
|
|
9
|
+
constructor(mode, standing, emit) {
|
|
10
|
+
if (mode === "auto")
|
|
11
|
+
throw new Error("Pi does not support Auto permissions");
|
|
12
|
+
this.mode = mode;
|
|
13
|
+
this.emit = emit;
|
|
14
|
+
this.grants = new Set(standing);
|
|
15
|
+
}
|
|
16
|
+
setMode(mode) {
|
|
17
|
+
if (mode === "auto")
|
|
18
|
+
throw new Error("Pi does not support Auto permissions");
|
|
19
|
+
this.mode = mode;
|
|
20
|
+
}
|
|
21
|
+
answer(id, decision) {
|
|
22
|
+
const entry = this.pending.get(id);
|
|
23
|
+
if (!entry)
|
|
24
|
+
return false;
|
|
25
|
+
entry.settle(decision);
|
|
26
|
+
return true;
|
|
27
|
+
}
|
|
28
|
+
cancel(producer) {
|
|
29
|
+
for (const entry of [...this.pending.values()]) {
|
|
30
|
+
if (producer === undefined || (producer.subagentId === "" ? !entry.producer : entry.producer?.subagentId === producer.subagentId))
|
|
31
|
+
entry.settle(undefined);
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
extension(producer) {
|
|
35
|
+
return { name: "flow-agent-permissions", hidden: true, factory: (pi) => {
|
|
36
|
+
pi.on("tool_call", async (event, ctx) => {
|
|
37
|
+
const tool = event.toolName;
|
|
38
|
+
if (tool === "read" || tool === "ask_question" || tool === "subagent" || tool === "bash_output" || tool === "kill_shell" || tool.startsWith("workflow_") ||
|
|
39
|
+
this.grants.has(tool) || this.mode === "always")
|
|
40
|
+
return;
|
|
41
|
+
const refusedKey = `${producer?.subagentId ?? "parent"}/${tool}`;
|
|
42
|
+
if (this.refused.has(refusedKey))
|
|
43
|
+
return { block: true, reason: `${tool} is not authorised` };
|
|
44
|
+
const id = callIdFor(event.toolCallId, producer);
|
|
45
|
+
const decision = await new Promise((resolve) => {
|
|
46
|
+
let settled = false;
|
|
47
|
+
const settle = (value) => {
|
|
48
|
+
if (settled)
|
|
49
|
+
return;
|
|
50
|
+
settled = true;
|
|
51
|
+
ctx.signal?.removeEventListener("abort", onAbort);
|
|
52
|
+
this.pending.delete(id);
|
|
53
|
+
this.emit(value ? { type: "permission", callId: id, tool, ...(producer ? { producer } : {}), state: "decided", decision: value } : { type: "permission", callId: id, tool, ...(producer ? { producer } : {}), state: "aborted" });
|
|
54
|
+
resolve(value);
|
|
55
|
+
};
|
|
56
|
+
const onAbort = () => settle(undefined);
|
|
57
|
+
this.pending.set(id, { tool, settle, ...(producer ? { producer } : {}) });
|
|
58
|
+
ctx.signal?.addEventListener("abort", onAbort, { once: true });
|
|
59
|
+
this.emit({ type: "permission", callId: id, tool, ...(producer ? { producer } : {}), state: "asked" });
|
|
60
|
+
if (ctx.signal?.aborted)
|
|
61
|
+
onAbort();
|
|
62
|
+
});
|
|
63
|
+
if (decision === "always")
|
|
64
|
+
this.grants.add(tool);
|
|
65
|
+
if (decision === "deny")
|
|
66
|
+
this.refused.add(refusedKey);
|
|
67
|
+
return decision === "allow" || decision === "always" ? undefined : { block: true, reason: `${tool} is not authorised` };
|
|
68
|
+
});
|
|
69
|
+
pi.on("agent_settled", () => { for (const key of this.refused)
|
|
70
|
+
if (key.startsWith(`${producer?.subagentId ?? "parent"}/`))
|
|
71
|
+
this.refused.delete(key); });
|
|
72
|
+
} };
|
|
73
|
+
}
|
|
74
|
+
}
|
|
@@ -1,8 +1,6 @@
|
|
|
1
|
-
export function piAutoCompaction(settings,
|
|
1
|
+
export function piAutoCompaction(settings, setting) {
|
|
2
2
|
const defaults = settings.getCompactionSettings();
|
|
3
3
|
return (model) => {
|
|
4
|
-
const id = model?.provider ? `${model.provider}/${model.id}` : model?.id;
|
|
5
|
-
const setting = id ? snapshot[id] : undefined;
|
|
6
4
|
const window = model?.contextWindow;
|
|
7
5
|
const compaction = { ...defaults };
|
|
8
6
|
if (setting?.mode === "disabled")
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
import { compact } from "@earendil-works/pi-coding-agent";
|
|
2
|
+
/** Keep Pi's preparation, split-turn handling, file tracking and usage accounting, changing only
|
|
3
|
+
* the model for its summary calls. External extensions remain disabled in Flow's Backend Sessions. */
|
|
4
|
+
export function compactionExtensionError(errors) {
|
|
5
|
+
return errors.find((entry) => entry.path === "<inline:flow-compaction-model>")?.error;
|
|
6
|
+
}
|
|
7
|
+
export function compactionModelExtension(modelId, notice) {
|
|
8
|
+
return { name: "flow-compaction-model", hidden: true, factory: (pi) => {
|
|
9
|
+
pi.on("session_before_compact", async (event, ctx) => {
|
|
10
|
+
try {
|
|
11
|
+
const model = ctx.modelRegistry.getAvailable().find((candidate) => `${candidate.provider}/${candidate.id}` === modelId);
|
|
12
|
+
if (!model)
|
|
13
|
+
throw new Error(`Configured compaction model “${modelId}” is unavailable`);
|
|
14
|
+
const auth = await ctx.modelRegistry.getApiKeyAndHeaders(model);
|
|
15
|
+
if (!auth.ok)
|
|
16
|
+
throw new Error(auth.error);
|
|
17
|
+
const requestModel = auth.baseUrl ? { ...model, baseUrl: auth.baseUrl } : model;
|
|
18
|
+
const headers = Object.fromEntries(Object.entries(auth.headers ?? {}).filter((entry) => entry[1] !== null));
|
|
19
|
+
const result = await compact(event.preparation, requestModel, auth.apiKey, headers, event.customInstructions, event.signal, "off", undefined, auth.env);
|
|
20
|
+
// Pi appends file-operation tags after generating the summary. Tags alone are not a
|
|
21
|
+
// usable checkpoint if the selected model answered with empty text.
|
|
22
|
+
const body = result.summary.replace(/<(read-files|modified-files)>[\s\S]*?<\/\1>/g, "").trim();
|
|
23
|
+
const prefix = body.split("**Turn Context (split turn):**")[1];
|
|
24
|
+
if (!body || (event.preparation.isSplitTurn && event.preparation.turnPrefixMessages.length > 0 && !prefix?.trim())) {
|
|
25
|
+
throw new Error("Compaction model returned an empty summary");
|
|
26
|
+
}
|
|
27
|
+
return { compaction: result };
|
|
28
|
+
}
|
|
29
|
+
catch (error) {
|
|
30
|
+
if (!event.signal.aborted)
|
|
31
|
+
notice(`Compaction with ${modelId} failed: ${error instanceof Error ? error.message : String(error)}. No other model was used.`);
|
|
32
|
+
// Errors in extension handlers are swallowed by Pi and fall back to its current model.
|
|
33
|
+
// Explicit cancellation instead protects the requested model choice.
|
|
34
|
+
return { cancel: true };
|
|
35
|
+
}
|
|
36
|
+
});
|
|
37
|
+
} };
|
|
38
|
+
}
|