@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,19 @@
|
|
|
1
|
+
export async function readBody(request, limit) {
|
|
2
|
+
const chunks = [];
|
|
3
|
+
let size = 0;
|
|
4
|
+
for await (const chunk of request) {
|
|
5
|
+
size += chunk.length;
|
|
6
|
+
if (limit !== undefined && size > limit)
|
|
7
|
+
throw new Error('Request body too large');
|
|
8
|
+
chunks.push(chunk);
|
|
9
|
+
}
|
|
10
|
+
return Buffer.concat(chunks).toString('utf8') || '{}';
|
|
11
|
+
}
|
|
12
|
+
export function send(response, status, body) {
|
|
13
|
+
const payload = JSON.stringify(body);
|
|
14
|
+
response.writeHead(status, {
|
|
15
|
+
'content-type': 'application/json',
|
|
16
|
+
'content-length': Buffer.byteLength(payload),
|
|
17
|
+
});
|
|
18
|
+
response.end(payload);
|
|
19
|
+
}
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* A Presentation Transcript: append-only, sequence-numbered, never rewritten (ADR 0001).
|
|
3
|
+
*
|
|
4
|
+
* Every transcript write in Flow goes through this module. Keeping it in one place is what
|
|
5
|
+
* makes a different storage backing a local change later rather than a sweep.
|
|
6
|
+
*/
|
|
7
|
+
export class SessionLog {
|
|
8
|
+
sessionId;
|
|
9
|
+
entries;
|
|
10
|
+
listeners = new Set();
|
|
11
|
+
sink;
|
|
12
|
+
constructor(sessionId, options = {}) {
|
|
13
|
+
this.sessionId = sessionId;
|
|
14
|
+
this.entries = options.existing ? [...options.existing] : [];
|
|
15
|
+
this.sink = options.sink;
|
|
16
|
+
}
|
|
17
|
+
get lastSeq() {
|
|
18
|
+
return this.entries.length;
|
|
19
|
+
}
|
|
20
|
+
append(event, at = new Date().toISOString()) {
|
|
21
|
+
const entry = { seq: this.entries.length + 1, sessionId: this.sessionId, at, event };
|
|
22
|
+
this.entries.push(entry);
|
|
23
|
+
// Durable before observable: a client must never see an event that a restart would lose.
|
|
24
|
+
this.sink?.(entry);
|
|
25
|
+
for (const listener of this.listeners)
|
|
26
|
+
listener(entry);
|
|
27
|
+
return entry;
|
|
28
|
+
}
|
|
29
|
+
/** Entries after `seq`. `since(0)` is the whole transcript, which makes reconnect a replay. */
|
|
30
|
+
since(seq) {
|
|
31
|
+
return seq <= 0 ? [...this.entries] : this.entries.slice(seq);
|
|
32
|
+
}
|
|
33
|
+
subscribe(listener) {
|
|
34
|
+
this.listeners.add(listener);
|
|
35
|
+
return () => this.listeners.delete(listener);
|
|
36
|
+
}
|
|
37
|
+
/**
|
|
38
|
+
* Drop every subscriber. Used when an Agent Session is reaped: an open stream to a transcript
|
|
39
|
+
* that no longer exists would otherwise wait forever on a log nothing can append to again.
|
|
40
|
+
*/
|
|
41
|
+
closeSubscribers() {
|
|
42
|
+
this.listeners.clear();
|
|
43
|
+
}
|
|
44
|
+
}
|
|
@@ -0,0 +1,164 @@
|
|
|
1
|
+
import { credentialKey } from "./credential-redaction.js";
|
|
2
|
+
import { randomBytes, createHash } from "node:crypto";
|
|
3
|
+
import { mkdirSync, readFileSync, renameSync, writeFileSync } from "node:fs";
|
|
4
|
+
import { join } from "node:path";
|
|
5
|
+
import { auth, } from "@modelcontextprotocol/sdk/client/auth.js";
|
|
6
|
+
export class McpAuth {
|
|
7
|
+
path;
|
|
8
|
+
values;
|
|
9
|
+
pending = new Map();
|
|
10
|
+
dispose() {
|
|
11
|
+
for (const entry of this.pending.values())
|
|
12
|
+
clearTimeout(entry.timer);
|
|
13
|
+
this.pending.clear();
|
|
14
|
+
}
|
|
15
|
+
constructor(root) {
|
|
16
|
+
mkdirSync(root, { recursive: true });
|
|
17
|
+
this.path = join(root, "mcp-credentials.json");
|
|
18
|
+
try {
|
|
19
|
+
this.values = JSON.parse(readFileSync(this.path, "utf8"));
|
|
20
|
+
}
|
|
21
|
+
catch {
|
|
22
|
+
this.values = {};
|
|
23
|
+
}
|
|
24
|
+
}
|
|
25
|
+
key(connection) {
|
|
26
|
+
return createHash("sha256")
|
|
27
|
+
.update(JSON.stringify([
|
|
28
|
+
connection.id,
|
|
29
|
+
connection.transport === "http" ? connection.url : "",
|
|
30
|
+
]))
|
|
31
|
+
.digest("hex");
|
|
32
|
+
}
|
|
33
|
+
credentialValues() {
|
|
34
|
+
const values = [];
|
|
35
|
+
const visit = (value) => {
|
|
36
|
+
if (!value || typeof value !== 'object')
|
|
37
|
+
return;
|
|
38
|
+
for (const [key, child] of Object.entries(value)) {
|
|
39
|
+
if ((credentialKey.test(key) || key === 'id_token' || key === 'registration_access_token') && typeof child === 'string' && child)
|
|
40
|
+
values.push(child);
|
|
41
|
+
else if (child && typeof child === 'object')
|
|
42
|
+
visit(child);
|
|
43
|
+
}
|
|
44
|
+
};
|
|
45
|
+
visit(this.values);
|
|
46
|
+
return values;
|
|
47
|
+
}
|
|
48
|
+
provider(connection, redirectUrl = "http://127.0.0.1/", redirect, state) {
|
|
49
|
+
const key = this.key(connection);
|
|
50
|
+
let verifier = "";
|
|
51
|
+
const save = (patch) => {
|
|
52
|
+
this.values[key] = { ...this.values[key], ...patch };
|
|
53
|
+
const scratch = `${this.path}.tmp`;
|
|
54
|
+
writeFileSync(scratch, JSON.stringify(this.values), { mode: 0o600 });
|
|
55
|
+
renameSync(scratch, this.path);
|
|
56
|
+
};
|
|
57
|
+
return {
|
|
58
|
+
redirectUrl,
|
|
59
|
+
clientMetadata: {
|
|
60
|
+
client_name: "Flow",
|
|
61
|
+
redirect_uris: [redirectUrl],
|
|
62
|
+
grant_types: ["authorization_code", "refresh_token"],
|
|
63
|
+
response_types: ["code"],
|
|
64
|
+
token_endpoint_auth_method: "none",
|
|
65
|
+
},
|
|
66
|
+
state: () => state ?? randomBytes(32).toString("hex"),
|
|
67
|
+
clientInformation: () => this.values[key]?.client,
|
|
68
|
+
saveClientInformation: (client) => save({ client }),
|
|
69
|
+
tokens: () => this.values[key]?.tokens,
|
|
70
|
+
saveTokens: (tokens) => save({ tokens }),
|
|
71
|
+
saveCodeVerifier: (value) => {
|
|
72
|
+
verifier = value;
|
|
73
|
+
},
|
|
74
|
+
codeVerifier: () => verifier,
|
|
75
|
+
redirectToAuthorization: (url) => {
|
|
76
|
+
if (!redirect)
|
|
77
|
+
throw new Error("MCP sign-in required");
|
|
78
|
+
redirect(url);
|
|
79
|
+
},
|
|
80
|
+
};
|
|
81
|
+
}
|
|
82
|
+
async login(connection, returnUrl) {
|
|
83
|
+
if (connection.transport !== "http" || !connection.oauth)
|
|
84
|
+
throw new Error("OAuth is not enabled");
|
|
85
|
+
const destination = new URL(returnUrl);
|
|
86
|
+
if (!["http:", "https:"].includes(destination.protocol) ||
|
|
87
|
+
destination.username ||
|
|
88
|
+
destination.password)
|
|
89
|
+
throw new Error("Invalid return URL");
|
|
90
|
+
if ([...this.pending.values()].some((entry) => entry.connectionId === connection.id))
|
|
91
|
+
throw new Error("Sign-in already in progress");
|
|
92
|
+
const state = randomBytes(32).toString("hex");
|
|
93
|
+
const timer = setTimeout(() => this.pending.delete(state), 300_000);
|
|
94
|
+
timer.unref();
|
|
95
|
+
try {
|
|
96
|
+
let authorizationUrl = "";
|
|
97
|
+
const provider = this.provider(connection, new URL("/api/mcp/callback", destination.origin).href, (url) => {
|
|
98
|
+
authorizationUrl = url.href;
|
|
99
|
+
}, state);
|
|
100
|
+
let client;
|
|
101
|
+
const saveClient = provider.saveClientInformation;
|
|
102
|
+
const saveTokens = provider.saveTokens;
|
|
103
|
+
provider.saveClientInformation = (value) => {
|
|
104
|
+
client = value;
|
|
105
|
+
};
|
|
106
|
+
provider.saveTokens = async (tokens) => {
|
|
107
|
+
if (client)
|
|
108
|
+
await saveClient(client);
|
|
109
|
+
await saveTokens(tokens);
|
|
110
|
+
};
|
|
111
|
+
provider.clientInformation = () => client;
|
|
112
|
+
provider.tokens = () => undefined;
|
|
113
|
+
this.pending.set(state, {
|
|
114
|
+
connectionId: connection.id,
|
|
115
|
+
consumed: false,
|
|
116
|
+
provider,
|
|
117
|
+
serverUrl: connection.url,
|
|
118
|
+
returnTo: destination.href,
|
|
119
|
+
timer,
|
|
120
|
+
});
|
|
121
|
+
await auth(provider, { serverUrl: connection.url, fetchFn: timedFetch });
|
|
122
|
+
if (!authorizationUrl)
|
|
123
|
+
throw new Error("No authorization URL");
|
|
124
|
+
return authorizationUrl;
|
|
125
|
+
}
|
|
126
|
+
catch (error) {
|
|
127
|
+
clearTimeout(timer);
|
|
128
|
+
this.pending.delete(state);
|
|
129
|
+
throw error;
|
|
130
|
+
}
|
|
131
|
+
}
|
|
132
|
+
async callback(url) {
|
|
133
|
+
const state = url.searchParams.get("state") ?? "";
|
|
134
|
+
const entry = this.pending.get(state);
|
|
135
|
+
if (!entry || entry.consumed)
|
|
136
|
+
throw new Error("Invalid or expired callback");
|
|
137
|
+
entry.consumed = true;
|
|
138
|
+
clearTimeout(entry.timer);
|
|
139
|
+
const destination = new URL(entry.returnTo);
|
|
140
|
+
const code = url.searchParams.get("code");
|
|
141
|
+
let result = "failed";
|
|
142
|
+
if (code && !url.searchParams.has("error")) {
|
|
143
|
+
try {
|
|
144
|
+
const status = await auth(entry.provider, {
|
|
145
|
+
serverUrl: entry.serverUrl,
|
|
146
|
+
authorizationCode: code,
|
|
147
|
+
fetchFn: timedFetch,
|
|
148
|
+
});
|
|
149
|
+
if (status === "AUTHORIZED")
|
|
150
|
+
result = "signed-in";
|
|
151
|
+
}
|
|
152
|
+
catch { }
|
|
153
|
+
}
|
|
154
|
+
this.pending.delete(state);
|
|
155
|
+
destination.searchParams.set("mcpAuth", result);
|
|
156
|
+
return destination.href;
|
|
157
|
+
}
|
|
158
|
+
}
|
|
159
|
+
export const timedFetch = (input, init) => fetch(input, {
|
|
160
|
+
...init,
|
|
161
|
+
signal: init?.signal
|
|
162
|
+
? AbortSignal.any([init.signal, AbortSignal.timeout(15_000)])
|
|
163
|
+
: AbortSignal.timeout(15_000),
|
|
164
|
+
});
|
|
@@ -0,0 +1,85 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Which models a Backend Adapter can actually reach, asked without an Agent Session.
|
|
3
|
+
*
|
|
4
|
+
* This exists because of an awkward fact the Settings run into: **model ids are only known from a
|
|
5
|
+
* live Backend Session**. Claude's list comes from `supportedModels()`, a control request on a
|
|
6
|
+
* running stream; pi's comes off a constructed session's registry. `Capabilities` is declared per
|
|
7
|
+
* Agent Session for exactly that reason, and the New Agent Session view refused to offer a model at
|
|
8
|
+
* all until this existed.
|
|
9
|
+
*
|
|
10
|
+
* A machine-wide Default Model and Summary Model cannot wait for a session that does not exist yet.
|
|
11
|
+
* So this opens a throwaway one — the same device the Summary Model uses (ADR 0020), tools and all
|
|
12
|
+
* off — reads its Capabilities, and disposes of it.
|
|
13
|
+
*/
|
|
14
|
+
/**
|
|
15
|
+
* A backend that has not answered in this long is not going to.
|
|
16
|
+
*
|
|
17
|
+
* Generous, because the probes run concurrently and the slow one makes the others slower. Claude
|
|
18
|
+
* spawns its CLI and answers in about nine seconds on its own; pi faults in its whole ESM and
|
|
19
|
+
* native dependency tree on first touch, and at fifteen seconds Claude lost that race on a healthy
|
|
20
|
+
* machine and reported a `problem` — a picker replaced by a text field for no reason but a
|
|
21
|
+
* stopwatch. Somebody who has just opened the Settings will wait half a minute once; they will not
|
|
22
|
+
* forgive being told their backend is broken when it is not.
|
|
23
|
+
*/
|
|
24
|
+
const PROBE_TIMEOUT_MS = 45_000;
|
|
25
|
+
/**
|
|
26
|
+
* Ask one Backend Adapter what models it can reach.
|
|
27
|
+
*
|
|
28
|
+
* Never throws: a backend that cannot answer reports a `problem`, and its section of the Settings
|
|
29
|
+
* offers a text field instead of a list. A refusal here must not make the whole page unreachable.
|
|
30
|
+
*/
|
|
31
|
+
export async function probeModels(backend, scope) {
|
|
32
|
+
let models = [];
|
|
33
|
+
let settle;
|
|
34
|
+
// Claude reports a provisional Capabilities at create and the real list moments later, over
|
|
35
|
+
// `capabilities_changed` — so waiting for that event rather than reading `session.capabilities`
|
|
36
|
+
// once is what makes the difference between the whole list and a list of one.
|
|
37
|
+
const listed = new Promise((resolve) => {
|
|
38
|
+
settle = resolve;
|
|
39
|
+
});
|
|
40
|
+
const emit = (event) => {
|
|
41
|
+
if (event.type !== "capabilities_changed")
|
|
42
|
+
return;
|
|
43
|
+
models = [...event.capabilities.models];
|
|
44
|
+
settle?.();
|
|
45
|
+
};
|
|
46
|
+
let session;
|
|
47
|
+
try {
|
|
48
|
+
session = await backend.create({ scope, tools: "none", emit });
|
|
49
|
+
}
|
|
50
|
+
catch (error) {
|
|
51
|
+
return { backend: backend.name, models: [], problem: message(error) };
|
|
52
|
+
}
|
|
53
|
+
try {
|
|
54
|
+
/*
|
|
55
|
+
* A backend that already knows is not waited on.
|
|
56
|
+
*
|
|
57
|
+
* pi and the fake build their whole list before `create` resolves and never emit
|
|
58
|
+
* `capabilities_changed` again, so waiting for one costs the entire timeout and answers with
|
|
59
|
+
* exactly what was on the session all along. Only Claude, which fetches over its control
|
|
60
|
+
* channel after the session is up, has anything to wait for.
|
|
61
|
+
*/
|
|
62
|
+
if (session.capabilities.models.length > 0)
|
|
63
|
+
return { backend: backend.name, models: [...session.capabilities.models], ...(session.capabilities.autoCompaction ? { autoCompaction: session.capabilities.autoCompaction } : {}) };
|
|
64
|
+
await within(listed, PROBE_TIMEOUT_MS);
|
|
65
|
+
return models.length > 0
|
|
66
|
+
? { backend: backend.name, models, ...(session.capabilities.autoCompaction ? { autoCompaction: session.capabilities.autoCompaction } : {}) }
|
|
67
|
+
: { backend: backend.name, models: [], problem: `${backend.name} listed no models` };
|
|
68
|
+
}
|
|
69
|
+
finally {
|
|
70
|
+
await session.dispose().catch(() => { });
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
function message(error) {
|
|
74
|
+
return error instanceof Error ? error.message : String(error);
|
|
75
|
+
}
|
|
76
|
+
/** Whichever comes first, clearing the timer either way — see `within` in ./summariser.ts. */
|
|
77
|
+
function within(work, ms) {
|
|
78
|
+
return new Promise((resolve) => {
|
|
79
|
+
const timer = setTimeout(resolve, ms);
|
|
80
|
+
void work.then(() => {
|
|
81
|
+
clearTimeout(timer);
|
|
82
|
+
resolve();
|
|
83
|
+
});
|
|
84
|
+
});
|
|
85
|
+
}
|
|
@@ -0,0 +1,104 @@
|
|
|
1
|
+
import { mkdirSync, realpathSync, readdirSync, readFileSync, writeFileSync, renameSync, unlinkSync, rmdirSync } from 'node:fs';
|
|
2
|
+
import { join } from 'node:path';
|
|
3
|
+
import { randomUUID, createHash } from 'node:crypto';
|
|
4
|
+
export function oidcFingerprint(env = process.env) {
|
|
5
|
+
return createHash('sha256').update(JSON.stringify(['ISSUER', 'CLIENT_ID', 'CLIENT_SECRET', 'PUBLIC_APP_URL'].map(key => env[`FLOW_OIDC_${key}`]?.trim() ?? ''))).digest('hex');
|
|
6
|
+
}
|
|
7
|
+
export function readHost(root) {
|
|
8
|
+
try {
|
|
9
|
+
return JSON.parse(readFileSync(join(root, 'daemon.json'), 'utf8'));
|
|
10
|
+
}
|
|
11
|
+
catch {
|
|
12
|
+
return undefined;
|
|
13
|
+
}
|
|
14
|
+
}
|
|
15
|
+
export function acquireHost(root) {
|
|
16
|
+
mkdirSync(root, { recursive: true, mode: 0o700 });
|
|
17
|
+
root = realpathSync(root);
|
|
18
|
+
const instanceId = randomUUID();
|
|
19
|
+
const lock = join(root, 'host.lock');
|
|
20
|
+
const candidate = join(root, `host.lock-${instanceId}`);
|
|
21
|
+
const owner = `${instanceId}.json`;
|
|
22
|
+
mkdirSync(candidate, { mode: 0o700 });
|
|
23
|
+
writeFileSync(join(candidate, owner), JSON.stringify({ pid: process.pid }), { mode: 0o600 });
|
|
24
|
+
const remove = (directory, filename) => {
|
|
25
|
+
try {
|
|
26
|
+
unlinkSync(join(directory, filename));
|
|
27
|
+
}
|
|
28
|
+
catch (error) {
|
|
29
|
+
if (error.code !== 'ENOENT')
|
|
30
|
+
throw error;
|
|
31
|
+
}
|
|
32
|
+
try {
|
|
33
|
+
rmdirSync(directory);
|
|
34
|
+
}
|
|
35
|
+
catch (error) {
|
|
36
|
+
if (!['ENOENT', 'ENOTEMPTY', 'EEXIST'].includes(error.code ?? ''))
|
|
37
|
+
throw error;
|
|
38
|
+
}
|
|
39
|
+
};
|
|
40
|
+
try {
|
|
41
|
+
for (let attempt = 0;; attempt++) {
|
|
42
|
+
try {
|
|
43
|
+
renameSync(candidate, lock);
|
|
44
|
+
break;
|
|
45
|
+
}
|
|
46
|
+
catch (error) {
|
|
47
|
+
if (!['ENOTEMPTY', 'EEXIST'].includes(error.code ?? '') || attempt >= 8)
|
|
48
|
+
throw error;
|
|
49
|
+
let entries;
|
|
50
|
+
try {
|
|
51
|
+
entries = readdirSync(lock);
|
|
52
|
+
}
|
|
53
|
+
catch {
|
|
54
|
+
continue;
|
|
55
|
+
}
|
|
56
|
+
if (entries.length === 0)
|
|
57
|
+
continue;
|
|
58
|
+
if (entries.length !== 1 || !/^[a-f0-9-]+\.json$/.test(entries[0]))
|
|
59
|
+
throw new Error('Session Host ownership is unknown');
|
|
60
|
+
const filename = entries[0];
|
|
61
|
+
let pid;
|
|
62
|
+
try {
|
|
63
|
+
pid = JSON.parse(readFileSync(join(lock, filename), 'utf8')).pid;
|
|
64
|
+
}
|
|
65
|
+
catch {
|
|
66
|
+
continue;
|
|
67
|
+
}
|
|
68
|
+
if (!Number.isInteger(pid) || pid <= 0)
|
|
69
|
+
throw new Error('Session Host ownership is invalid');
|
|
70
|
+
try {
|
|
71
|
+
process.kill(pid, 0);
|
|
72
|
+
}
|
|
73
|
+
catch (failure) {
|
|
74
|
+
if (failure.code === 'ESRCH') {
|
|
75
|
+
remove(lock, filename);
|
|
76
|
+
continue;
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
throw new Error('A Session Host already owns this state root');
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
catch (error) {
|
|
84
|
+
remove(candidate, owner);
|
|
85
|
+
throw error;
|
|
86
|
+
}
|
|
87
|
+
let released = false;
|
|
88
|
+
return {
|
|
89
|
+
root, instanceId,
|
|
90
|
+
publish(identity) {
|
|
91
|
+
const temporary = join(root, `daemon-${instanceId}.json`);
|
|
92
|
+
writeFileSync(temporary, JSON.stringify(identity), { mode: 0o600 });
|
|
93
|
+
renameSync(temporary, join(root, 'daemon.json'));
|
|
94
|
+
},
|
|
95
|
+
release() {
|
|
96
|
+
if (released)
|
|
97
|
+
return;
|
|
98
|
+
released = true;
|
|
99
|
+
if (readHost(root)?.instanceId === instanceId)
|
|
100
|
+
unlinkSync(join(root, 'daemon.json'));
|
|
101
|
+
remove(lock, owner);
|
|
102
|
+
},
|
|
103
|
+
};
|
|
104
|
+
}
|