@nathanstephenson/flow 0.1.0
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 +641 -0
- package/build/workflow-runtime.cjs +213964 -0
- package/dist/backend/claude/async-queue.js +44 -0
- package/dist/backend/claude/auto-compaction.js +10 -0
- package/dist/backend/claude/background-calls.js +116 -0
- package/dist/backend/claude/enquiries.js +162 -0
- package/dist/backend/claude/index.js +1138 -0
- package/dist/backend/claude/mcp.js +55 -0
- package/dist/backend/claude/permissions.js +106 -0
- package/dist/backend/claude/streamed-message.js +120 -0
- package/dist/backend/claude/subagents.js +128 -0
- package/dist/backend/claude/workflow-parent.js +12 -0
- package/dist/backend/claude/workflow-processes.js +95 -0
- package/dist/backend/claude/workflow-subagent.js +234 -0
- package/dist/backend/effort.js +30 -0
- package/dist/backend/fake/index.js +570 -0
- package/dist/backend/mcp.js +190 -0
- package/dist/backend/pi/auto-compaction.js +16 -0
- package/dist/backend/pi/background-calls.js +56 -0
- package/dist/backend/pi/enquiries.js +63 -0
- package/dist/backend/pi/index.js +597 -0
- package/dist/backend/pi/mcp.js +35 -0
- package/dist/backend/pi/subagents.js +23 -0
- package/dist/backend/pi/work.js +104 -0
- package/dist/backend/pi/workflow-parent.js +21 -0
- package/dist/backend/pi/workflow-subagent.js +199 -0
- package/dist/backend/registry.js +34 -0
- package/dist/backend/types.js +1 -0
- package/dist/backend/workflow-tools.js +25 -0
- package/dist/build-id +1 -0
- package/dist/cli/application.js +397 -0
- package/dist/cli/bootstrap.js +535 -0
- package/dist/cli/host-control.js +100 -0
- package/dist/cli/install-guard.js +270 -0
- package/dist/cli/install-process.js +52 -0
- package/dist/cli/main.js +12 -0
- package/dist/cli/update.js +128 -0
- package/dist/client/connection.js +183 -0
- package/dist/client/context-usage.js +66 -0
- package/dist/client/diff.js +36 -0
- package/dist/client/enquiry.js +105 -0
- package/dist/client/markdown.js +192 -0
- package/dist/client/model-choices.js +32 -0
- package/dist/client/permission.js +60 -0
- package/dist/client/project-name.js +19 -0
- package/dist/client/reduce.js +463 -0
- package/dist/client/relative-time.js +30 -0
- package/dist/client/scope-kind.js +28 -0
- package/dist/client/search.js +136 -0
- package/dist/client/session-label.js +9 -0
- package/dist/client/status.js +84 -0
- package/dist/client/tool-chains.js +52 -0
- package/dist/client/tool-summary.js +98 -0
- package/dist/daemon/auth.js +590 -0
- package/dist/daemon/config-store.js +183 -0
- package/dist/daemon/config.js +687 -0
- package/dist/daemon/credential-redaction.js +9 -0
- package/dist/daemon/git.js +312 -0
- package/dist/daemon/host-control-routes.js +29 -0
- package/dist/daemon/host.js +2343 -0
- package/dist/daemon/http.js +19 -0
- package/dist/daemon/log.js +44 -0
- package/dist/daemon/mcp-auth.js +164 -0
- package/dist/daemon/models.js +85 -0
- package/dist/daemon/ownership.js +104 -0
- package/dist/daemon/projects.js +317 -0
- package/dist/daemon/publish.js +289 -0
- package/dist/daemon/pull-request.js +198 -0
- package/dist/daemon/runtime.js +100 -0
- package/dist/daemon/secret-store.js +65 -0
- package/dist/daemon/server.js +827 -0
- package/dist/daemon/shell.js +220 -0
- package/dist/daemon/skills.js +104 -0
- package/dist/daemon/stack-metadata.js +24 -0
- package/dist/daemon/stack.js +743 -0
- package/dist/daemon/store.js +130 -0
- package/dist/daemon/summariser.js +476 -0
- package/dist/daemon/workflow-execution-routes.js +105 -0
- package/dist/daemon/workflow-executions.js +1018 -0
- package/dist/daemon/workflow-mcp.js +20 -0
- package/dist/daemon/workflow-routes.js +102 -0
- package/dist/protocol/attachments.js +59 -0
- package/dist/protocol/commands.js +1 -0
- package/dist/protocol/events.js +20 -0
- package/dist/protocol/fonts.js +26 -0
- package/dist/protocol/git.js +12 -0
- package/dist/protocol/mcp.js +51 -0
- package/dist/protocol/projects.js +21 -0
- package/dist/protocol/publish.js +1 -0
- package/dist/protocol/pull-request.js +1 -0
- package/dist/protocol/secrets.js +4 -0
- package/dist/protocol/settings.js +63 -0
- package/dist/protocol/shells.js +8 -0
- package/dist/protocol/skills.js +16 -0
- package/dist/protocol/stack.js +41 -0
- package/dist/protocol/workflow-executions.js +1 -0
- package/dist/protocol/workflows.js +1 -0
- package/dist/tui/app.js +518 -0
- package/dist/tui/keys.js +54 -0
- package/dist/tui/render.js +366 -0
- package/dist/web/assets.js +10 -0
- package/dist/web/embedded.js +12 -0
- package/dist/web/manifest.js +70 -0
- package/dist/workflows/decisions.js +65 -0
- package/dist/workflows/executors.js +132 -0
- package/dist/workflows/graph.js +276 -0
- package/dist/workflows/json-schema.js +49 -0
- package/dist/workflows/loops.js +102 -0
- package/dist/workflows/mcp.js +18 -0
- package/dist/workflows/records.js +111 -0
- package/dist/workflows/recovery.js +25 -0
- package/dist/workflows/runtime-asset.js +17 -0
- package/dist/workflows/runtime-libs.js +1 -0
- package/dist/workflows/runtime-settings.js +23 -0
- package/dist/workflows/runtime.js +343 -0
- package/dist/workflows/scheduler.js +573 -0
- package/dist/workflows/schema.js +161 -0
- package/dist/workflows/store.js +93 -0
- package/package.json +87 -0
- package/web/dist/assets/__vite-browser-external-2447137e-BvRk9kiK.js +0 -0
- package/web/dist/assets/ghostty-vt-DOMeXDrv.wasm +0 -0
- package/web/dist/assets/index-BC0gLS53.js +106 -0
- package/web/dist/assets/index-CCeZYKES.css +2 -0
- package/web/dist/assets/inter-cyrillic-ext-wght-normal-BOeWTOD4.woff2 +0 -0
- package/web/dist/assets/inter-cyrillic-wght-normal-DqGufNeO.woff2 +0 -0
- package/web/dist/assets/inter-greek-ext-wght-normal-DlzME5K_.woff2 +0 -0
- package/web/dist/assets/inter-greek-wght-normal-CkhJZR-_.woff2 +0 -0
- package/web/dist/assets/inter-latin-ext-wght-normal-DO1Apj_S.woff2 +0 -0
- package/web/dist/assets/inter-latin-wght-normal-Dx4kXJAl.woff2 +0 -0
- package/web/dist/assets/inter-vietnamese-wght-normal-CBcvBZtf.woff2 +0 -0
- package/web/dist/assets/rolldown-runtime-B0Z9INg1.js +1 -0
- package/web/dist/assets/select-6i3wxovH.js +1 -0
- package/web/dist/assets/settings-mcp-CcT0ADJR.js +1 -0
- package/web/dist/assets/settings-secrets-CK4uF7fd.js +1 -0
- package/web/dist/assets/settings-workflows-CrbZF-nM.js +23 -0
- package/web/dist/assets/switch-ftZleVB8.js +6 -0
- package/web/dist/assets/workflow-editors-naPqAmYO.js +65 -0
- package/web/dist/assets/workflows-D4T4Gy_7.css +1 -0
- package/web/dist/assets/workflows-hh6ioeEA.js +7 -0
- package/web/dist/assets/workflows-pane-Db-MHf7Z.js +1 -0
- package/web/dist/index.html +31 -0
|
@@ -0,0 +1,535 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
|
|
3
|
+
// src/cli/bootstrap.ts
|
|
4
|
+
import { homedir } from "node:os";
|
|
5
|
+
import { resolve as resolve3, join as join5 } from "node:path";
|
|
6
|
+
import { fileURLToPath } from "node:url";
|
|
7
|
+
|
|
8
|
+
// src/cli/install-guard.ts
|
|
9
|
+
import { mkdirSync as mkdirSync3, realpathSync as realpathSync3, lstatSync, readFileSync as readFileSync2, writeFileSync as writeFileSync2, readdirSync as readdirSync2, renameSync as renameSync2, unlinkSync as unlinkSync2, rmdirSync as rmdirSync2 } from "node:fs";
|
|
10
|
+
import { basename, dirname, isAbsolute, join as join3, resolve } from "node:path";
|
|
11
|
+
import { createHash as createHash2, randomUUID as randomUUID2 } from "node:crypto";
|
|
12
|
+
import { setTimeout as delay2 } from "node:timers/promises";
|
|
13
|
+
|
|
14
|
+
// src/cli/host-control.ts
|
|
15
|
+
import { spawn } from "node:child_process";
|
|
16
|
+
import { closeSync, constants, fchmodSync, mkdirSync as mkdirSync2, openSync, realpathSync as realpathSync2, statSync } from "node:fs";
|
|
17
|
+
import { join as join2 } from "node:path";
|
|
18
|
+
import { setTimeout as delay } from "node:timers/promises";
|
|
19
|
+
|
|
20
|
+
// src/daemon/ownership.ts
|
|
21
|
+
import { mkdirSync, realpathSync, readdirSync, readFileSync, writeFileSync, renameSync, unlinkSync, rmdirSync } from "node:fs";
|
|
22
|
+
import { join } from "node:path";
|
|
23
|
+
import { randomUUID, createHash } from "node:crypto";
|
|
24
|
+
function oidcFingerprint(env = process.env) {
|
|
25
|
+
return createHash("sha256").update(JSON.stringify(["ISSUER", "CLIENT_ID", "CLIENT_SECRET", "PUBLIC_APP_URL"].map((key) => env[`FLOW_OIDC_${key}`]?.trim() ?? ""))).digest("hex");
|
|
26
|
+
}
|
|
27
|
+
function readHost(root) {
|
|
28
|
+
try {
|
|
29
|
+
return JSON.parse(readFileSync(join(root, "daemon.json"), "utf8"));
|
|
30
|
+
} catch {
|
|
31
|
+
return void 0;
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
// src/cli/host-control.ts
|
|
36
|
+
var HostRefusal = class extends Error {
|
|
37
|
+
};
|
|
38
|
+
function processAlive(pid) {
|
|
39
|
+
if (!Number.isInteger(pid) || pid <= 0) throw new Error("Invalid process owner");
|
|
40
|
+
try {
|
|
41
|
+
process.kill(pid, 0);
|
|
42
|
+
return true;
|
|
43
|
+
} catch (error) {
|
|
44
|
+
if (error.code === "ESRCH") return false;
|
|
45
|
+
throw error;
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
async function getHostStatus(host) {
|
|
49
|
+
const response = await fetch(`${host.url}/api/host`, {
|
|
50
|
+
headers: { authorization: `Bearer ${host.token}` },
|
|
51
|
+
signal: AbortSignal.timeout(5e3)
|
|
52
|
+
});
|
|
53
|
+
if (!response.ok) throw new HostRefusal(`Session Host refused: ${await response.text()}`);
|
|
54
|
+
const status = await response.json();
|
|
55
|
+
if (status.instanceId !== host.instanceId || status.pid !== host.pid) throw new Error("Session Host identity changed");
|
|
56
|
+
return status;
|
|
57
|
+
}
|
|
58
|
+
async function requestHostStop(host, force) {
|
|
59
|
+
const response = await fetch(`${host.url}/api/host/stop`, {
|
|
60
|
+
method: "POST",
|
|
61
|
+
headers: { authorization: `Bearer ${host.token}`, "content-type": "application/json" },
|
|
62
|
+
body: JSON.stringify({ instanceId: host.instanceId, force }),
|
|
63
|
+
signal: AbortSignal.timeout(5e3)
|
|
64
|
+
});
|
|
65
|
+
if (!response.ok) throw new HostRefusal(`Session Host refused: ${await response.text()}`);
|
|
66
|
+
}
|
|
67
|
+
function requireRestartable(host) {
|
|
68
|
+
if (host.mode !== "background") throw new Error("Only a background-owned Session Host can restart");
|
|
69
|
+
if (host.settings.oidc !== oidcFingerprint()) throw new Error("Restart requires matching OIDC configuration");
|
|
70
|
+
if (!statSync(host.settings.cwd).isDirectory()) throw new Error("Saved working directory is unavailable");
|
|
71
|
+
}
|
|
72
|
+
async function waitUntil(check, message) {
|
|
73
|
+
const deadline = Date.now() + 15e3;
|
|
74
|
+
while (Date.now() < deadline) {
|
|
75
|
+
if (await check()) return;
|
|
76
|
+
await delay(100);
|
|
77
|
+
}
|
|
78
|
+
throw new Error(message);
|
|
79
|
+
}
|
|
80
|
+
function backgroundHostArgs(settings) {
|
|
81
|
+
return ["serve", "--background-host", "--port", String(settings.port), "--address", settings.address];
|
|
82
|
+
}
|
|
83
|
+
async function launchBackground(options) {
|
|
84
|
+
mkdirSync2(options.root, { recursive: true, mode: 448 });
|
|
85
|
+
const root = realpathSync2(options.root);
|
|
86
|
+
const logPath = join2(root, "host.log");
|
|
87
|
+
const log = openSync(logPath, constants.O_WRONLY | constants.O_CREAT | constants.O_APPEND | constants.O_NOFOLLOW, 384);
|
|
88
|
+
let child;
|
|
89
|
+
try {
|
|
90
|
+
fchmodSync(log, 384);
|
|
91
|
+
child = spawn(process.execPath, [...options.entry, ...backgroundHostArgs(options.settings)], {
|
|
92
|
+
cwd: options.settings.cwd,
|
|
93
|
+
detached: true,
|
|
94
|
+
stdio: ["ignore", log, log],
|
|
95
|
+
env: { ...options.env, FLOW_STATE_DIR: root }
|
|
96
|
+
});
|
|
97
|
+
} finally {
|
|
98
|
+
closeSync(log);
|
|
99
|
+
}
|
|
100
|
+
let failure;
|
|
101
|
+
child.on("error", (error) => {
|
|
102
|
+
failure = error;
|
|
103
|
+
});
|
|
104
|
+
child.on("exit", (code) => {
|
|
105
|
+
failure = new Error(`Session Host startup failed (${code})`);
|
|
106
|
+
});
|
|
107
|
+
child.unref();
|
|
108
|
+
let started;
|
|
109
|
+
try {
|
|
110
|
+
await waitUntil(async () => {
|
|
111
|
+
if (failure) throw failure;
|
|
112
|
+
const identity = readHost(root);
|
|
113
|
+
if (!identity || identity.pid !== child.pid) return false;
|
|
114
|
+
const status = await getHostStatus(identity);
|
|
115
|
+
options.validate?.(status);
|
|
116
|
+
started = { ...identity, ...status };
|
|
117
|
+
return true;
|
|
118
|
+
}, "Session Host startup timed out");
|
|
119
|
+
} catch (error) {
|
|
120
|
+
child.kill("SIGTERM");
|
|
121
|
+
if (child.pid) await waitUntil(async () => !processAlive(child.pid), `Session Host did not exit; see ${logPath}`);
|
|
122
|
+
throw new Error(`${String(error)}; see ${logPath}`);
|
|
123
|
+
}
|
|
124
|
+
return started;
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
// src/cli/install-guard.ts
|
|
128
|
+
var packageName = "@nathanstephenson/flow";
|
|
129
|
+
function record(path) {
|
|
130
|
+
try {
|
|
131
|
+
const value = JSON.parse(readFileSync2(path, "utf8"));
|
|
132
|
+
if (!value || typeof value !== "object" || Array.isArray(value)) throw new Error(`Invalid registry record: ${path}`);
|
|
133
|
+
return value;
|
|
134
|
+
} catch (error) {
|
|
135
|
+
if (error.code === "ENOENT") return void 0;
|
|
136
|
+
throw error;
|
|
137
|
+
}
|
|
138
|
+
}
|
|
139
|
+
function owner(value) {
|
|
140
|
+
if (typeof value.pid !== "number" || !Number.isInteger(value.pid) || value.pid <= 0 || typeof value.id !== "string" || !/^[a-zA-Z0-9-]+$/.test(value.id)) throw new Error("Invalid installation owner");
|
|
141
|
+
return { pid: value.pid, id: value.id };
|
|
142
|
+
}
|
|
143
|
+
function argumentsOf(value) {
|
|
144
|
+
if (!Array.isArray(value) || !value.every((arg) => typeof arg === "string")) throw new Error("Invalid installation arguments");
|
|
145
|
+
return value;
|
|
146
|
+
}
|
|
147
|
+
function readBarrier(path) {
|
|
148
|
+
const value = record(path);
|
|
149
|
+
if (!value) return void 0;
|
|
150
|
+
if (!["preparing", "replacing", "restoring"].includes(String(value.phase)) || typeof value.previous !== "string") throw new Error("Invalid update barrier");
|
|
151
|
+
const result = { ...owner(value), phase: value.phase, previous: value.previous };
|
|
152
|
+
if (value.capability !== void 0) {
|
|
153
|
+
const capability = value.capability;
|
|
154
|
+
if (!capability || typeof capability.token !== "string" || typeof capability.root !== "string" || !isAbsolute(capability.root)) throw new Error("Invalid update authorization");
|
|
155
|
+
result.capability = { token: capability.token, root: capability.root, args: argumentsOf(capability.args) };
|
|
156
|
+
}
|
|
157
|
+
return result;
|
|
158
|
+
}
|
|
159
|
+
function canonicalRoot(path) {
|
|
160
|
+
const missing = [];
|
|
161
|
+
let current = resolve(path);
|
|
162
|
+
for (; ; ) {
|
|
163
|
+
try {
|
|
164
|
+
return join3(realpathSync3(current), ...missing.reverse());
|
|
165
|
+
} catch (error) {
|
|
166
|
+
if (error.code !== "ENOENT" || dirname(current) === current) throw error;
|
|
167
|
+
missing.push(basename(current));
|
|
168
|
+
current = dirname(current);
|
|
169
|
+
}
|
|
170
|
+
}
|
|
171
|
+
}
|
|
172
|
+
function privatePath(path) {
|
|
173
|
+
const stat = lstatSync(path);
|
|
174
|
+
if (stat.isSymbolicLink() || stat.uid !== process.getuid?.() || (stat.mode & 18) !== 0) throw new Error(`Not a user-owned, private installation path: ${path}`);
|
|
175
|
+
}
|
|
176
|
+
function registryPath(slot) {
|
|
177
|
+
return join3(resolve(slot, "../../../.."), ".flow-installations", createHash2("sha256").update(resolve(slot)).digest("hex").slice(0, 24));
|
|
178
|
+
}
|
|
179
|
+
function registryExists(slot) {
|
|
180
|
+
try {
|
|
181
|
+
lstatSync(registryPath(slot));
|
|
182
|
+
return true;
|
|
183
|
+
} catch (error) {
|
|
184
|
+
if (error.code === "ENOENT") return false;
|
|
185
|
+
throw error;
|
|
186
|
+
}
|
|
187
|
+
}
|
|
188
|
+
function updateEligible(slot) {
|
|
189
|
+
slot = resolve(slot);
|
|
190
|
+
const prefix = resolve(slot, "../../../..");
|
|
191
|
+
const uid = process.getuid?.();
|
|
192
|
+
if (slot !== join3(prefix, "lib/node_modules", packageName) || uid === 0) return false;
|
|
193
|
+
for (const path of [prefix, join3(prefix, "lib"), join3(prefix, "lib/node_modules"), join3(prefix, "lib/node_modules/@nathanstephenson"), slot]) {
|
|
194
|
+
const stat = lstatSync(path);
|
|
195
|
+
if (stat.isSymbolicLink() || stat.uid !== uid || (stat.mode & 18) !== 0) return false;
|
|
196
|
+
}
|
|
197
|
+
for (let path = dirname(prefix); ; path = dirname(path)) {
|
|
198
|
+
const stat = lstatSync(path);
|
|
199
|
+
if (stat.isSymbolicLink() || stat.uid !== 0 && stat.uid !== uid || (stat.mode & 18) !== 0 && (stat.mode & 512) === 0) return false;
|
|
200
|
+
if (dirname(path) === path) break;
|
|
201
|
+
}
|
|
202
|
+
return realpathSync3(prefix) === prefix;
|
|
203
|
+
}
|
|
204
|
+
function installation(slot) {
|
|
205
|
+
slot = resolve(slot);
|
|
206
|
+
const prefix = resolve(slot, "../../../..");
|
|
207
|
+
if (!updateEligible(slot)) throw new Error("Self-update requires a user-owned, non-root private installation in a canonical global npm prefix. Guarded startup cannot continue after permissions change; repair the installation or update it manually with npm.");
|
|
208
|
+
const directory = registryPath(slot), base = dirname(directory);
|
|
209
|
+
mkdirSync3(base, { recursive: true, mode: 448 });
|
|
210
|
+
privatePath(base);
|
|
211
|
+
mkdirSync3(directory, { recursive: true, mode: 448 });
|
|
212
|
+
privatePath(directory);
|
|
213
|
+
if (lstatSync(base).mode & 63 || lstatSync(directory).mode & 63) throw new Error("Installation registry must have mode 0700");
|
|
214
|
+
const removeOwner = (path, filename) => {
|
|
215
|
+
try {
|
|
216
|
+
unlinkSync2(join3(path, filename));
|
|
217
|
+
} catch (error) {
|
|
218
|
+
if (error.code !== "ENOENT") throw error;
|
|
219
|
+
}
|
|
220
|
+
try {
|
|
221
|
+
rmdirSync2(path);
|
|
222
|
+
} catch (error) {
|
|
223
|
+
if (!["ENOENT", "ENOTEMPTY", "EEXIST"].includes(error.code ?? "")) throw error;
|
|
224
|
+
}
|
|
225
|
+
};
|
|
226
|
+
async function locked(action) {
|
|
227
|
+
const ownerId = randomUUID2(), filename = `${ownerId}.json`;
|
|
228
|
+
const candidate = join3(directory, `mutex-${ownerId}`), lock = join3(directory, "mutex");
|
|
229
|
+
mkdirSync3(candidate, { mode: 448 });
|
|
230
|
+
writeFileSync2(join3(candidate, filename), JSON.stringify({ pid: process.pid, id: ownerId }), { mode: 384 });
|
|
231
|
+
let acquired = false;
|
|
232
|
+
try {
|
|
233
|
+
for (let attempt = 0; !acquired; attempt++) {
|
|
234
|
+
try {
|
|
235
|
+
renameSync2(candidate, lock);
|
|
236
|
+
acquired = true;
|
|
237
|
+
} catch (error) {
|
|
238
|
+
if (!["ENOTEMPTY", "EEXIST"].includes(error.code ?? "")) throw error;
|
|
239
|
+
if (attempt >= 100) throw new Error("Installation registry is busy");
|
|
240
|
+
let entries;
|
|
241
|
+
try {
|
|
242
|
+
entries = readdirSync2(lock);
|
|
243
|
+
} catch (error2) {
|
|
244
|
+
if (error2.code === "ENOENT") continue;
|
|
245
|
+
throw error2;
|
|
246
|
+
}
|
|
247
|
+
if (entries.length) {
|
|
248
|
+
if (entries.length !== 1 || !/^[a-f0-9-]+\.json$/.test(entries[0])) throw new Error("Invalid installation registry owner");
|
|
249
|
+
const value = record(join3(lock, entries[0]));
|
|
250
|
+
if (value) {
|
|
251
|
+
const held = owner(value);
|
|
252
|
+
if (`${held.id}.json` !== entries[0]) throw new Error("Invalid installation registry owner");
|
|
253
|
+
if (!processAlive(held.pid)) removeOwner(lock, entries[0]);
|
|
254
|
+
}
|
|
255
|
+
}
|
|
256
|
+
await delay2(25);
|
|
257
|
+
}
|
|
258
|
+
}
|
|
259
|
+
return action();
|
|
260
|
+
} finally {
|
|
261
|
+
removeOwner(acquired ? lock : candidate, filename);
|
|
262
|
+
}
|
|
263
|
+
}
|
|
264
|
+
const barrierPath = join3(directory, "update.json");
|
|
265
|
+
function save(barrier) {
|
|
266
|
+
const temporary = join3(directory, `update-${barrier.id}.json`);
|
|
267
|
+
writeFileSync2(temporary, JSON.stringify(barrier), { mode: 384 });
|
|
268
|
+
renameSync2(temporary, barrierPath);
|
|
269
|
+
}
|
|
270
|
+
function leases() {
|
|
271
|
+
return readdirSync2(directory).filter((name) => name.startsWith("lease-")).flatMap((name) => {
|
|
272
|
+
const path = join3(directory, name), value = record(path);
|
|
273
|
+
if (!value) return [];
|
|
274
|
+
const held = owner(value);
|
|
275
|
+
if (name !== `lease-${held.id}.json` || typeof value.root !== "string" || !isAbsolute(value.root)) throw new Error("Invalid installation lease");
|
|
276
|
+
const lease = { ...held, root: canonicalRoot(value.root), args: argumentsOf(value.args) };
|
|
277
|
+
if (processAlive(lease.pid)) return [lease];
|
|
278
|
+
unlinkSync2(path);
|
|
279
|
+
return [];
|
|
280
|
+
});
|
|
281
|
+
}
|
|
282
|
+
async function register(build, root, args, capability) {
|
|
283
|
+
root = canonicalRoot(root);
|
|
284
|
+
return locked(() => {
|
|
285
|
+
const barrier = readBarrier(barrierPath);
|
|
286
|
+
if (barrier) {
|
|
287
|
+
const allowed = barrier.capability;
|
|
288
|
+
if (!processAlive(barrier.pid) || !allowed || !capability || allowed.token !== capability || allowed.root !== root || JSON.stringify(allowed.args) !== JSON.stringify(args)) throw new Error(`Flow startup blocked by ${barrierPath}. An update is active or needs manual repair; see README, Updating Flow.`);
|
|
289
|
+
delete barrier.capability;
|
|
290
|
+
save(barrier);
|
|
291
|
+
}
|
|
292
|
+
if (readFileSync2(join3(slot, "dist/build-id"), "utf8") !== build) throw new Error("Flow was replaced during startup. Run the command again.");
|
|
293
|
+
const lease = { pid: process.pid, id: randomUUID2(), root, args };
|
|
294
|
+
const path = join3(directory, `lease-${lease.id}.json`);
|
|
295
|
+
writeFileSync2(path, JSON.stringify(lease), { mode: 384 });
|
|
296
|
+
return { ...lease, release() {
|
|
297
|
+
try {
|
|
298
|
+
unlinkSync2(path);
|
|
299
|
+
} catch (error) {
|
|
300
|
+
if (error.code !== "ENOENT") throw error;
|
|
301
|
+
}
|
|
302
|
+
} };
|
|
303
|
+
});
|
|
304
|
+
}
|
|
305
|
+
async function beginUpdate(lease, previous, host) {
|
|
306
|
+
const barrier = { pid: process.pid, id: randomUUID2(), phase: "preparing", previous };
|
|
307
|
+
await locked(() => {
|
|
308
|
+
if (readBarrier(barrierPath)) throw new Error(`Update already blocked: ${barrierPath}`);
|
|
309
|
+
const active = leases();
|
|
310
|
+
if (!active.some((other) => other.id === lease.id && other.pid === process.pid && other.root === lease.root)) throw new Error("Update process has no installation lease");
|
|
311
|
+
if (active.some((other) => other.id !== lease.id && !(host && other.pid === host.pid && other.root === lease.root && other.args.includes("--background-host")))) throw new Error("Stop all other Flow hosts and CLI/TUI clients using this installation first");
|
|
312
|
+
if (host && !active.some((other) => other.pid === host.pid && other.root === lease.root)) throw new Error("Stop all pre-guard Flow processes before updating");
|
|
313
|
+
save(barrier);
|
|
314
|
+
});
|
|
315
|
+
function assertOwner() {
|
|
316
|
+
const current = readBarrier(barrierPath);
|
|
317
|
+
if (current?.id !== barrier.id || current.pid !== process.pid) throw new Error("Update ownership changed; manual repair is required");
|
|
318
|
+
}
|
|
319
|
+
async function authorize(args, phase) {
|
|
320
|
+
const token = randomUUID2();
|
|
321
|
+
await locked(() => {
|
|
322
|
+
assertOwner();
|
|
323
|
+
barrier.phase = phase;
|
|
324
|
+
barrier.capability = { token, root: lease.root, args };
|
|
325
|
+
save(barrier);
|
|
326
|
+
});
|
|
327
|
+
return { ...process.env, FLOW_STATE_DIR: lease.root, FLOW_UPDATE_CAPABILITY: token };
|
|
328
|
+
}
|
|
329
|
+
return {
|
|
330
|
+
authorizeVerification: () => authorize(["--version"], "replacing"),
|
|
331
|
+
authorizeRestoration: (args) => authorize(args, "restoring"),
|
|
332
|
+
async assertAuthorizationConsumed() {
|
|
333
|
+
await locked(() => {
|
|
334
|
+
assertOwner();
|
|
335
|
+
if (readBarrier(barrierPath)?.capability) throw new Error("Fresh Flow did not use the installation guard");
|
|
336
|
+
});
|
|
337
|
+
},
|
|
338
|
+
async beginReplacement() {
|
|
339
|
+
await locked(() => {
|
|
340
|
+
assertOwner();
|
|
341
|
+
if (leases().some((other) => other.id !== lease.id)) throw new Error("A Flow process remains; replacement cannot run safely");
|
|
342
|
+
barrier.phase = "replacing";
|
|
343
|
+
delete barrier.capability;
|
|
344
|
+
save(barrier);
|
|
345
|
+
});
|
|
346
|
+
},
|
|
347
|
+
async complete() {
|
|
348
|
+
await locked(() => {
|
|
349
|
+
assertOwner();
|
|
350
|
+
unlinkSync2(barrierPath);
|
|
351
|
+
});
|
|
352
|
+
}
|
|
353
|
+
};
|
|
354
|
+
}
|
|
355
|
+
return { slot, prefix, directory, barrierPath, register, beginUpdate };
|
|
356
|
+
}
|
|
357
|
+
|
|
358
|
+
// src/cli/update.ts
|
|
359
|
+
import { execFileSync } from "node:child_process";
|
|
360
|
+
import { accessSync, constants as constants2, readFileSync as readFileSync3, realpathSync as realpathSync4 } from "node:fs";
|
|
361
|
+
import { delimiter, join as join4, resolve as resolve2 } from "node:path";
|
|
362
|
+
|
|
363
|
+
// src/cli/install-process.ts
|
|
364
|
+
import { spawn as spawn2 } from "node:child_process";
|
|
365
|
+
import { setTimeout as delay3 } from "node:timers/promises";
|
|
366
|
+
var InstallationProcessUncertain = class extends Error {
|
|
367
|
+
};
|
|
368
|
+
function groupAlive(pid) {
|
|
369
|
+
try {
|
|
370
|
+
process.kill(-pid, 0);
|
|
371
|
+
return true;
|
|
372
|
+
} catch (error) {
|
|
373
|
+
if (error.code === "ESRCH") return false;
|
|
374
|
+
if (error.code === "EPERM") return true;
|
|
375
|
+
throw error;
|
|
376
|
+
}
|
|
377
|
+
}
|
|
378
|
+
async function stopGroup(pid) {
|
|
379
|
+
for (const [signal, timeout] of [["SIGTERM", 1e3], ["SIGKILL", 5e3]]) {
|
|
380
|
+
try {
|
|
381
|
+
process.kill(-pid, signal);
|
|
382
|
+
} catch (error) {
|
|
383
|
+
if (error.code === "ESRCH") return;
|
|
384
|
+
if (error.code !== "EPERM") throw error;
|
|
385
|
+
}
|
|
386
|
+
const deadline = Date.now() + timeout;
|
|
387
|
+
while (groupAlive(pid) && Date.now() < deadline) await delay3(25);
|
|
388
|
+
if (!groupAlive(pid)) return;
|
|
389
|
+
}
|
|
390
|
+
throw new Error("npm process group did not exit");
|
|
391
|
+
}
|
|
392
|
+
async function replacePackage(npm, prefix, packageSpec) {
|
|
393
|
+
const child = spawn2(npm, ["install", "--global", "--prefix", prefix, packageSpec], { detached: true, stdio: "inherit" });
|
|
394
|
+
const result = await new Promise((resolve4, reject) => {
|
|
395
|
+
child.once("error", reject);
|
|
396
|
+
child.once("exit", (code, signal) => resolve4({ code, signal }));
|
|
397
|
+
});
|
|
398
|
+
try {
|
|
399
|
+
if (child.pid) await stopGroup(child.pid);
|
|
400
|
+
} catch (error) {
|
|
401
|
+
throw new InstallationProcessUncertain(`Cannot confirm npm descendants stopped: ${String(error)}`);
|
|
402
|
+
}
|
|
403
|
+
if (result.code !== 0) throw new Error(`npm installation failed (${result.signal ?? result.code})`);
|
|
404
|
+
}
|
|
405
|
+
|
|
406
|
+
// src/cli/update.ts
|
|
407
|
+
function npmExecutable() {
|
|
408
|
+
for (const directory of (process.env.PATH ?? "").split(delimiter)) {
|
|
409
|
+
const path = resolve2(directory, "npm");
|
|
410
|
+
try {
|
|
411
|
+
accessSync(path, constants2.X_OK);
|
|
412
|
+
return realpathSync4(path);
|
|
413
|
+
} catch {
|
|
414
|
+
}
|
|
415
|
+
}
|
|
416
|
+
throw new Error("npm was not found in PATH");
|
|
417
|
+
}
|
|
418
|
+
function npmPath(npm, command) {
|
|
419
|
+
return realpathSync4(execFileSync(npm, [command, "--global"], { encoding: "utf8", stdio: ["ignore", "pipe", "pipe"], timeout: 15e3 }).trim());
|
|
420
|
+
}
|
|
421
|
+
function packageVersion(slot) {
|
|
422
|
+
privatePath(slot);
|
|
423
|
+
const metadata = JSON.parse(readFileSync3(join4(slot, "package.json"), "utf8"));
|
|
424
|
+
if (metadata?.name !== packageName || typeof metadata.version !== "string" || !/^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?(?:\+[0-9A-Za-z.-]+)?$/.test(metadata.version)) throw new Error("Installed package identity is invalid");
|
|
425
|
+
return metadata.version;
|
|
426
|
+
}
|
|
427
|
+
async function verify(install, transaction, expected) {
|
|
428
|
+
const version = packageVersion(install.slot);
|
|
429
|
+
if (expected && version !== expected) throw new Error("Installed package verification failed");
|
|
430
|
+
if (!readFileSync3(join4(install.slot, "dist/build-id"), "utf8").trim()) throw new Error("Installed build identity is missing");
|
|
431
|
+
const env = await transaction.authorizeVerification();
|
|
432
|
+
const reported = execFileSync(process.execPath, [join4(install.slot, "dist/cli/bootstrap.js"), "--version"], { env, encoding: "utf8", timeout: 15e3 }).trim();
|
|
433
|
+
if (reported !== version) throw new Error("Fresh Flow process reports the wrong version");
|
|
434
|
+
await transaction.assertAuthorizationConsumed();
|
|
435
|
+
return version;
|
|
436
|
+
}
|
|
437
|
+
async function restore(install, transaction, root, host, version) {
|
|
438
|
+
const env = await transaction.authorizeRestoration(backgroundHostArgs(host.settings));
|
|
439
|
+
await launchBackground({
|
|
440
|
+
root,
|
|
441
|
+
settings: host.settings,
|
|
442
|
+
entry: [join4(install.slot, "dist/cli/bootstrap.js")],
|
|
443
|
+
env,
|
|
444
|
+
validate(status) {
|
|
445
|
+
if (status.instanceId === host.instanceId || status.version !== version || status.mode !== "background" || ["port", "address", "cwd", "oidc"].some((key) => status.settings[key] !== host.settings[key])) {
|
|
446
|
+
throw new Error("Restored Session Host settings or version differ");
|
|
447
|
+
}
|
|
448
|
+
}
|
|
449
|
+
});
|
|
450
|
+
await transaction.assertAuthorizationConsumed();
|
|
451
|
+
}
|
|
452
|
+
async function update(install, lease, args) {
|
|
453
|
+
if (args.length > 2 || args[0] !== "update" || args.length === 2 && args[1] !== "--force") throw new Error("usage: flow update [--force]");
|
|
454
|
+
const npm = npmExecutable();
|
|
455
|
+
const prefix = npmPath(npm, "prefix"), root = npmPath(npm, "root");
|
|
456
|
+
if (prefix !== install.prefix || root !== join4(prefix, "lib/node_modules") || realpathSync4(join4(root, packageName)) !== install.slot) throw new Error("npm selects a different installation. Put the matching npm in PATH and select its prefix.");
|
|
457
|
+
const previous = packageVersion(install.slot);
|
|
458
|
+
let host = readHost(lease.root);
|
|
459
|
+
if (host && processAlive(host.pid)) {
|
|
460
|
+
const status = await getHostStatus(host);
|
|
461
|
+
requireRestartable(status);
|
|
462
|
+
host = { ...host, ...status };
|
|
463
|
+
} else host = void 0;
|
|
464
|
+
const transaction = await install.beginUpdate(lease, previous, host);
|
|
465
|
+
let needsRestoration = false, replacing = false;
|
|
466
|
+
const repair = () => `Flow startup remains blocked by ${install.barrierPath}. Stop all Flow and npm processes for this prefix. Reinstall ${packageName}@${previous} with the matching npm and prefix ${JSON.stringify(prefix)}. Verify the package files manually, then remove ${install.barrierPath} and start the Session Host again.`;
|
|
467
|
+
async function replace(version, expected) {
|
|
468
|
+
await transaction.beginReplacement();
|
|
469
|
+
replacing = true;
|
|
470
|
+
await replacePackage(npm, prefix, `${packageName}@${version}`);
|
|
471
|
+
const installed = await verify(install, transaction, expected);
|
|
472
|
+
if (host && needsRestoration) {
|
|
473
|
+
await restore(install, transaction, lease.root, host, installed);
|
|
474
|
+
needsRestoration = false;
|
|
475
|
+
}
|
|
476
|
+
await transaction.complete();
|
|
477
|
+
return installed;
|
|
478
|
+
}
|
|
479
|
+
try {
|
|
480
|
+
if (host) {
|
|
481
|
+
needsRestoration = true;
|
|
482
|
+
try {
|
|
483
|
+
await requestHostStop(host, args.includes("--force"));
|
|
484
|
+
} catch (error) {
|
|
485
|
+
if (error instanceof HostRefusal) needsRestoration = false;
|
|
486
|
+
throw error;
|
|
487
|
+
}
|
|
488
|
+
const pid = host.pid;
|
|
489
|
+
await waitUntil(async () => !processAlive(pid), "Session Host process did not exit; installation was not changed");
|
|
490
|
+
}
|
|
491
|
+
const version = await replace("latest");
|
|
492
|
+
console.log(version === previous ? `Flow is already at ${version}.` : `Flow updated: ${previous} \u2192 ${version}`);
|
|
493
|
+
} catch (error) {
|
|
494
|
+
if (error instanceof InstallationProcessUncertain) throw new Error(`${String(error)}. ${repair()}`);
|
|
495
|
+
if (!replacing) {
|
|
496
|
+
if (needsRestoration && host && processAlive(host.pid)) throw new Error(`${String(error)}. No package files were changed; wait for the stopping host to exit. ${repair()}`);
|
|
497
|
+
if (needsRestoration && host) {
|
|
498
|
+
try {
|
|
499
|
+
await restore(install, transaction, lease.root, host, previous);
|
|
500
|
+
} catch (failure) {
|
|
501
|
+
throw new Error(`${String(error)}; restoration failed: ${String(failure)}. ${repair()}`);
|
|
502
|
+
}
|
|
503
|
+
}
|
|
504
|
+
await transaction.complete();
|
|
505
|
+
throw error;
|
|
506
|
+
}
|
|
507
|
+
try {
|
|
508
|
+
await replace(previous, previous);
|
|
509
|
+
} catch (failure) {
|
|
510
|
+
throw new Error(`Update failed: ${String(error)}; recovery failed: ${String(failure)}. ${repair()}`);
|
|
511
|
+
}
|
|
512
|
+
throw new Error(`Update failed: ${String(error)}. Reinstalled and verified ${previous}; the previous files were not preserved.`);
|
|
513
|
+
}
|
|
514
|
+
}
|
|
515
|
+
|
|
516
|
+
// src/cli/bootstrap.ts
|
|
517
|
+
async function bootstrap() {
|
|
518
|
+
const slot = resolve3(fileURLToPath(new URL("../..", import.meta.url)));
|
|
519
|
+
const args = process.argv.slice(2);
|
|
520
|
+
const root = canonicalRoot(process.env.FLOW_STATE_DIR ?? join5(homedir(), ".flow"));
|
|
521
|
+
const globalSlot = slot.endsWith("/lib/node_modules/@nathanstephenson/flow");
|
|
522
|
+
if (globalSlot && (args[0] === "update" || updateEligible(slot) || registryExists(slot))) {
|
|
523
|
+
const install = installation(slot);
|
|
524
|
+
const lease = await install.register("5c6019d6-3a5b-4de8-b299-042673073db0", root, args, process.env.FLOW_UPDATE_CAPABILITY);
|
|
525
|
+
delete process.env.FLOW_UPDATE_CAPABILITY;
|
|
526
|
+
process.on("exit", lease.release);
|
|
527
|
+
if (args[0] === "update") return update(install, lease, args);
|
|
528
|
+
} else if (args[0] === "update") throw new Error("Self-update requires a private global npm installation; source and npm link are unsupported");
|
|
529
|
+
const { runCli } = await import(new URL("./application.js", import.meta.url).href);
|
|
530
|
+
await runCli();
|
|
531
|
+
}
|
|
532
|
+
bootstrap().catch((error) => {
|
|
533
|
+
console.error(error instanceof Error ? error.message : error);
|
|
534
|
+
process.exitCode = 1;
|
|
535
|
+
});
|
|
@@ -0,0 +1,100 @@
|
|
|
1
|
+
import { spawn } from 'node:child_process';
|
|
2
|
+
import { closeSync, constants, fchmodSync, mkdirSync, openSync, realpathSync, statSync } from 'node:fs';
|
|
3
|
+
import { join } from 'node:path';
|
|
4
|
+
import { setTimeout as delay } from 'node:timers/promises';
|
|
5
|
+
import { oidcFingerprint, readHost } from "../daemon/ownership.js";
|
|
6
|
+
export class HostRefusal extends Error {
|
|
7
|
+
}
|
|
8
|
+
export function processAlive(pid) {
|
|
9
|
+
if (!Number.isInteger(pid) || pid <= 0)
|
|
10
|
+
throw new Error('Invalid process owner');
|
|
11
|
+
try {
|
|
12
|
+
process.kill(pid, 0);
|
|
13
|
+
return true;
|
|
14
|
+
}
|
|
15
|
+
catch (error) {
|
|
16
|
+
if (error.code === 'ESRCH')
|
|
17
|
+
return false;
|
|
18
|
+
throw error;
|
|
19
|
+
}
|
|
20
|
+
}
|
|
21
|
+
export async function getHostStatus(host) {
|
|
22
|
+
const response = await fetch(`${host.url}/api/host`, {
|
|
23
|
+
headers: { authorization: `Bearer ${host.token}` }, signal: AbortSignal.timeout(5000),
|
|
24
|
+
});
|
|
25
|
+
if (!response.ok)
|
|
26
|
+
throw new HostRefusal(`Session Host refused: ${await response.text()}`);
|
|
27
|
+
const status = await response.json();
|
|
28
|
+
if (status.instanceId !== host.instanceId || status.pid !== host.pid)
|
|
29
|
+
throw new Error('Session Host identity changed');
|
|
30
|
+
return status;
|
|
31
|
+
}
|
|
32
|
+
export async function requestHostStop(host, force) {
|
|
33
|
+
const response = await fetch(`${host.url}/api/host/stop`, {
|
|
34
|
+
method: 'POST', headers: { authorization: `Bearer ${host.token}`, 'content-type': 'application/json' },
|
|
35
|
+
body: JSON.stringify({ instanceId: host.instanceId, force }), signal: AbortSignal.timeout(5000),
|
|
36
|
+
});
|
|
37
|
+
if (!response.ok)
|
|
38
|
+
throw new HostRefusal(`Session Host refused: ${await response.text()}`);
|
|
39
|
+
}
|
|
40
|
+
export function requireRestartable(host) {
|
|
41
|
+
if (host.mode !== 'background')
|
|
42
|
+
throw new Error('Only a background-owned Session Host can restart');
|
|
43
|
+
if (host.settings.oidc !== oidcFingerprint())
|
|
44
|
+
throw new Error('Restart requires matching OIDC configuration');
|
|
45
|
+
if (!statSync(host.settings.cwd).isDirectory())
|
|
46
|
+
throw new Error('Saved working directory is unavailable');
|
|
47
|
+
}
|
|
48
|
+
export async function waitUntil(check, message) {
|
|
49
|
+
const deadline = Date.now() + 15000;
|
|
50
|
+
while (Date.now() < deadline) {
|
|
51
|
+
if (await check())
|
|
52
|
+
return;
|
|
53
|
+
await delay(100);
|
|
54
|
+
}
|
|
55
|
+
throw new Error(message);
|
|
56
|
+
}
|
|
57
|
+
export function backgroundHostArgs(settings) {
|
|
58
|
+
return ['serve', '--background-host', '--port', String(settings.port), '--address', settings.address];
|
|
59
|
+
}
|
|
60
|
+
export async function launchBackground(options) {
|
|
61
|
+
mkdirSync(options.root, { recursive: true, mode: 0o700 });
|
|
62
|
+
const root = realpathSync(options.root);
|
|
63
|
+
const logPath = join(root, 'host.log');
|
|
64
|
+
const log = openSync(logPath, constants.O_WRONLY | constants.O_CREAT | constants.O_APPEND | constants.O_NOFOLLOW, 0o600);
|
|
65
|
+
let child;
|
|
66
|
+
try {
|
|
67
|
+
fchmodSync(log, 0o600);
|
|
68
|
+
child = spawn(process.execPath, [...options.entry, ...backgroundHostArgs(options.settings)], {
|
|
69
|
+
cwd: options.settings.cwd, detached: true, stdio: ['ignore', log, log], env: { ...options.env, FLOW_STATE_DIR: root },
|
|
70
|
+
});
|
|
71
|
+
}
|
|
72
|
+
finally {
|
|
73
|
+
closeSync(log);
|
|
74
|
+
}
|
|
75
|
+
let failure;
|
|
76
|
+
child.on('error', error => { failure = error; });
|
|
77
|
+
child.on('exit', code => { failure = new Error(`Session Host startup failed (${code})`); });
|
|
78
|
+
child.unref();
|
|
79
|
+
let started;
|
|
80
|
+
try {
|
|
81
|
+
await waitUntil(async () => {
|
|
82
|
+
if (failure)
|
|
83
|
+
throw failure;
|
|
84
|
+
const identity = readHost(root);
|
|
85
|
+
if (!identity || identity.pid !== child.pid)
|
|
86
|
+
return false;
|
|
87
|
+
const status = await getHostStatus(identity);
|
|
88
|
+
options.validate?.(status);
|
|
89
|
+
started = { ...identity, ...status };
|
|
90
|
+
return true;
|
|
91
|
+
}, 'Session Host startup timed out');
|
|
92
|
+
}
|
|
93
|
+
catch (error) {
|
|
94
|
+
child.kill('SIGTERM');
|
|
95
|
+
if (child.pid)
|
|
96
|
+
await waitUntil(async () => !processAlive(child.pid), `Session Host did not exit; see ${logPath}`);
|
|
97
|
+
throw new Error(`${String(error)}; see ${logPath}`);
|
|
98
|
+
}
|
|
99
|
+
return started;
|
|
100
|
+
}
|