@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,270 @@
|
|
|
1
|
+
import { mkdirSync, realpathSync, lstatSync, readFileSync, writeFileSync, readdirSync, renameSync, unlinkSync, rmdirSync } from 'node:fs';
|
|
2
|
+
import { basename, dirname, isAbsolute, join, resolve } from 'node:path';
|
|
3
|
+
import { createHash, randomUUID } from 'node:crypto';
|
|
4
|
+
import { setTimeout as delay } from 'node:timers/promises';
|
|
5
|
+
import { processAlive } from "./host-control.js";
|
|
6
|
+
export const packageName = '@nathanstephenson/flow';
|
|
7
|
+
function record(path) {
|
|
8
|
+
try {
|
|
9
|
+
const value = JSON.parse(readFileSync(path, 'utf8'));
|
|
10
|
+
if (!value || typeof value !== 'object' || Array.isArray(value))
|
|
11
|
+
throw new Error(`Invalid registry record: ${path}`);
|
|
12
|
+
return value;
|
|
13
|
+
}
|
|
14
|
+
catch (error) {
|
|
15
|
+
if (error.code === 'ENOENT')
|
|
16
|
+
return undefined;
|
|
17
|
+
throw error;
|
|
18
|
+
}
|
|
19
|
+
}
|
|
20
|
+
function owner(value) {
|
|
21
|
+
if (typeof value.pid !== 'number' || !Number.isInteger(value.pid) || value.pid <= 0 || typeof value.id !== 'string' || !/^[a-zA-Z0-9-]+$/.test(value.id))
|
|
22
|
+
throw new Error('Invalid installation owner');
|
|
23
|
+
return { pid: value.pid, id: value.id };
|
|
24
|
+
}
|
|
25
|
+
function argumentsOf(value) {
|
|
26
|
+
if (!Array.isArray(value) || !value.every(arg => typeof arg === 'string'))
|
|
27
|
+
throw new Error('Invalid installation arguments');
|
|
28
|
+
return value;
|
|
29
|
+
}
|
|
30
|
+
function readBarrier(path) {
|
|
31
|
+
const value = record(path);
|
|
32
|
+
if (!value)
|
|
33
|
+
return undefined;
|
|
34
|
+
if (!['preparing', 'replacing', 'restoring'].includes(String(value.phase)) || typeof value.previous !== 'string')
|
|
35
|
+
throw new Error('Invalid update barrier');
|
|
36
|
+
const result = { ...owner(value), phase: value.phase, previous: value.previous };
|
|
37
|
+
if (value.capability !== undefined) {
|
|
38
|
+
const capability = value.capability;
|
|
39
|
+
if (!capability || typeof capability.token !== 'string' || typeof capability.root !== 'string' || !isAbsolute(capability.root))
|
|
40
|
+
throw new Error('Invalid update authorization');
|
|
41
|
+
result.capability = { token: capability.token, root: capability.root, args: argumentsOf(capability.args) };
|
|
42
|
+
}
|
|
43
|
+
return result;
|
|
44
|
+
}
|
|
45
|
+
export function canonicalRoot(path) {
|
|
46
|
+
const missing = [];
|
|
47
|
+
let current = resolve(path);
|
|
48
|
+
for (;;) {
|
|
49
|
+
try {
|
|
50
|
+
return join(realpathSync(current), ...missing.reverse());
|
|
51
|
+
}
|
|
52
|
+
catch (error) {
|
|
53
|
+
if (error.code !== 'ENOENT' || dirname(current) === current)
|
|
54
|
+
throw error;
|
|
55
|
+
missing.push(basename(current));
|
|
56
|
+
current = dirname(current);
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
export function privatePath(path) {
|
|
61
|
+
const stat = lstatSync(path);
|
|
62
|
+
if (stat.isSymbolicLink() || stat.uid !== process.getuid?.() || (stat.mode & 0o022) !== 0)
|
|
63
|
+
throw new Error(`Not a user-owned, private installation path: ${path}`);
|
|
64
|
+
}
|
|
65
|
+
function registryPath(slot) {
|
|
66
|
+
return join(resolve(slot, '../../../..'), '.flow-installations', createHash('sha256').update(resolve(slot)).digest('hex').slice(0, 24));
|
|
67
|
+
}
|
|
68
|
+
export function registryExists(slot) {
|
|
69
|
+
try {
|
|
70
|
+
lstatSync(registryPath(slot));
|
|
71
|
+
return true;
|
|
72
|
+
}
|
|
73
|
+
catch (error) {
|
|
74
|
+
if (error.code === 'ENOENT')
|
|
75
|
+
return false;
|
|
76
|
+
throw error;
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
export function updateEligible(slot) {
|
|
80
|
+
slot = resolve(slot);
|
|
81
|
+
const prefix = resolve(slot, '../../../..');
|
|
82
|
+
const uid = process.getuid?.();
|
|
83
|
+
if (slot !== join(prefix, 'lib/node_modules', packageName) || uid === 0)
|
|
84
|
+
return false;
|
|
85
|
+
for (const path of [prefix, join(prefix, 'lib'), join(prefix, 'lib/node_modules'), join(prefix, 'lib/node_modules/@nathanstephenson'), slot]) {
|
|
86
|
+
const stat = lstatSync(path);
|
|
87
|
+
if (stat.isSymbolicLink() || stat.uid !== uid || (stat.mode & 0o022) !== 0)
|
|
88
|
+
return false;
|
|
89
|
+
}
|
|
90
|
+
for (let path = dirname(prefix);; path = dirname(path)) {
|
|
91
|
+
const stat = lstatSync(path);
|
|
92
|
+
if (stat.isSymbolicLink() || (stat.uid !== 0 && stat.uid !== uid) || ((stat.mode & 0o022) !== 0 && (stat.mode & 0o1000) === 0))
|
|
93
|
+
return false;
|
|
94
|
+
if (dirname(path) === path)
|
|
95
|
+
break;
|
|
96
|
+
}
|
|
97
|
+
return realpathSync(prefix) === prefix;
|
|
98
|
+
}
|
|
99
|
+
export function installation(slot) {
|
|
100
|
+
slot = resolve(slot);
|
|
101
|
+
const prefix = resolve(slot, '../../../..');
|
|
102
|
+
if (!updateEligible(slot))
|
|
103
|
+
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.');
|
|
104
|
+
const directory = registryPath(slot), base = dirname(directory);
|
|
105
|
+
mkdirSync(base, { recursive: true, mode: 0o700 });
|
|
106
|
+
privatePath(base);
|
|
107
|
+
mkdirSync(directory, { recursive: true, mode: 0o700 });
|
|
108
|
+
privatePath(directory);
|
|
109
|
+
if ((lstatSync(base).mode & 0o077) || (lstatSync(directory).mode & 0o077))
|
|
110
|
+
throw new Error('Installation registry must have mode 0700');
|
|
111
|
+
const removeOwner = (path, filename) => {
|
|
112
|
+
try {
|
|
113
|
+
unlinkSync(join(path, filename));
|
|
114
|
+
}
|
|
115
|
+
catch (error) {
|
|
116
|
+
if (error.code !== 'ENOENT')
|
|
117
|
+
throw error;
|
|
118
|
+
}
|
|
119
|
+
try {
|
|
120
|
+
rmdirSync(path);
|
|
121
|
+
}
|
|
122
|
+
catch (error) {
|
|
123
|
+
if (!['ENOENT', 'ENOTEMPTY', 'EEXIST'].includes(error.code ?? ''))
|
|
124
|
+
throw error;
|
|
125
|
+
}
|
|
126
|
+
};
|
|
127
|
+
async function locked(action) {
|
|
128
|
+
const ownerId = randomUUID(), filename = `${ownerId}.json`;
|
|
129
|
+
const candidate = join(directory, `mutex-${ownerId}`), lock = join(directory, 'mutex');
|
|
130
|
+
mkdirSync(candidate, { mode: 0o700 });
|
|
131
|
+
writeFileSync(join(candidate, filename), JSON.stringify({ pid: process.pid, id: ownerId }), { mode: 0o600 });
|
|
132
|
+
let acquired = false;
|
|
133
|
+
try {
|
|
134
|
+
for (let attempt = 0; !acquired; attempt++) {
|
|
135
|
+
try {
|
|
136
|
+
renameSync(candidate, lock);
|
|
137
|
+
acquired = true;
|
|
138
|
+
}
|
|
139
|
+
catch (error) {
|
|
140
|
+
if (!['ENOTEMPTY', 'EEXIST'].includes(error.code ?? ''))
|
|
141
|
+
throw error;
|
|
142
|
+
if (attempt >= 100)
|
|
143
|
+
throw new Error('Installation registry is busy');
|
|
144
|
+
let entries;
|
|
145
|
+
try {
|
|
146
|
+
entries = readdirSync(lock);
|
|
147
|
+
}
|
|
148
|
+
catch (error) {
|
|
149
|
+
if (error.code === 'ENOENT')
|
|
150
|
+
continue;
|
|
151
|
+
throw error;
|
|
152
|
+
}
|
|
153
|
+
if (entries.length) {
|
|
154
|
+
if (entries.length !== 1 || !/^[a-f0-9-]+\.json$/.test(entries[0]))
|
|
155
|
+
throw new Error('Invalid installation registry owner');
|
|
156
|
+
const value = record(join(lock, entries[0]));
|
|
157
|
+
if (value) {
|
|
158
|
+
const held = owner(value);
|
|
159
|
+
if (`${held.id}.json` !== entries[0])
|
|
160
|
+
throw new Error('Invalid installation registry owner');
|
|
161
|
+
if (!processAlive(held.pid))
|
|
162
|
+
removeOwner(lock, entries[0]);
|
|
163
|
+
}
|
|
164
|
+
}
|
|
165
|
+
await delay(25);
|
|
166
|
+
}
|
|
167
|
+
}
|
|
168
|
+
return action();
|
|
169
|
+
}
|
|
170
|
+
finally {
|
|
171
|
+
removeOwner(acquired ? lock : candidate, filename);
|
|
172
|
+
}
|
|
173
|
+
}
|
|
174
|
+
const barrierPath = join(directory, 'update.json');
|
|
175
|
+
function save(barrier) {
|
|
176
|
+
const temporary = join(directory, `update-${barrier.id}.json`);
|
|
177
|
+
writeFileSync(temporary, JSON.stringify(barrier), { mode: 0o600 });
|
|
178
|
+
renameSync(temporary, barrierPath);
|
|
179
|
+
}
|
|
180
|
+
function leases() {
|
|
181
|
+
return readdirSync(directory).filter(name => name.startsWith('lease-')).flatMap(name => {
|
|
182
|
+
const path = join(directory, name), value = record(path);
|
|
183
|
+
if (!value)
|
|
184
|
+
return [];
|
|
185
|
+
const held = owner(value);
|
|
186
|
+
if (name !== `lease-${held.id}.json` || typeof value.root !== 'string' || !isAbsolute(value.root))
|
|
187
|
+
throw new Error('Invalid installation lease');
|
|
188
|
+
const lease = { ...held, root: canonicalRoot(value.root), args: argumentsOf(value.args) };
|
|
189
|
+
if (processAlive(lease.pid))
|
|
190
|
+
return [lease];
|
|
191
|
+
unlinkSync(path);
|
|
192
|
+
return [];
|
|
193
|
+
});
|
|
194
|
+
}
|
|
195
|
+
async function register(build, root, args, capability) {
|
|
196
|
+
root = canonicalRoot(root);
|
|
197
|
+
return locked(() => {
|
|
198
|
+
const barrier = readBarrier(barrierPath);
|
|
199
|
+
if (barrier) {
|
|
200
|
+
const allowed = barrier.capability;
|
|
201
|
+
if (!processAlive(barrier.pid) || !allowed || !capability || allowed.token !== capability || allowed.root !== root || JSON.stringify(allowed.args) !== JSON.stringify(args))
|
|
202
|
+
throw new Error(`Flow startup blocked by ${barrierPath}. An update is active or needs manual repair; see README, Updating Flow.`);
|
|
203
|
+
delete barrier.capability;
|
|
204
|
+
save(barrier);
|
|
205
|
+
}
|
|
206
|
+
if (readFileSync(join(slot, 'dist/build-id'), 'utf8') !== build)
|
|
207
|
+
throw new Error('Flow was replaced during startup. Run the command again.');
|
|
208
|
+
const lease = { pid: process.pid, id: randomUUID(), root, args };
|
|
209
|
+
const path = join(directory, `lease-${lease.id}.json`);
|
|
210
|
+
writeFileSync(path, JSON.stringify(lease), { mode: 0o600 });
|
|
211
|
+
return { ...lease, release() { try {
|
|
212
|
+
unlinkSync(path);
|
|
213
|
+
}
|
|
214
|
+
catch (error) {
|
|
215
|
+
if (error.code !== 'ENOENT')
|
|
216
|
+
throw error;
|
|
217
|
+
} } };
|
|
218
|
+
});
|
|
219
|
+
}
|
|
220
|
+
async function beginUpdate(lease, previous, host) {
|
|
221
|
+
const barrier = { pid: process.pid, id: randomUUID(), phase: 'preparing', previous };
|
|
222
|
+
await locked(() => {
|
|
223
|
+
if (readBarrier(barrierPath))
|
|
224
|
+
throw new Error(`Update already blocked: ${barrierPath}`);
|
|
225
|
+
const active = leases();
|
|
226
|
+
if (!active.some(other => other.id === lease.id && other.pid === process.pid && other.root === lease.root))
|
|
227
|
+
throw new Error('Update process has no installation lease');
|
|
228
|
+
if (active.some(other => other.id !== lease.id && !(host && other.pid === host.pid && other.root === lease.root && other.args.includes('--background-host'))))
|
|
229
|
+
throw new Error('Stop all other Flow hosts and CLI/TUI clients using this installation first');
|
|
230
|
+
if (host && !active.some(other => other.pid === host.pid && other.root === lease.root))
|
|
231
|
+
throw new Error('Stop all pre-guard Flow processes before updating');
|
|
232
|
+
save(barrier);
|
|
233
|
+
});
|
|
234
|
+
function assertOwner() {
|
|
235
|
+
const current = readBarrier(barrierPath);
|
|
236
|
+
if (current?.id !== barrier.id || current.pid !== process.pid)
|
|
237
|
+
throw new Error('Update ownership changed; manual repair is required');
|
|
238
|
+
}
|
|
239
|
+
async function authorize(args, phase) {
|
|
240
|
+
const token = randomUUID();
|
|
241
|
+
await locked(() => {
|
|
242
|
+
assertOwner();
|
|
243
|
+
barrier.phase = phase;
|
|
244
|
+
barrier.capability = { token, root: lease.root, args };
|
|
245
|
+
save(barrier);
|
|
246
|
+
});
|
|
247
|
+
return { ...process.env, FLOW_STATE_DIR: lease.root, FLOW_UPDATE_CAPABILITY: token };
|
|
248
|
+
}
|
|
249
|
+
return {
|
|
250
|
+
authorizeVerification: () => authorize(['--version'], 'replacing'),
|
|
251
|
+
authorizeRestoration: (args) => authorize(args, 'restoring'),
|
|
252
|
+
async assertAuthorizationConsumed() {
|
|
253
|
+
await locked(() => { assertOwner(); if (readBarrier(barrierPath)?.capability)
|
|
254
|
+
throw new Error('Fresh Flow did not use the installation guard'); });
|
|
255
|
+
},
|
|
256
|
+
async beginReplacement() {
|
|
257
|
+
await locked(() => {
|
|
258
|
+
assertOwner();
|
|
259
|
+
if (leases().some(other => other.id !== lease.id))
|
|
260
|
+
throw new Error('A Flow process remains; replacement cannot run safely');
|
|
261
|
+
barrier.phase = 'replacing';
|
|
262
|
+
delete barrier.capability;
|
|
263
|
+
save(barrier);
|
|
264
|
+
});
|
|
265
|
+
},
|
|
266
|
+
async complete() { await locked(() => { assertOwner(); unlinkSync(barrierPath); }); },
|
|
267
|
+
};
|
|
268
|
+
}
|
|
269
|
+
return { slot, prefix, directory, barrierPath, register, beginUpdate };
|
|
270
|
+
}
|
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
import { spawn } from 'node:child_process';
|
|
2
|
+
import { setTimeout as delay } from 'node:timers/promises';
|
|
3
|
+
export class InstallationProcessUncertain extends Error {
|
|
4
|
+
}
|
|
5
|
+
function groupAlive(pid) {
|
|
6
|
+
try {
|
|
7
|
+
process.kill(-pid, 0);
|
|
8
|
+
return true;
|
|
9
|
+
}
|
|
10
|
+
catch (error) {
|
|
11
|
+
if (error.code === 'ESRCH')
|
|
12
|
+
return false;
|
|
13
|
+
if (error.code === 'EPERM')
|
|
14
|
+
return true;
|
|
15
|
+
throw error;
|
|
16
|
+
}
|
|
17
|
+
}
|
|
18
|
+
async function stopGroup(pid) {
|
|
19
|
+
for (const [signal, timeout] of [['SIGTERM', 1000], ['SIGKILL', 5000]]) {
|
|
20
|
+
try {
|
|
21
|
+
process.kill(-pid, signal);
|
|
22
|
+
}
|
|
23
|
+
catch (error) {
|
|
24
|
+
if (error.code === 'ESRCH')
|
|
25
|
+
return;
|
|
26
|
+
if (error.code !== 'EPERM')
|
|
27
|
+
throw error;
|
|
28
|
+
}
|
|
29
|
+
const deadline = Date.now() + timeout;
|
|
30
|
+
while (groupAlive(pid) && Date.now() < deadline)
|
|
31
|
+
await delay(25);
|
|
32
|
+
if (!groupAlive(pid))
|
|
33
|
+
return;
|
|
34
|
+
}
|
|
35
|
+
throw new Error('npm process group did not exit');
|
|
36
|
+
}
|
|
37
|
+
export async function replacePackage(npm, prefix, packageSpec) {
|
|
38
|
+
const child = spawn(npm, ['install', '--global', '--prefix', prefix, packageSpec], { detached: true, stdio: 'inherit' });
|
|
39
|
+
const result = await new Promise((resolve, reject) => {
|
|
40
|
+
child.once('error', reject);
|
|
41
|
+
child.once('exit', (code, signal) => resolve({ code, signal }));
|
|
42
|
+
});
|
|
43
|
+
try {
|
|
44
|
+
if (child.pid)
|
|
45
|
+
await stopGroup(child.pid);
|
|
46
|
+
}
|
|
47
|
+
catch (error) {
|
|
48
|
+
throw new InstallationProcessUncertain(`Cannot confirm npm descendants stopped: ${String(error)}`);
|
|
49
|
+
}
|
|
50
|
+
if (result.code !== 0)
|
|
51
|
+
throw new Error(`npm installation failed (${result.signal ?? result.code})`);
|
|
52
|
+
}
|
package/dist/cli/main.js
ADDED
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import { isSea } from 'node:sea';
|
|
3
|
+
if (!isSea() && import.meta.url.endsWith('.js')) {
|
|
4
|
+
console.error('Use the flow executable, not the internal CLI entry');
|
|
5
|
+
process.exitCode = 1;
|
|
6
|
+
}
|
|
7
|
+
else {
|
|
8
|
+
void import("./application.js").then(({ runCli }) => runCli()).catch(error => {
|
|
9
|
+
console.error(error instanceof Error ? error.message : error);
|
|
10
|
+
process.exitCode = 1;
|
|
11
|
+
});
|
|
12
|
+
}
|
|
@@ -0,0 +1,128 @@
|
|
|
1
|
+
import { execFileSync } from 'node:child_process';
|
|
2
|
+
import { accessSync, constants, readFileSync, realpathSync } from 'node:fs';
|
|
3
|
+
import { delimiter, join, resolve } from 'node:path';
|
|
4
|
+
import { packageName, privatePath } from "./install-guard.js";
|
|
5
|
+
import { readHost } from "../daemon/ownership.js";
|
|
6
|
+
import { backgroundHostArgs, getHostStatus, HostRefusal, launchBackground, processAlive, requestHostStop, requireRestartable, waitUntil } from "./host-control.js";
|
|
7
|
+
import { InstallationProcessUncertain, replacePackage } from "./install-process.js";
|
|
8
|
+
function npmExecutable() {
|
|
9
|
+
for (const directory of (process.env.PATH ?? '').split(delimiter)) {
|
|
10
|
+
const path = resolve(directory, 'npm');
|
|
11
|
+
try {
|
|
12
|
+
accessSync(path, constants.X_OK);
|
|
13
|
+
return realpathSync(path);
|
|
14
|
+
}
|
|
15
|
+
catch { }
|
|
16
|
+
}
|
|
17
|
+
throw new Error('npm was not found in PATH');
|
|
18
|
+
}
|
|
19
|
+
function npmPath(npm, command) {
|
|
20
|
+
return realpathSync(execFileSync(npm, [command, '--global'], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'], timeout: 15000 }).trim());
|
|
21
|
+
}
|
|
22
|
+
function packageVersion(slot) {
|
|
23
|
+
privatePath(slot);
|
|
24
|
+
const metadata = JSON.parse(readFileSync(join(slot, 'package.json'), 'utf8'));
|
|
25
|
+
if (metadata?.name !== packageName || typeof metadata.version !== 'string' || !/^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?(?:\+[0-9A-Za-z.-]+)?$/.test(metadata.version))
|
|
26
|
+
throw new Error('Installed package identity is invalid');
|
|
27
|
+
return metadata.version;
|
|
28
|
+
}
|
|
29
|
+
async function verify(install, transaction, expected) {
|
|
30
|
+
const version = packageVersion(install.slot);
|
|
31
|
+
if (expected && version !== expected)
|
|
32
|
+
throw new Error('Installed package verification failed');
|
|
33
|
+
if (!readFileSync(join(install.slot, 'dist/build-id'), 'utf8').trim())
|
|
34
|
+
throw new Error('Installed build identity is missing');
|
|
35
|
+
const env = await transaction.authorizeVerification();
|
|
36
|
+
const reported = execFileSync(process.execPath, [join(install.slot, 'dist/cli/bootstrap.js'), '--version'], { env, encoding: 'utf8', timeout: 15000 }).trim();
|
|
37
|
+
if (reported !== version)
|
|
38
|
+
throw new Error('Fresh Flow process reports the wrong version');
|
|
39
|
+
await transaction.assertAuthorizationConsumed();
|
|
40
|
+
return version;
|
|
41
|
+
}
|
|
42
|
+
async function restore(install, transaction, root, host, version) {
|
|
43
|
+
const env = await transaction.authorizeRestoration(backgroundHostArgs(host.settings));
|
|
44
|
+
await launchBackground({
|
|
45
|
+
root, settings: host.settings, entry: [join(install.slot, 'dist/cli/bootstrap.js')], env,
|
|
46
|
+
validate(status) {
|
|
47
|
+
if (status.instanceId === host.instanceId || status.version !== version || status.mode !== 'background' ||
|
|
48
|
+
['port', 'address', 'cwd', 'oidc'].some(key => status.settings[key] !== host.settings[key])) {
|
|
49
|
+
throw new Error('Restored Session Host settings or version differ');
|
|
50
|
+
}
|
|
51
|
+
},
|
|
52
|
+
});
|
|
53
|
+
await transaction.assertAuthorizationConsumed();
|
|
54
|
+
}
|
|
55
|
+
export async function update(install, lease, args) {
|
|
56
|
+
if (args.length > 2 || args[0] !== 'update' || (args.length === 2 && args[1] !== '--force'))
|
|
57
|
+
throw new Error('usage: flow update [--force]');
|
|
58
|
+
const npm = npmExecutable();
|
|
59
|
+
const prefix = npmPath(npm, 'prefix'), root = npmPath(npm, 'root');
|
|
60
|
+
if (prefix !== install.prefix || root !== join(prefix, 'lib/node_modules') || realpathSync(join(root, packageName)) !== install.slot)
|
|
61
|
+
throw new Error('npm selects a different installation. Put the matching npm in PATH and select its prefix.');
|
|
62
|
+
const previous = packageVersion(install.slot);
|
|
63
|
+
let host = readHost(lease.root);
|
|
64
|
+
if (host && processAlive(host.pid)) {
|
|
65
|
+
const status = await getHostStatus(host);
|
|
66
|
+
requireRestartable(status);
|
|
67
|
+
host = { ...host, ...status };
|
|
68
|
+
}
|
|
69
|
+
else
|
|
70
|
+
host = undefined;
|
|
71
|
+
const transaction = await install.beginUpdate(lease, previous, host);
|
|
72
|
+
let needsRestoration = false, replacing = false;
|
|
73
|
+
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.`;
|
|
74
|
+
async function replace(version, expected) {
|
|
75
|
+
await transaction.beginReplacement();
|
|
76
|
+
replacing = true;
|
|
77
|
+
await replacePackage(npm, prefix, `${packageName}@${version}`);
|
|
78
|
+
const installed = await verify(install, transaction, expected);
|
|
79
|
+
if (host && needsRestoration) {
|
|
80
|
+
await restore(install, transaction, lease.root, host, installed);
|
|
81
|
+
needsRestoration = false;
|
|
82
|
+
}
|
|
83
|
+
await transaction.complete();
|
|
84
|
+
return installed;
|
|
85
|
+
}
|
|
86
|
+
try {
|
|
87
|
+
if (host) {
|
|
88
|
+
needsRestoration = true;
|
|
89
|
+
try {
|
|
90
|
+
await requestHostStop(host, args.includes('--force'));
|
|
91
|
+
}
|
|
92
|
+
catch (error) {
|
|
93
|
+
if (error instanceof HostRefusal)
|
|
94
|
+
needsRestoration = false;
|
|
95
|
+
throw error;
|
|
96
|
+
}
|
|
97
|
+
const pid = host.pid;
|
|
98
|
+
await waitUntil(async () => !processAlive(pid), 'Session Host process did not exit; installation was not changed');
|
|
99
|
+
}
|
|
100
|
+
const version = await replace('latest');
|
|
101
|
+
console.log(version === previous ? `Flow is already at ${version}.` : `Flow updated: ${previous} → ${version}`);
|
|
102
|
+
}
|
|
103
|
+
catch (error) {
|
|
104
|
+
if (error instanceof InstallationProcessUncertain)
|
|
105
|
+
throw new Error(`${String(error)}. ${repair()}`);
|
|
106
|
+
if (!replacing) {
|
|
107
|
+
if (needsRestoration && host && processAlive(host.pid))
|
|
108
|
+
throw new Error(`${String(error)}. No package files were changed; wait for the stopping host to exit. ${repair()}`);
|
|
109
|
+
if (needsRestoration && host) {
|
|
110
|
+
try {
|
|
111
|
+
await restore(install, transaction, lease.root, host, previous);
|
|
112
|
+
}
|
|
113
|
+
catch (failure) {
|
|
114
|
+
throw new Error(`${String(error)}; restoration failed: ${String(failure)}. ${repair()}`);
|
|
115
|
+
}
|
|
116
|
+
}
|
|
117
|
+
await transaction.complete();
|
|
118
|
+
throw error;
|
|
119
|
+
}
|
|
120
|
+
try {
|
|
121
|
+
await replace(previous, previous);
|
|
122
|
+
}
|
|
123
|
+
catch (failure) {
|
|
124
|
+
throw new Error(`Update failed: ${String(error)}; recovery failed: ${String(failure)}. ${repair()}`);
|
|
125
|
+
}
|
|
126
|
+
throw new Error(`Update failed: ${String(error)}. Reinstalled and verified ${previous}; the previous files were not preserved.`);
|
|
127
|
+
}
|
|
128
|
+
}
|
|
@@ -0,0 +1,183 @@
|
|
|
1
|
+
/** Reconnect backoff floor and ceiling, jittered so several clients do not retry in lockstep. */
|
|
2
|
+
const BACKOFF_MIN_MS = 500;
|
|
3
|
+
const BACKOFF_MAX_MS = 8_000;
|
|
4
|
+
/**
|
|
5
|
+
* The Session Host sends no heartbeat, so at this layer a stream that has gone quiet is
|
|
6
|
+
* indistinguishable from an Agent Session with nothing to say. README documents `--address 0.0.0.0`
|
|
7
|
+
* for containers, where a proxy's idle timeout drops a quiet stream without telling either end.
|
|
8
|
+
* Treating silence as death costs one resumed reconnect when the stream was merely idle, and is the
|
|
9
|
+
* only thing that recovers the case where it was real.
|
|
10
|
+
*/
|
|
11
|
+
const SILENCE_MS = 45_000;
|
|
12
|
+
/**
|
|
13
|
+
* Statuses no amount of retrying fixes: the Agent Session does not exist or has been reaped (404),
|
|
14
|
+
* or this client may not read it (401/403 — in the browser, the /auth handoff was never completed
|
|
15
|
+
* or its cookie has gone). Retrying these is a hot loop against a wall, so the link goes "gone".
|
|
16
|
+
*/
|
|
17
|
+
const FATAL_STATUS = new Set([401, 403, 404]);
|
|
18
|
+
export function connect(options) {
|
|
19
|
+
// In the browser there is no token to put in a header: it is the HttpOnly cookie the /auth handoff
|
|
20
|
+
// set, which is the whole reason that handoff exists (ADR 0004). Both of these are spread
|
|
21
|
+
// conditionally rather than assigned `undefined`, because exactOptionalPropertyTypes is on.
|
|
22
|
+
const headers = options.token
|
|
23
|
+
? { authorization: `Bearer ${options.token}` }
|
|
24
|
+
: {};
|
|
25
|
+
const credentials = options.token ? {} : { credentials: "same-origin" };
|
|
26
|
+
return {
|
|
27
|
+
async command(command) {
|
|
28
|
+
const response = await fetch(`${options.url}/api/command`, {
|
|
29
|
+
method: "POST",
|
|
30
|
+
headers: { ...headers, "content-type": "application/json" },
|
|
31
|
+
...credentials,
|
|
32
|
+
body: JSON.stringify(command),
|
|
33
|
+
});
|
|
34
|
+
await requireOk(response, options.token, options.authenticationRequired);
|
|
35
|
+
return (await response.json()).result;
|
|
36
|
+
},
|
|
37
|
+
async listSessions() {
|
|
38
|
+
const response = await fetch(`${options.url}/api/sessions`, { headers, ...credentials });
|
|
39
|
+
await requireOk(response, options.token, options.authenticationRequired);
|
|
40
|
+
return (await response.json());
|
|
41
|
+
},
|
|
42
|
+
async branches(scope) {
|
|
43
|
+
const url = `${options.url}/api/branches?scope=${encodeURIComponent(scope)}`;
|
|
44
|
+
const response = await fetch(url, { headers, ...credentials });
|
|
45
|
+
await requireOk(response, options.token, options.authenticationRequired);
|
|
46
|
+
return (await response.json());
|
|
47
|
+
},
|
|
48
|
+
subscribe({ sessionId, since, onEntry, onError, onLink, silenceMs }) {
|
|
49
|
+
const events = `${options.url}/api/sessions/${encodeURIComponent(sessionId)}/events`;
|
|
50
|
+
const silence = silenceMs ?? SILENCE_MS;
|
|
51
|
+
let lastSeq = since;
|
|
52
|
+
let attempt = 0;
|
|
53
|
+
let stopped = false;
|
|
54
|
+
let stream;
|
|
55
|
+
let wake;
|
|
56
|
+
const stop = () => {
|
|
57
|
+
stopped = true;
|
|
58
|
+
stream?.abort();
|
|
59
|
+
wake?.();
|
|
60
|
+
};
|
|
61
|
+
void (async () => {
|
|
62
|
+
while (!stopped) {
|
|
63
|
+
onLink?.("connecting");
|
|
64
|
+
// One controller per attempt: both the watchdog and stop() abort the *current* stream.
|
|
65
|
+
const controller = new AbortController();
|
|
66
|
+
stream = controller;
|
|
67
|
+
// Whether the abort below was the watchdog's rather than a real fault.
|
|
68
|
+
let silent = false;
|
|
69
|
+
const arm = () => setTimeout(() => {
|
|
70
|
+
silent = true;
|
|
71
|
+
controller.abort();
|
|
72
|
+
}, silence);
|
|
73
|
+
let watchdog = arm();
|
|
74
|
+
const openedAt = Date.now();
|
|
75
|
+
try {
|
|
76
|
+
// Resume, never replay. `since` is exclusive — SessionLog.since(seq) is slice(seq) —
|
|
77
|
+
// and reduce stamps lastSeq from the entry's own seq, so this is exactly where we left
|
|
78
|
+
// off with no off-by-one. Asking for 0 again would re-append every notice and every
|
|
79
|
+
// Dormant/Settled marker, because their Entry ids are derived from the transcript's
|
|
80
|
+
// length at the time (reduce.ts) and so differ on a second pass over a state that
|
|
81
|
+
// already holds them.
|
|
82
|
+
const response = await fetch(`${events}?since=${lastSeq}`, {
|
|
83
|
+
headers,
|
|
84
|
+
...credentials,
|
|
85
|
+
signal: controller.signal,
|
|
86
|
+
});
|
|
87
|
+
if (!response.ok || !response.body) {
|
|
88
|
+
const error = await responseError(response, options.token, options.authenticationRequired);
|
|
89
|
+
if (FATAL_STATUS.has(response.status)) {
|
|
90
|
+
onLink?.("gone");
|
|
91
|
+
onError?.(error);
|
|
92
|
+
return;
|
|
93
|
+
}
|
|
94
|
+
throw error;
|
|
95
|
+
}
|
|
96
|
+
onLink?.("live");
|
|
97
|
+
for await (const entry of readEventStream(response.body)) {
|
|
98
|
+
clearTimeout(watchdog);
|
|
99
|
+
watchdog = arm();
|
|
100
|
+
if (entry.seq > lastSeq)
|
|
101
|
+
lastSeq = entry.seq;
|
|
102
|
+
onEntry(entry);
|
|
103
|
+
}
|
|
104
|
+
// Falling out of that loop is a lost link too, not an ending: the host closes a stream
|
|
105
|
+
// only when it shuts down or the Agent Session is reaped.
|
|
106
|
+
}
|
|
107
|
+
catch (error) {
|
|
108
|
+
if (stopped)
|
|
109
|
+
return;
|
|
110
|
+
// A watchdog abort is this code's own doing, and the reconnect is the whole response to
|
|
111
|
+
// it — reporting it would put "operation aborted" in front of the user every SILENCE_MS
|
|
112
|
+
// that an Agent Session had nothing to say.
|
|
113
|
+
if (!silent)
|
|
114
|
+
onError?.(error instanceof Error ? error : new Error(String(error)));
|
|
115
|
+
}
|
|
116
|
+
finally {
|
|
117
|
+
clearTimeout(watchdog);
|
|
118
|
+
}
|
|
119
|
+
if (stopped)
|
|
120
|
+
return;
|
|
121
|
+
// A link that lasted counts as healthy, so the next drop backs off from the floor again;
|
|
122
|
+
// one that dies on arrival keeps escalating.
|
|
123
|
+
attempt = Date.now() - openedAt >= BACKOFF_MIN_MS ? 1 : attempt + 1;
|
|
124
|
+
onLink?.("retrying");
|
|
125
|
+
await new Promise((resolve) => {
|
|
126
|
+
const timer = setTimeout(resolve, backoffMs(attempt));
|
|
127
|
+
wake = () => {
|
|
128
|
+
clearTimeout(timer);
|
|
129
|
+
resolve();
|
|
130
|
+
};
|
|
131
|
+
});
|
|
132
|
+
wake = undefined;
|
|
133
|
+
}
|
|
134
|
+
})();
|
|
135
|
+
return stop;
|
|
136
|
+
},
|
|
137
|
+
};
|
|
138
|
+
}
|
|
139
|
+
function backoffMs(attempt) {
|
|
140
|
+
const ceiling = Math.min(BACKOFF_MAX_MS, BACKOFF_MIN_MS * 2 ** (attempt - 1));
|
|
141
|
+
// Jitter over the upper half of the window: still monotonic in `attempt`, but two clients that
|
|
142
|
+
// dropped together do not come back together.
|
|
143
|
+
return Math.round(ceiling * (0.5 + Math.random() / 2));
|
|
144
|
+
}
|
|
145
|
+
/** Minimal SSE reader: enough for `id:`/`data:` frames, which is all the host emits. */
|
|
146
|
+
async function* readEventStream(body) {
|
|
147
|
+
const decoder = new TextDecoder();
|
|
148
|
+
let buffer = "";
|
|
149
|
+
for await (const chunk of body) {
|
|
150
|
+
buffer += decoder.decode(chunk, { stream: true });
|
|
151
|
+
let split = buffer.indexOf("\n\n");
|
|
152
|
+
while (split !== -1) {
|
|
153
|
+
const frame = buffer.slice(0, split);
|
|
154
|
+
buffer = buffer.slice(split + 2);
|
|
155
|
+
const data = frame
|
|
156
|
+
.split("\n")
|
|
157
|
+
.filter((line) => line.startsWith("data:"))
|
|
158
|
+
.map((line) => line.slice("data:".length).trim())
|
|
159
|
+
.join("");
|
|
160
|
+
if (data)
|
|
161
|
+
yield JSON.parse(data);
|
|
162
|
+
split = buffer.indexOf("\n\n");
|
|
163
|
+
}
|
|
164
|
+
}
|
|
165
|
+
}
|
|
166
|
+
/**
|
|
167
|
+
* OIDC 401s carry an explicit login endpoint. A command is never replayed: its refused response is
|
|
168
|
+
* handled first, then a fresh top-level navigation starts authentication. Bearer clients and legacy
|
|
169
|
+
* local mode never take this browser-only path.
|
|
170
|
+
*/
|
|
171
|
+
async function requireOk(response, token, authenticationRequired) {
|
|
172
|
+
if (!response.ok)
|
|
173
|
+
throw await responseError(response, token, authenticationRequired);
|
|
174
|
+
}
|
|
175
|
+
async function responseError(response, token, authenticationRequired) {
|
|
176
|
+
if (!token)
|
|
177
|
+
authenticationRequired?.(response);
|
|
178
|
+
return new Error(await describe(response));
|
|
179
|
+
}
|
|
180
|
+
async function describe(response) {
|
|
181
|
+
const body = await response.text().catch(() => "");
|
|
182
|
+
return `${response.status} ${response.statusText}${body ? `: ${body}` : ""}`;
|
|
183
|
+
}
|