@aiwayds/dsh-opentui 0.18.6 → 0.19.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/CHANGELOG.md +47 -0
- package/bin/dsh-opentui.mjs +54 -24
- package/bin/lib/launcher.mjs +29 -2
- package/dist/client/index.js +2625 -1280
- package/dist/client/index.js.map +16 -10
- package/dist/host-launch.mjs +1276 -0
- package/dist/host-launch.mjs.map +19 -0
- package/dist/scripts/idle-reaper.mjs +9 -3
- package/dist/watchdog.mjs +467 -0
- package/dist/watchdog.mjs.map +16 -0
- package/package.json +5 -1
- package/scripts/idle-reaper.mjs +9 -3
package/dist/client/index.js
CHANGED
|
@@ -58,874 +58,166 @@ var __esm = (fn, res, err) => () => {
|
|
|
58
58
|
};
|
|
59
59
|
var __require = import.meta.require;
|
|
60
60
|
|
|
61
|
-
// src/client/
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
chmodSync,
|
|
65
|
-
constants,
|
|
66
|
-
existsSync,
|
|
67
|
-
mkdirSync,
|
|
68
|
-
readFileSync,
|
|
69
|
-
renameSync,
|
|
70
|
-
statSync,
|
|
71
|
-
unlinkSync,
|
|
72
|
-
writeFileSync
|
|
73
|
-
} from "fs";
|
|
74
|
-
import { join } from "path";
|
|
75
|
-
function workspaceConfigPath(workspaceDir) {
|
|
76
|
-
return join(workspaceDir, CONFIG_DIR, CONFIG_FILE);
|
|
61
|
+
// src/client/mux-frame.ts
|
|
62
|
+
function openEventsStreamFrame(streamId) {
|
|
63
|
+
return { type: "open", streamId, endpoint: "$events", payload: { args: {} } };
|
|
77
64
|
}
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
if (!existsSync(path))
|
|
81
|
-
return {};
|
|
82
|
-
let text;
|
|
65
|
+
function parseMuxFrame(text) {
|
|
66
|
+
let decoded;
|
|
83
67
|
try {
|
|
84
|
-
|
|
85
|
-
} catch (
|
|
86
|
-
throw new
|
|
87
|
-
}
|
|
88
|
-
const tree = parseConfigDoc(text, path);
|
|
89
|
-
assertNoCredentialKeys(tree, path);
|
|
90
|
-
return overlayFromTree(tree, path);
|
|
91
|
-
}
|
|
92
|
-
function mergeConfig(base, overlay, env) {
|
|
93
|
-
const envTheme = pickEnv(env, ENV_THEME);
|
|
94
|
-
const envRoute = pickEnv(env, ENV_MODEL);
|
|
95
|
-
let envProvider;
|
|
96
|
-
let envModel;
|
|
97
|
-
if (envRoute !== undefined) {
|
|
98
|
-
const slash = envRoute.indexOf("/");
|
|
99
|
-
if (slash === -1) {
|
|
100
|
-
envModel = envRoute;
|
|
101
|
-
} else {
|
|
102
|
-
envProvider = nonEmpty(envRoute.slice(0, slash));
|
|
103
|
-
envModel = nonEmpty(envRoute.slice(slash + 1));
|
|
104
|
-
}
|
|
105
|
-
}
|
|
106
|
-
const theme = envTheme ?? nonEmpty(overlay.theme) ?? nonEmpty(base.theme);
|
|
107
|
-
const themeMode = nonEmpty(overlay.themeMode) ?? nonEmpty(base.themeMode);
|
|
108
|
-
const provider = envProvider ?? nonEmpty(overlay.model?.provider) ?? nonEmpty(base.model?.provider);
|
|
109
|
-
const model = envModel ?? nonEmpty(overlay.model?.model) ?? nonEmpty(base.model?.model);
|
|
110
|
-
const reasoningEffort = nonEmpty(overlay.model?.reasoningEffort) ?? nonEmpty(base.model?.reasoningEffort);
|
|
111
|
-
const mergedModel = provider !== undefined || model !== undefined || reasoningEffort !== undefined ? {
|
|
112
|
-
...provider !== undefined && { provider },
|
|
113
|
-
...model !== undefined && { model },
|
|
114
|
-
...reasoningEffort !== undefined && { reasoningEffort }
|
|
115
|
-
} : undefined;
|
|
116
|
-
return {
|
|
117
|
-
...theme !== undefined && { theme },
|
|
118
|
-
...themeMode !== undefined && { themeMode },
|
|
119
|
-
...mergedModel !== undefined && { model: mergedModel }
|
|
120
|
-
};
|
|
121
|
-
}
|
|
122
|
-
async function saveWorkspaceConfig(workspaceDir, overlay) {
|
|
123
|
-
validateOverlayShape(overlay);
|
|
124
|
-
const configDir = join(workspaceDir, CONFIG_DIR);
|
|
125
|
-
const path = workspaceConfigPath(workspaceDir);
|
|
126
|
-
ensureWritableDir(workspaceDir, configDir);
|
|
127
|
-
let tree = mkMap(0);
|
|
128
|
-
if (existsSync(path)) {
|
|
129
|
-
let text;
|
|
130
|
-
try {
|
|
131
|
-
text = readFileSync(path, "utf8");
|
|
132
|
-
} catch (error) {
|
|
133
|
-
throw new WorkspaceConfigWriteError(path, `cannot read existing config (${error.message})`);
|
|
134
|
-
}
|
|
135
|
-
tree = parseConfigDoc(text, path);
|
|
136
|
-
}
|
|
137
|
-
applyOverlayToTree(tree, overlay);
|
|
138
|
-
assertNoCredentialKeys(tree, path);
|
|
139
|
-
const body = serializeTree(tree);
|
|
140
|
-
const doc = FILE_HEADER + (body.length === 0 ? "" : body.join(`
|
|
141
|
-
`) + `
|
|
142
|
-
`);
|
|
143
|
-
atomicWrite(path, doc);
|
|
144
|
-
}
|
|
145
|
-
function isCredentialKey(key) {
|
|
146
|
-
return CREDENTIAL_KEY_DENYLIST.has(key.toLowerCase().replaceAll(/[ \t_-]+/gu, ""));
|
|
147
|
-
}
|
|
148
|
-
function validateOverlayShape(overlay) {
|
|
149
|
-
if (overlay === null || typeof overlay !== "object" || Array.isArray(overlay)) {
|
|
150
|
-
throw new WorkspaceConfigError("workspace overlay must be an object");
|
|
151
|
-
}
|
|
152
|
-
for (const key of Object.keys(overlay)) {
|
|
153
|
-
if (key === "theme" || key === "themeMode" || key === "model")
|
|
154
|
-
continue;
|
|
155
|
-
if (isCredentialKey(key))
|
|
156
|
-
throw new WorkspaceConfigCredentialError(key, "the workspace overlay");
|
|
157
|
-
throw new WorkspaceConfigError(`unknown overlay key "${key}" \u2014 workspace config supports only theme and model preferences`);
|
|
158
|
-
}
|
|
159
|
-
if (overlay.theme !== undefined && !isNonEmptyString(overlay.theme)) {
|
|
160
|
-
throw new WorkspaceConfigError("overlay.theme must be a non-empty string");
|
|
68
|
+
decoded = JSON.parse(text);
|
|
69
|
+
} catch (cause) {
|
|
70
|
+
throw new MuxFrameError("mux frame is not JSON", { cause });
|
|
161
71
|
}
|
|
162
|
-
if (
|
|
163
|
-
throw new
|
|
72
|
+
if (!isRecord(decoded))
|
|
73
|
+
throw new MuxFrameError("mux frame must be an object");
|
|
74
|
+
const value = decoded;
|
|
75
|
+
const type = value.type;
|
|
76
|
+
const streamId = value.streamId;
|
|
77
|
+
if (typeof streamId !== "string" || streamId.length === 0) {
|
|
78
|
+
throw new MuxFrameError("mux frame streamId is missing or empty");
|
|
164
79
|
}
|
|
165
|
-
if (
|
|
166
|
-
if (
|
|
167
|
-
throw new
|
|
168
|
-
}
|
|
169
|
-
for (const key of Object.keys(overlay.model)) {
|
|
170
|
-
if (!MODEL_FIELDS.includes(key)) {
|
|
171
|
-
if (isCredentialKey(key))
|
|
172
|
-
throw new WorkspaceConfigCredentialError(`model.${key}`, "the workspace overlay");
|
|
173
|
-
throw new WorkspaceConfigError(`unknown overlay key "model.${key}" \u2014 model supports only provider, model, reasoningEffort`);
|
|
174
|
-
}
|
|
175
|
-
}
|
|
176
|
-
for (const field of MODEL_FIELDS) {
|
|
177
|
-
const value = overlay.model[field];
|
|
178
|
-
if (value !== undefined && !isNonEmptyString(value)) {
|
|
179
|
-
throw new WorkspaceConfigError(`overlay.model.${field} must be a non-empty string`);
|
|
180
|
-
}
|
|
80
|
+
if (type === "item") {
|
|
81
|
+
if (!exactKeys(value, ["type", "streamId"]) && !exactKeys(value, ["type", "streamId", "value"])) {
|
|
82
|
+
throw new MuxFrameError("item frame must carry exactly type, streamId [, value]");
|
|
181
83
|
}
|
|
84
|
+
return { type: "item", streamId, value: value.value };
|
|
182
85
|
}
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
}
|
|
187
|
-
function mkScalar(text, line, quoted, raw) {
|
|
188
|
-
return { kind: "scalar", text, quoted, raw: raw ?? (quoted ? doubleQuote(text) : text), line };
|
|
189
|
-
}
|
|
190
|
-
function parseConfigDoc(text, path) {
|
|
191
|
-
const root = mkMap(0);
|
|
192
|
-
const stack = [{ map: root, indent: 0 }];
|
|
193
|
-
let sawContent = false;
|
|
194
|
-
const lines = text.replace(/^\uFEFF/u, "").split(`
|
|
195
|
-
`);
|
|
196
|
-
for (let i = 0;i < lines.length; i++) {
|
|
197
|
-
const lineNo = i + 1;
|
|
198
|
-
const line = lines[i].replace(/\r$/u, "");
|
|
199
|
-
const trimmed = line.trim();
|
|
200
|
-
if (trimmed === "" || trimmed.startsWith("#"))
|
|
201
|
-
continue;
|
|
202
|
-
if (trimmed === "---" && !sawContent)
|
|
203
|
-
continue;
|
|
204
|
-
if (trimmed === "---" || trimmed === "...") {
|
|
205
|
-
throw new WorkspaceConfigParseError(path, lineNo, "document markers beyond a single leading `---` are not supported");
|
|
206
|
-
}
|
|
207
|
-
if (trimmed.startsWith("%")) {
|
|
208
|
-
throw new WorkspaceConfigParseError(path, lineNo, "YAML directives are not supported");
|
|
209
|
-
}
|
|
210
|
-
sawContent = true;
|
|
211
|
-
if (/^ *\t/u.test(line)) {
|
|
212
|
-
throw new WorkspaceConfigParseError(path, lineNo, "tab indentation is not supported \u2014 indent with spaces");
|
|
213
|
-
}
|
|
214
|
-
const indent = leadingSpaces(line);
|
|
215
|
-
const rest = line.slice(indent);
|
|
216
|
-
if (rest.startsWith("- ") || rest === "-") {
|
|
217
|
-
throw new WorkspaceConfigParseError(path, lineNo, "sequences (lists) are not supported in workspace config");
|
|
86
|
+
if (type === "end") {
|
|
87
|
+
if (!exactKeys(value, ["type", "streamId"])) {
|
|
88
|
+
throw new MuxFrameError("end frame must carry exactly type, streamId");
|
|
218
89
|
}
|
|
219
|
-
|
|
220
|
-
const node = parseValue(valueText, path, lineNo);
|
|
221
|
-
attachEntry(stack, indent, key, node, path, lineNo);
|
|
90
|
+
return { type: "end", streamId };
|
|
222
91
|
}
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
const first = rest[0];
|
|
227
|
-
if (first === "'" || first === '"') {
|
|
228
|
-
const scanned = scanQuoted(rest, path, lineNo);
|
|
229
|
-
let idx = scanned.end;
|
|
230
|
-
while (rest[idx] === " ")
|
|
231
|
-
idx++;
|
|
232
|
-
if (rest[idx] !== ":") {
|
|
233
|
-
throw new WorkspaceConfigParseError(path, lineNo, 'expected "key: value" \u2014 quoted key not followed by ":"');
|
|
92
|
+
if (type === "error") {
|
|
93
|
+
if (!exactKeys(value, ["type", "streamId", "error"])) {
|
|
94
|
+
throw new MuxFrameError("error frame must carry exactly type, streamId, error");
|
|
234
95
|
}
|
|
235
|
-
|
|
236
|
-
return { key: scanned.text, valueText: valueText === "" ? undefined : valueText };
|
|
237
|
-
}
|
|
238
|
-
const colon = findKeyColon(rest);
|
|
239
|
-
if (colon === -1) {
|
|
240
|
-
throw new WorkspaceConfigParseError(path, lineNo, 'expected "key: value" (missing space after colon?)');
|
|
241
|
-
}
|
|
242
|
-
const key = rest.slice(0, colon).trim();
|
|
243
|
-
if (!key)
|
|
244
|
-
throw new WorkspaceConfigParseError(path, lineNo, "empty key");
|
|
245
|
-
const valueText = rest.slice(colon + 1).trim();
|
|
246
|
-
return { key, valueText: valueText === "" ? undefined : valueText };
|
|
247
|
-
}
|
|
248
|
-
function findKeyColon(rest) {
|
|
249
|
-
for (let i = 0;i < rest.length; i++) {
|
|
250
|
-
if (rest[i] !== ":")
|
|
251
|
-
continue;
|
|
252
|
-
const next = rest[i + 1];
|
|
253
|
-
if (i + 1 === rest.length || next === " " || next === "\t")
|
|
254
|
-
return i;
|
|
96
|
+
return { type: "error", streamId, error: parseRemoteErrorFields(value.error) };
|
|
255
97
|
}
|
|
256
|
-
|
|
98
|
+
throw new MuxFrameError(`unknown mux frame type: ${String(type)}`);
|
|
257
99
|
}
|
|
258
|
-
function
|
|
259
|
-
if (
|
|
260
|
-
|
|
261
|
-
if (valueText.startsWith("#"))
|
|
262
|
-
return { kind: "null", line: lineNo };
|
|
263
|
-
const first = valueText[0];
|
|
264
|
-
if (first === "|" || first === ">") {
|
|
265
|
-
throw new WorkspaceConfigParseError(path, lineNo, "block scalars (| >) are not supported in workspace config");
|
|
266
|
-
}
|
|
267
|
-
if (first === "[" || first === "{") {
|
|
268
|
-
throw new WorkspaceConfigParseError(path, lineNo, "flow collections ([] {}) are not supported in workspace config");
|
|
100
|
+
function parseEventsReady(value) {
|
|
101
|
+
if (!isPlainRecord(value) || !exactKeys(value, ["type", "clientId", "host"])) {
|
|
102
|
+
throw new MuxFrameError("$events opening item must carry exactly type, clientId, host");
|
|
269
103
|
}
|
|
270
|
-
|
|
271
|
-
|
|
104
|
+
const record = value;
|
|
105
|
+
if (record.type !== "ready") {
|
|
106
|
+
throw new MuxFrameError(`$events opening item must be ready, got: ${String(record.type)}`);
|
|
272
107
|
}
|
|
273
|
-
if (
|
|
274
|
-
|
|
275
|
-
let idx = scanned.end;
|
|
276
|
-
while (valueText[idx] === " ")
|
|
277
|
-
idx++;
|
|
278
|
-
if (idx < valueText.length && valueText[idx] !== "#") {
|
|
279
|
-
throw new WorkspaceConfigParseError(path, lineNo, "unexpected content after closing quote");
|
|
280
|
-
}
|
|
281
|
-
return mkScalar(scanned.text, lineNo, true);
|
|
108
|
+
if (typeof record.clientId !== "string" || record.clientId.length === 0) {
|
|
109
|
+
throw new MuxFrameError("$events ready clientId must be a non-empty string");
|
|
282
110
|
}
|
|
283
|
-
const
|
|
284
|
-
|
|
285
|
-
|
|
286
|
-
return { kind: "null", line: lineNo };
|
|
287
|
-
if (raw.includes(": ")) {
|
|
288
|
-
throw new WorkspaceConfigParseError(path, lineNo, `plain scalar cannot contain ": " \u2014 quote the value`);
|
|
111
|
+
const host = record.host;
|
|
112
|
+
if (!isPlainRecord(host) || !exactKeys(host, ["home"]) || typeof host.home !== "string") {
|
|
113
|
+
throw new MuxFrameError("$events ready host must carry exactly home: string");
|
|
289
114
|
}
|
|
290
|
-
return
|
|
115
|
+
return { type: "ready", clientId: record.clientId, host: { home: host.home } };
|
|
291
116
|
}
|
|
292
|
-
function
|
|
293
|
-
|
|
294
|
-
|
|
295
|
-
|
|
296
|
-
|
|
297
|
-
|
|
298
|
-
|
|
299
|
-
if (ch === "'") {
|
|
300
|
-
if (text[i + 1] === "'") {
|
|
301
|
-
out += "'";
|
|
302
|
-
i += 2;
|
|
303
|
-
continue;
|
|
304
|
-
}
|
|
305
|
-
return { text: out, end: i + 1 };
|
|
306
|
-
}
|
|
307
|
-
out += ch;
|
|
308
|
-
i++;
|
|
309
|
-
continue;
|
|
310
|
-
}
|
|
311
|
-
if (ch === "\\") {
|
|
312
|
-
const esc = text[i + 1];
|
|
313
|
-
if (esc === '"' || esc === "\\") {
|
|
314
|
-
out += esc;
|
|
315
|
-
i += 2;
|
|
316
|
-
continue;
|
|
317
|
-
}
|
|
318
|
-
throw new WorkspaceConfigParseError(path, lineNo, `unsupported escape "\\${esc ?? ""}" in double-quoted scalar`);
|
|
117
|
+
function parseEventsItem(value) {
|
|
118
|
+
if (!isPlainRecord(value))
|
|
119
|
+
throw new MuxFrameError("$events item must be a plain object");
|
|
120
|
+
const record = value;
|
|
121
|
+
if (record.type === "cancel") {
|
|
122
|
+
if (!exactKeys(record, ["type", "eventId"]) || typeof record.eventId !== "string" || record.eventId.length === 0) {
|
|
123
|
+
throw new MuxFrameError("$events cancel item must carry exactly type, eventId: string");
|
|
319
124
|
}
|
|
320
|
-
|
|
321
|
-
return { text: out, end: i + 1 };
|
|
322
|
-
out += ch;
|
|
323
|
-
i++;
|
|
125
|
+
return { type: "cancel", eventId: record.eventId };
|
|
324
126
|
}
|
|
325
|
-
|
|
326
|
-
|
|
327
|
-
|
|
328
|
-
while (stack.length > 1 && stack[stack.length - 1].indent > indent)
|
|
329
|
-
stack.pop();
|
|
330
|
-
const frame = stack[stack.length - 1];
|
|
331
|
-
if (frame.indent === indent) {
|
|
332
|
-
if (frame.map.entries.has(key)) {
|
|
333
|
-
throw new WorkspaceConfigParseError(path, lineNo, `duplicate key "${key}"`);
|
|
127
|
+
if (record.type === "emit") {
|
|
128
|
+
if (!exactKeys(record, ["type", "event", "args"]) || typeof record.event !== "string" || record.event.length === 0 || !Array.isArray(record.args) || !isRemoteJson(record.args)) {
|
|
129
|
+
throw new MuxFrameError("$events emit item must carry exactly type, event: string, args: JSON[]");
|
|
334
130
|
}
|
|
335
|
-
|
|
336
|
-
frame.lastKey = key;
|
|
337
|
-
return;
|
|
338
|
-
}
|
|
339
|
-
if (frame.lastKey === undefined) {
|
|
340
|
-
throw new WorkspaceConfigParseError(path, lineNo, "unexpected indentation (no parent key above)");
|
|
341
|
-
}
|
|
342
|
-
const parent = frame.map.entries.get(frame.lastKey);
|
|
343
|
-
if (parent === undefined)
|
|
344
|
-
throw new WorkspaceConfigParseError(path, lineNo, "unexpected indentation");
|
|
345
|
-
if (parent.kind === "scalar") {
|
|
346
|
-
throw new WorkspaceConfigParseError(path, lineNo, `unexpected indentation under scalar "${frame.lastKey}"`);
|
|
347
|
-
}
|
|
348
|
-
let map;
|
|
349
|
-
if (parent.kind === "map") {
|
|
350
|
-
throw new WorkspaceConfigParseError(path, lineNo, "inconsistent indentation");
|
|
131
|
+
return { type: "emit", event: record.event, args: record.args };
|
|
351
132
|
}
|
|
352
|
-
|
|
353
|
-
|
|
354
|
-
|
|
355
|
-
|
|
356
|
-
throw new WorkspaceConfigParseError(path, lineNo, `duplicate key "${key}"`);
|
|
357
|
-
map.entries.set(key, node);
|
|
358
|
-
}
|
|
359
|
-
function leadingSpaces(line) {
|
|
360
|
-
let n = 0;
|
|
361
|
-
while (n < line.length && line[n] === " ")
|
|
362
|
-
n++;
|
|
363
|
-
return n;
|
|
364
|
-
}
|
|
365
|
-
function overlayFromTree(tree, path) {
|
|
366
|
-
const overlay = {};
|
|
367
|
-
const theme = tree.entries.get("theme");
|
|
368
|
-
if (theme !== undefined)
|
|
369
|
-
overlay.theme = readStringField(tree, "theme", path);
|
|
370
|
-
const themeMode = tree.entries.get("themeMode");
|
|
371
|
-
if (themeMode !== undefined)
|
|
372
|
-
overlay.themeMode = readStringField(tree, "themeMode", path);
|
|
373
|
-
const model = tree.entries.get("model");
|
|
374
|
-
if (model !== undefined) {
|
|
375
|
-
if (model.kind !== "map") {
|
|
376
|
-
throw new WorkspaceConfigParseError(path, model.line, '"model" must be a block of provider/model/reasoningEffort');
|
|
377
|
-
}
|
|
378
|
-
const prefs = {};
|
|
379
|
-
for (const field of MODEL_FIELDS) {
|
|
380
|
-
const entry = model.entries.get(field);
|
|
381
|
-
if (entry !== undefined)
|
|
382
|
-
prefs[field] = readStringField(model, field, path);
|
|
383
|
-
}
|
|
384
|
-
if (prefs.provider !== undefined || prefs.model !== undefined || prefs.reasoningEffort !== undefined) {
|
|
385
|
-
overlay.model = prefs;
|
|
133
|
+
if (record.type === "waterfall") {
|
|
134
|
+
const request = record.request;
|
|
135
|
+
if (!exactKeys(record, ["type", "event", "eventId", "agentId", "request"]) || typeof record.event !== "string" || record.event.length === 0 || typeof record.eventId !== "string" || record.eventId.length === 0 || typeof record.agentId !== "string" || record.agentId.length === 0 || !isPlainRecord(request) || Object.hasOwn(request, "agent") || Object.hasOwn(request, "signal") || !isRemoteJson(request)) {
|
|
136
|
+
throw new MuxFrameError("$events waterfall item has an invalid frame shape");
|
|
386
137
|
}
|
|
138
|
+
return {
|
|
139
|
+
type: "waterfall",
|
|
140
|
+
event: record.event,
|
|
141
|
+
eventId: record.eventId,
|
|
142
|
+
agentId: record.agentId,
|
|
143
|
+
request
|
|
144
|
+
};
|
|
387
145
|
}
|
|
388
|
-
|
|
389
|
-
}
|
|
390
|
-
function readStringField(parent, key, path) {
|
|
391
|
-
const node = parent.entries.get(key);
|
|
392
|
-
if (node === undefined)
|
|
393
|
-
throw new WorkspaceConfigParseError(path, parent.line, `"${key}" disappeared mid-read`);
|
|
394
|
-
if (node.kind === "null")
|
|
395
|
-
throw new WorkspaceConfigParseError(path, node.line, `"${key}" must be a string value`);
|
|
396
|
-
if (node.kind === "map") {
|
|
397
|
-
throw new WorkspaceConfigParseError(path, node.line, `"${key}" must be a string value, got a nested block`);
|
|
398
|
-
}
|
|
399
|
-
if (!node.quoted && ATOMIC_SCALAR.test(node.text)) {
|
|
400
|
-
throw new WorkspaceConfigParseError(path, node.line, `"${key}" must be a quoted string (bare value reads as non-string)`);
|
|
401
|
-
}
|
|
402
|
-
if (node.text.trim() === "")
|
|
403
|
-
throw new WorkspaceConfigParseError(path, node.line, `"${key}" must be a non-empty string`);
|
|
404
|
-
return node.text;
|
|
146
|
+
throw new MuxFrameError(`unknown $events item type: ${String(record.type)}`);
|
|
405
147
|
}
|
|
406
|
-
function
|
|
407
|
-
if (
|
|
408
|
-
|
|
409
|
-
tree.entries.delete("theme");
|
|
410
|
-
else
|
|
411
|
-
tree.entries.set("theme", mkScalar(overlay.theme, 0, needsQuote(overlay.theme)));
|
|
412
|
-
}
|
|
413
|
-
if (Object.hasOwn(overlay, "themeMode")) {
|
|
414
|
-
if (overlay.themeMode === undefined)
|
|
415
|
-
tree.entries.delete("themeMode");
|
|
416
|
-
else
|
|
417
|
-
tree.entries.set("themeMode", mkScalar(overlay.themeMode, 0, needsQuote(overlay.themeMode)));
|
|
148
|
+
function parseRemoteErrorFields(value) {
|
|
149
|
+
if (!isPlainRecord(value) || !exactKeys(value, ["code", "message", "details"])) {
|
|
150
|
+
throw new MuxFrameError("remote error must carry exactly code, message, details");
|
|
418
151
|
}
|
|
419
|
-
|
|
420
|
-
|
|
421
|
-
|
|
422
|
-
tree.entries.delete("model");
|
|
423
|
-
return;
|
|
152
|
+
const record = value;
|
|
153
|
+
if (typeof record.code !== "string" || typeof record.message !== "string" || !isPlainRecord(record.details)) {
|
|
154
|
+
throw new MuxFrameError("remote error code/message must be strings and details an object");
|
|
424
155
|
}
|
|
425
|
-
|
|
426
|
-
|
|
427
|
-
tree.entries.set("model", block);
|
|
428
|
-
for (const field of MODEL_FIELDS) {
|
|
429
|
-
if (!Object.hasOwn(overlay.model, field))
|
|
430
|
-
continue;
|
|
431
|
-
const value = overlay.model[field];
|
|
432
|
-
if (value === undefined)
|
|
433
|
-
block.entries.delete(field);
|
|
434
|
-
else
|
|
435
|
-
block.entries.set(field, mkScalar(value, 0, needsQuote(value)));
|
|
156
|
+
if (!isRemoteJson(record.details)) {
|
|
157
|
+
throw new MuxFrameError("remote error details must be JSON data");
|
|
436
158
|
}
|
|
437
|
-
|
|
438
|
-
tree.entries.delete("model");
|
|
159
|
+
return record;
|
|
439
160
|
}
|
|
440
|
-
function
|
|
441
|
-
|
|
442
|
-
for (const [key, node] of map.entries) {
|
|
443
|
-
const keyPath = prefix === "" ? key : `${prefix}.${key}`;
|
|
444
|
-
if (isCredentialKey(key))
|
|
445
|
-
throw new WorkspaceConfigCredentialError(keyPath, path);
|
|
446
|
-
if (node.kind === "map")
|
|
447
|
-
visit(node, keyPath);
|
|
448
|
-
}
|
|
449
|
-
};
|
|
450
|
-
visit(tree, "");
|
|
161
|
+
function isRecord(value) {
|
|
162
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
451
163
|
}
|
|
452
|
-
function
|
|
453
|
-
|
|
454
|
-
|
|
455
|
-
|
|
164
|
+
function isPlainRecord(value) {
|
|
165
|
+
if (!isRecord(value))
|
|
166
|
+
return false;
|
|
167
|
+
const prototype = Object.getPrototypeOf(value);
|
|
168
|
+
return prototype === Object.prototype || prototype === null;
|
|
456
169
|
}
|
|
457
|
-
function
|
|
458
|
-
|
|
459
|
-
for (const [key, node] of map.entries) {
|
|
460
|
-
const keyText = needsQuote(key) ? doubleQuote(key) : key;
|
|
461
|
-
if (node.kind === "null" || node.kind === "map" && node.entries.size === 0) {
|
|
462
|
-
out.push(`${pad}${keyText}:`);
|
|
463
|
-
if (node.kind === "map")
|
|
464
|
-
emitMap(node, indent + 2, out);
|
|
465
|
-
continue;
|
|
466
|
-
}
|
|
467
|
-
if (node.kind === "scalar") {
|
|
468
|
-
out.push(`${pad}${keyText}: ${node.quoted ? doubleQuote(node.text) : node.raw}`);
|
|
469
|
-
continue;
|
|
470
|
-
}
|
|
471
|
-
out.push(`${pad}${keyText}:`);
|
|
472
|
-
emitMap(node, indent + 2, out);
|
|
473
|
-
}
|
|
170
|
+
function exactKeys(value, expected) {
|
|
171
|
+
return Reflect.ownKeys(value).length === expected.length && expected.every((key) => Object.hasOwn(value, key));
|
|
474
172
|
}
|
|
475
|
-
function
|
|
476
|
-
if (
|
|
477
|
-
return true;
|
|
478
|
-
if (text !== text.trim())
|
|
479
|
-
return true;
|
|
480
|
-
if (/[\t\r\n]/u.test(text))
|
|
481
|
-
return true;
|
|
482
|
-
if (text.includes(" #"))
|
|
483
|
-
return true;
|
|
484
|
-
if (text.includes(": "))
|
|
485
|
-
return true;
|
|
486
|
-
if (text.endsWith(":"))
|
|
487
|
-
return true;
|
|
488
|
-
if (ATOMIC_SCALAR.test(text))
|
|
173
|
+
function isRemoteJson(value) {
|
|
174
|
+
if (value === null)
|
|
489
175
|
return true;
|
|
490
|
-
const
|
|
491
|
-
if ("
|
|
176
|
+
const kind = typeof value;
|
|
177
|
+
if (kind === "boolean" || kind === "number" || kind === "string")
|
|
492
178
|
return true;
|
|
493
|
-
if (
|
|
494
|
-
return
|
|
179
|
+
if (Array.isArray(value))
|
|
180
|
+
return value.every(isRemoteJson);
|
|
181
|
+
if (isPlainRecord(value))
|
|
182
|
+
return Object.values(value).every(isRemoteJson);
|
|
495
183
|
return false;
|
|
496
184
|
}
|
|
497
|
-
|
|
498
|
-
|
|
185
|
+
var MuxFrameError;
|
|
186
|
+
var init_mux_frame = __esm(() => {
|
|
187
|
+
MuxFrameError = class MuxFrameError extends Error {
|
|
188
|
+
constructor(message, options) {
|
|
189
|
+
super(message, options);
|
|
190
|
+
this.name = "MuxFrameError";
|
|
191
|
+
}
|
|
192
|
+
};
|
|
193
|
+
});
|
|
194
|
+
|
|
195
|
+
// src/client/host-probe.ts
|
|
196
|
+
import { randomUUID } from "crypto";
|
|
197
|
+
import WS from "ws";
|
|
198
|
+
function validAuthority(authority) {
|
|
199
|
+
return typeof authority === "string" && authority.length > 0 && !/[\r\n/]/.test(authority);
|
|
499
200
|
}
|
|
500
|
-
function
|
|
501
|
-
|
|
502
|
-
|
|
503
|
-
|
|
504
|
-
writeFileSync(tmp, doc, { mode: 384 });
|
|
505
|
-
} catch (error) {
|
|
506
|
-
sweepTmp(tmp);
|
|
507
|
-
throw fail(`cannot write config (${error.message}) \u2014 check disk space and directory permissions`);
|
|
508
|
-
}
|
|
201
|
+
async function probeHostHttpStatus(options) {
|
|
202
|
+
if (!validAuthority(options.authority))
|
|
203
|
+
return null;
|
|
204
|
+
const timeoutMs = options.timeoutMs ?? DEFAULT_HOST_PROBE_TIMEOUT_MS;
|
|
509
205
|
try {
|
|
510
|
-
|
|
511
|
-
|
|
512
|
-
|
|
513
|
-
|
|
206
|
+
const response = await fetch(`http://${options.authority}/`, {
|
|
207
|
+
headers: { cookie: options.cookieHeader },
|
|
208
|
+
signal: AbortSignal.timeout(timeoutMs)
|
|
209
|
+
});
|
|
210
|
+
try {
|
|
211
|
+
await response.body?.cancel();
|
|
212
|
+
} catch {}
|
|
213
|
+
return response.status;
|
|
214
|
+
} catch {
|
|
215
|
+
return null;
|
|
514
216
|
}
|
|
515
|
-
try {
|
|
516
|
-
chmodSync(path, 384);
|
|
517
|
-
} catch (error) {
|
|
518
|
-
throw fail(`cannot enforce 0600 permissions (${error.message})`);
|
|
519
|
-
}
|
|
520
|
-
}
|
|
521
|
-
function sweepTmp(tmp) {
|
|
522
|
-
try {
|
|
523
|
-
unlinkSync(tmp);
|
|
524
|
-
} catch {}
|
|
525
|
-
}
|
|
526
|
-
function ensureWritableDir(workspaceDir, configDir) {
|
|
527
|
-
const fail = (message) => new WorkspaceConfigWriteError(configDir, message);
|
|
528
|
-
if (!existsSync(workspaceDir) || !statSync(workspaceDir).isDirectory()) {
|
|
529
|
-
throw new WorkspaceConfigWriteError(workspaceDir, "workspace directory does not exist or is not a directory \u2014 the workspace is the directory the TUI is launched in");
|
|
530
|
-
}
|
|
531
|
-
if (existsSync(configDir)) {
|
|
532
|
-
if (!statSync(configDir).isDirectory()) {
|
|
533
|
-
throw fail("exists but is not a directory \u2014 remove or rename it");
|
|
534
|
-
}
|
|
535
|
-
} else {
|
|
536
|
-
try {
|
|
537
|
-
mkdirSync(configDir, { recursive: true, mode: 448 });
|
|
538
|
-
} catch (error) {
|
|
539
|
-
throw fail(`cannot create directory (${error.message}) \u2014 create it manually or check parent permissions`);
|
|
540
|
-
}
|
|
541
|
-
}
|
|
542
|
-
try {
|
|
543
|
-
accessSync(configDir, constants.W_OK);
|
|
544
|
-
} catch {
|
|
545
|
-
throw fail("is not writable \u2014 fix permissions (chmod u+w) or run from a writable workspace");
|
|
546
|
-
}
|
|
547
|
-
}
|
|
548
|
-
function isNonEmptyString(value) {
|
|
549
|
-
return typeof value === "string" && value.trim() !== "";
|
|
550
|
-
}
|
|
551
|
-
function pickEnv(env, name) {
|
|
552
|
-
const value = env?.[name];
|
|
553
|
-
return nonEmpty(value);
|
|
554
|
-
}
|
|
555
|
-
function nonEmpty(value) {
|
|
556
|
-
return value !== undefined && value.trim() !== "" ? value : undefined;
|
|
557
|
-
}
|
|
558
|
-
var ENV_THEME = "DSH_OPENTUI_THEME", ENV_MODEL = "DSH_OPENTUI_MODEL", CONFIG_DIR = ".dsh", CONFIG_FILE = "config.yml", WorkspaceConfigError, WorkspaceConfigParseError, WorkspaceConfigCredentialError, WorkspaceConfigWriteError, CREDENTIAL_KEY_DENYLIST, MODEL_FIELDS, ATOMIC_SCALAR, FILE_HEADER;
|
|
559
|
-
var init_workspace_config = __esm(() => {
|
|
560
|
-
WorkspaceConfigError = class WorkspaceConfigError extends Error {
|
|
561
|
-
constructor(message) {
|
|
562
|
-
super(message);
|
|
563
|
-
this.name = "WorkspaceConfigError";
|
|
564
|
-
}
|
|
565
|
-
};
|
|
566
|
-
WorkspaceConfigParseError = class WorkspaceConfigParseError extends WorkspaceConfigError {
|
|
567
|
-
path;
|
|
568
|
-
line;
|
|
569
|
-
constructor(path, line, reason) {
|
|
570
|
-
super(`${path}${line === undefined ? "" : `:${line}`}: ${reason}`);
|
|
571
|
-
this.name = "WorkspaceConfigParseError";
|
|
572
|
-
this.path = path;
|
|
573
|
-
this.line = line;
|
|
574
|
-
}
|
|
575
|
-
};
|
|
576
|
-
WorkspaceConfigCredentialError = class WorkspaceConfigCredentialError extends WorkspaceConfigError {
|
|
577
|
-
keyPath;
|
|
578
|
-
constructor(keyPath, where) {
|
|
579
|
-
super(`credential-like key "${keyPath}" in ${where} \u2014 workspace config must never hold credentials ` + "(the file lives next to the working tree and would leak into version control); remove it");
|
|
580
|
-
this.name = "WorkspaceConfigCredentialError";
|
|
581
|
-
this.keyPath = keyPath;
|
|
582
|
-
}
|
|
583
|
-
};
|
|
584
|
-
WorkspaceConfigWriteError = class WorkspaceConfigWriteError extends WorkspaceConfigError {
|
|
585
|
-
path;
|
|
586
|
-
constructor(path, message) {
|
|
587
|
-
super(`${path}: ${message}`);
|
|
588
|
-
this.name = "WorkspaceConfigWriteError";
|
|
589
|
-
this.path = path;
|
|
590
|
-
}
|
|
591
|
-
};
|
|
592
|
-
CREDENTIAL_KEY_DENYLIST = new Set([
|
|
593
|
-
"apikey",
|
|
594
|
-
"apisecret",
|
|
595
|
-
"token",
|
|
596
|
-
"accesstoken",
|
|
597
|
-
"refreshtoken",
|
|
598
|
-
"idtoken",
|
|
599
|
-
"sessiontoken",
|
|
600
|
-
"secret",
|
|
601
|
-
"secretkey",
|
|
602
|
-
"clientsecret",
|
|
603
|
-
"privatekey",
|
|
604
|
-
"password",
|
|
605
|
-
"passwd",
|
|
606
|
-
"credential",
|
|
607
|
-
"credentials",
|
|
608
|
-
"auth",
|
|
609
|
-
"authorization",
|
|
610
|
-
"cookie",
|
|
611
|
-
"bearer",
|
|
612
|
-
"sessionkey",
|
|
613
|
-
"signingkey"
|
|
614
|
-
]);
|
|
615
|
-
MODEL_FIELDS = ["provider", "model", "reasoningEffort"];
|
|
616
|
-
ATOMIC_SCALAR = /^(?:~|null|Null|NULL|true|True|TRUE|false|False|FALSE|yes|Yes|YES|no|No|NO|on|On|ON|off|Off|OFF|[-+]?(?:\d+|\d+\.\d+|\.\d+)(?:[eE][-+]?\d+)?|[-+]?(?:inf|Inf|INF)|\.nan|\.NaN|\.NAN)$/u;
|
|
617
|
-
FILE_HEADER = `# dsh-opentui workspace-local config \u2014 theme + model preferences ONLY.
|
|
618
|
-
` + `# Credentials and plugin installs must NEVER live in this file (it would
|
|
619
|
-
` + `# leak into version control). Unknown keys are preserved on rewrite.
|
|
620
|
-
`;
|
|
621
|
-
});
|
|
622
|
-
|
|
623
|
-
// src/client/boot-shared.ts
|
|
624
|
-
var exports_boot_shared = {};
|
|
625
|
-
__export(exports_boot_shared, {
|
|
626
|
-
BOOT_LABEL_BUDGET_MS: () => BOOT_LABEL_BUDGET_MS,
|
|
627
|
-
ENV_MOTION: () => ENV_MOTION,
|
|
628
|
-
ENV_THEME: () => ENV_THEME,
|
|
629
|
-
SHUTDOWN_GRACE_MS: () => SHUTDOWN_GRACE_MS,
|
|
630
|
-
SKIN_MIGRATION_NOTICE: () => SKIN_MIGRATION_NOTICE,
|
|
631
|
-
SKIN_MIGRATION_THEME: () => SKIN_MIGRATION_THEME,
|
|
632
|
-
bootCallOrder: () => bootCallOrder,
|
|
633
|
-
clientErrorLogPath: () => clientErrorLogPath,
|
|
634
|
-
defaultSpawnReaper: () => defaultSpawnReaper,
|
|
635
|
-
hostLockPath: () => hostLockPath,
|
|
636
|
-
installClientErrorLog: () => installClientErrorLog,
|
|
637
|
-
installExitPaths: () => installExitPaths,
|
|
638
|
-
motionFromConfig: () => motionFromConfig,
|
|
639
|
-
resolveReaperScript: () => resolveReaperScript,
|
|
640
|
-
skinMigrationPlan: () => skinMigrationPlan,
|
|
641
|
-
spawnIdleReaper: () => spawnIdleReaper,
|
|
642
|
-
themeModeFromConfig: () => themeModeFromConfig,
|
|
643
|
-
themeNameFromConfig: () => themeNameFromConfig
|
|
644
|
-
});
|
|
645
|
-
import { join as join2 } from "path";
|
|
646
|
-
import { appendFileSync, existsSync as existsSync2 } from "fs";
|
|
647
|
-
import { spawn } from "child_process";
|
|
648
|
-
function installExitPaths(shutdown, target = process, graceMs = SHUTDOWN_GRACE_MS) {
|
|
649
|
-
const realExit = target.exit.bind(target);
|
|
650
|
-
const exitAfterShutdown = (code) => {
|
|
651
|
-
Promise.race([
|
|
652
|
-
shutdown(),
|
|
653
|
-
new Promise((resolve) => setTimeout(resolve, graceMs))
|
|
654
|
-
]).then(() => realExit(code));
|
|
655
|
-
};
|
|
656
|
-
target.exit = (code) => exitAfterShutdown(code);
|
|
657
|
-
for (const signal of ["SIGINT", "SIGTERM", "SIGHUP"]) {
|
|
658
|
-
target.on(signal, () => exitAfterShutdown(0));
|
|
659
|
-
}
|
|
660
|
-
}
|
|
661
|
-
function hostLockPath(dshHome, profile) {
|
|
662
|
-
return join2(dshHome, `opentui-host.${profile}.json`);
|
|
663
|
-
}
|
|
664
|
-
function clientErrorLogPath(dshHome) {
|
|
665
|
-
return join2(dshHome, "opentui-client.errors.log");
|
|
666
|
-
}
|
|
667
|
-
function installClientErrorLog(dshHome, target = process) {
|
|
668
|
-
const logPath = clientErrorLogPath(dshHome);
|
|
669
|
-
const record = (kind, error) => {
|
|
670
|
-
const message = error instanceof Error ? error.stack ?? error.message : String(error);
|
|
671
|
-
const line = `${new Date().toISOString()} kind=${kind} pid=${process.pid}
|
|
672
|
-
${message}
|
|
673
|
-
|
|
674
|
-
`;
|
|
675
|
-
try {
|
|
676
|
-
appendFileSync(logPath, line);
|
|
677
|
-
} catch {}
|
|
678
|
-
try {
|
|
679
|
-
process.stderr.write(`[dsh-opentui] ${kind}: ${message.split(`
|
|
680
|
-
`)[0]}
|
|
681
|
-
`);
|
|
682
|
-
} catch {}
|
|
683
|
-
};
|
|
684
|
-
target.on("unhandledRejection", (reason) => {
|
|
685
|
-
record("unhandledRejection", reason);
|
|
686
|
-
});
|
|
687
|
-
target.on("uncaughtException", (error) => {
|
|
688
|
-
record("uncaughtException", error);
|
|
689
|
-
target.exit(1);
|
|
690
|
-
});
|
|
691
|
-
}
|
|
692
|
-
function resolveReaperScript() {
|
|
693
|
-
const candidates = [
|
|
694
|
-
join2(import.meta.dir, "..", "scripts", "idle-reaper.mjs"),
|
|
695
|
-
join2(import.meta.dir, "..", "..", "scripts", "idle-reaper.mjs")
|
|
696
|
-
];
|
|
697
|
-
for (const candidate of candidates) {
|
|
698
|
-
if (existsSync2(candidate))
|
|
699
|
-
return candidate;
|
|
700
|
-
}
|
|
701
|
-
throw new Error(`idle-reaper.mjs not found (looked in: ${candidates.join(", ")})`);
|
|
702
|
-
}
|
|
703
|
-
function defaultSpawnReaper(args) {
|
|
704
|
-
const script = resolveReaperScript();
|
|
705
|
-
const child = spawn(process.execPath, [script, String(args.pid), String(args.port), args.lockPath, String(args.idleMs)], {
|
|
706
|
-
detached: true,
|
|
707
|
-
stdio: "ignore"
|
|
708
|
-
});
|
|
709
|
-
child.unref?.();
|
|
710
|
-
}
|
|
711
|
-
function spawnIdleReaper(host, idleMs, spawnReaper = defaultSpawnReaper) {
|
|
712
|
-
if (!(idleMs > 0))
|
|
713
|
-
return;
|
|
714
|
-
try {
|
|
715
|
-
spawnReaper({
|
|
716
|
-
pid: host.pid,
|
|
717
|
-
port: host.port,
|
|
718
|
-
lockPath: hostLockPath(host.dshHome, host.profile),
|
|
719
|
-
idleMs
|
|
720
|
-
});
|
|
721
|
-
} catch (error) {
|
|
722
|
-
console.error("[client-entry] idle reaper spawn failed:", error);
|
|
723
|
-
}
|
|
724
|
-
}
|
|
725
|
-
function themeNameFromConfig(session) {
|
|
726
|
-
try {
|
|
727
|
-
const theme = session.configLoad().theme;
|
|
728
|
-
return typeof theme === "string" && theme ? theme : undefined;
|
|
729
|
-
} catch {
|
|
730
|
-
return;
|
|
731
|
-
}
|
|
732
|
-
}
|
|
733
|
-
function themeModeFromConfig(session) {
|
|
734
|
-
try {
|
|
735
|
-
const mode = session.configLoad().themeMode;
|
|
736
|
-
return mode === "dark" || mode === "light" ? mode : undefined;
|
|
737
|
-
} catch {
|
|
738
|
-
return;
|
|
739
|
-
}
|
|
740
|
-
}
|
|
741
|
-
function motionFromConfig(session) {
|
|
742
|
-
try {
|
|
743
|
-
const motion = session.configLoad().motion;
|
|
744
|
-
return typeof motion === "string" && motion ? motion : undefined;
|
|
745
|
-
} catch {
|
|
746
|
-
return;
|
|
747
|
-
}
|
|
748
|
-
}
|
|
749
|
-
function storedTheme(value) {
|
|
750
|
-
return typeof value === "string" && value.length > 0 ? value : undefined;
|
|
751
|
-
}
|
|
752
|
-
function skinMigrationPlan(input) {
|
|
753
|
-
if (storedTheme(input.envTheme) !== undefined)
|
|
754
|
-
return;
|
|
755
|
-
if (input.profileConfig.skinMigration !== undefined)
|
|
756
|
-
return;
|
|
757
|
-
const workspaceTheme = storedTheme(input.workspaceConfig.theme);
|
|
758
|
-
if (workspaceTheme !== undefined && workspaceTheme !== SKIN_MIGRATION_THEME) {
|
|
759
|
-
return { layer: "workspace", theme: SKIN_MIGRATION_THEME, skinMigration: 1, notice: SKIN_MIGRATION_NOTICE };
|
|
760
|
-
}
|
|
761
|
-
const profileTheme = storedTheme(input.profileConfig.theme);
|
|
762
|
-
if (profileTheme !== undefined && profileTheme !== SKIN_MIGRATION_THEME) {
|
|
763
|
-
return { layer: "profile", theme: SKIN_MIGRATION_THEME, skinMigration: 1, notice: SKIN_MIGRATION_NOTICE };
|
|
764
|
-
}
|
|
765
|
-
return;
|
|
766
|
-
}
|
|
767
|
-
var SHUTDOWN_GRACE_MS = 2500, BOOT_LABEL_BUDGET_MS = 4000, bootCallOrder, ENV_MOTION = "DSH_OPENTUI_MOTION", SKIN_MIGRATION_THEME = "dsh-blue", SKIN_MIGRATION_NOTICE = "Theme switched to dsh-blue (new default). Use /theme to switch back.";
|
|
768
|
-
var init_boot_shared = __esm(() => {
|
|
769
|
-
init_workspace_config();
|
|
770
|
-
bootCallOrder = [];
|
|
771
|
-
});
|
|
772
|
-
|
|
773
|
-
// src/client/mux-frame.ts
|
|
774
|
-
function openEventsStreamFrame(streamId) {
|
|
775
|
-
return { type: "open", streamId, endpoint: "$events", payload: { args: {} } };
|
|
776
|
-
}
|
|
777
|
-
function parseMuxFrame(text) {
|
|
778
|
-
let decoded;
|
|
779
|
-
try {
|
|
780
|
-
decoded = JSON.parse(text);
|
|
781
|
-
} catch (cause) {
|
|
782
|
-
throw new MuxFrameError("mux frame is not JSON", { cause });
|
|
783
|
-
}
|
|
784
|
-
if (!isRecord(decoded))
|
|
785
|
-
throw new MuxFrameError("mux frame must be an object");
|
|
786
|
-
const value = decoded;
|
|
787
|
-
const type = value.type;
|
|
788
|
-
const streamId = value.streamId;
|
|
789
|
-
if (typeof streamId !== "string" || streamId.length === 0) {
|
|
790
|
-
throw new MuxFrameError("mux frame streamId is missing or empty");
|
|
791
|
-
}
|
|
792
|
-
if (type === "item") {
|
|
793
|
-
if (!exactKeys(value, ["type", "streamId"]) && !exactKeys(value, ["type", "streamId", "value"])) {
|
|
794
|
-
throw new MuxFrameError("item frame must carry exactly type, streamId [, value]");
|
|
795
|
-
}
|
|
796
|
-
return { type: "item", streamId, value: value.value };
|
|
797
|
-
}
|
|
798
|
-
if (type === "end") {
|
|
799
|
-
if (!exactKeys(value, ["type", "streamId"])) {
|
|
800
|
-
throw new MuxFrameError("end frame must carry exactly type, streamId");
|
|
801
|
-
}
|
|
802
|
-
return { type: "end", streamId };
|
|
803
|
-
}
|
|
804
|
-
if (type === "error") {
|
|
805
|
-
if (!exactKeys(value, ["type", "streamId", "error"])) {
|
|
806
|
-
throw new MuxFrameError("error frame must carry exactly type, streamId, error");
|
|
807
|
-
}
|
|
808
|
-
return { type: "error", streamId, error: parseRemoteErrorFields(value.error) };
|
|
809
|
-
}
|
|
810
|
-
throw new MuxFrameError(`unknown mux frame type: ${String(type)}`);
|
|
811
|
-
}
|
|
812
|
-
function parseEventsReady(value) {
|
|
813
|
-
if (!isPlainRecord(value) || !exactKeys(value, ["type", "clientId", "host"])) {
|
|
814
|
-
throw new MuxFrameError("$events opening item must carry exactly type, clientId, host");
|
|
815
|
-
}
|
|
816
|
-
const record = value;
|
|
817
|
-
if (record.type !== "ready") {
|
|
818
|
-
throw new MuxFrameError(`$events opening item must be ready, got: ${String(record.type)}`);
|
|
819
|
-
}
|
|
820
|
-
if (typeof record.clientId !== "string" || record.clientId.length === 0) {
|
|
821
|
-
throw new MuxFrameError("$events ready clientId must be a non-empty string");
|
|
822
|
-
}
|
|
823
|
-
const host = record.host;
|
|
824
|
-
if (!isPlainRecord(host) || !exactKeys(host, ["home"]) || typeof host.home !== "string") {
|
|
825
|
-
throw new MuxFrameError("$events ready host must carry exactly home: string");
|
|
826
|
-
}
|
|
827
|
-
return { type: "ready", clientId: record.clientId, host: { home: host.home } };
|
|
828
|
-
}
|
|
829
|
-
function parseEventsItem(value) {
|
|
830
|
-
if (!isPlainRecord(value))
|
|
831
|
-
throw new MuxFrameError("$events item must be a plain object");
|
|
832
|
-
const record = value;
|
|
833
|
-
if (record.type === "cancel") {
|
|
834
|
-
if (!exactKeys(record, ["type", "eventId"]) || typeof record.eventId !== "string" || record.eventId.length === 0) {
|
|
835
|
-
throw new MuxFrameError("$events cancel item must carry exactly type, eventId: string");
|
|
836
|
-
}
|
|
837
|
-
return { type: "cancel", eventId: record.eventId };
|
|
838
|
-
}
|
|
839
|
-
if (record.type === "emit") {
|
|
840
|
-
if (!exactKeys(record, ["type", "event", "args"]) || typeof record.event !== "string" || record.event.length === 0 || !Array.isArray(record.args) || !isRemoteJson(record.args)) {
|
|
841
|
-
throw new MuxFrameError("$events emit item must carry exactly type, event: string, args: JSON[]");
|
|
842
|
-
}
|
|
843
|
-
return { type: "emit", event: record.event, args: record.args };
|
|
844
|
-
}
|
|
845
|
-
if (record.type === "waterfall") {
|
|
846
|
-
const request = record.request;
|
|
847
|
-
if (!exactKeys(record, ["type", "event", "eventId", "agentId", "request"]) || typeof record.event !== "string" || record.event.length === 0 || typeof record.eventId !== "string" || record.eventId.length === 0 || typeof record.agentId !== "string" || record.agentId.length === 0 || !isPlainRecord(request) || Object.hasOwn(request, "agent") || Object.hasOwn(request, "signal") || !isRemoteJson(request)) {
|
|
848
|
-
throw new MuxFrameError("$events waterfall item has an invalid frame shape");
|
|
849
|
-
}
|
|
850
|
-
return {
|
|
851
|
-
type: "waterfall",
|
|
852
|
-
event: record.event,
|
|
853
|
-
eventId: record.eventId,
|
|
854
|
-
agentId: record.agentId,
|
|
855
|
-
request
|
|
856
|
-
};
|
|
857
|
-
}
|
|
858
|
-
throw new MuxFrameError(`unknown $events item type: ${String(record.type)}`);
|
|
859
|
-
}
|
|
860
|
-
function parseRemoteErrorFields(value) {
|
|
861
|
-
if (!isPlainRecord(value) || !exactKeys(value, ["code", "message", "details"])) {
|
|
862
|
-
throw new MuxFrameError("remote error must carry exactly code, message, details");
|
|
863
|
-
}
|
|
864
|
-
const record = value;
|
|
865
|
-
if (typeof record.code !== "string" || typeof record.message !== "string" || !isPlainRecord(record.details)) {
|
|
866
|
-
throw new MuxFrameError("remote error code/message must be strings and details an object");
|
|
867
|
-
}
|
|
868
|
-
if (!isRemoteJson(record.details)) {
|
|
869
|
-
throw new MuxFrameError("remote error details must be JSON data");
|
|
870
|
-
}
|
|
871
|
-
return record;
|
|
872
|
-
}
|
|
873
|
-
function isRecord(value) {
|
|
874
|
-
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
875
|
-
}
|
|
876
|
-
function isPlainRecord(value) {
|
|
877
|
-
if (!isRecord(value))
|
|
878
|
-
return false;
|
|
879
|
-
const prototype = Object.getPrototypeOf(value);
|
|
880
|
-
return prototype === Object.prototype || prototype === null;
|
|
881
|
-
}
|
|
882
|
-
function exactKeys(value, expected) {
|
|
883
|
-
return Reflect.ownKeys(value).length === expected.length && expected.every((key) => Object.hasOwn(value, key));
|
|
884
|
-
}
|
|
885
|
-
function isRemoteJson(value) {
|
|
886
|
-
if (value === null)
|
|
887
|
-
return true;
|
|
888
|
-
const kind = typeof value;
|
|
889
|
-
if (kind === "boolean" || kind === "number" || kind === "string")
|
|
890
|
-
return true;
|
|
891
|
-
if (Array.isArray(value))
|
|
892
|
-
return value.every(isRemoteJson);
|
|
893
|
-
if (isPlainRecord(value))
|
|
894
|
-
return Object.values(value).every(isRemoteJson);
|
|
895
|
-
return false;
|
|
896
|
-
}
|
|
897
|
-
var MuxFrameError;
|
|
898
|
-
var init_mux_frame = __esm(() => {
|
|
899
|
-
MuxFrameError = class MuxFrameError extends Error {
|
|
900
|
-
constructor(message, options) {
|
|
901
|
-
super(message, options);
|
|
902
|
-
this.name = "MuxFrameError";
|
|
903
|
-
}
|
|
904
|
-
};
|
|
905
|
-
});
|
|
906
|
-
|
|
907
|
-
// src/client/host-probe.ts
|
|
908
|
-
import { randomUUID } from "crypto";
|
|
909
|
-
import WS from "ws";
|
|
910
|
-
function validAuthority(authority) {
|
|
911
|
-
return typeof authority === "string" && authority.length > 0 && !/[\r\n/]/.test(authority);
|
|
912
217
|
}
|
|
913
218
|
async function probeHostHttp(options) {
|
|
914
|
-
|
|
915
|
-
|
|
916
|
-
const timeoutMs = options.timeoutMs ?? DEFAULT_HOST_PROBE_TIMEOUT_MS;
|
|
917
|
-
try {
|
|
918
|
-
const response = await fetch(`http://${options.authority}/`, {
|
|
919
|
-
headers: { cookie: options.cookieHeader },
|
|
920
|
-
signal: AbortSignal.timeout(timeoutMs)
|
|
921
|
-
});
|
|
922
|
-
try {
|
|
923
|
-
await response.body?.cancel();
|
|
924
|
-
} catch {}
|
|
925
|
-
return response.status >= 200 && response.status < 400;
|
|
926
|
-
} catch {
|
|
927
|
-
return false;
|
|
928
|
-
}
|
|
219
|
+
const status = await probeHostHttpStatus(options);
|
|
220
|
+
return status !== null && status >= 200 && status < 400;
|
|
929
221
|
}
|
|
930
222
|
async function probeHostMux(options) {
|
|
931
223
|
if (!validAuthority(options.authority))
|
|
@@ -942,9 +234,10 @@ async function probeHostMux(options) {
|
|
|
942
234
|
settled = true;
|
|
943
235
|
clearTimeout(timer);
|
|
944
236
|
try {
|
|
945
|
-
socket
|
|
237
|
+
const teardown = socket;
|
|
238
|
+
teardown?.removeAllListeners();
|
|
946
239
|
socket?.on("error", () => {});
|
|
947
|
-
|
|
240
|
+
teardown?.terminate();
|
|
948
241
|
} catch {}
|
|
949
242
|
resolve(ok);
|
|
950
243
|
}
|
|
@@ -990,14 +283,14 @@ var init_host_probe = __esm(() => {
|
|
|
990
283
|
});
|
|
991
284
|
|
|
992
285
|
// src/client/append-system.ts
|
|
993
|
-
import { chmodSync
|
|
286
|
+
import { chmodSync, mkdirSync, readFileSync, renameSync, unlinkSync, writeFileSync } from "fs";
|
|
994
287
|
import { homedir } from "os";
|
|
995
|
-
import { join
|
|
288
|
+
import { join } from "path";
|
|
996
289
|
function defaultDshHome() {
|
|
997
|
-
return process.env.DSH_HOME ||
|
|
290
|
+
return process.env.DSH_HOME || join(homedir(), ".dsh");
|
|
998
291
|
}
|
|
999
292
|
function appendSystemPath(home = defaultDshHome()) {
|
|
1000
|
-
return
|
|
293
|
+
return join(home, "APPEND_SYSTEM.md");
|
|
1001
294
|
}
|
|
1002
295
|
function appendSystemPresetBlock() {
|
|
1003
296
|
return `${APPEND_SYSTEM_MARKER} \u2014 managed block (client-owned; the client appends it once and never rewrites other lines).
|
|
@@ -1142,32 +435,32 @@ ${APPEND_SYSTEM_MARKER} persona suffix = $DSH_HOME/APPEND_SYSTEM.md, evaluated b
|
|
|
1142
435
|
`;
|
|
1143
436
|
}
|
|
1144
437
|
function writeAtomically(path, content, mode) {
|
|
1145
|
-
|
|
438
|
+
mkdirSync(join(path, ".."), { recursive: true });
|
|
1146
439
|
const tmp = `${path}.${process.pid}.tmp`;
|
|
1147
440
|
try {
|
|
1148
|
-
|
|
1149
|
-
|
|
441
|
+
writeFileSync(tmp, content, { mode });
|
|
442
|
+
renameSync(tmp, path);
|
|
1150
443
|
} catch (error) {
|
|
1151
444
|
try {
|
|
1152
|
-
|
|
445
|
+
unlinkSync(tmp);
|
|
1153
446
|
} catch {}
|
|
1154
447
|
throw error;
|
|
1155
448
|
}
|
|
1156
449
|
}
|
|
1157
450
|
function ensureAppendSystemFile(path = appendSystemPath()) {
|
|
1158
451
|
try {
|
|
1159
|
-
|
|
452
|
+
readFileSync(path, "utf8");
|
|
1160
453
|
return "kept";
|
|
1161
454
|
} catch {
|
|
1162
455
|
writeAtomically(path, APPEND_SYSTEM_TEMPLATE, 420);
|
|
1163
456
|
try {
|
|
1164
|
-
|
|
457
|
+
chmodSync(path, 420);
|
|
1165
458
|
} catch {}
|
|
1166
459
|
return "seeded";
|
|
1167
460
|
}
|
|
1168
461
|
}
|
|
1169
462
|
function profilePatchPath(home, profile) {
|
|
1170
|
-
return
|
|
463
|
+
return join(home, "profiles", profile, "cordis.patch.yml");
|
|
1171
464
|
}
|
|
1172
465
|
function managedSpan(lines) {
|
|
1173
466
|
const start = lines.findIndex((line) => line.startsWith(APPEND_SYSTEM_MARKER));
|
|
@@ -1190,7 +483,7 @@ function managedSpan(lines) {
|
|
|
1190
483
|
function provisionAppendSystem(home, profile) {
|
|
1191
484
|
let preText;
|
|
1192
485
|
try {
|
|
1193
|
-
preText =
|
|
486
|
+
preText = readFileSync(profilePatchPath(home, profile), "utf8");
|
|
1194
487
|
} catch {
|
|
1195
488
|
preText = undefined;
|
|
1196
489
|
}
|
|
@@ -1205,7 +498,7 @@ function syncAppendSystemPreset(home, profile) {
|
|
|
1205
498
|
const path = profilePatchPath(home, profile);
|
|
1206
499
|
let before;
|
|
1207
500
|
try {
|
|
1208
|
-
before =
|
|
501
|
+
before = readFileSync(path, "utf8");
|
|
1209
502
|
} catch {
|
|
1210
503
|
return { status: "skipped", detail: `no profile patch at ${path}` };
|
|
1211
504
|
}
|
|
@@ -1262,10 +555,137 @@ var init_append_system = __esm(() => {
|
|
|
1262
555
|
APPEND_SYSTEM_ROW_ID = `preset-${APPEND_SYSTEM_PRESET_ID}`;
|
|
1263
556
|
});
|
|
1264
557
|
|
|
558
|
+
// src/client/safe-kill.ts
|
|
559
|
+
import { spawnSync } from "child_process";
|
|
560
|
+
function psStat(pid) {
|
|
561
|
+
try {
|
|
562
|
+
const result = spawnSync("ps", ["-p", String(pid), "-o", "stat="], { encoding: "utf8" });
|
|
563
|
+
if (result.error || result.status !== 0)
|
|
564
|
+
return null;
|
|
565
|
+
return (result.stdout ?? "").trim() || null;
|
|
566
|
+
} catch {
|
|
567
|
+
return null;
|
|
568
|
+
}
|
|
569
|
+
}
|
|
570
|
+
function statIsZombie(stat) {
|
|
571
|
+
return stat.startsWith("Z");
|
|
572
|
+
}
|
|
573
|
+
function defaultPidAlive(pid) {
|
|
574
|
+
try {
|
|
575
|
+
process.kill(pid, 0);
|
|
576
|
+
} catch (err) {
|
|
577
|
+
return err.code === "EPERM";
|
|
578
|
+
}
|
|
579
|
+
const stat = psStat(pid);
|
|
580
|
+
if (stat !== null && statIsZombie(stat))
|
|
581
|
+
return false;
|
|
582
|
+
return true;
|
|
583
|
+
}
|
|
584
|
+
function evidencesAgree(pid, registryPid, hooks) {
|
|
585
|
+
if (!Number.isInteger(pid) || pid <= 0)
|
|
586
|
+
return false;
|
|
587
|
+
if (registryPid !== pid)
|
|
588
|
+
return false;
|
|
589
|
+
const cmd = hooks.cmdline(pid);
|
|
590
|
+
if (!cmd)
|
|
591
|
+
return false;
|
|
592
|
+
const profiles = [...cmd.matchAll(/--profile[= ]+([^\s]+)/g)].map((m) => m[1]);
|
|
593
|
+
if (profiles.length === 0 || profiles.some((p) => p !== HOST_PROFILE))
|
|
594
|
+
return false;
|
|
595
|
+
if (hooks.hasServerEnv(pid))
|
|
596
|
+
return true;
|
|
597
|
+
if (hooks.envReadable && !hooks.envReadable(pid)) {
|
|
598
|
+
hooks.onEnvFallback?.(pid);
|
|
599
|
+
return true;
|
|
600
|
+
}
|
|
601
|
+
return false;
|
|
602
|
+
}
|
|
603
|
+
async function waitGone(pid, budgetMs, alive, sleep, now) {
|
|
604
|
+
if (!alive(pid))
|
|
605
|
+
return true;
|
|
606
|
+
const deadline = now() + budgetMs;
|
|
607
|
+
const maxIterations = Math.max(1, Math.ceil(budgetMs / DEFAULT_EXIT_POLL_MS) + 8);
|
|
608
|
+
for (let i = 0;i < maxIterations && now() < deadline; i++) {
|
|
609
|
+
await sleep(DEFAULT_EXIT_POLL_MS);
|
|
610
|
+
if (!alive(pid))
|
|
611
|
+
return true;
|
|
612
|
+
}
|
|
613
|
+
return !alive(pid);
|
|
614
|
+
}
|
|
615
|
+
async function safeStopHost(options) {
|
|
616
|
+
const {
|
|
617
|
+
pid,
|
|
618
|
+
registryPid,
|
|
619
|
+
hooks,
|
|
620
|
+
termGraceMs = DEFAULT_TERM_GRACE_MS,
|
|
621
|
+
killGraceMs = DEFAULT_KILL_GRACE_MS,
|
|
622
|
+
sleep = defaultSleep,
|
|
623
|
+
pidAlive = hooks.pidAlive ?? defaultPidAlive,
|
|
624
|
+
now = Date.now
|
|
625
|
+
} = options;
|
|
626
|
+
if (!evidencesAgree(pid, registryPid, hooks)) {
|
|
627
|
+
return { attempted: false, evidencesOk: false, signals: [], stopped: !pidAlive(pid) };
|
|
628
|
+
}
|
|
629
|
+
const signals = [];
|
|
630
|
+
hooks.kill(pid, "SIGTERM");
|
|
631
|
+
signals.push("SIGTERM");
|
|
632
|
+
if (await waitGone(pid, termGraceMs, pidAlive, sleep, now)) {
|
|
633
|
+
return { attempted: true, evidencesOk: true, signals, stopped: true };
|
|
634
|
+
}
|
|
635
|
+
hooks.kill(pid, "SIGKILL");
|
|
636
|
+
signals.push("SIGKILL");
|
|
637
|
+
const stopped = await waitGone(pid, killGraceMs, pidAlive, sleep, now);
|
|
638
|
+
return { attempted: true, evidencesOk: true, signals, stopped };
|
|
639
|
+
}
|
|
640
|
+
var SERVER_ENV_NAME = "DSH_OPENTUI_SERVER", SERVER_ENV_VALUE = "1", HOST_PROFILE = "opentui", DEFAULT_TERM_GRACE_MS = 5000, DEFAULT_KILL_GRACE_MS = 2000, DEFAULT_EXIT_POLL_MS = 50, psKillHooks, defaultSleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
|
|
641
|
+
var init_safe_kill = __esm(() => {
|
|
642
|
+
psKillHooks = {
|
|
643
|
+
cmdline(pid) {
|
|
644
|
+
try {
|
|
645
|
+
return spawnSync("ps", ["-p", String(pid), "-o", "command="], { encoding: "utf8" }).stdout?.trim() || null;
|
|
646
|
+
} catch {
|
|
647
|
+
return null;
|
|
648
|
+
}
|
|
649
|
+
},
|
|
650
|
+
hasServerEnv(pid) {
|
|
651
|
+
try {
|
|
652
|
+
const out = spawnSync("ps", ["eww", "-p", String(pid), "-o", "command="], { encoding: "utf8" }).stdout ?? "";
|
|
653
|
+
return out.includes(`${SERVER_ENV_NAME}=${SERVER_ENV_VALUE}`);
|
|
654
|
+
} catch {
|
|
655
|
+
return false;
|
|
656
|
+
}
|
|
657
|
+
},
|
|
658
|
+
envReadable(pid) {
|
|
659
|
+
try {
|
|
660
|
+
const result = spawnSync("ps", ["eww", "-p", String(pid), "-o", "command="], { encoding: "utf8" });
|
|
661
|
+
if (result.error || result.status !== null && result.status !== 0)
|
|
662
|
+
return false;
|
|
663
|
+
const out = (result.stdout ?? "").trim();
|
|
664
|
+
if (!out || out.includes("<defunct>"))
|
|
665
|
+
return false;
|
|
666
|
+
const stat = psStat(pid);
|
|
667
|
+
if (stat !== null && statIsZombie(stat))
|
|
668
|
+
return false;
|
|
669
|
+
return true;
|
|
670
|
+
} catch {
|
|
671
|
+
return false;
|
|
672
|
+
}
|
|
673
|
+
},
|
|
674
|
+
onEnvFallback(pid) {
|
|
675
|
+
console.warn(`[safe-kill] ${SERVER_ENV_NAME} env unreadable for pid ${pid}; ` + `using registry + cmdline two-evidence fallback (no "dsh" match)`);
|
|
676
|
+
},
|
|
677
|
+
kill(pid, signal) {
|
|
678
|
+
try {
|
|
679
|
+
process.kill(pid, signal);
|
|
680
|
+
} catch {}
|
|
681
|
+
}
|
|
682
|
+
};
|
|
683
|
+
});
|
|
684
|
+
|
|
1265
685
|
// src/client/cookie-mint.ts
|
|
1266
686
|
import { createHash, createHmac } from "crypto";
|
|
1267
|
-
import { readFileSync as
|
|
1268
|
-
import { join as
|
|
687
|
+
import { readFileSync as readFileSync2, statSync } from "fs";
|
|
688
|
+
import { join as join2 } from "path";
|
|
1269
689
|
function ownerCookieName(authority) {
|
|
1270
690
|
return "dsh-auth-" + base64url(createHash("sha256").update(authority).digest());
|
|
1271
691
|
}
|
|
@@ -1283,14 +703,14 @@ function mintOwnerCookie(options) {
|
|
|
1283
703
|
return `${ownerCookieName(authority)}=v1.${body}.${signature}`;
|
|
1284
704
|
}
|
|
1285
705
|
function readGrantSecret(home) {
|
|
1286
|
-
const path =
|
|
706
|
+
const path = join2(home, ".credentials.yaml");
|
|
1287
707
|
const deadline = Date.now() + RETRY_WINDOW_MS;
|
|
1288
708
|
let sawFile = false;
|
|
1289
709
|
while (true) {
|
|
1290
710
|
let file = "";
|
|
1291
711
|
try {
|
|
1292
712
|
assertOwnerOnly(path);
|
|
1293
|
-
file =
|
|
713
|
+
file = readFileSync2(path, "utf8");
|
|
1294
714
|
sawFile = true;
|
|
1295
715
|
} catch (error) {
|
|
1296
716
|
if (error instanceof CredentialsFileInsecureError)
|
|
@@ -1314,7 +734,7 @@ function readGrantSecret(home) {
|
|
|
1314
734
|
function assertOwnerOnly(path) {
|
|
1315
735
|
let mode;
|
|
1316
736
|
try {
|
|
1317
|
-
mode =
|
|
737
|
+
mode = statSync(path).mode;
|
|
1318
738
|
} catch {
|
|
1319
739
|
return;
|
|
1320
740
|
}
|
|
@@ -1389,7 +809,7 @@ function blockRange(lines, from, atIndent) {
|
|
|
1389
809
|
const line = lines[i];
|
|
1390
810
|
if (!line.trim() || line.trimStart().startsWith("#"))
|
|
1391
811
|
continue;
|
|
1392
|
-
if (
|
|
812
|
+
if (leadingSpaces(line) < atIndent)
|
|
1393
813
|
break;
|
|
1394
814
|
if (start === -1)
|
|
1395
815
|
start = i;
|
|
@@ -1397,17 +817,17 @@ function blockRange(lines, from, atIndent) {
|
|
|
1397
817
|
return { start: start === -1 ? lines.length : start, end: i };
|
|
1398
818
|
}
|
|
1399
819
|
function nextChildIndent(lines, entryLine) {
|
|
1400
|
-
const parentIndent =
|
|
820
|
+
const parentIndent = leadingSpaces(lines[entryLine]);
|
|
1401
821
|
for (let i = entryLine + 1;i < lines.length; i++) {
|
|
1402
822
|
const line = lines[i];
|
|
1403
823
|
if (!line.trim() || line.trimStart().startsWith("#"))
|
|
1404
824
|
continue;
|
|
1405
|
-
const indent =
|
|
825
|
+
const indent = leadingSpaces(line);
|
|
1406
826
|
return indent > parentIndent ? indent : -1;
|
|
1407
827
|
}
|
|
1408
828
|
return -1;
|
|
1409
829
|
}
|
|
1410
|
-
function
|
|
830
|
+
function leadingSpaces(line) {
|
|
1411
831
|
let n = 0;
|
|
1412
832
|
while (n < line.length && line[n] === " ")
|
|
1413
833
|
n++;
|
|
@@ -1419,7 +839,7 @@ function parseEntryLine(line) {
|
|
|
1419
839
|
return;
|
|
1420
840
|
if (line.includes("\t"))
|
|
1421
841
|
return;
|
|
1422
|
-
const indent =
|
|
842
|
+
const indent = leadingSpaces(line);
|
|
1423
843
|
const rest = line.slice(indent);
|
|
1424
844
|
const colon = rest.indexOf(":");
|
|
1425
845
|
if (colon === -1)
|
|
@@ -1499,56 +919,470 @@ var init_cookie_mint = __esm(() => {
|
|
|
1499
919
|
};
|
|
1500
920
|
});
|
|
1501
921
|
|
|
1502
|
-
// src/client/
|
|
1503
|
-
|
|
1504
|
-
|
|
1505
|
-
|
|
1506
|
-
|
|
1507
|
-
|
|
1508
|
-
|
|
1509
|
-
|
|
1510
|
-
|
|
1511
|
-
|
|
1512
|
-
|
|
1513
|
-
|
|
1514
|
-
|
|
1515
|
-
|
|
1516
|
-
|
|
1517
|
-
|
|
1518
|
-
|
|
1519
|
-
|
|
1520
|
-
HostNotServingError: () => HostNotServingError,
|
|
1521
|
-
HostRespawnLoopError: () => HostRespawnLoopError,
|
|
1522
|
-
HostSpawnError: () => HostSpawnError,
|
|
1523
|
-
MintUnavailableError: () => MintUnavailableError,
|
|
1524
|
-
ProfileMissingError: () => ProfileMissingError,
|
|
1525
|
-
__internals: () => __internals,
|
|
1526
|
-
defaultDshHome: () => defaultDshHome2,
|
|
1527
|
-
ensureHost: () => ensureHost,
|
|
1528
|
-
isListening: () => isListening,
|
|
1529
|
-
pidAlive: () => pidAlive,
|
|
1530
|
-
resolveBootTimeoutMs: () => resolveBootTimeoutMs,
|
|
1531
|
-
resolveConnectTimeoutMs: () => resolveConnectTimeoutMs,
|
|
1532
|
-
resolveIdleExitMs: () => resolveIdleExitMs,
|
|
1533
|
-
resolveIdleExitSec: () => resolveIdleExitSec,
|
|
1534
|
-
resolveMuxTimeoutMs: () => resolveMuxTimeoutMs
|
|
1535
|
-
});
|
|
1536
|
-
import { spawn as spawn2 } from "child_process";
|
|
1537
|
-
import { existsSync as existsSync3, linkSync, mkdirSync as mkdirSync3, readFileSync as readFileSync4, renameSync as renameSync3, rmSync, writeFileSync as writeFileSync3 } from "fs";
|
|
1538
|
-
import { homedir as homedir2 } from "os";
|
|
1539
|
-
import { connect as netConnect, Server } from "net";
|
|
1540
|
-
import { join as join5 } from "path";
|
|
1541
|
-
function resolveIdleExitMs(explicitSec) {
|
|
1542
|
-
if (explicitSec !== undefined && Number.isFinite(explicitSec)) {
|
|
1543
|
-
return Math.max(0, Math.round(explicitSec * 1000));
|
|
1544
|
-
}
|
|
1545
|
-
const raw = process.env[ENV_IDLE_EXIT_MS];
|
|
1546
|
-
if (raw !== undefined && raw.trim() !== "") {
|
|
1547
|
-
const parsed = Number(raw);
|
|
1548
|
-
if (Number.isFinite(parsed))
|
|
1549
|
-
return Math.max(0, Math.round(parsed));
|
|
922
|
+
// src/client/host-health.ts
|
|
923
|
+
function authorityPort(authority) {
|
|
924
|
+
if (typeof authority !== "string" || authority.length === 0)
|
|
925
|
+
return null;
|
|
926
|
+
let host = authority;
|
|
927
|
+
if (host.startsWith("[")) {
|
|
928
|
+
const end = host.indexOf("]");
|
|
929
|
+
if (end === -1)
|
|
930
|
+
return null;
|
|
931
|
+
host = host.slice(end + 1);
|
|
932
|
+
if (!host.startsWith(":"))
|
|
933
|
+
return null;
|
|
934
|
+
host = host.slice(1);
|
|
935
|
+
} else {
|
|
936
|
+
const colon = host.lastIndexOf(":");
|
|
937
|
+
if (colon === -1)
|
|
938
|
+
return null;
|
|
939
|
+
host = host.slice(colon + 1);
|
|
1550
940
|
}
|
|
1551
|
-
|
|
941
|
+
if (!/^\d+$/.test(host))
|
|
942
|
+
return null;
|
|
943
|
+
const port = Number(host);
|
|
944
|
+
return Number.isInteger(port) && port > 0 && port <= 65535 ? port : null;
|
|
945
|
+
}
|
|
946
|
+
function isHealthyStatus(status) {
|
|
947
|
+
return status !== null && status >= HEALTH_STATUS_MIN && status < HEALTH_STATUS_MAX_EXCLUSIVE;
|
|
948
|
+
}
|
|
949
|
+
async function checkHostHealth(target, probes = defaultHealthProbes) {
|
|
950
|
+
let tcp = false;
|
|
951
|
+
try {
|
|
952
|
+
tcp = await probes.connectTcp(target.authority);
|
|
953
|
+
} catch {
|
|
954
|
+
tcp = false;
|
|
955
|
+
}
|
|
956
|
+
if (!tcp)
|
|
957
|
+
return { healthy: false, tcp: false, httpStatus: null, reason: "tcp-failed" };
|
|
958
|
+
let status = null;
|
|
959
|
+
try {
|
|
960
|
+
status = await probes.requestStatus(target.authority, target.cookieHeader);
|
|
961
|
+
} catch {
|
|
962
|
+
status = null;
|
|
963
|
+
}
|
|
964
|
+
if (status === null)
|
|
965
|
+
return { healthy: false, tcp: true, httpStatus: null, reason: "http-no-response" };
|
|
966
|
+
if (!isHealthyStatus(status))
|
|
967
|
+
return { healthy: false, tcp: true, httpStatus: status, reason: "http-unhealthy-status" };
|
|
968
|
+
return { healthy: true, tcp: true, httpStatus: status, reason: "ok" };
|
|
969
|
+
}
|
|
970
|
+
var HEALTH_STATUS_MIN = 200, HEALTH_STATUS_MAX_EXCLUSIVE = 400, defaultHealthProbes;
|
|
971
|
+
var init_host_health = __esm(() => {
|
|
972
|
+
init_lifecycle();
|
|
973
|
+
init_host_probe();
|
|
974
|
+
defaultHealthProbes = {
|
|
975
|
+
async connectTcp(authority) {
|
|
976
|
+
const port = authorityPort(authority);
|
|
977
|
+
return port === null ? false : isListening(port);
|
|
978
|
+
},
|
|
979
|
+
async requestStatus(authority, cookieHeader) {
|
|
980
|
+
return probeHostHttpStatus({ authority, cookieHeader });
|
|
981
|
+
}
|
|
982
|
+
};
|
|
983
|
+
});
|
|
984
|
+
|
|
985
|
+
// src/client/host-port.ts
|
|
986
|
+
import { resolve } from "path";
|
|
987
|
+
function canonicalHome(home) {
|
|
988
|
+
const resolved = resolve(home);
|
|
989
|
+
if (process.platform !== "win32")
|
|
990
|
+
return resolved;
|
|
991
|
+
return resolved.replace(/\\/g, "/").replace(/^([A-Za-z]):/, (_match, drive) => drive.toLowerCase() + ":");
|
|
992
|
+
}
|
|
993
|
+
function fnv1a32(text) {
|
|
994
|
+
let hash = FNV_OFFSET_BASIS;
|
|
995
|
+
for (let i = 0;i < text.length; i++) {
|
|
996
|
+
hash ^= text.charCodeAt(i);
|
|
997
|
+
hash = Math.imul(hash, FNV_PRIME);
|
|
998
|
+
}
|
|
999
|
+
return hash >>> 0;
|
|
1000
|
+
}
|
|
1001
|
+
function derivePort(home, profile, options = {}) {
|
|
1002
|
+
const base = options.base ?? DEFAULT_PORT_BASE;
|
|
1003
|
+
const count = options.count ?? DEFAULT_PORT_COUNT;
|
|
1004
|
+
if (!Number.isInteger(base) || !Number.isInteger(count) || count <= 0) {
|
|
1005
|
+
throw new RangeError("derivePort: base and count must be integers and count > 0");
|
|
1006
|
+
}
|
|
1007
|
+
const offset = fnv1a32(`${canonicalHome(home)}:${profile}`) % count;
|
|
1008
|
+
return base + offset;
|
|
1009
|
+
}
|
|
1010
|
+
async function findFreePort(home, profile, options = {}) {
|
|
1011
|
+
const base = options.base ?? DEFAULT_PORT_BASE;
|
|
1012
|
+
const count = options.count ?? DEFAULT_PORT_COUNT;
|
|
1013
|
+
if (!Number.isInteger(base) || !Number.isInteger(count) || count <= 0) {
|
|
1014
|
+
throw new RangeError("findFreePort: base and count must be integers and count > 0");
|
|
1015
|
+
}
|
|
1016
|
+
const derived = derivePort(home, profile, { base, count });
|
|
1017
|
+
const probe = options.probe ?? isListening;
|
|
1018
|
+
for (let port = derived;port < derived + count; port++) {
|
|
1019
|
+
if (!await probe(port))
|
|
1020
|
+
return port;
|
|
1021
|
+
}
|
|
1022
|
+
throw new NoFreePortError(home, profile, derived, count);
|
|
1023
|
+
}
|
|
1024
|
+
var DEFAULT_PORT_BASE = 60000, DEFAULT_PORT_COUNT = 1000, FNV_OFFSET_BASIS = 2166136261, FNV_PRIME = 16777619, NoFreePortError;
|
|
1025
|
+
var init_host_port = __esm(() => {
|
|
1026
|
+
init_lifecycle();
|
|
1027
|
+
NoFreePortError = class NoFreePortError extends Error {
|
|
1028
|
+
home;
|
|
1029
|
+
profile;
|
|
1030
|
+
base;
|
|
1031
|
+
count;
|
|
1032
|
+
code = "no-free-port";
|
|
1033
|
+
constructor(home, profile, base, count) {
|
|
1034
|
+
super(`no free port for ${profile} in [${base}, ${base + count}) under ${home}`);
|
|
1035
|
+
this.home = home;
|
|
1036
|
+
this.profile = profile;
|
|
1037
|
+
this.base = base;
|
|
1038
|
+
this.count = count;
|
|
1039
|
+
this.name = "NoFreePortError";
|
|
1040
|
+
}
|
|
1041
|
+
};
|
|
1042
|
+
});
|
|
1043
|
+
|
|
1044
|
+
// src/client/host-launch.ts
|
|
1045
|
+
import { spawn } from "child_process";
|
|
1046
|
+
import { homedir as homedir2 } from "os";
|
|
1047
|
+
import { connect as netConnect, Server } from "net";
|
|
1048
|
+
import { dirname, join as join3 } from "path";
|
|
1049
|
+
function defaultDshHome2() {
|
|
1050
|
+
return process.env.DSH_HOME || join3(homedir2(), ".dsh");
|
|
1051
|
+
}
|
|
1052
|
+
function withFfiFlag(env) {
|
|
1053
|
+
const existing = env.NODE_OPTIONS ?? "";
|
|
1054
|
+
if (existing.split(/\s+/).includes(FFI_FLAG))
|
|
1055
|
+
return env;
|
|
1056
|
+
return { ...env, NODE_OPTIONS: `${existing} ${FFI_FLAG}`.trim() };
|
|
1057
|
+
}
|
|
1058
|
+
function resolveDeps(d) {
|
|
1059
|
+
const home = d.home ?? defaultDshHome2();
|
|
1060
|
+
const profile = d.profile ?? DEFAULT_LAUNCH_PROFILE;
|
|
1061
|
+
return {
|
|
1062
|
+
home,
|
|
1063
|
+
profile,
|
|
1064
|
+
cwd: d.cwd ?? process.cwd(),
|
|
1065
|
+
force: d.force ?? false,
|
|
1066
|
+
yes: d.yes ?? false,
|
|
1067
|
+
fs: d.fs ?? nodeRegistryFs,
|
|
1068
|
+
lifecycleFs: d.lifecycleFs ?? nodeLifecycleFs,
|
|
1069
|
+
now: d.now ?? Date.now,
|
|
1070
|
+
sleep: d.sleep ?? defaultSleep2,
|
|
1071
|
+
spawnHost: d.spawnHost ?? defaultSpawnHost,
|
|
1072
|
+
pidAlive: d.pidAlive ?? defaultPidAlive,
|
|
1073
|
+
health: d.health ?? defaultHealth,
|
|
1074
|
+
mintCookie: d.mintCookie ?? mintOwnerCookie,
|
|
1075
|
+
findPort: d.findPort ?? ((home, profile, probe) => findFreePort(home, profile, { probe })),
|
|
1076
|
+
portProbe: d.portProbe ?? defaultPortProbe,
|
|
1077
|
+
...d.progress ? { progress: d.progress } : {},
|
|
1078
|
+
killHooks: d.killHooks ?? psKillHooks,
|
|
1079
|
+
timeoutMs: d.timeoutMs ?? DEFAULT_LAUNCH_TIMEOUT_MS,
|
|
1080
|
+
pollMs: d.pollMs ?? DEFAULT_POLL_MS,
|
|
1081
|
+
registryMaxAgeMs: d.registryMaxAgeMs ?? DEFAULT_REGISTRY_MAX_AGE_MS,
|
|
1082
|
+
logPath: d.logPath ?? ((h, p) => join3(h, `opentui-host.${p}.log`)),
|
|
1083
|
+
baseEnv: d.baseEnv ?? process.env
|
|
1084
|
+
};
|
|
1085
|
+
}
|
|
1086
|
+
function removeStaleRecord(home, profile, stale, o) {
|
|
1087
|
+
const current = readRegistry(home, profile, o.fs);
|
|
1088
|
+
if (current.kind === "v2" && current.value.pid === stale.pid && current.value.startedAt === stale.startedAt) {
|
|
1089
|
+
try {
|
|
1090
|
+
o.fs.unlinkSync(registryPath(home, profile));
|
|
1091
|
+
} catch {}
|
|
1092
|
+
}
|
|
1093
|
+
}
|
|
1094
|
+
function removeInvalidRecord(home, profile, o) {
|
|
1095
|
+
try {
|
|
1096
|
+
o.fs.unlinkSync(registryPath(home, profile));
|
|
1097
|
+
} catch {}
|
|
1098
|
+
}
|
|
1099
|
+
function captureOutput(child, tail) {
|
|
1100
|
+
const push = (chunk) => {
|
|
1101
|
+
tail.text = (tail.text + String(chunk)).slice(-8000);
|
|
1102
|
+
};
|
|
1103
|
+
child.stdout?.on("data", push);
|
|
1104
|
+
child.stderr?.on("data", push);
|
|
1105
|
+
}
|
|
1106
|
+
function flushLog(o, tail) {
|
|
1107
|
+
const path = o.logPath(o.home, o.profile);
|
|
1108
|
+
try {
|
|
1109
|
+
o.fs.mkdirSync(dirname(path), { recursive: true });
|
|
1110
|
+
o.fs.writeFileSync(path, `[dsh-opentui] host output tail
|
|
1111
|
+
${tail.text}
|
|
1112
|
+
`);
|
|
1113
|
+
} catch {}
|
|
1114
|
+
return path;
|
|
1115
|
+
}
|
|
1116
|
+
async function ensureHost(deps = {}) {
|
|
1117
|
+
const o = resolveDeps(deps);
|
|
1118
|
+
if (o.force) {
|
|
1119
|
+
const hbDeps = { fs: o.lifecycleFs, now: o.now };
|
|
1120
|
+
assertForceAllowed(o.home, { ...hbDeps, yes: o.yes });
|
|
1121
|
+
const current = readRegistry(o.home, o.profile, o.fs);
|
|
1122
|
+
const forcePid = current.kind === "v2" ? current.value.pid : current.kind === "legacy" ? current.raw.pid : 0;
|
|
1123
|
+
if (forcePid > 0) {
|
|
1124
|
+
const stop = await safeStopHost({
|
|
1125
|
+
pid: forcePid,
|
|
1126
|
+
registryPid: forcePid,
|
|
1127
|
+
hooks: o.killHooks,
|
|
1128
|
+
termGraceMs: FORCE_TERM_GRACE_MS,
|
|
1129
|
+
killGraceMs: FORCE_KILL_GRACE_MS,
|
|
1130
|
+
sleep: o.sleep,
|
|
1131
|
+
now: o.now,
|
|
1132
|
+
pidAlive: o.pidAlive
|
|
1133
|
+
});
|
|
1134
|
+
if (!stop.stopped) {
|
|
1135
|
+
throw new Error(`dsh-opentui: --force could not confirm the old host pid ${forcePid} is stopped ` + `(evidences ${stop.evidencesOk ? "matched but pid survived" : "refused"}); ` + `registry left intact \u2014 retry --force or stop it manually.`);
|
|
1136
|
+
}
|
|
1137
|
+
try {
|
|
1138
|
+
o.fs.unlinkSync(registryPath(o.home, o.profile));
|
|
1139
|
+
} catch {}
|
|
1140
|
+
}
|
|
1141
|
+
purgeAllHeartbeats(o.home, hbDeps);
|
|
1142
|
+
}
|
|
1143
|
+
const startedAt = o.now();
|
|
1144
|
+
const deadline = startedAt + o.timeoutMs;
|
|
1145
|
+
const emit = (phase) => o.progress?.({ phase, elapsedMs: o.now() - startedAt });
|
|
1146
|
+
let read = readRegistry(o.home, o.profile, o.fs);
|
|
1147
|
+
if (read.kind === "v2" && !o.force) {
|
|
1148
|
+
const reg = read.value;
|
|
1149
|
+
const authority = reg.authority || `127.0.0.1:${reg.port}`;
|
|
1150
|
+
if (reg.phase === "ready" && reg.port > 0 && o.pidAlive(reg.pid)) {
|
|
1151
|
+
const cookie = o.mintCookie({ home: o.home, authority });
|
|
1152
|
+
if ((await o.health(authority, cookie)).healthy) {
|
|
1153
|
+
return { port: reg.port, mode: "adopted", adopted: true, spawned: false, hostPid: reg.pid };
|
|
1154
|
+
}
|
|
1155
|
+
}
|
|
1156
|
+
}
|
|
1157
|
+
for (let attempt = 0;attempt < 4; attempt++) {
|
|
1158
|
+
read = readRegistry(o.home, o.profile, o.fs);
|
|
1159
|
+
if (read.kind === "missing")
|
|
1160
|
+
break;
|
|
1161
|
+
if (read.kind === "legacy") {
|
|
1162
|
+
const cleared = safeClearLegacy(o.home, o.profile, { fs: o.fs, read, pidAlive: o.pidAlive });
|
|
1163
|
+
if (!cleared.removed) {
|
|
1164
|
+
throw new Error(`dsh-opentui: legacy host pid ${read.raw.pid} is still alive; ` + `its registry record is kept \u2014 stop it manually or use --force --yes.`);
|
|
1165
|
+
}
|
|
1166
|
+
continue;
|
|
1167
|
+
}
|
|
1168
|
+
if (read.kind === "invalid") {
|
|
1169
|
+
removeInvalidRecord(o.home, o.profile, o);
|
|
1170
|
+
continue;
|
|
1171
|
+
}
|
|
1172
|
+
const verdict = isRegistryStale(read, {
|
|
1173
|
+
now: o.now,
|
|
1174
|
+
pidAlive: o.pidAlive,
|
|
1175
|
+
registryMaxAgeMs: o.registryMaxAgeMs
|
|
1176
|
+
});
|
|
1177
|
+
if (verdict.stale) {
|
|
1178
|
+
removeStaleRecord(o.home, o.profile, read.value, o);
|
|
1179
|
+
continue;
|
|
1180
|
+
}
|
|
1181
|
+
if (read.value.phase === "ready" && read.value.pid > 0) {
|
|
1182
|
+
const stop = await safeStopHost({
|
|
1183
|
+
pid: read.value.pid,
|
|
1184
|
+
registryPid: read.value.pid,
|
|
1185
|
+
hooks: o.killHooks,
|
|
1186
|
+
termGraceMs: FORCE_TERM_GRACE_MS,
|
|
1187
|
+
killGraceMs: FORCE_KILL_GRACE_MS,
|
|
1188
|
+
sleep: o.sleep,
|
|
1189
|
+
now: o.now,
|
|
1190
|
+
pidAlive: o.pidAlive
|
|
1191
|
+
});
|
|
1192
|
+
if (!stop.stopped) {
|
|
1193
|
+
throw new Error(`dsh-opentui: unhealthy host pid ${read.value.pid} could not be stopped ` + `(evidences ${stop.evidencesOk ? "matched but pid survived" : "refused"}); ` + `registry record kept \u2014 retry or stop it manually.`);
|
|
1194
|
+
}
|
|
1195
|
+
removeStaleRecord(o.home, o.profile, read.value, o);
|
|
1196
|
+
}
|
|
1197
|
+
break;
|
|
1198
|
+
}
|
|
1199
|
+
const claim = claimRegistry(o.home, o.profile, { fs: o.fs, now: o.now, pid: process.pid });
|
|
1200
|
+
if (!claim.ok) {
|
|
1201
|
+
while (o.now() < deadline) {
|
|
1202
|
+
const current = readRegistry(o.home, o.profile, o.fs);
|
|
1203
|
+
if (current.kind === "v2" && current.value.phase === "ready" && current.value.port > 0) {
|
|
1204
|
+
return {
|
|
1205
|
+
port: current.value.port,
|
|
1206
|
+
mode: "adopted",
|
|
1207
|
+
adopted: true,
|
|
1208
|
+
spawned: false,
|
|
1209
|
+
hostPid: current.value.pid
|
|
1210
|
+
};
|
|
1211
|
+
}
|
|
1212
|
+
await o.sleep(o.pollMs);
|
|
1213
|
+
}
|
|
1214
|
+
throw new HostLaunchTimeoutError(`timed out waiting for the host claimed by another launcher (${o.timeoutMs}ms)`, o.logPath(o.home, o.profile));
|
|
1215
|
+
}
|
|
1216
|
+
const port = await o.findPort(o.home, o.profile, o.portProbe);
|
|
1217
|
+
const booting = {
|
|
1218
|
+
...claim.registry,
|
|
1219
|
+
pid: 0,
|
|
1220
|
+
port,
|
|
1221
|
+
phase: "booting",
|
|
1222
|
+
authority: `127.0.0.1:${port}`,
|
|
1223
|
+
updatedAt: new Date(o.now()).toISOString()
|
|
1224
|
+
};
|
|
1225
|
+
const env = withFfiFlag({
|
|
1226
|
+
...o.baseEnv,
|
|
1227
|
+
[SERVER_ENV_NAME]: SERVER_ENV_VALUE,
|
|
1228
|
+
DSH_HOME: o.home
|
|
1229
|
+
});
|
|
1230
|
+
const child = o.spawnHost(["--profile", o.profile, "--no-open", "--port", String(port)], {
|
|
1231
|
+
cwd: o.cwd,
|
|
1232
|
+
env
|
|
1233
|
+
});
|
|
1234
|
+
writeRegistry(o.home, o.profile, { ...booting, pid: child.pid }, o.fs);
|
|
1235
|
+
const bootingRecord = { ...booting, pid: child.pid };
|
|
1236
|
+
emit("spawn");
|
|
1237
|
+
const tail = { text: "" };
|
|
1238
|
+
captureOutput(child, tail);
|
|
1239
|
+
const authority = `127.0.0.1:${port}`;
|
|
1240
|
+
const cookie = o.mintCookie({ home: o.home, authority });
|
|
1241
|
+
let ready = false;
|
|
1242
|
+
let died = false;
|
|
1243
|
+
child.on?.("exit", () => {
|
|
1244
|
+
died = true;
|
|
1245
|
+
});
|
|
1246
|
+
while (o.now() < deadline) {
|
|
1247
|
+
if (died || !o.pidAlive(child.pid))
|
|
1248
|
+
break;
|
|
1249
|
+
if ((await o.health(authority, cookie)).healthy) {
|
|
1250
|
+
ready = true;
|
|
1251
|
+
break;
|
|
1252
|
+
}
|
|
1253
|
+
emit("booting");
|
|
1254
|
+
await o.sleep(o.pollMs);
|
|
1255
|
+
}
|
|
1256
|
+
if (ready) {
|
|
1257
|
+
writeRegistry(o.home, o.profile, withPhase(bootingRecord, "ready", new Date(o.now()).toISOString()), o.fs);
|
|
1258
|
+
emit("ready");
|
|
1259
|
+
return { port, mode: "spawned", adopted: false, spawned: true, hostPid: child.pid };
|
|
1260
|
+
}
|
|
1261
|
+
const log = flushLog(o, tail);
|
|
1262
|
+
const current = readRegistry(o.home, o.profile, o.fs);
|
|
1263
|
+
const registryPid = current.kind === "v2" ? current.value.pid : -1;
|
|
1264
|
+
await safeStopHost({
|
|
1265
|
+
pid: child.pid,
|
|
1266
|
+
registryPid,
|
|
1267
|
+
hooks: o.killHooks,
|
|
1268
|
+
termGraceMs: FORCE_TERM_GRACE_MS,
|
|
1269
|
+
killGraceMs: FORCE_KILL_GRACE_MS,
|
|
1270
|
+
sleep: o.sleep,
|
|
1271
|
+
now: o.now,
|
|
1272
|
+
pidAlive: o.pidAlive
|
|
1273
|
+
});
|
|
1274
|
+
if (current.kind === "v2" && current.value.pid === child.pid) {
|
|
1275
|
+
try {
|
|
1276
|
+
o.fs.unlinkSync(registryPath(o.home, o.profile));
|
|
1277
|
+
} catch {}
|
|
1278
|
+
}
|
|
1279
|
+
throw new HostLaunchTimeoutError(`host did not become ready within ${o.timeoutMs}ms (port ${port}, pid ${child.pid})`, log);
|
|
1280
|
+
}
|
|
1281
|
+
var DEFAULT_LAUNCH_PROFILE = "opentui", DEFAULT_LAUNCH_TIMEOUT_MS, DEFAULT_POLL_MS = 150, DEFAULT_REGISTRY_MAX_AGE_MS = 60000, FORCE_TERM_GRACE_MS = 2000, FORCE_KILL_GRACE_MS = 1000, HostLaunchTimeoutError, defaultSleep2 = (ms) => new Promise((resolve) => setTimeout(resolve, ms)), defaultPortProbe = (port) => new Promise((resolve) => {
|
|
1282
|
+
let settled = false;
|
|
1283
|
+
const socket = netConnect({ host: "127.0.0.1", port });
|
|
1284
|
+
const finish = (value) => {
|
|
1285
|
+
if (settled)
|
|
1286
|
+
return;
|
|
1287
|
+
settled = true;
|
|
1288
|
+
socket.destroy();
|
|
1289
|
+
resolve(value);
|
|
1290
|
+
};
|
|
1291
|
+
socket.setTimeout(750);
|
|
1292
|
+
socket.once("connect", () => finish(true));
|
|
1293
|
+
socket.once("error", () => finish(false));
|
|
1294
|
+
socket.once("timeout", () => finish(false));
|
|
1295
|
+
}), FFI_FLAG = "--experimental-ffi", defaultSpawnHost = (argv, options) => {
|
|
1296
|
+
const env = { ...options.env };
|
|
1297
|
+
for (const key of Object.keys(env)) {
|
|
1298
|
+
if (key.startsWith("npm_config_"))
|
|
1299
|
+
delete env[key];
|
|
1300
|
+
}
|
|
1301
|
+
const child = spawn("dsh", argv, {
|
|
1302
|
+
cwd: options.cwd,
|
|
1303
|
+
env,
|
|
1304
|
+
detached: true,
|
|
1305
|
+
stdio: ["ignore", "pipe", "pipe"]
|
|
1306
|
+
});
|
|
1307
|
+
child.unref();
|
|
1308
|
+
for (const pipe of [child.stdout, child.stderr]) {
|
|
1309
|
+
pipe.unref?.();
|
|
1310
|
+
}
|
|
1311
|
+
return child;
|
|
1312
|
+
}, defaultHealth = (authority, cookieHeader) => checkHostHealth({ authority, cookieHeader }, defaultHealthProbes);
|
|
1313
|
+
var init_host_launch = __esm(() => {
|
|
1314
|
+
init_client_lifecycle();
|
|
1315
|
+
init_cookie_mint();
|
|
1316
|
+
init_host_health();
|
|
1317
|
+
init_host_port();
|
|
1318
|
+
init_safe_kill();
|
|
1319
|
+
init_host_registry();
|
|
1320
|
+
init_safe_kill();
|
|
1321
|
+
init_client_lifecycle();
|
|
1322
|
+
DEFAULT_LAUNCH_TIMEOUT_MS = 5 * 60000;
|
|
1323
|
+
HostLaunchTimeoutError = class HostLaunchTimeoutError extends Error {
|
|
1324
|
+
logPath;
|
|
1325
|
+
code = "host-launch-timeout";
|
|
1326
|
+
constructor(message, logPath) {
|
|
1327
|
+
super(`${message}
|
|
1328
|
+
--- dsh host log: ${logPath} ---`);
|
|
1329
|
+
this.logPath = logPath;
|
|
1330
|
+
this.name = new.target.name;
|
|
1331
|
+
}
|
|
1332
|
+
};
|
|
1333
|
+
});
|
|
1334
|
+
|
|
1335
|
+
// src/client/lifecycle.ts
|
|
1336
|
+
var exports_lifecycle = {};
|
|
1337
|
+
__export(exports_lifecycle, {
|
|
1338
|
+
DEFAULT_CONNECT_TIMEOUT_MS: () => DEFAULT_CONNECT_TIMEOUT_MS,
|
|
1339
|
+
DEFAULT_IDLE_EXIT_MS: () => DEFAULT_IDLE_EXIT_MS,
|
|
1340
|
+
DEFAULT_IDLE_EXIT_SEC: () => DEFAULT_IDLE_EXIT_SEC,
|
|
1341
|
+
DEFAULT_PROFILE: () => DEFAULT_PROFILE,
|
|
1342
|
+
DEFAULT_READINESS_TIMEOUT_MS: () => DEFAULT_READINESS_TIMEOUT_MS,
|
|
1343
|
+
DEFAULT_SERVE_PROBE_BUDGET_MS: () => DEFAULT_SERVE_PROBE_BUDGET_MS,
|
|
1344
|
+
DEFAULT_STALE_PROBE_MS: () => DEFAULT_STALE_PROBE_MS,
|
|
1345
|
+
ENV_BOOT_TIMEOUT_MS: () => ENV_BOOT_TIMEOUT_MS,
|
|
1346
|
+
ENV_CONNECT_TIMEOUT_MS: () => ENV_CONNECT_TIMEOUT_MS,
|
|
1347
|
+
ENV_IDLE_EXIT_MS: () => ENV_IDLE_EXIT_MS,
|
|
1348
|
+
ENV_MUX_TIMEOUT_MS: () => ENV_MUX_TIMEOUT_MS,
|
|
1349
|
+
HostBootSupersededError: () => HostBootSupersededError,
|
|
1350
|
+
HostBootTimeoutError: () => HostBootTimeoutError,
|
|
1351
|
+
HostDiedError: () => HostDiedError,
|
|
1352
|
+
HostLifecycleError: () => HostLifecycleError,
|
|
1353
|
+
HostNotServingError: () => HostNotServingError,
|
|
1354
|
+
HostRespawnLoopError: () => HostRespawnLoopError,
|
|
1355
|
+
HostSpawnError: () => HostSpawnError,
|
|
1356
|
+
MintUnavailableError: () => MintUnavailableError,
|
|
1357
|
+
ProfileMissingError: () => ProfileMissingError,
|
|
1358
|
+
__internals: () => __internals,
|
|
1359
|
+
defaultDshHome: () => defaultDshHome3,
|
|
1360
|
+
ensureHost: () => ensureHost2,
|
|
1361
|
+
ensureV2Host: () => ensureV2Host,
|
|
1362
|
+
isListening: () => isListening,
|
|
1363
|
+
pidAlive: () => pidAlive,
|
|
1364
|
+
resolveBootTimeoutMs: () => resolveBootTimeoutMs,
|
|
1365
|
+
resolveConnectTimeoutMs: () => resolveConnectTimeoutMs,
|
|
1366
|
+
resolveIdleExitMs: () => resolveIdleExitMs,
|
|
1367
|
+
resolveIdleExitSec: () => resolveIdleExitSec,
|
|
1368
|
+
resolveMuxTimeoutMs: () => resolveMuxTimeoutMs
|
|
1369
|
+
});
|
|
1370
|
+
import { spawn as spawn2 } from "child_process";
|
|
1371
|
+
import { existsSync, linkSync, mkdirSync as mkdirSync2, readFileSync as readFileSync3, renameSync as renameSync2, rmSync, writeFileSync as writeFileSync2 } from "fs";
|
|
1372
|
+
import { homedir as homedir3 } from "os";
|
|
1373
|
+
import { connect as netConnect2, Server as Server2 } from "net";
|
|
1374
|
+
import { join as join4 } from "path";
|
|
1375
|
+
function resolveIdleExitMs(explicitSec) {
|
|
1376
|
+
if (explicitSec !== undefined && Number.isFinite(explicitSec)) {
|
|
1377
|
+
return Math.max(0, Math.round(explicitSec * 1000));
|
|
1378
|
+
}
|
|
1379
|
+
const raw = process.env[ENV_IDLE_EXIT_MS];
|
|
1380
|
+
if (raw !== undefined && raw.trim() !== "") {
|
|
1381
|
+
const parsed = Number(raw);
|
|
1382
|
+
if (Number.isFinite(parsed))
|
|
1383
|
+
return Math.max(0, Math.round(parsed));
|
|
1384
|
+
}
|
|
1385
|
+
return DEFAULT_IDLE_EXIT_MS;
|
|
1552
1386
|
}
|
|
1553
1387
|
function resolveIdleExitSec(explicitSec) {
|
|
1554
1388
|
return resolveIdleExitMs(explicitSec) / 1000;
|
|
@@ -1588,24 +1422,19 @@ ${lines.slice(-ERROR_TAIL_LINES).join(`
|
|
|
1588
1422
|
function registryKey(dshHome, profile) {
|
|
1589
1423
|
return `${dshHome}\x00${profile}`;
|
|
1590
1424
|
}
|
|
1591
|
-
function
|
|
1592
|
-
return process.env.DSH_HOME ||
|
|
1425
|
+
function defaultDshHome3() {
|
|
1426
|
+
return process.env.DSH_HOME || join4(homedir3(), ".dsh");
|
|
1593
1427
|
}
|
|
1594
1428
|
function lockPathFor(dshHome, profile) {
|
|
1595
|
-
return
|
|
1429
|
+
return join4(dshHome, `opentui-host.${profile}.json`);
|
|
1596
1430
|
}
|
|
1597
1431
|
function pidAlive(pid) {
|
|
1598
|
-
|
|
1599
|
-
process.kill(pid, 0);
|
|
1600
|
-
return true;
|
|
1601
|
-
} catch (err) {
|
|
1602
|
-
return err.code === "EPERM";
|
|
1603
|
-
}
|
|
1432
|
+
return defaultPidAlive(pid);
|
|
1604
1433
|
}
|
|
1605
1434
|
function isListening(port) {
|
|
1606
1435
|
return new Promise((resolve) => {
|
|
1607
1436
|
let settled = false;
|
|
1608
|
-
const socket =
|
|
1437
|
+
const socket = netConnect2({ host: "127.0.0.1", port });
|
|
1609
1438
|
const finish = (value) => {
|
|
1610
1439
|
if (settled)
|
|
1611
1440
|
return;
|
|
@@ -1635,7 +1464,7 @@ async function httpResponds(port) {
|
|
|
1635
1464
|
}
|
|
1636
1465
|
function getFreePort() {
|
|
1637
1466
|
return new Promise((resolve, reject) => {
|
|
1638
|
-
const server = new
|
|
1467
|
+
const server = new Server2((socket) => socket.destroy());
|
|
1639
1468
|
server.once("error", reject);
|
|
1640
1469
|
server.listen(0, "127.0.0.1", () => {
|
|
1641
1470
|
const { port } = server.address();
|
|
@@ -1643,9 +1472,19 @@ function getFreePort() {
|
|
|
1643
1472
|
});
|
|
1644
1473
|
});
|
|
1645
1474
|
}
|
|
1475
|
+
function isV2Registry(dshHome, profile) {
|
|
1476
|
+
try {
|
|
1477
|
+
const raw = JSON.parse(readFileSync3(lockPathFor(dshHome, profile), "utf8"));
|
|
1478
|
+
return raw !== null && typeof raw === "object" && raw.version === 2;
|
|
1479
|
+
} catch {
|
|
1480
|
+
return false;
|
|
1481
|
+
}
|
|
1482
|
+
}
|
|
1646
1483
|
function readLock(dshHome, profile) {
|
|
1647
1484
|
try {
|
|
1648
|
-
const raw = JSON.parse(
|
|
1485
|
+
const raw = JSON.parse(readFileSync3(lockPathFor(dshHome, profile), "utf8"));
|
|
1486
|
+
if (raw.version === 2)
|
|
1487
|
+
return null;
|
|
1649
1488
|
if (typeof raw.pid !== "number" || typeof raw.port !== "number")
|
|
1650
1489
|
return null;
|
|
1651
1490
|
return {
|
|
@@ -1661,7 +1500,9 @@ function readLock(dshHome, profile) {
|
|
|
1661
1500
|
}
|
|
1662
1501
|
}
|
|
1663
1502
|
function writeLock(dshHome, profile, host) {
|
|
1664
|
-
|
|
1503
|
+
if (isV2Registry(dshHome, profile))
|
|
1504
|
+
return;
|
|
1505
|
+
mkdirSync2(dshHome, { recursive: true });
|
|
1665
1506
|
const path = lockPathFor(dshHome, profile);
|
|
1666
1507
|
const payload = {
|
|
1667
1508
|
pid: host.pid,
|
|
@@ -1671,9 +1512,9 @@ function writeLock(dshHome, profile, host) {
|
|
|
1671
1512
|
profile
|
|
1672
1513
|
};
|
|
1673
1514
|
const tmp = `${path}.tmp`;
|
|
1674
|
-
|
|
1515
|
+
writeFileSync2(tmp, JSON.stringify(payload, null, 2) + `
|
|
1675
1516
|
`);
|
|
1676
|
-
|
|
1517
|
+
renameSync2(tmp, path);
|
|
1677
1518
|
}
|
|
1678
1519
|
function clearOurLock(host) {
|
|
1679
1520
|
if (!host.lockOwned)
|
|
@@ -1684,7 +1525,9 @@ function clearOurLock(host) {
|
|
|
1684
1525
|
}
|
|
1685
1526
|
}
|
|
1686
1527
|
function claimBootLock(dshHome, profile) {
|
|
1687
|
-
|
|
1528
|
+
if (isV2Registry(dshHome, profile))
|
|
1529
|
+
return null;
|
|
1530
|
+
mkdirSync2(dshHome, { recursive: true });
|
|
1688
1531
|
const path = lockPathFor(dshHome, profile);
|
|
1689
1532
|
const payload = {
|
|
1690
1533
|
pid: process.pid,
|
|
@@ -1695,7 +1538,7 @@ function claimBootLock(dshHome, profile) {
|
|
|
1695
1538
|
booting: true
|
|
1696
1539
|
};
|
|
1697
1540
|
const tmp = `${path}.claim-${process.pid}-${Date.now()}`;
|
|
1698
|
-
|
|
1541
|
+
writeFileSync2(tmp, JSON.stringify(payload, null, 2) + `
|
|
1699
1542
|
`);
|
|
1700
1543
|
try {
|
|
1701
1544
|
linkSync(tmp, path);
|
|
@@ -1711,7 +1554,7 @@ function claimBootLock(dshHome, profile) {
|
|
|
1711
1554
|
function removeBootClaim(dshHome, profile, claim) {
|
|
1712
1555
|
const path = lockPathFor(dshHome, profile);
|
|
1713
1556
|
try {
|
|
1714
|
-
const raw = JSON.parse(
|
|
1557
|
+
const raw = JSON.parse(readFileSync3(path, "utf8"));
|
|
1715
1558
|
if (raw.booting !== true || raw.pid !== claim.pid)
|
|
1716
1559
|
return false;
|
|
1717
1560
|
if (claim.startedAt !== undefined && raw.startedAt !== claim.startedAt)
|
|
@@ -1725,7 +1568,7 @@ function removeBootClaim(dshHome, profile, claim) {
|
|
|
1725
1568
|
function removeStaleLock(dshHome, profile, stale) {
|
|
1726
1569
|
const path = lockPathFor(dshHome, profile);
|
|
1727
1570
|
try {
|
|
1728
|
-
const raw = JSON.parse(
|
|
1571
|
+
const raw = JSON.parse(readFileSync3(path, "utf8"));
|
|
1729
1572
|
if (raw.booting === true || raw.pid !== stale.pid || raw.port !== stale.port)
|
|
1730
1573
|
return false;
|
|
1731
1574
|
} catch {
|
|
@@ -1736,7 +1579,7 @@ function removeStaleLock(dshHome, profile, stale) {
|
|
|
1736
1579
|
}
|
|
1737
1580
|
function bootClaimIntact(dshHome, profile, startedAt) {
|
|
1738
1581
|
try {
|
|
1739
|
-
const raw = JSON.parse(
|
|
1582
|
+
const raw = JSON.parse(readFileSync3(lockPathFor(dshHome, profile), "utf8"));
|
|
1740
1583
|
return raw.booting === true && raw.pid === process.pid && raw.startedAt === startedAt;
|
|
1741
1584
|
} catch {
|
|
1742
1585
|
return false;
|
|
@@ -1817,14 +1660,14 @@ function defaultSpawnDsh(argv, options) {
|
|
|
1817
1660
|
}
|
|
1818
1661
|
return child;
|
|
1819
1662
|
}
|
|
1820
|
-
function
|
|
1663
|
+
function withFfiFlag2(env) {
|
|
1821
1664
|
const existing = env.NODE_OPTIONS ?? "";
|
|
1822
|
-
if (existing.split(/\s+/).includes(
|
|
1665
|
+
if (existing.split(/\s+/).includes(FFI_FLAG2))
|
|
1823
1666
|
return env;
|
|
1824
|
-
return { ...env, NODE_OPTIONS: `${existing} ${
|
|
1667
|
+
return { ...env, NODE_OPTIONS: `${existing} ${FFI_FLAG2}`.trim() };
|
|
1825
1668
|
}
|
|
1826
1669
|
function childEnv(dshHome) {
|
|
1827
|
-
return
|
|
1670
|
+
return withFfiFlag2({ ...process.env, DSH_HOME: dshHome });
|
|
1828
1671
|
}
|
|
1829
1672
|
function attachChildWatchers(host, child) {
|
|
1830
1673
|
const push = (chunk) => {
|
|
@@ -1930,6 +1773,9 @@ function makeHandle(host) {
|
|
|
1930
1773
|
get adopted() {
|
|
1931
1774
|
return host.adopted;
|
|
1932
1775
|
},
|
|
1776
|
+
get v2Managed() {
|
|
1777
|
+
return host.v2Managed === true;
|
|
1778
|
+
},
|
|
1933
1779
|
get refCount() {
|
|
1934
1780
|
return host.refCount;
|
|
1935
1781
|
},
|
|
@@ -1978,7 +1824,7 @@ function adoptHost(lock, o) {
|
|
|
1978
1824
|
}
|
|
1979
1825
|
function resolveOptions(opts) {
|
|
1980
1826
|
const profile = opts.profile ?? DEFAULT_PROFILE;
|
|
1981
|
-
const dshHome = opts.dshHome ??
|
|
1827
|
+
const dshHome = opts.dshHome ?? defaultDshHome3();
|
|
1982
1828
|
const idleExitSec = resolveIdleExitSec(opts.idleExitSec);
|
|
1983
1829
|
return {
|
|
1984
1830
|
profile,
|
|
@@ -2026,9 +1872,9 @@ async function bootHost(o) {
|
|
|
2026
1872
|
if (lock)
|
|
2027
1873
|
removeStaleLock(o.dshHome, o.profile, lock);
|
|
2028
1874
|
const lockPath = lockPathFor(o.dshHome, o.profile);
|
|
2029
|
-
if (!
|
|
2030
|
-
const profileDir =
|
|
2031
|
-
if (!
|
|
1875
|
+
if (!existsSync(lockPath)) {
|
|
1876
|
+
const profileDir = join4(o.dshHome, "profiles", o.profile);
|
|
1877
|
+
if (!existsSync(profileDir))
|
|
2032
1878
|
throw new ProfileMissingError(o.profile, profileDir);
|
|
2033
1879
|
const claimed = claimBootLock(o.dshHome, o.profile);
|
|
2034
1880
|
if (claimed !== null) {
|
|
@@ -2040,7 +1886,7 @@ async function bootHost(o) {
|
|
|
2040
1886
|
}
|
|
2041
1887
|
await sleep(BOOT_JOIN_POLL_MS);
|
|
2042
1888
|
}
|
|
2043
|
-
const profileDir =
|
|
1889
|
+
const profileDir = join4(o.dshHome, "profiles", o.profile);
|
|
2044
1890
|
try {
|
|
2045
1891
|
const provision = provisionAppendSystem(o.dshHome, o.profile);
|
|
2046
1892
|
if (provision.patch.status === "collision" || provision.patch.status === "skipped") {
|
|
@@ -2115,210 +1961,1614 @@ async function bootHost(o) {
|
|
|
2115
1961
|
if (!serving)
|
|
2116
1962
|
throw new HostNotServingError(host.outputTail, o.serveProbeBudgetMs);
|
|
2117
1963
|
}
|
|
2118
|
-
if (!bootClaimIntact(o.dshHome, o.profile, claimStartedAt)) {
|
|
2119
|
-
throw new HostBootSupersededError;
|
|
1964
|
+
if (!bootClaimIntact(o.dshHome, o.profile, claimStartedAt)) {
|
|
1965
|
+
throw new HostBootSupersededError;
|
|
1966
|
+
}
|
|
1967
|
+
writeLock(o.dshHome, o.profile, host);
|
|
1968
|
+
host.lockOwned = true;
|
|
1969
|
+
host.state = "ready";
|
|
1970
|
+
respawnHistory.delete(o.key);
|
|
1971
|
+
registry.set(o.key, host);
|
|
1972
|
+
return host;
|
|
1973
|
+
} catch (err) {
|
|
1974
|
+
removeBootClaim(o.dshHome, o.profile, { pid: process.pid, startedAt: claimStartedAt });
|
|
1975
|
+
await terminateHost(host).catch(() => {});
|
|
1976
|
+
throw err;
|
|
1977
|
+
}
|
|
1978
|
+
}
|
|
1979
|
+
async function lockIsFresh(lock, staleProbeMs) {
|
|
1980
|
+
if (!pidAlive(lock.pid))
|
|
1981
|
+
return false;
|
|
1982
|
+
if (await isListening(lock.port))
|
|
1983
|
+
return true;
|
|
1984
|
+
const deadline = Date.now() + staleProbeMs;
|
|
1985
|
+
while (Date.now() < deadline) {
|
|
1986
|
+
await sleep(LISTEN_POLL_MS);
|
|
1987
|
+
if (!pidAlive(lock.pid))
|
|
1988
|
+
return false;
|
|
1989
|
+
if (await isListening(lock.port))
|
|
1990
|
+
return true;
|
|
1991
|
+
}
|
|
1992
|
+
return false;
|
|
1993
|
+
}
|
|
1994
|
+
function attachHost(host) {
|
|
1995
|
+
host.refCount += 1;
|
|
1996
|
+
if (host.idleTimer) {
|
|
1997
|
+
clearTimeout(host.idleTimer);
|
|
1998
|
+
host.idleTimer = null;
|
|
1999
|
+
}
|
|
2000
|
+
}
|
|
2001
|
+
function releaseHost(host) {
|
|
2002
|
+
host.refCount = Math.max(0, host.refCount - 1);
|
|
2003
|
+
if (host.v2Managed)
|
|
2004
|
+
return;
|
|
2005
|
+
if (host.refCount === 0 && host.state === "ready" && host.idleExitSec > 0) {
|
|
2006
|
+
const timer = setTimeout(() => {
|
|
2007
|
+
host.idleTimer = null;
|
|
2008
|
+
terminateHost(host);
|
|
2009
|
+
}, host.idleExitSec * 1000);
|
|
2010
|
+
timer.unref?.();
|
|
2011
|
+
host.idleTimer = timer;
|
|
2012
|
+
}
|
|
2013
|
+
}
|
|
2014
|
+
function signalPid(pid, signal) {
|
|
2015
|
+
try {
|
|
2016
|
+
process.kill(pid, signal);
|
|
2017
|
+
} catch {}
|
|
2018
|
+
}
|
|
2019
|
+
async function waitPidGone(pid, budgetMs) {
|
|
2020
|
+
const deadline = Date.now() + budgetMs;
|
|
2021
|
+
while (pidAlive(pid)) {
|
|
2022
|
+
if (Date.now() > deadline)
|
|
2023
|
+
return false;
|
|
2024
|
+
await sleep(LISTEN_POLL_MS);
|
|
2025
|
+
}
|
|
2026
|
+
return true;
|
|
2027
|
+
}
|
|
2028
|
+
async function terminateHost(host) {
|
|
2029
|
+
if (host.state === "dead") {
|
|
2030
|
+
clearOurLock(host);
|
|
2031
|
+
registry.delete(host.key);
|
|
2032
|
+
return;
|
|
2033
|
+
}
|
|
2034
|
+
if (host.state === "disposing" && host.termination)
|
|
2035
|
+
return host.termination;
|
|
2036
|
+
if (host.termination)
|
|
2037
|
+
return host.termination;
|
|
2038
|
+
host.state = "disposing";
|
|
2039
|
+
clearOurLock(host);
|
|
2040
|
+
registry.delete(host.key);
|
|
2041
|
+
host.termination = (async () => {
|
|
2042
|
+
if (host.child) {
|
|
2043
|
+
host.child.kill("SIGTERM");
|
|
2044
|
+
await Promise.race([host.exitPromise, sleep(KILL_GRACE_MS)]);
|
|
2045
|
+
if (!host.exitInfo) {
|
|
2046
|
+
signalPid(host.pid, "SIGKILL");
|
|
2047
|
+
await Promise.race([host.exitPromise, sleep(KILL_ESCALATE_MS)]);
|
|
2048
|
+
}
|
|
2049
|
+
} else {
|
|
2050
|
+
signalPid(host.pid, "SIGTERM");
|
|
2051
|
+
if (!await waitPidGone(host.pid, KILL_GRACE_MS)) {
|
|
2052
|
+
signalPid(host.pid, "SIGKILL");
|
|
2053
|
+
await waitPidGone(host.pid, KILL_ESCALATE_MS);
|
|
2054
|
+
}
|
|
2055
|
+
}
|
|
2056
|
+
host.state = "dead";
|
|
2057
|
+
})();
|
|
2058
|
+
return host.termination;
|
|
2059
|
+
}
|
|
2060
|
+
function readV2Record(dshHome, profile) {
|
|
2061
|
+
try {
|
|
2062
|
+
const raw = JSON.parse(readFileSync3(lockPathFor(dshHome, profile), "utf8"));
|
|
2063
|
+
if (raw === null || typeof raw !== "object" || raw.version !== 2)
|
|
2064
|
+
return null;
|
|
2065
|
+
if (typeof raw.pid !== "number" || typeof raw.port !== "number")
|
|
2066
|
+
return null;
|
|
2067
|
+
return {
|
|
2068
|
+
pid: raw.pid,
|
|
2069
|
+
port: raw.port,
|
|
2070
|
+
authority: typeof raw.authority === "string" ? raw.authority : `127.0.0.1:${raw.port}`
|
|
2071
|
+
};
|
|
2072
|
+
} catch {
|
|
2073
|
+
return null;
|
|
2074
|
+
}
|
|
2075
|
+
}
|
|
2076
|
+
async function defaultLaunchHost(deps) {
|
|
2077
|
+
const mod = await Promise.resolve().then(() => (init_host_launch(), {}));
|
|
2078
|
+
return ensureHost({ home: deps.home, profile: deps.profile, cwd: deps.cwd });
|
|
2079
|
+
}
|
|
2080
|
+
async function bootV2Host(o, opts) {
|
|
2081
|
+
const launch = opts.launchHost ?? defaultLaunchHost;
|
|
2082
|
+
const result = await launch({ home: o.dshHome, profile: o.profile, cwd: opts.cwd ?? process.cwd() });
|
|
2083
|
+
const record = readV2Record(o.dshHome, o.profile);
|
|
2084
|
+
const port = record?.port ?? result.port;
|
|
2085
|
+
const pid = record?.pid ?? result.hostPid ?? 0;
|
|
2086
|
+
const authority = record?.authority ?? `127.0.0.1:${port}`;
|
|
2087
|
+
const host = {
|
|
2088
|
+
key: o.key,
|
|
2089
|
+
profile: o.profile,
|
|
2090
|
+
dshHome: o.dshHome,
|
|
2091
|
+
pid,
|
|
2092
|
+
port,
|
|
2093
|
+
authority,
|
|
2094
|
+
cookieHeader: "",
|
|
2095
|
+
url: null,
|
|
2096
|
+
token: null,
|
|
2097
|
+
adopted: result.adopted,
|
|
2098
|
+
v2Managed: true,
|
|
2099
|
+
child: null,
|
|
2100
|
+
refCount: 0,
|
|
2101
|
+
idleTimer: null,
|
|
2102
|
+
idleExitSec: 0,
|
|
2103
|
+
state: "ready",
|
|
2104
|
+
lockOwned: false,
|
|
2105
|
+
outputTail: "",
|
|
2106
|
+
exitInfo: null,
|
|
2107
|
+
resolveExit: () => {},
|
|
2108
|
+
exitPromise: Promise.resolve(),
|
|
2109
|
+
termination: null,
|
|
2110
|
+
handle: null,
|
|
2111
|
+
...o.maxAgeMs !== undefined ? { maxAgeMs: o.maxAgeMs } : {},
|
|
2112
|
+
...o.mintCookie !== undefined ? { mintCookie: o.mintCookie } : {}
|
|
2113
|
+
};
|
|
2114
|
+
registry.set(o.key, host);
|
|
2115
|
+
host.cookieHeader = await mintCookieWithRetry(host);
|
|
2116
|
+
return host;
|
|
2117
|
+
}
|
|
2118
|
+
async function ensureV2Host(opts = {}) {
|
|
2119
|
+
const o = resolveOptions(opts);
|
|
2120
|
+
const live = registry.get(o.key);
|
|
2121
|
+
if (live && live.state === "ready" && live.v2Managed) {
|
|
2122
|
+
attachHost(live);
|
|
2123
|
+
return makeHandle(live);
|
|
2124
|
+
}
|
|
2125
|
+
const pending = pendingBoots.get(o.key);
|
|
2126
|
+
if (pending) {
|
|
2127
|
+
const host = await pending;
|
|
2128
|
+
attachHost(host);
|
|
2129
|
+
return makeHandle(host);
|
|
2130
|
+
}
|
|
2131
|
+
const boot = bootV2Host(o, opts).finally(() => pendingBoots.delete(o.key));
|
|
2132
|
+
pendingBoots.set(o.key, boot);
|
|
2133
|
+
const host = await boot;
|
|
2134
|
+
attachHost(host);
|
|
2135
|
+
return makeHandle(host);
|
|
2136
|
+
}
|
|
2137
|
+
async function ensureHost2(opts = {}) {
|
|
2138
|
+
const o = resolveOptions(opts);
|
|
2139
|
+
if (isV2Registry(o.dshHome, o.profile))
|
|
2140
|
+
return ensureV2Host(opts);
|
|
2141
|
+
const live = registry.get(o.key);
|
|
2142
|
+
if (live && live.state === "ready") {
|
|
2143
|
+
attachHost(live);
|
|
2144
|
+
return makeHandle(live);
|
|
2145
|
+
}
|
|
2146
|
+
const pending = pendingBoots.get(o.key);
|
|
2147
|
+
if (pending) {
|
|
2148
|
+
const host = await pending;
|
|
2149
|
+
attachHost(host);
|
|
2150
|
+
return makeHandle(host);
|
|
2151
|
+
}
|
|
2152
|
+
const boot = bootHost(o).finally(() => pendingBoots.delete(o.key));
|
|
2153
|
+
pendingBoots.set(o.key, boot);
|
|
2154
|
+
const host = await boot;
|
|
2155
|
+
attachHost(host);
|
|
2156
|
+
return makeHandle(host);
|
|
2157
|
+
}
|
|
2158
|
+
var DEFAULT_PROFILE = "opentui", DEFAULT_IDLE_EXIT_MS = 5000, DEFAULT_IDLE_EXIT_SEC, ENV_IDLE_EXIT_MS = "DSH_OPENTUI_HOST_IDLE_MS", DEFAULT_READINESS_TIMEOUT_MS = 30000, ENV_BOOT_TIMEOUT_MS = "DSH_OPENTUI_BOOT_TIMEOUT_MS", ENV_MUX_TIMEOUT_MS = "DSH_OPENTUI_MUX_TIMEOUT_MS", DEFAULT_SERVE_PROBE_BUDGET_MS = 20000, ENV_CONNECT_TIMEOUT_MS = "DSH_OPENTUI_CONNECT_TIMEOUT_MS", DEFAULT_CONNECT_TIMEOUT_MS = 30000, DEFAULT_STALE_PROBE_MS = 8000, BOOT_JOIN_MARGIN_MS = 20000, BOOT_JOIN_POLL_MS = 200, RESPAWN_WINDOW_MS = 15000, MAX_RAPID_RESPAWNS = 3, LISTEN_PROBE_TIMEOUT_MS = 750, LISTEN_POLL_MS = 200, ADOPT_PROBE_TIMEOUT_MS = 2000, SERVE_PROBE_POLL_MS = 250, ERROR_TAIL_LINES = 12, KILL_GRACE_MS = 5000, KILL_ESCALATE_MS = 2000, OUTPUT_TAIL_CAP = 8000, URL_LINE, HostLifecycleError, HostBootTimeoutError, HostDiedError, HostNotServingError, HostSpawnError, HostRespawnLoopError, HostBootSupersededError, ProfileMissingError, MintUnavailableError, registry, pendingBoots, respawnHistory, sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms)), realMintPromise = null, RETRYABLE_MINT_ERRORS, MINT_RETRY_BUDGET_MS = 15000, MINT_RETRY_INTERVAL_MS = 250, FFI_FLAG2 = "--experimental-ffi", __internals;
|
|
2159
|
+
var init_lifecycle = __esm(() => {
|
|
2160
|
+
init_host_probe();
|
|
2161
|
+
init_append_system();
|
|
2162
|
+
init_safe_kill();
|
|
2163
|
+
DEFAULT_IDLE_EXIT_SEC = DEFAULT_IDLE_EXIT_MS / 1000;
|
|
2164
|
+
URL_LINE = /dsh web: (https?:\/\/\S+)/;
|
|
2165
|
+
HostLifecycleError = class HostLifecycleError extends Error {
|
|
2166
|
+
code;
|
|
2167
|
+
constructor(code, message) {
|
|
2168
|
+
super(message);
|
|
2169
|
+
this.name = new.target.name;
|
|
2170
|
+
this.code = code;
|
|
2171
|
+
}
|
|
2172
|
+
};
|
|
2173
|
+
HostBootTimeoutError = class HostBootTimeoutError extends HostLifecycleError {
|
|
2174
|
+
budgetMs;
|
|
2175
|
+
outputTail;
|
|
2176
|
+
constructor(budgetMs, outputTail) {
|
|
2177
|
+
super("host-boot-timeout", `dsh host did not become ready within ${budgetMs}ms${errorTail(outputTail)}`);
|
|
2178
|
+
this.budgetMs = budgetMs;
|
|
2179
|
+
this.outputTail = outputTail;
|
|
2180
|
+
}
|
|
2181
|
+
};
|
|
2182
|
+
HostDiedError = class HostDiedError extends HostLifecycleError {
|
|
2183
|
+
exitCode;
|
|
2184
|
+
signal;
|
|
2185
|
+
outputTail;
|
|
2186
|
+
constructor(exitCode, signal, outputTail) {
|
|
2187
|
+
super("host-died", `dsh host exited before readiness (code=${exitCode ?? "null"}, signal=${signal ?? "null"})${errorTail(outputTail)}`);
|
|
2188
|
+
this.exitCode = exitCode;
|
|
2189
|
+
this.signal = signal;
|
|
2190
|
+
this.outputTail = outputTail;
|
|
2191
|
+
}
|
|
2192
|
+
};
|
|
2193
|
+
HostNotServingError = class HostNotServingError extends HostLifecycleError {
|
|
2194
|
+
outputTail;
|
|
2195
|
+
budgetMs;
|
|
2196
|
+
constructor(outputTail, budgetMs = DEFAULT_SERVE_PROBE_BUDGET_MS) {
|
|
2197
|
+
super("host-not-serving", `dsh host is listening but never served the client mux (${budgetMs}ms budget)${errorTail(outputTail)}`);
|
|
2198
|
+
this.outputTail = outputTail;
|
|
2199
|
+
this.budgetMs = budgetMs;
|
|
2200
|
+
}
|
|
2201
|
+
};
|
|
2202
|
+
HostSpawnError = class HostSpawnError extends HostLifecycleError {
|
|
2203
|
+
cause;
|
|
2204
|
+
constructor(cause) {
|
|
2205
|
+
super("host-spawn-failed", `failed to start dsh host: ${cause.message}`);
|
|
2206
|
+
this.cause = cause;
|
|
2207
|
+
this.name = new.target.name;
|
|
2208
|
+
}
|
|
2209
|
+
};
|
|
2210
|
+
HostRespawnLoopError = class HostRespawnLoopError extends HostLifecycleError {
|
|
2211
|
+
attempts;
|
|
2212
|
+
windowMs;
|
|
2213
|
+
constructor(attempts, windowMs) {
|
|
2214
|
+
super("host-respawn-loop", `dsh host failed ${attempts} rapid spawn attempts within ${windowMs}ms \u2014 giving up instead of looping`);
|
|
2215
|
+
this.attempts = attempts;
|
|
2216
|
+
this.windowMs = windowMs;
|
|
2217
|
+
}
|
|
2218
|
+
};
|
|
2219
|
+
HostBootSupersededError = class HostBootSupersededError extends HostLifecycleError {
|
|
2220
|
+
constructor() {
|
|
2221
|
+
super("host-boot-superseded", "another client took over this boot while it was coming up \u2014 our child was shut down; retry ensureHost to join the winner");
|
|
2222
|
+
}
|
|
2223
|
+
};
|
|
2224
|
+
ProfileMissingError = class ProfileMissingError extends HostLifecycleError {
|
|
2225
|
+
profile;
|
|
2226
|
+
profileDir;
|
|
2227
|
+
constructor(profile, profileDir) {
|
|
2228
|
+
super("profile-missing", `profile '${profile}' is not provisioned (${profileDir} missing) \u2014 run scripts/provision-opentui-profile.mjs or: dsh ${profile} --from-default-profile web --dump-config`);
|
|
2229
|
+
this.profile = profile;
|
|
2230
|
+
this.profileDir = profileDir;
|
|
2231
|
+
}
|
|
2232
|
+
};
|
|
2233
|
+
MintUnavailableError = class MintUnavailableError extends HostLifecycleError {
|
|
2234
|
+
constructor() {
|
|
2235
|
+
super("mint-unavailable", "mintOwnerCookie is unavailable: ./cookie-mint.ts not found and no mintCookie injected");
|
|
2236
|
+
}
|
|
2237
|
+
};
|
|
2238
|
+
registry = new Map;
|
|
2239
|
+
pendingBoots = new Map;
|
|
2240
|
+
respawnHistory = new Map;
|
|
2241
|
+
RETRYABLE_MINT_ERRORS = new Set(["CredentialsFileMissingError", "CredentialsGrantMissingError"]);
|
|
2242
|
+
__internals = {
|
|
2243
|
+
registry,
|
|
2244
|
+
pendingBoots,
|
|
2245
|
+
respawnHistory,
|
|
2246
|
+
loadRealMint,
|
|
2247
|
+
lockPathFor,
|
|
2248
|
+
registryKey
|
|
2249
|
+
};
|
|
2250
|
+
});
|
|
2251
|
+
|
|
2252
|
+
// src/client/host-registry.ts
|
|
2253
|
+
import { randomUUID as randomUUID2 } from "crypto";
|
|
2254
|
+
import {
|
|
2255
|
+
existsSync as existsSync2,
|
|
2256
|
+
linkSync as linkSync2,
|
|
2257
|
+
mkdirSync as mkdirSync3,
|
|
2258
|
+
readFileSync as readFileSync4,
|
|
2259
|
+
renameSync as renameSync3,
|
|
2260
|
+
unlinkSync as unlinkSync2,
|
|
2261
|
+
writeFileSync as writeFileSync3
|
|
2262
|
+
} from "fs";
|
|
2263
|
+
import { join as join5 } from "path";
|
|
2264
|
+
function registryPath(home, profile) {
|
|
2265
|
+
return join5(home, `opentui-host.${profile}.json`);
|
|
2266
|
+
}
|
|
2267
|
+
function isPlainObject(value) {
|
|
2268
|
+
return value !== null && typeof value === "object" && !Array.isArray(value);
|
|
2269
|
+
}
|
|
2270
|
+
function isInteger(value) {
|
|
2271
|
+
return typeof value === "number" && Number.isInteger(value);
|
|
2272
|
+
}
|
|
2273
|
+
function isString(value) {
|
|
2274
|
+
return typeof value === "string";
|
|
2275
|
+
}
|
|
2276
|
+
function nonEmpty(value) {
|
|
2277
|
+
return isString(value) && value.trim() !== "";
|
|
2278
|
+
}
|
|
2279
|
+
function invalid(reason, raw) {
|
|
2280
|
+
return { kind: "invalid", raw, reason };
|
|
2281
|
+
}
|
|
2282
|
+
function validateRegistry(raw) {
|
|
2283
|
+
if (!isPlainObject(raw))
|
|
2284
|
+
return invalid("registry is not an object", raw);
|
|
2285
|
+
if (raw.version === REGISTRY_SCHEMA_VERSION) {
|
|
2286
|
+
if (!nonEmpty(raw.profile))
|
|
2287
|
+
return invalid("profile must be a non-empty string", raw);
|
|
2288
|
+
if (!nonEmpty(raw.home))
|
|
2289
|
+
return invalid("home must be a non-empty string", raw);
|
|
2290
|
+
if (!isInteger(raw.pid) || raw.pid < 0)
|
|
2291
|
+
return invalid("pid must be a non-negative integer", raw);
|
|
2292
|
+
if (!isInteger(raw.port) || raw.port < 0 || raw.port > 65535)
|
|
2293
|
+
return invalid("port must be an integer in [0, 65535]", raw);
|
|
2294
|
+
if (!REGISTRY_PHASES.includes(raw.phase)) {
|
|
2295
|
+
return invalid(`phase must be one of ${REGISTRY_PHASES.join("|")}`, raw);
|
|
2296
|
+
}
|
|
2297
|
+
if (!nonEmpty(raw.startedAt))
|
|
2298
|
+
return invalid("startedAt must be a non-empty string", raw);
|
|
2299
|
+
if (!nonEmpty(raw.updatedAt))
|
|
2300
|
+
return invalid("updatedAt must be a non-empty string", raw);
|
|
2301
|
+
if (!isString(raw.authority))
|
|
2302
|
+
return invalid("authority must be a string", raw);
|
|
2303
|
+
if (!Array.isArray(raw.clients))
|
|
2304
|
+
return invalid("clients must be an array", raw);
|
|
2305
|
+
const clients = [];
|
|
2306
|
+
for (const [index, item] of raw.clients.entries()) {
|
|
2307
|
+
if (!isPlainObject(item))
|
|
2308
|
+
return invalid(`clients[${index}] must be an object`, raw);
|
|
2309
|
+
if (!nonEmpty(item.id))
|
|
2310
|
+
return invalid(`clients[${index}].id must be a non-empty string`, raw);
|
|
2311
|
+
if (!isInteger(item.pid) || item.pid < 0)
|
|
2312
|
+
return invalid(`clients[${index}].pid must be a non-negative integer`, raw);
|
|
2313
|
+
if (!nonEmpty(item.lastSeen))
|
|
2314
|
+
return invalid(`clients[${index}].lastSeen must be a non-empty string`, raw);
|
|
2315
|
+
clients.push({ id: item.id, pid: item.pid, lastSeen: item.lastSeen });
|
|
2316
|
+
}
|
|
2317
|
+
return {
|
|
2318
|
+
kind: "v2",
|
|
2319
|
+
value: {
|
|
2320
|
+
version: 2,
|
|
2321
|
+
profile: raw.profile,
|
|
2322
|
+
home: raw.home,
|
|
2323
|
+
pid: raw.pid,
|
|
2324
|
+
port: raw.port,
|
|
2325
|
+
phase: raw.phase,
|
|
2326
|
+
startedAt: raw.startedAt,
|
|
2327
|
+
updatedAt: raw.updatedAt,
|
|
2328
|
+
authority: raw.authority,
|
|
2329
|
+
clients
|
|
2330
|
+
}
|
|
2331
|
+
};
|
|
2332
|
+
}
|
|
2333
|
+
if (raw.version !== undefined)
|
|
2334
|
+
return invalid(`unsupported registry version ${String(raw.version)}`, raw);
|
|
2335
|
+
if (!isInteger(raw.pid) || !isInteger(raw.port)) {
|
|
2336
|
+
return invalid("legacy registry is missing pid/port", raw);
|
|
2337
|
+
}
|
|
2338
|
+
return {
|
|
2339
|
+
kind: "legacy",
|
|
2340
|
+
raw: {
|
|
2341
|
+
pid: raw.pid,
|
|
2342
|
+
port: raw.port,
|
|
2343
|
+
...isString(raw.authority) ? { authority: raw.authority } : {},
|
|
2344
|
+
...isString(raw.startedAt) ? { startedAt: raw.startedAt } : {},
|
|
2345
|
+
...isString(raw.profile) ? { profile: raw.profile } : {},
|
|
2346
|
+
...raw.booting === true ? { booting: true } : {}
|
|
2347
|
+
}
|
|
2348
|
+
};
|
|
2349
|
+
}
|
|
2350
|
+
function createClaimRegistry(home, profile, pid, nowIso) {
|
|
2351
|
+
return {
|
|
2352
|
+
version: 2,
|
|
2353
|
+
profile,
|
|
2354
|
+
home,
|
|
2355
|
+
pid,
|
|
2356
|
+
port: 0,
|
|
2357
|
+
phase: "claim",
|
|
2358
|
+
startedAt: nowIso,
|
|
2359
|
+
updatedAt: nowIso,
|
|
2360
|
+
authority: "",
|
|
2361
|
+
clients: []
|
|
2362
|
+
};
|
|
2363
|
+
}
|
|
2364
|
+
function withPhase(reg, phase, nowIso) {
|
|
2365
|
+
return { ...reg, phase, updatedAt: nowIso };
|
|
2366
|
+
}
|
|
2367
|
+
function readRegistryAt(path, fs = nodeRegistryFs) {
|
|
2368
|
+
let text;
|
|
2369
|
+
try {
|
|
2370
|
+
text = fs.readFileSync(path, "utf8");
|
|
2371
|
+
} catch {
|
|
2372
|
+
return { kind: "missing" };
|
|
2373
|
+
}
|
|
2374
|
+
let raw;
|
|
2375
|
+
try {
|
|
2376
|
+
raw = JSON.parse(text);
|
|
2377
|
+
} catch {
|
|
2378
|
+
return invalid("registry file is not valid JSON", text);
|
|
2379
|
+
}
|
|
2380
|
+
return validateRegistry(raw);
|
|
2381
|
+
}
|
|
2382
|
+
function readRegistry(home, profile, fs = nodeRegistryFs) {
|
|
2383
|
+
return readRegistryAt(registryPath(home, profile), fs);
|
|
2384
|
+
}
|
|
2385
|
+
function writeRegistry(home, profile, record, fs = nodeRegistryFs) {
|
|
2386
|
+
const checked = validateRegistry(record);
|
|
2387
|
+
if (checked.kind !== "v2") {
|
|
2388
|
+
throw new Error(`writeRegistry: refusing to write invalid v2 record (${checked.kind === "invalid" ? checked.reason : checked.kind})`);
|
|
2389
|
+
}
|
|
2390
|
+
fs.mkdirSync(home, { recursive: true });
|
|
2391
|
+
const path = registryPath(home, profile);
|
|
2392
|
+
const tmp = `${path}.tmp-${process.pid}-${++writeSeq}`;
|
|
2393
|
+
fs.writeFileSync(tmp, JSON.stringify(checked.value, null, 2) + `
|
|
2394
|
+
`);
|
|
2395
|
+
try {
|
|
2396
|
+
fs.renameSync(tmp, path);
|
|
2397
|
+
} catch (error) {
|
|
2398
|
+
try {
|
|
2399
|
+
fs.unlinkSync(tmp);
|
|
2400
|
+
} catch {}
|
|
2401
|
+
throw error;
|
|
2402
|
+
}
|
|
2403
|
+
}
|
|
2404
|
+
function isErrno(error, code) {
|
|
2405
|
+
return error instanceof Error && error.code === code;
|
|
2406
|
+
}
|
|
2407
|
+
function claimRegistry(home, profile, options = {}) {
|
|
2408
|
+
const fs = options.fs ?? nodeRegistryFs;
|
|
2409
|
+
const now = options.now ?? Date.now;
|
|
2410
|
+
const pid = options.pid ?? process.pid;
|
|
2411
|
+
const nowIso = new Date(now()).toISOString();
|
|
2412
|
+
fs.mkdirSync(home, { recursive: true });
|
|
2413
|
+
const path = registryPath(home, profile);
|
|
2414
|
+
const registry = createClaimRegistry(home, profile, pid, nowIso);
|
|
2415
|
+
const tmp = `${path}.claim-${process.pid}-${randomUUID2()}`;
|
|
2416
|
+
fs.writeFileSync(tmp, JSON.stringify(registry, null, 2) + `
|
|
2417
|
+
`);
|
|
2418
|
+
try {
|
|
2419
|
+
fs.linkSync(tmp, path);
|
|
2420
|
+
return { ok: true, token: registry.startedAt, path, registry };
|
|
2421
|
+
} catch (error) {
|
|
2422
|
+
if (isErrno(error, "EEXIST"))
|
|
2423
|
+
return { ok: false, reason: "occupied", path };
|
|
2424
|
+
throw error;
|
|
2425
|
+
} finally {
|
|
2426
|
+
try {
|
|
2427
|
+
fs.unlinkSync(tmp);
|
|
2428
|
+
} catch {}
|
|
2429
|
+
}
|
|
2430
|
+
}
|
|
2431
|
+
function looksLikeV2(value) {
|
|
2432
|
+
const candidate = value;
|
|
2433
|
+
return isPlainObject(candidate) && candidate.version === REGISTRY_SCHEMA_VERSION;
|
|
2434
|
+
}
|
|
2435
|
+
function isRegistryStale(input, deps = {}) {
|
|
2436
|
+
const read = looksLikeV2(input) ? { kind: "v2", value: input } : input;
|
|
2437
|
+
if (read.kind === "missing")
|
|
2438
|
+
return { stale: false, reasons: [] };
|
|
2439
|
+
if (read.kind === "legacy")
|
|
2440
|
+
return { stale: true, reasons: ["legacy-schema"] };
|
|
2441
|
+
if (read.kind === "invalid")
|
|
2442
|
+
return { stale: true, reasons: ["invalid-schema"] };
|
|
2443
|
+
const reasons = [];
|
|
2444
|
+
const alive = deps.pidAlive ?? pidAlive;
|
|
2445
|
+
if (!alive(read.value.pid))
|
|
2446
|
+
reasons.push("dead-pid");
|
|
2447
|
+
if (deps.registryMaxAgeMs !== undefined && (read.value.phase === "claim" || read.value.phase === "booting")) {
|
|
2448
|
+
const now = (deps.now ?? Date.now)();
|
|
2449
|
+
const updated = Date.parse(read.value.updatedAt);
|
|
2450
|
+
if (!Number.isNaN(updated) && now - updated > deps.registryMaxAgeMs)
|
|
2451
|
+
reasons.push("registry-too-old");
|
|
2452
|
+
}
|
|
2453
|
+
return { stale: reasons.length > 0, reasons };
|
|
2454
|
+
}
|
|
2455
|
+
function safeClearLegacy(home, profile, options = {}) {
|
|
2456
|
+
const fs = options.fs ?? nodeRegistryFs;
|
|
2457
|
+
const path = registryPath(home, profile);
|
|
2458
|
+
const read = options.read ?? readRegistryAt(path, fs);
|
|
2459
|
+
if (read.kind === "missing")
|
|
2460
|
+
return { removed: false, reason: "missing" };
|
|
2461
|
+
if (read.kind !== "legacy")
|
|
2462
|
+
return { removed: false, reason: "not-legacy" };
|
|
2463
|
+
const alive = options.pidAlive ?? pidAlive;
|
|
2464
|
+
if (read.raw.pid > 0 && alive(read.raw.pid)) {
|
|
2465
|
+
return { removed: false, reason: "legacy-host-alive" };
|
|
2466
|
+
}
|
|
2467
|
+
fs.unlinkSync(path);
|
|
2468
|
+
return { removed: true, reason: "legacy-removed" };
|
|
2469
|
+
}
|
|
2470
|
+
var REGISTRY_SCHEMA_VERSION = 2, REGISTRY_PHASES, nodeRegistryFs, writeSeq = 0;
|
|
2471
|
+
var init_host_registry = __esm(() => {
|
|
2472
|
+
init_lifecycle();
|
|
2473
|
+
REGISTRY_PHASES = ["claim", "booting", "ready", "stopping"];
|
|
2474
|
+
nodeRegistryFs = {
|
|
2475
|
+
existsSync: (path) => existsSync2(path),
|
|
2476
|
+
mkdirSync: (path, options) => {
|
|
2477
|
+
mkdirSync3(path, options);
|
|
2478
|
+
},
|
|
2479
|
+
readFileSync: (path, encoding) => readFileSync4(path, encoding),
|
|
2480
|
+
writeFileSync: (path, data, options) => {
|
|
2481
|
+
writeFileSync3(path, data, options);
|
|
2482
|
+
},
|
|
2483
|
+
renameSync: (from, to) => renameSync3(from, to),
|
|
2484
|
+
linkSync: (from, to) => linkSync2(from, to),
|
|
2485
|
+
unlinkSync: (path) => unlinkSync2(path)
|
|
2486
|
+
};
|
|
2487
|
+
});
|
|
2488
|
+
|
|
2489
|
+
// src/client/client-lifecycle.ts
|
|
2490
|
+
var exports_client_lifecycle = {};
|
|
2491
|
+
__export(exports_client_lifecycle, {
|
|
2492
|
+
CLIENTS_DIR_NAME: () => CLIENTS_DIR_NAME,
|
|
2493
|
+
DEFAULT_CLIENT_TTL_MS: () => DEFAULT_CLIENT_TTL_MS,
|
|
2494
|
+
DEFAULT_HEARTBEAT_INTERVAL_MS: () => DEFAULT_HEARTBEAT_INTERVAL_MS,
|
|
2495
|
+
DEFAULT_LAST_ONE_GRACE_MS: () => DEFAULT_LAST_ONE_GRACE_MS,
|
|
2496
|
+
DEFAULT_WATCHDOG_POLL_MS: () => DEFAULT_WATCHDOG_POLL_MS,
|
|
2497
|
+
ENV_IDLE_MS: () => ENV_IDLE_MS,
|
|
2498
|
+
ENV_WATCHDOG: () => ENV_WATCHDOG,
|
|
2499
|
+
ENV_WATCHDOG_HOME: () => ENV_WATCHDOG_HOME,
|
|
2500
|
+
ENV_WATCHDOG_PROFILE: () => ENV_WATCHDOG_PROFILE,
|
|
2501
|
+
ForceNeedsYesError: () => ForceNeedsYesError,
|
|
2502
|
+
IncompleteLifecycleFsError: () => IncompleteLifecycleFsError,
|
|
2503
|
+
assertForceAllowed: () => assertForceAllowed,
|
|
2504
|
+
clientsDir: () => clientsDir,
|
|
2505
|
+
freshClients: () => freshClients,
|
|
2506
|
+
heartbeatPath: () => heartbeatPath,
|
|
2507
|
+
isFresh: () => isFresh,
|
|
2508
|
+
lastOneGracefulShutdown: () => lastOneGracefulShutdown,
|
|
2509
|
+
listHeartbeats: () => listHeartbeats,
|
|
2510
|
+
newClientId: () => newClientId,
|
|
2511
|
+
nodeLifecycleFs: () => nodeLifecycleFs,
|
|
2512
|
+
psKillHooks: () => psKillHooks,
|
|
2513
|
+
purgeAllHeartbeats: () => purgeAllHeartbeats,
|
|
2514
|
+
purgeStaleHeartbeats: () => purgeStaleHeartbeats,
|
|
2515
|
+
registerHeartbeat: () => registerHeartbeat,
|
|
2516
|
+
resolveGraceMs: () => resolveGraceMs,
|
|
2517
|
+
runWatchdog: () => runWatchdog,
|
|
2518
|
+
spawnWatchdog: () => spawnWatchdog,
|
|
2519
|
+
validateHeartbeat: () => validateHeartbeat
|
|
2520
|
+
});
|
|
2521
|
+
import { spawn as nodeSpawn } from "child_process";
|
|
2522
|
+
import { randomUUID as randomUUID3 } from "crypto";
|
|
2523
|
+
import {
|
|
2524
|
+
existsSync as nodeExistsSync,
|
|
2525
|
+
mkdirSync as nodeMkdirSync,
|
|
2526
|
+
readFileSync as nodeReadFileSync,
|
|
2527
|
+
readdirSync as nodeReaddirSync,
|
|
2528
|
+
renameSync as nodeRenameSync,
|
|
2529
|
+
unlinkSync as nodeUnlinkSync,
|
|
2530
|
+
writeFileSync as nodeWriteFileSync
|
|
2531
|
+
} from "fs";
|
|
2532
|
+
import { join as join6 } from "path";
|
|
2533
|
+
function clientsDir(home) {
|
|
2534
|
+
return join6(home, CLIENTS_DIR_NAME);
|
|
2535
|
+
}
|
|
2536
|
+
function heartbeatPath(home, clientId) {
|
|
2537
|
+
return join6(clientsDir(home), `${clientId}.json`);
|
|
2538
|
+
}
|
|
2539
|
+
function validateHeartbeat(raw) {
|
|
2540
|
+
if (raw === null || typeof raw !== "object" || Array.isArray(raw))
|
|
2541
|
+
return null;
|
|
2542
|
+
const r = raw;
|
|
2543
|
+
if (typeof r.id !== "string" || r.id.trim() === "")
|
|
2544
|
+
return null;
|
|
2545
|
+
if (typeof r.pid !== "number" || !Number.isInteger(r.pid) || r.pid < 0)
|
|
2546
|
+
return null;
|
|
2547
|
+
if (typeof r.lastSeen !== "string" || r.lastSeen.trim() === "")
|
|
2548
|
+
return null;
|
|
2549
|
+
if (Number.isNaN(Date.parse(r.lastSeen)))
|
|
2550
|
+
return null;
|
|
2551
|
+
if (typeof r.workspace !== "string")
|
|
2552
|
+
return null;
|
|
2553
|
+
return { id: r.id, pid: r.pid, lastSeen: r.lastSeen, workspace: r.workspace };
|
|
2554
|
+
}
|
|
2555
|
+
function isFresh(hb, nowMs, ttlMs) {
|
|
2556
|
+
const seen = Date.parse(hb.lastSeen);
|
|
2557
|
+
if (Number.isNaN(seen))
|
|
2558
|
+
return false;
|
|
2559
|
+
const age = nowMs - seen;
|
|
2560
|
+
return age >= 0 && age <= ttlMs;
|
|
2561
|
+
}
|
|
2562
|
+
function resolveGraceMs(explicitMs, env) {
|
|
2563
|
+
if (explicitMs !== undefined && Number.isFinite(explicitMs))
|
|
2564
|
+
return Math.max(0, Math.round(explicitMs));
|
|
2565
|
+
const raw = (env ?? process.env)[ENV_IDLE_MS];
|
|
2566
|
+
if (raw !== undefined && /^\d+$/.test(raw)) {
|
|
2567
|
+
const parsed = Number(raw);
|
|
2568
|
+
if (Number.isFinite(parsed))
|
|
2569
|
+
return Math.round(parsed);
|
|
2570
|
+
}
|
|
2571
|
+
return DEFAULT_LAST_ONE_GRACE_MS;
|
|
2572
|
+
}
|
|
2573
|
+
function writeHeartbeatFile(home, hb, fs) {
|
|
2574
|
+
fs.mkdirSync(clientsDir(home), { recursive: true });
|
|
2575
|
+
const path = heartbeatPath(home, hb.id);
|
|
2576
|
+
const payload = JSON.stringify(hb, null, 2) + `
|
|
2577
|
+
`;
|
|
2578
|
+
if (fs.renameSync) {
|
|
2579
|
+
const tmp = `${path}.tmp-${hb.id}`;
|
|
2580
|
+
fs.writeFileSync(tmp, payload);
|
|
2581
|
+
fs.renameSync(tmp, path);
|
|
2582
|
+
} else {
|
|
2583
|
+
fs.writeFileSync(path, payload);
|
|
2584
|
+
}
|
|
2585
|
+
}
|
|
2586
|
+
function newClientId() {
|
|
2587
|
+
return `${process.pid}-${randomUUID3()}`;
|
|
2588
|
+
}
|
|
2589
|
+
function registerHeartbeat(home, info, deps = {}) {
|
|
2590
|
+
const fs = deps.fs ?? nodeLifecycleFs;
|
|
2591
|
+
const now = deps.now ?? Date.now;
|
|
2592
|
+
const id = info.id ?? newClientId();
|
|
2593
|
+
const pid = info.pid ?? process.pid;
|
|
2594
|
+
const started = {
|
|
2595
|
+
id,
|
|
2596
|
+
pid,
|
|
2597
|
+
lastSeen: new Date(now()).toISOString(),
|
|
2598
|
+
workspace: info.workspace
|
|
2599
|
+
};
|
|
2600
|
+
writeHeartbeatFile(home, started, fs);
|
|
2601
|
+
let record = started;
|
|
2602
|
+
let timer = null;
|
|
2603
|
+
const refresh = () => {
|
|
2604
|
+
record = { ...record, lastSeen: new Date(now()).toISOString() };
|
|
2605
|
+
writeHeartbeatFile(home, record, fs);
|
|
2606
|
+
return record;
|
|
2607
|
+
};
|
|
2608
|
+
return {
|
|
2609
|
+
id,
|
|
2610
|
+
get record() {
|
|
2611
|
+
return record;
|
|
2612
|
+
},
|
|
2613
|
+
refresh,
|
|
2614
|
+
start(intervalMs = DEFAULT_HEARTBEAT_INTERVAL_MS) {
|
|
2615
|
+
if (timer)
|
|
2616
|
+
return;
|
|
2617
|
+
timer = setInterval(() => {
|
|
2618
|
+
try {
|
|
2619
|
+
refresh();
|
|
2620
|
+
} catch {}
|
|
2621
|
+
}, intervalMs);
|
|
2622
|
+
timer.unref?.();
|
|
2623
|
+
},
|
|
2624
|
+
stop() {
|
|
2625
|
+
if (timer) {
|
|
2626
|
+
clearInterval(timer);
|
|
2627
|
+
timer = null;
|
|
2628
|
+
}
|
|
2629
|
+
},
|
|
2630
|
+
remove() {
|
|
2631
|
+
try {
|
|
2632
|
+
if (!fs.existsSync(heartbeatPath(home, id)))
|
|
2633
|
+
return false;
|
|
2634
|
+
fs.unlinkSync(heartbeatPath(home, id));
|
|
2635
|
+
return true;
|
|
2636
|
+
} catch {
|
|
2637
|
+
return false;
|
|
2638
|
+
}
|
|
2639
|
+
}
|
|
2640
|
+
};
|
|
2641
|
+
}
|
|
2642
|
+
function listHeartbeats(home, deps = {}) {
|
|
2643
|
+
const fs = deps.fs ?? nodeLifecycleFs;
|
|
2644
|
+
if (!fs.readdirSync)
|
|
2645
|
+
return [];
|
|
2646
|
+
let names;
|
|
2647
|
+
try {
|
|
2648
|
+
names = fs.readdirSync(clientsDir(home));
|
|
2649
|
+
} catch {
|
|
2650
|
+
return [];
|
|
2651
|
+
}
|
|
2652
|
+
const out = [];
|
|
2653
|
+
for (const name of names) {
|
|
2654
|
+
if (!name.endsWith(".json"))
|
|
2655
|
+
continue;
|
|
2656
|
+
try {
|
|
2657
|
+
const raw = JSON.parse(fs.readFileSync(join6(clientsDir(home), name), "utf8"));
|
|
2658
|
+
const hb = validateHeartbeat(raw);
|
|
2659
|
+
if (hb)
|
|
2660
|
+
out.push(hb);
|
|
2661
|
+
} catch {}
|
|
2662
|
+
}
|
|
2663
|
+
return out;
|
|
2664
|
+
}
|
|
2665
|
+
function freshClients(home, deps = {}, ttlMs = DEFAULT_CLIENT_TTL_MS) {
|
|
2666
|
+
const now = deps.now ?? Date.now;
|
|
2667
|
+
const nowMs = now();
|
|
2668
|
+
return listHeartbeats(home, deps).filter((hb) => isFresh(hb, nowMs, ttlMs));
|
|
2669
|
+
}
|
|
2670
|
+
function purgeAllHeartbeats(home, deps = {}) {
|
|
2671
|
+
const fs = deps.fs ?? nodeLifecycleFs;
|
|
2672
|
+
const removed = [];
|
|
2673
|
+
for (const hb of listHeartbeats(home, deps)) {
|
|
2674
|
+
try {
|
|
2675
|
+
fs.unlinkSync(heartbeatPath(home, hb.id));
|
|
2676
|
+
removed.push(hb.id);
|
|
2677
|
+
} catch {}
|
|
2678
|
+
}
|
|
2679
|
+
return removed;
|
|
2680
|
+
}
|
|
2681
|
+
function purgeStaleHeartbeats(home, deps = {}, ttlMs = DEFAULT_CLIENT_TTL_MS) {
|
|
2682
|
+
const fs = deps.fs ?? nodeLifecycleFs;
|
|
2683
|
+
const now = deps.now ?? Date.now;
|
|
2684
|
+
const nowMs = now();
|
|
2685
|
+
const removed = [];
|
|
2686
|
+
for (const hb of listHeartbeats(home, deps)) {
|
|
2687
|
+
if (isFresh(hb, nowMs, ttlMs))
|
|
2688
|
+
continue;
|
|
2689
|
+
try {
|
|
2690
|
+
fs.unlinkSync(heartbeatPath(home, hb.id));
|
|
2691
|
+
removed.push(hb.id);
|
|
2692
|
+
} catch {}
|
|
2693
|
+
}
|
|
2694
|
+
return removed;
|
|
2695
|
+
}
|
|
2696
|
+
async function lastOneGracefulShutdown(home, options) {
|
|
2697
|
+
const profile = options.profile ?? "opentui";
|
|
2698
|
+
const fs = options.fs ?? nodeLifecycleFs;
|
|
2699
|
+
const read = readRegistry(home, profile, fs);
|
|
2700
|
+
if (read.kind !== "v2" || read.value.pid <= 0) {
|
|
2701
|
+
return { action: "no-host", freshCount: freshClients(home, options, options.ttlMs).length };
|
|
2702
|
+
}
|
|
2703
|
+
const graceMs = resolveGraceMs(options.graceMs);
|
|
2704
|
+
if (graceMs === 0)
|
|
2705
|
+
return { action: "resident", freshCount: freshClients(home, options, options.ttlMs).length };
|
|
2706
|
+
const nowCount = freshClients(home, options, options.ttlMs).length;
|
|
2707
|
+
if (nowCount > 0)
|
|
2708
|
+
return { action: "others-alive", freshCount: nowCount };
|
|
2709
|
+
const sleep = options.sleep ?? defaultSleep3;
|
|
2710
|
+
await sleep(graceMs);
|
|
2711
|
+
const afterCount = freshClients(home, options, options.ttlMs).length;
|
|
2712
|
+
if (afterCount > 0)
|
|
2713
|
+
return { action: "others-alive", freshCount: afterCount };
|
|
2714
|
+
const still = readRegistry(home, profile, fs);
|
|
2715
|
+
if (still.kind !== "v2" || still.value.pid !== read.value.pid)
|
|
2716
|
+
return { action: "no-host", freshCount: 0 };
|
|
2717
|
+
const stop = await safeStopHost({
|
|
2718
|
+
pid: read.value.pid,
|
|
2719
|
+
registryPid: read.value.pid,
|
|
2720
|
+
hooks: options.hooks,
|
|
2721
|
+
termGraceMs: options.termGraceMs,
|
|
2722
|
+
killGraceMs: options.killGraceMs,
|
|
2723
|
+
sleep,
|
|
2724
|
+
now: options.now,
|
|
2725
|
+
pidAlive: options.hooks.pidAlive
|
|
2726
|
+
});
|
|
2727
|
+
if (!stop.evidencesOk)
|
|
2728
|
+
return { action: "evidence-refused", freshCount: 0, stop };
|
|
2729
|
+
if (!stop.stopped)
|
|
2730
|
+
return { action: "stop-failed", freshCount: 0, stop };
|
|
2731
|
+
clearRegistryIfPid(home, profile, still, still.value.pid, fs);
|
|
2732
|
+
return { action: "shutdown", freshCount: 0, stop };
|
|
2733
|
+
}
|
|
2734
|
+
function clearRegistryIfPid(home, profile, read, pid, fs) {
|
|
2735
|
+
if (read.kind === "v2" && read.value.pid === pid) {
|
|
2736
|
+
try {
|
|
2737
|
+
fs.unlinkSync(registryPath(home, profile));
|
|
2738
|
+
} catch {}
|
|
2739
|
+
}
|
|
2740
|
+
}
|
|
2741
|
+
function assertLifecycleFsComplete(fs) {
|
|
2742
|
+
const f = fs ?? nodeLifecycleFs;
|
|
2743
|
+
const missing = ["readdirSync", "readFileSync"].filter((method) => typeof f[method] !== "function");
|
|
2744
|
+
if (missing.length > 0)
|
|
2745
|
+
throw new IncompleteLifecycleFsError([...missing]);
|
|
2746
|
+
}
|
|
2747
|
+
function assertForceAllowed(home, options) {
|
|
2748
|
+
assertLifecycleFsComplete(options.fs);
|
|
2749
|
+
const live = freshClients(home, options, options.ttlMs);
|
|
2750
|
+
if (live.length > 0 && !options.yes)
|
|
2751
|
+
throw new ForceNeedsYesError(live.length);
|
|
2752
|
+
return { liveClients: live.length, allowed: true };
|
|
2753
|
+
}
|
|
2754
|
+
async function runWatchdog(home, options) {
|
|
2755
|
+
const profile = options.profile ?? "opentui";
|
|
2756
|
+
const graceMs = resolveGraceMs(options.graceMs);
|
|
2757
|
+
if (graceMs === 0)
|
|
2758
|
+
return { reclaimed: false, reason: "resident" };
|
|
2759
|
+
const pollMs = options.pollMs ?? DEFAULT_WATCHDOG_POLL_MS;
|
|
2760
|
+
const sleep = options.sleep ?? defaultSleep3;
|
|
2761
|
+
const alive = options.hooks.pidAlive ?? defaultPidAlive;
|
|
2762
|
+
const fs = options.fs ?? nodeLifecycleFs;
|
|
2763
|
+
for (let tick = 0;options.maxTicks === undefined || tick < options.maxTicks; tick++) {
|
|
2764
|
+
const read = readRegistry(home, profile, fs);
|
|
2765
|
+
if (read.kind !== "v2" || read.value.pid <= 0 || !alive(read.value.pid)) {
|
|
2766
|
+
if (read.kind === "v2" && !alive(read.value.pid)) {
|
|
2767
|
+
try {
|
|
2768
|
+
fs.unlinkSync(registryPath(home, profile));
|
|
2769
|
+
} catch {}
|
|
2770
|
+
}
|
|
2771
|
+
return { reclaimed: false, reason: "host-gone" };
|
|
2772
|
+
}
|
|
2773
|
+
const freshCount = freshClients(home, options, options.ttlMs).length;
|
|
2774
|
+
options.onTick?.({ tick, freshCount, hostPid: read.value.pid });
|
|
2775
|
+
if (freshCount > 0) {
|
|
2776
|
+
await sleep(pollMs);
|
|
2777
|
+
continue;
|
|
2778
|
+
}
|
|
2779
|
+
await sleep(graceMs);
|
|
2780
|
+
const again = readRegistry(home, profile, fs);
|
|
2781
|
+
if (again.kind !== "v2" || again.value.pid !== read.value.pid)
|
|
2782
|
+
continue;
|
|
2783
|
+
if (freshClients(home, options, options.ttlMs).length > 0)
|
|
2784
|
+
continue;
|
|
2785
|
+
if (!alive(again.value.pid))
|
|
2786
|
+
continue;
|
|
2787
|
+
const stop = await safeStopHost({
|
|
2788
|
+
pid: again.value.pid,
|
|
2789
|
+
registryPid: again.value.pid,
|
|
2790
|
+
hooks: options.hooks,
|
|
2791
|
+
termGraceMs: options.termGraceMs,
|
|
2792
|
+
killGraceMs: options.killGraceMs,
|
|
2793
|
+
sleep,
|
|
2794
|
+
now: options.now,
|
|
2795
|
+
pidAlive: alive
|
|
2796
|
+
});
|
|
2797
|
+
if (!stop.stopped) {
|
|
2798
|
+
options.onEvidenceRefused?.({ pid: again.value.pid, evidencesOk: stop.evidencesOk });
|
|
2799
|
+
continue;
|
|
2800
|
+
}
|
|
2801
|
+
clearRegistryIfPid(home, profile, again, again.value.pid, fs);
|
|
2802
|
+
return { reclaimed: stop.evidencesOk, reason: "reclaimed", stop };
|
|
2803
|
+
}
|
|
2804
|
+
return { reclaimed: false, reason: "max-ticks" };
|
|
2805
|
+
}
|
|
2806
|
+
function spawnWatchdog(home, options) {
|
|
2807
|
+
const profile = options.profile ?? "opentui";
|
|
2808
|
+
const env = {
|
|
2809
|
+
...options.env ?? process.env,
|
|
2810
|
+
[SERVER_ENV_NAME]: SERVER_ENV_VALUE,
|
|
2811
|
+
[ENV_WATCHDOG]: "1",
|
|
2812
|
+
[ENV_WATCHDOG_HOME]: home,
|
|
2813
|
+
[ENV_WATCHDOG_PROFILE]: profile
|
|
2814
|
+
};
|
|
2815
|
+
const command = options.command ?? process.execPath;
|
|
2816
|
+
const child = (options.spawn ?? defaultSpawnWatchdog)(command, [options.scriptPath, "--profile", profile], {
|
|
2817
|
+
env,
|
|
2818
|
+
detached: true,
|
|
2819
|
+
stdio: "ignore"
|
|
2820
|
+
});
|
|
2821
|
+
child.unref?.();
|
|
2822
|
+
return { pid: child.pid };
|
|
2823
|
+
}
|
|
2824
|
+
function defaultSpawnWatchdog(command, args, options) {
|
|
2825
|
+
const child = nodeSpawn(command, args, options);
|
|
2826
|
+
child.unref();
|
|
2827
|
+
return child;
|
|
2828
|
+
}
|
|
2829
|
+
var CLIENTS_DIR_NAME = "opentui-clients", DEFAULT_HEARTBEAT_INTERVAL_MS = 3000, DEFAULT_CLIENT_TTL_MS = 15000, DEFAULT_LAST_ONE_GRACE_MS = 2000, ENV_IDLE_MS = "DSH_OPENTUI_HOST_IDLE_MS", DEFAULT_WATCHDOG_POLL_MS = 1000, ENV_WATCHDOG = "DSH_OPENTUI_WATCHDOG", ENV_WATCHDOG_HOME = "DSH_OPENTUI_WATCHDOG_HOME", ENV_WATCHDOG_PROFILE = "DSH_OPENTUI_WATCHDOG_PROFILE", nodeLifecycleFs, defaultSleep3 = (ms) => new Promise((resolve) => setTimeout(resolve, ms)), ForceNeedsYesError, IncompleteLifecycleFsError;
|
|
2830
|
+
var init_client_lifecycle = __esm(() => {
|
|
2831
|
+
init_host_registry();
|
|
2832
|
+
init_safe_kill();
|
|
2833
|
+
nodeLifecycleFs = {
|
|
2834
|
+
existsSync: (p) => nodeExistsSync(p),
|
|
2835
|
+
mkdirSync: (p, o) => nodeMkdirSync(p, o),
|
|
2836
|
+
readFileSync: (p, e) => nodeReadFileSync(p, e),
|
|
2837
|
+
writeFileSync: (p, d, o) => nodeWriteFileSync(p, d, o),
|
|
2838
|
+
unlinkSync: (p) => nodeUnlinkSync(p),
|
|
2839
|
+
readdirSync: (p) => nodeReaddirSync(p),
|
|
2840
|
+
renameSync: (from, to) => nodeRenameSync(from, to)
|
|
2841
|
+
};
|
|
2842
|
+
ForceNeedsYesError = class ForceNeedsYesError extends Error {
|
|
2843
|
+
clientCount;
|
|
2844
|
+
code = "force-needs-yes";
|
|
2845
|
+
constructor(clientCount) {
|
|
2846
|
+
super(`--force would disconnect ${clientCount} live client(s); re-run with --force --yes to confirm.`);
|
|
2847
|
+
this.clientCount = clientCount;
|
|
2848
|
+
this.name = new.target.name;
|
|
2849
|
+
}
|
|
2850
|
+
};
|
|
2851
|
+
IncompleteLifecycleFsError = class IncompleteLifecycleFsError extends Error {
|
|
2852
|
+
missing;
|
|
2853
|
+
code = "lifecycle-fs-incomplete";
|
|
2854
|
+
constructor(missing) {
|
|
2855
|
+
super(`dsh-opentui: --force guard fs is missing required method(s): ${missing.join(", ")}; ` + `refusing to read an unlistable heartbeat dir as "no live clients" (that would bypass --yes).`);
|
|
2856
|
+
this.missing = missing;
|
|
2857
|
+
this.name = new.target.name;
|
|
2858
|
+
}
|
|
2859
|
+
};
|
|
2860
|
+
});
|
|
2861
|
+
|
|
2862
|
+
// src/client/workspace-config.ts
|
|
2863
|
+
import {
|
|
2864
|
+
accessSync,
|
|
2865
|
+
chmodSync as chmodSync2,
|
|
2866
|
+
constants,
|
|
2867
|
+
existsSync as existsSync3,
|
|
2868
|
+
mkdirSync as mkdirSync4,
|
|
2869
|
+
readFileSync as readFileSync5,
|
|
2870
|
+
renameSync as renameSync4,
|
|
2871
|
+
statSync as statSync2,
|
|
2872
|
+
unlinkSync as unlinkSync3,
|
|
2873
|
+
writeFileSync as writeFileSync4
|
|
2874
|
+
} from "fs";
|
|
2875
|
+
import { join as join7 } from "path";
|
|
2876
|
+
function workspaceConfigPath(workspaceDir) {
|
|
2877
|
+
return join7(workspaceDir, CONFIG_DIR, CONFIG_FILE);
|
|
2878
|
+
}
|
|
2879
|
+
async function loadWorkspaceConfig(workspaceDir) {
|
|
2880
|
+
const path = workspaceConfigPath(workspaceDir);
|
|
2881
|
+
if (!existsSync3(path))
|
|
2882
|
+
return {};
|
|
2883
|
+
let text;
|
|
2884
|
+
try {
|
|
2885
|
+
text = readFileSync5(path, "utf8");
|
|
2886
|
+
} catch (error) {
|
|
2887
|
+
throw new WorkspaceConfigWriteError(path, `cannot read existing config (${error.message})`);
|
|
2888
|
+
}
|
|
2889
|
+
const tree = parseConfigDoc(text, path);
|
|
2890
|
+
assertNoCredentialKeys(tree, path);
|
|
2891
|
+
return overlayFromTree(tree, path);
|
|
2892
|
+
}
|
|
2893
|
+
function mergeConfig(base, overlay, env) {
|
|
2894
|
+
const envTheme = pickEnv(env, ENV_THEME);
|
|
2895
|
+
const envRoute = pickEnv(env, ENV_MODEL);
|
|
2896
|
+
let envProvider;
|
|
2897
|
+
let envModel;
|
|
2898
|
+
if (envRoute !== undefined) {
|
|
2899
|
+
const slash = envRoute.indexOf("/");
|
|
2900
|
+
if (slash === -1) {
|
|
2901
|
+
envModel = envRoute;
|
|
2902
|
+
} else {
|
|
2903
|
+
envProvider = nonEmpty2(envRoute.slice(0, slash));
|
|
2904
|
+
envModel = nonEmpty2(envRoute.slice(slash + 1));
|
|
2905
|
+
}
|
|
2906
|
+
}
|
|
2907
|
+
const theme = envTheme ?? nonEmpty2(overlay.theme) ?? nonEmpty2(base.theme);
|
|
2908
|
+
const themeMode = nonEmpty2(overlay.themeMode) ?? nonEmpty2(base.themeMode);
|
|
2909
|
+
const provider = envProvider ?? nonEmpty2(overlay.model?.provider) ?? nonEmpty2(base.model?.provider);
|
|
2910
|
+
const model = envModel ?? nonEmpty2(overlay.model?.model) ?? nonEmpty2(base.model?.model);
|
|
2911
|
+
const reasoningEffort = nonEmpty2(overlay.model?.reasoningEffort) ?? nonEmpty2(base.model?.reasoningEffort);
|
|
2912
|
+
const mergedModel = provider !== undefined || model !== undefined || reasoningEffort !== undefined ? {
|
|
2913
|
+
...provider !== undefined && { provider },
|
|
2914
|
+
...model !== undefined && { model },
|
|
2915
|
+
...reasoningEffort !== undefined && { reasoningEffort }
|
|
2916
|
+
} : undefined;
|
|
2917
|
+
return {
|
|
2918
|
+
...theme !== undefined && { theme },
|
|
2919
|
+
...themeMode !== undefined && { themeMode },
|
|
2920
|
+
...mergedModel !== undefined && { model: mergedModel }
|
|
2921
|
+
};
|
|
2922
|
+
}
|
|
2923
|
+
async function saveWorkspaceConfig(workspaceDir, overlay) {
|
|
2924
|
+
validateOverlayShape(overlay);
|
|
2925
|
+
const configDir = join7(workspaceDir, CONFIG_DIR);
|
|
2926
|
+
const path = workspaceConfigPath(workspaceDir);
|
|
2927
|
+
ensureWritableDir(workspaceDir, configDir);
|
|
2928
|
+
let tree = mkMap(0);
|
|
2929
|
+
if (existsSync3(path)) {
|
|
2930
|
+
let text;
|
|
2931
|
+
try {
|
|
2932
|
+
text = readFileSync5(path, "utf8");
|
|
2933
|
+
} catch (error) {
|
|
2934
|
+
throw new WorkspaceConfigWriteError(path, `cannot read existing config (${error.message})`);
|
|
2935
|
+
}
|
|
2936
|
+
tree = parseConfigDoc(text, path);
|
|
2937
|
+
}
|
|
2938
|
+
applyOverlayToTree(tree, overlay);
|
|
2939
|
+
assertNoCredentialKeys(tree, path);
|
|
2940
|
+
const body = serializeTree(tree);
|
|
2941
|
+
const doc = FILE_HEADER + (body.length === 0 ? "" : body.join(`
|
|
2942
|
+
`) + `
|
|
2943
|
+
`);
|
|
2944
|
+
atomicWrite(path, doc);
|
|
2945
|
+
}
|
|
2946
|
+
function isCredentialKey(key) {
|
|
2947
|
+
return CREDENTIAL_KEY_DENYLIST.has(key.toLowerCase().replaceAll(/[ \t_-]+/gu, ""));
|
|
2948
|
+
}
|
|
2949
|
+
function validateOverlayShape(overlay) {
|
|
2950
|
+
if (overlay === null || typeof overlay !== "object" || Array.isArray(overlay)) {
|
|
2951
|
+
throw new WorkspaceConfigError("workspace overlay must be an object");
|
|
2952
|
+
}
|
|
2953
|
+
for (const key of Object.keys(overlay)) {
|
|
2954
|
+
if (key === "theme" || key === "themeMode" || key === "model")
|
|
2955
|
+
continue;
|
|
2956
|
+
if (isCredentialKey(key))
|
|
2957
|
+
throw new WorkspaceConfigCredentialError(key, "the workspace overlay");
|
|
2958
|
+
throw new WorkspaceConfigError(`unknown overlay key "${key}" \u2014 workspace config supports only theme and model preferences`);
|
|
2959
|
+
}
|
|
2960
|
+
if (overlay.theme !== undefined && !isNonEmptyString(overlay.theme)) {
|
|
2961
|
+
throw new WorkspaceConfigError("overlay.theme must be a non-empty string");
|
|
2962
|
+
}
|
|
2963
|
+
if (overlay.themeMode !== undefined && !["dark", "light", "auto"].includes(overlay.themeMode)) {
|
|
2964
|
+
throw new WorkspaceConfigError('overlay.themeMode must be "dark", "light" or "auto"');
|
|
2965
|
+
}
|
|
2966
|
+
if (overlay.model !== undefined) {
|
|
2967
|
+
if (overlay.model === null || typeof overlay.model !== "object" || Array.isArray(overlay.model)) {
|
|
2968
|
+
throw new WorkspaceConfigError("overlay.model must be an object");
|
|
2969
|
+
}
|
|
2970
|
+
for (const key of Object.keys(overlay.model)) {
|
|
2971
|
+
if (!MODEL_FIELDS.includes(key)) {
|
|
2972
|
+
if (isCredentialKey(key))
|
|
2973
|
+
throw new WorkspaceConfigCredentialError(`model.${key}`, "the workspace overlay");
|
|
2974
|
+
throw new WorkspaceConfigError(`unknown overlay key "model.${key}" \u2014 model supports only provider, model, reasoningEffort`);
|
|
2975
|
+
}
|
|
2976
|
+
}
|
|
2977
|
+
for (const field of MODEL_FIELDS) {
|
|
2978
|
+
const value = overlay.model[field];
|
|
2979
|
+
if (value !== undefined && !isNonEmptyString(value)) {
|
|
2980
|
+
throw new WorkspaceConfigError(`overlay.model.${field} must be a non-empty string`);
|
|
2981
|
+
}
|
|
2982
|
+
}
|
|
2983
|
+
}
|
|
2984
|
+
}
|
|
2985
|
+
function mkMap(line) {
|
|
2986
|
+
return { kind: "map", entries: new Map, line };
|
|
2987
|
+
}
|
|
2988
|
+
function mkScalar(text, line, quoted, raw) {
|
|
2989
|
+
return { kind: "scalar", text, quoted, raw: raw ?? (quoted ? doubleQuote(text) : text), line };
|
|
2990
|
+
}
|
|
2991
|
+
function parseConfigDoc(text, path) {
|
|
2992
|
+
const root = mkMap(0);
|
|
2993
|
+
const stack = [{ map: root, indent: 0 }];
|
|
2994
|
+
let sawContent = false;
|
|
2995
|
+
const lines = text.replace(/^\uFEFF/u, "").split(`
|
|
2996
|
+
`);
|
|
2997
|
+
for (let i = 0;i < lines.length; i++) {
|
|
2998
|
+
const lineNo = i + 1;
|
|
2999
|
+
const line = lines[i].replace(/\r$/u, "");
|
|
3000
|
+
const trimmed = line.trim();
|
|
3001
|
+
if (trimmed === "" || trimmed.startsWith("#"))
|
|
3002
|
+
continue;
|
|
3003
|
+
if (trimmed === "---" && !sawContent)
|
|
3004
|
+
continue;
|
|
3005
|
+
if (trimmed === "---" || trimmed === "...") {
|
|
3006
|
+
throw new WorkspaceConfigParseError(path, lineNo, "document markers beyond a single leading `---` are not supported");
|
|
3007
|
+
}
|
|
3008
|
+
if (trimmed.startsWith("%")) {
|
|
3009
|
+
throw new WorkspaceConfigParseError(path, lineNo, "YAML directives are not supported");
|
|
3010
|
+
}
|
|
3011
|
+
sawContent = true;
|
|
3012
|
+
if (/^ *\t/u.test(line)) {
|
|
3013
|
+
throw new WorkspaceConfigParseError(path, lineNo, "tab indentation is not supported \u2014 indent with spaces");
|
|
3014
|
+
}
|
|
3015
|
+
const indent = leadingSpaces2(line);
|
|
3016
|
+
const rest = line.slice(indent);
|
|
3017
|
+
if (rest.startsWith("- ") || rest === "-") {
|
|
3018
|
+
throw new WorkspaceConfigParseError(path, lineNo, "sequences (lists) are not supported in workspace config");
|
|
3019
|
+
}
|
|
3020
|
+
const { key, valueText } = splitEntry(rest, path, lineNo);
|
|
3021
|
+
const node = parseValue(valueText, path, lineNo);
|
|
3022
|
+
attachEntry(stack, indent, key, node, path, lineNo);
|
|
3023
|
+
}
|
|
3024
|
+
return root;
|
|
3025
|
+
}
|
|
3026
|
+
function splitEntry(rest, path, lineNo) {
|
|
3027
|
+
const first = rest[0];
|
|
3028
|
+
if (first === "'" || first === '"') {
|
|
3029
|
+
const scanned = scanQuoted(rest, path, lineNo);
|
|
3030
|
+
let idx = scanned.end;
|
|
3031
|
+
while (rest[idx] === " ")
|
|
3032
|
+
idx++;
|
|
3033
|
+
if (rest[idx] !== ":") {
|
|
3034
|
+
throw new WorkspaceConfigParseError(path, lineNo, 'expected "key: value" \u2014 quoted key not followed by ":"');
|
|
3035
|
+
}
|
|
3036
|
+
const valueText = rest.slice(idx + 1).trim();
|
|
3037
|
+
return { key: scanned.text, valueText: valueText === "" ? undefined : valueText };
|
|
3038
|
+
}
|
|
3039
|
+
const colon = findKeyColon(rest);
|
|
3040
|
+
if (colon === -1) {
|
|
3041
|
+
throw new WorkspaceConfigParseError(path, lineNo, 'expected "key: value" (missing space after colon?)');
|
|
3042
|
+
}
|
|
3043
|
+
const key = rest.slice(0, colon).trim();
|
|
3044
|
+
if (!key)
|
|
3045
|
+
throw new WorkspaceConfigParseError(path, lineNo, "empty key");
|
|
3046
|
+
const valueText = rest.slice(colon + 1).trim();
|
|
3047
|
+
return { key, valueText: valueText === "" ? undefined : valueText };
|
|
3048
|
+
}
|
|
3049
|
+
function findKeyColon(rest) {
|
|
3050
|
+
for (let i = 0;i < rest.length; i++) {
|
|
3051
|
+
if (rest[i] !== ":")
|
|
3052
|
+
continue;
|
|
3053
|
+
const next = rest[i + 1];
|
|
3054
|
+
if (i + 1 === rest.length || next === " " || next === "\t")
|
|
3055
|
+
return i;
|
|
3056
|
+
}
|
|
3057
|
+
return -1;
|
|
3058
|
+
}
|
|
3059
|
+
function parseValue(valueText, path, lineNo) {
|
|
3060
|
+
if (valueText === undefined)
|
|
3061
|
+
return { kind: "null", line: lineNo };
|
|
3062
|
+
if (valueText.startsWith("#"))
|
|
3063
|
+
return { kind: "null", line: lineNo };
|
|
3064
|
+
const first = valueText[0];
|
|
3065
|
+
if (first === "|" || first === ">") {
|
|
3066
|
+
throw new WorkspaceConfigParseError(path, lineNo, "block scalars (| >) are not supported in workspace config");
|
|
3067
|
+
}
|
|
3068
|
+
if (first === "[" || first === "{") {
|
|
3069
|
+
throw new WorkspaceConfigParseError(path, lineNo, "flow collections ([] {}) are not supported in workspace config");
|
|
3070
|
+
}
|
|
3071
|
+
if (first === "&" || first === "*" || first === "!") {
|
|
3072
|
+
throw new WorkspaceConfigParseError(path, lineNo, "anchors, aliases, and tags are not supported in workspace config");
|
|
3073
|
+
}
|
|
3074
|
+
if (first === "'" || first === '"') {
|
|
3075
|
+
const scanned = scanQuoted(valueText, path, lineNo);
|
|
3076
|
+
let idx = scanned.end;
|
|
3077
|
+
while (valueText[idx] === " ")
|
|
3078
|
+
idx++;
|
|
3079
|
+
if (idx < valueText.length && valueText[idx] !== "#") {
|
|
3080
|
+
throw new WorkspaceConfigParseError(path, lineNo, "unexpected content after closing quote");
|
|
3081
|
+
}
|
|
3082
|
+
return mkScalar(scanned.text, lineNo, true);
|
|
3083
|
+
}
|
|
3084
|
+
const comment = valueText.indexOf(" #");
|
|
3085
|
+
const raw = (comment === -1 ? valueText : valueText.slice(0, comment)).trimEnd();
|
|
3086
|
+
if (raw === "")
|
|
3087
|
+
return { kind: "null", line: lineNo };
|
|
3088
|
+
if (raw.includes(": ")) {
|
|
3089
|
+
throw new WorkspaceConfigParseError(path, lineNo, `plain scalar cannot contain ": " \u2014 quote the value`);
|
|
3090
|
+
}
|
|
3091
|
+
return mkScalar(raw, lineNo, false, raw);
|
|
3092
|
+
}
|
|
3093
|
+
function scanQuoted(text, path, lineNo) {
|
|
3094
|
+
const quote = text[0];
|
|
3095
|
+
let out = "";
|
|
3096
|
+
let i = 1;
|
|
3097
|
+
while (i < text.length) {
|
|
3098
|
+
const ch = text[i];
|
|
3099
|
+
if (quote === "'") {
|
|
3100
|
+
if (ch === "'") {
|
|
3101
|
+
if (text[i + 1] === "'") {
|
|
3102
|
+
out += "'";
|
|
3103
|
+
i += 2;
|
|
3104
|
+
continue;
|
|
3105
|
+
}
|
|
3106
|
+
return { text: out, end: i + 1 };
|
|
3107
|
+
}
|
|
3108
|
+
out += ch;
|
|
3109
|
+
i++;
|
|
3110
|
+
continue;
|
|
3111
|
+
}
|
|
3112
|
+
if (ch === "\\") {
|
|
3113
|
+
const esc = text[i + 1];
|
|
3114
|
+
if (esc === '"' || esc === "\\") {
|
|
3115
|
+
out += esc;
|
|
3116
|
+
i += 2;
|
|
3117
|
+
continue;
|
|
3118
|
+
}
|
|
3119
|
+
throw new WorkspaceConfigParseError(path, lineNo, `unsupported escape "\\${esc ?? ""}" in double-quoted scalar`);
|
|
3120
|
+
}
|
|
3121
|
+
if (ch === '"')
|
|
3122
|
+
return { text: out, end: i + 1 };
|
|
3123
|
+
out += ch;
|
|
3124
|
+
i++;
|
|
3125
|
+
}
|
|
3126
|
+
throw new WorkspaceConfigParseError(path, lineNo, "unclosed quoted scalar");
|
|
3127
|
+
}
|
|
3128
|
+
function attachEntry(stack, indent, key, node, path, lineNo) {
|
|
3129
|
+
while (stack.length > 1 && stack[stack.length - 1].indent > indent)
|
|
3130
|
+
stack.pop();
|
|
3131
|
+
const frame = stack[stack.length - 1];
|
|
3132
|
+
if (frame.indent === indent) {
|
|
3133
|
+
if (frame.map.entries.has(key)) {
|
|
3134
|
+
throw new WorkspaceConfigParseError(path, lineNo, `duplicate key "${key}"`);
|
|
3135
|
+
}
|
|
3136
|
+
frame.map.entries.set(key, node);
|
|
3137
|
+
frame.lastKey = key;
|
|
3138
|
+
return;
|
|
3139
|
+
}
|
|
3140
|
+
if (frame.lastKey === undefined) {
|
|
3141
|
+
throw new WorkspaceConfigParseError(path, lineNo, "unexpected indentation (no parent key above)");
|
|
3142
|
+
}
|
|
3143
|
+
const parent = frame.map.entries.get(frame.lastKey);
|
|
3144
|
+
if (parent === undefined)
|
|
3145
|
+
throw new WorkspaceConfigParseError(path, lineNo, "unexpected indentation");
|
|
3146
|
+
if (parent.kind === "scalar") {
|
|
3147
|
+
throw new WorkspaceConfigParseError(path, lineNo, `unexpected indentation under scalar "${frame.lastKey}"`);
|
|
3148
|
+
}
|
|
3149
|
+
let map;
|
|
3150
|
+
if (parent.kind === "map") {
|
|
3151
|
+
throw new WorkspaceConfigParseError(path, lineNo, "inconsistent indentation");
|
|
3152
|
+
}
|
|
3153
|
+
map = mkMap(lineNo);
|
|
3154
|
+
frame.map.entries.set(frame.lastKey, map);
|
|
3155
|
+
stack.push({ map, indent, lastKey: undefined });
|
|
3156
|
+
if (map.entries.has(key))
|
|
3157
|
+
throw new WorkspaceConfigParseError(path, lineNo, `duplicate key "${key}"`);
|
|
3158
|
+
map.entries.set(key, node);
|
|
3159
|
+
}
|
|
3160
|
+
function leadingSpaces2(line) {
|
|
3161
|
+
let n = 0;
|
|
3162
|
+
while (n < line.length && line[n] === " ")
|
|
3163
|
+
n++;
|
|
3164
|
+
return n;
|
|
3165
|
+
}
|
|
3166
|
+
function overlayFromTree(tree, path) {
|
|
3167
|
+
const overlay = {};
|
|
3168
|
+
const theme = tree.entries.get("theme");
|
|
3169
|
+
if (theme !== undefined)
|
|
3170
|
+
overlay.theme = readStringField(tree, "theme", path);
|
|
3171
|
+
const themeMode = tree.entries.get("themeMode");
|
|
3172
|
+
if (themeMode !== undefined)
|
|
3173
|
+
overlay.themeMode = readStringField(tree, "themeMode", path);
|
|
3174
|
+
const model = tree.entries.get("model");
|
|
3175
|
+
if (model !== undefined) {
|
|
3176
|
+
if (model.kind !== "map") {
|
|
3177
|
+
throw new WorkspaceConfigParseError(path, model.line, '"model" must be a block of provider/model/reasoningEffort');
|
|
3178
|
+
}
|
|
3179
|
+
const prefs = {};
|
|
3180
|
+
for (const field of MODEL_FIELDS) {
|
|
3181
|
+
const entry = model.entries.get(field);
|
|
3182
|
+
if (entry !== undefined)
|
|
3183
|
+
prefs[field] = readStringField(model, field, path);
|
|
3184
|
+
}
|
|
3185
|
+
if (prefs.provider !== undefined || prefs.model !== undefined || prefs.reasoningEffort !== undefined) {
|
|
3186
|
+
overlay.model = prefs;
|
|
3187
|
+
}
|
|
3188
|
+
}
|
|
3189
|
+
return overlay;
|
|
3190
|
+
}
|
|
3191
|
+
function readStringField(parent, key, path) {
|
|
3192
|
+
const node = parent.entries.get(key);
|
|
3193
|
+
if (node === undefined)
|
|
3194
|
+
throw new WorkspaceConfigParseError(path, parent.line, `"${key}" disappeared mid-read`);
|
|
3195
|
+
if (node.kind === "null")
|
|
3196
|
+
throw new WorkspaceConfigParseError(path, node.line, `"${key}" must be a string value`);
|
|
3197
|
+
if (node.kind === "map") {
|
|
3198
|
+
throw new WorkspaceConfigParseError(path, node.line, `"${key}" must be a string value, got a nested block`);
|
|
3199
|
+
}
|
|
3200
|
+
if (!node.quoted && ATOMIC_SCALAR.test(node.text)) {
|
|
3201
|
+
throw new WorkspaceConfigParseError(path, node.line, `"${key}" must be a quoted string (bare value reads as non-string)`);
|
|
3202
|
+
}
|
|
3203
|
+
if (node.text.trim() === "")
|
|
3204
|
+
throw new WorkspaceConfigParseError(path, node.line, `"${key}" must be a non-empty string`);
|
|
3205
|
+
return node.text;
|
|
3206
|
+
}
|
|
3207
|
+
function applyOverlayToTree(tree, overlay) {
|
|
3208
|
+
if (Object.hasOwn(overlay, "theme")) {
|
|
3209
|
+
if (overlay.theme === undefined)
|
|
3210
|
+
tree.entries.delete("theme");
|
|
3211
|
+
else
|
|
3212
|
+
tree.entries.set("theme", mkScalar(overlay.theme, 0, needsQuote(overlay.theme)));
|
|
3213
|
+
}
|
|
3214
|
+
if (Object.hasOwn(overlay, "themeMode")) {
|
|
3215
|
+
if (overlay.themeMode === undefined)
|
|
3216
|
+
tree.entries.delete("themeMode");
|
|
3217
|
+
else
|
|
3218
|
+
tree.entries.set("themeMode", mkScalar(overlay.themeMode, 0, needsQuote(overlay.themeMode)));
|
|
3219
|
+
}
|
|
3220
|
+
if (!Object.hasOwn(overlay, "model"))
|
|
3221
|
+
return;
|
|
3222
|
+
if (overlay.model === undefined) {
|
|
3223
|
+
tree.entries.delete("model");
|
|
3224
|
+
return;
|
|
3225
|
+
}
|
|
3226
|
+
const existing = tree.entries.get("model");
|
|
3227
|
+
const block = existing !== undefined && existing.kind === "map" ? existing : mkMap(existing?.line ?? 0);
|
|
3228
|
+
tree.entries.set("model", block);
|
|
3229
|
+
for (const field of MODEL_FIELDS) {
|
|
3230
|
+
if (!Object.hasOwn(overlay.model, field))
|
|
3231
|
+
continue;
|
|
3232
|
+
const value = overlay.model[field];
|
|
3233
|
+
if (value === undefined)
|
|
3234
|
+
block.entries.delete(field);
|
|
3235
|
+
else
|
|
3236
|
+
block.entries.set(field, mkScalar(value, 0, needsQuote(value)));
|
|
3237
|
+
}
|
|
3238
|
+
if (block.entries.size === 0)
|
|
3239
|
+
tree.entries.delete("model");
|
|
3240
|
+
}
|
|
3241
|
+
function assertNoCredentialKeys(tree, path) {
|
|
3242
|
+
const visit = (map, prefix) => {
|
|
3243
|
+
for (const [key, node] of map.entries) {
|
|
3244
|
+
const keyPath = prefix === "" ? key : `${prefix}.${key}`;
|
|
3245
|
+
if (isCredentialKey(key))
|
|
3246
|
+
throw new WorkspaceConfigCredentialError(keyPath, path);
|
|
3247
|
+
if (node.kind === "map")
|
|
3248
|
+
visit(node, keyPath);
|
|
3249
|
+
}
|
|
3250
|
+
};
|
|
3251
|
+
visit(tree, "");
|
|
3252
|
+
}
|
|
3253
|
+
function serializeTree(tree) {
|
|
3254
|
+
const out = [];
|
|
3255
|
+
emitMap(tree, 0, out);
|
|
3256
|
+
return out;
|
|
3257
|
+
}
|
|
3258
|
+
function emitMap(map, indent, out) {
|
|
3259
|
+
const pad = " ".repeat(indent);
|
|
3260
|
+
for (const [key, node] of map.entries) {
|
|
3261
|
+
const keyText = needsQuote(key) ? doubleQuote(key) : key;
|
|
3262
|
+
if (node.kind === "null" || node.kind === "map" && node.entries.size === 0) {
|
|
3263
|
+
out.push(`${pad}${keyText}:`);
|
|
3264
|
+
if (node.kind === "map")
|
|
3265
|
+
emitMap(node, indent + 2, out);
|
|
3266
|
+
continue;
|
|
3267
|
+
}
|
|
3268
|
+
if (node.kind === "scalar") {
|
|
3269
|
+
out.push(`${pad}${keyText}: ${node.quoted ? doubleQuote(node.text) : node.raw}`);
|
|
3270
|
+
continue;
|
|
2120
3271
|
}
|
|
2121
|
-
|
|
2122
|
-
|
|
2123
|
-
host.state = "ready";
|
|
2124
|
-
respawnHistory.delete(o.key);
|
|
2125
|
-
registry.set(o.key, host);
|
|
2126
|
-
return host;
|
|
2127
|
-
} catch (err) {
|
|
2128
|
-
removeBootClaim(o.dshHome, o.profile, { pid: process.pid, startedAt: claimStartedAt });
|
|
2129
|
-
await terminateHost(host).catch(() => {});
|
|
2130
|
-
throw err;
|
|
3272
|
+
out.push(`${pad}${keyText}:`);
|
|
3273
|
+
emitMap(node, indent + 2, out);
|
|
2131
3274
|
}
|
|
2132
3275
|
}
|
|
2133
|
-
|
|
2134
|
-
if (
|
|
2135
|
-
return false;
|
|
2136
|
-
if (await isListening(lock.port))
|
|
3276
|
+
function needsQuote(text) {
|
|
3277
|
+
if (text === "")
|
|
2137
3278
|
return true;
|
|
2138
|
-
|
|
2139
|
-
|
|
2140
|
-
|
|
2141
|
-
|
|
2142
|
-
|
|
2143
|
-
|
|
2144
|
-
|
|
2145
|
-
|
|
3279
|
+
if (text !== text.trim())
|
|
3280
|
+
return true;
|
|
3281
|
+
if (/[\t\r\n]/u.test(text))
|
|
3282
|
+
return true;
|
|
3283
|
+
if (text.includes(" #"))
|
|
3284
|
+
return true;
|
|
3285
|
+
if (text.includes(": "))
|
|
3286
|
+
return true;
|
|
3287
|
+
if (text.endsWith(":"))
|
|
3288
|
+
return true;
|
|
3289
|
+
if (ATOMIC_SCALAR.test(text))
|
|
3290
|
+
return true;
|
|
3291
|
+
const first = text[0];
|
|
3292
|
+
if ("#&*!|>'\"%@`,[]{}".includes(first))
|
|
3293
|
+
return true;
|
|
3294
|
+
if (first === "-" || first === "?")
|
|
3295
|
+
return text.length === 1 || text[1] === " ";
|
|
2146
3296
|
return false;
|
|
2147
3297
|
}
|
|
2148
|
-
function
|
|
2149
|
-
|
|
2150
|
-
if (host.idleTimer) {
|
|
2151
|
-
clearTimeout(host.idleTimer);
|
|
2152
|
-
host.idleTimer = null;
|
|
2153
|
-
}
|
|
3298
|
+
function doubleQuote(text) {
|
|
3299
|
+
return `"${text.replaceAll("\\", "\\\\").replaceAll('"', "\\\"")}"`;
|
|
2154
3300
|
}
|
|
2155
|
-
function
|
|
2156
|
-
|
|
2157
|
-
|
|
2158
|
-
|
|
2159
|
-
|
|
2160
|
-
|
|
2161
|
-
|
|
2162
|
-
|
|
2163
|
-
|
|
3301
|
+
function atomicWrite(path, doc) {
|
|
3302
|
+
const tmp = `${path}.${process.pid}.tmp`;
|
|
3303
|
+
const fail = (message) => new WorkspaceConfigWriteError(path, message);
|
|
3304
|
+
try {
|
|
3305
|
+
writeFileSync4(tmp, doc, { mode: 384 });
|
|
3306
|
+
} catch (error) {
|
|
3307
|
+
sweepTmp(tmp);
|
|
3308
|
+
throw fail(`cannot write config (${error.message}) \u2014 check disk space and directory permissions`);
|
|
3309
|
+
}
|
|
3310
|
+
try {
|
|
3311
|
+
renameSync4(tmp, path);
|
|
3312
|
+
} catch (error) {
|
|
3313
|
+
sweepTmp(tmp);
|
|
3314
|
+
throw fail(`cannot replace config (${error.message})`);
|
|
3315
|
+
}
|
|
3316
|
+
try {
|
|
3317
|
+
chmodSync2(path, 384);
|
|
3318
|
+
} catch (error) {
|
|
3319
|
+
throw fail(`cannot enforce 0600 permissions (${error.message})`);
|
|
2164
3320
|
}
|
|
2165
3321
|
}
|
|
2166
|
-
function
|
|
3322
|
+
function sweepTmp(tmp) {
|
|
2167
3323
|
try {
|
|
2168
|
-
|
|
3324
|
+
unlinkSync3(tmp);
|
|
2169
3325
|
} catch {}
|
|
2170
3326
|
}
|
|
2171
|
-
|
|
2172
|
-
const
|
|
2173
|
-
|
|
2174
|
-
|
|
2175
|
-
return false;
|
|
2176
|
-
await sleep(LISTEN_POLL_MS);
|
|
2177
|
-
}
|
|
2178
|
-
return true;
|
|
2179
|
-
}
|
|
2180
|
-
async function terminateHost(host) {
|
|
2181
|
-
if (host.state === "dead") {
|
|
2182
|
-
clearOurLock(host);
|
|
2183
|
-
registry.delete(host.key);
|
|
2184
|
-
return;
|
|
3327
|
+
function ensureWritableDir(workspaceDir, configDir) {
|
|
3328
|
+
const fail = (message) => new WorkspaceConfigWriteError(configDir, message);
|
|
3329
|
+
if (!existsSync3(workspaceDir) || !statSync2(workspaceDir).isDirectory()) {
|
|
3330
|
+
throw new WorkspaceConfigWriteError(workspaceDir, "workspace directory does not exist or is not a directory \u2014 the workspace is the directory the TUI is launched in");
|
|
2185
3331
|
}
|
|
2186
|
-
if (
|
|
2187
|
-
|
|
2188
|
-
|
|
2189
|
-
|
|
2190
|
-
|
|
2191
|
-
|
|
2192
|
-
|
|
2193
|
-
|
|
2194
|
-
|
|
2195
|
-
host.child.kill("SIGTERM");
|
|
2196
|
-
await Promise.race([host.exitPromise, sleep(KILL_GRACE_MS)]);
|
|
2197
|
-
if (!host.exitInfo) {
|
|
2198
|
-
signalPid(host.pid, "SIGKILL");
|
|
2199
|
-
await Promise.race([host.exitPromise, sleep(KILL_ESCALATE_MS)]);
|
|
2200
|
-
}
|
|
2201
|
-
} else {
|
|
2202
|
-
signalPid(host.pid, "SIGTERM");
|
|
2203
|
-
if (!await waitPidGone(host.pid, KILL_GRACE_MS)) {
|
|
2204
|
-
signalPid(host.pid, "SIGKILL");
|
|
2205
|
-
await waitPidGone(host.pid, KILL_ESCALATE_MS);
|
|
2206
|
-
}
|
|
3332
|
+
if (existsSync3(configDir)) {
|
|
3333
|
+
if (!statSync2(configDir).isDirectory()) {
|
|
3334
|
+
throw fail("exists but is not a directory \u2014 remove or rename it");
|
|
3335
|
+
}
|
|
3336
|
+
} else {
|
|
3337
|
+
try {
|
|
3338
|
+
mkdirSync4(configDir, { recursive: true, mode: 448 });
|
|
3339
|
+
} catch (error) {
|
|
3340
|
+
throw fail(`cannot create directory (${error.message}) \u2014 create it manually or check parent permissions`);
|
|
2207
3341
|
}
|
|
2208
|
-
host.state = "dead";
|
|
2209
|
-
})();
|
|
2210
|
-
return host.termination;
|
|
2211
|
-
}
|
|
2212
|
-
async function ensureHost(opts = {}) {
|
|
2213
|
-
const o = resolveOptions(opts);
|
|
2214
|
-
const live = registry.get(o.key);
|
|
2215
|
-
if (live && live.state === "ready") {
|
|
2216
|
-
attachHost(live);
|
|
2217
|
-
return makeHandle(live);
|
|
2218
3342
|
}
|
|
2219
|
-
|
|
2220
|
-
|
|
2221
|
-
|
|
2222
|
-
|
|
2223
|
-
return makeHandle(host);
|
|
3343
|
+
try {
|
|
3344
|
+
accessSync(configDir, constants.W_OK);
|
|
3345
|
+
} catch {
|
|
3346
|
+
throw fail("is not writable \u2014 fix permissions (chmod u+w) or run from a writable workspace");
|
|
2224
3347
|
}
|
|
2225
|
-
const boot = bootHost(o).finally(() => pendingBoots.delete(o.key));
|
|
2226
|
-
pendingBoots.set(o.key, boot);
|
|
2227
|
-
const host = await boot;
|
|
2228
|
-
attachHost(host);
|
|
2229
|
-
return makeHandle(host);
|
|
2230
3348
|
}
|
|
2231
|
-
|
|
2232
|
-
|
|
2233
|
-
|
|
2234
|
-
|
|
2235
|
-
|
|
2236
|
-
|
|
2237
|
-
|
|
2238
|
-
|
|
2239
|
-
|
|
3349
|
+
function isNonEmptyString(value) {
|
|
3350
|
+
return typeof value === "string" && value.trim() !== "";
|
|
3351
|
+
}
|
|
3352
|
+
function pickEnv(env, name) {
|
|
3353
|
+
const value = env?.[name];
|
|
3354
|
+
return nonEmpty2(value);
|
|
3355
|
+
}
|
|
3356
|
+
function nonEmpty2(value) {
|
|
3357
|
+
return value !== undefined && value.trim() !== "" ? value : undefined;
|
|
3358
|
+
}
|
|
3359
|
+
var ENV_THEME = "DSH_OPENTUI_THEME", ENV_MODEL = "DSH_OPENTUI_MODEL", CONFIG_DIR = ".dsh", CONFIG_FILE = "config.yml", WorkspaceConfigError, WorkspaceConfigParseError, WorkspaceConfigCredentialError, WorkspaceConfigWriteError, CREDENTIAL_KEY_DENYLIST, MODEL_FIELDS, ATOMIC_SCALAR, FILE_HEADER;
|
|
3360
|
+
var init_workspace_config = __esm(() => {
|
|
3361
|
+
WorkspaceConfigError = class WorkspaceConfigError extends Error {
|
|
3362
|
+
constructor(message) {
|
|
2240
3363
|
super(message);
|
|
2241
|
-
this.name =
|
|
2242
|
-
this.code = code;
|
|
2243
|
-
}
|
|
2244
|
-
};
|
|
2245
|
-
HostBootTimeoutError = class HostBootTimeoutError extends HostLifecycleError {
|
|
2246
|
-
budgetMs;
|
|
2247
|
-
outputTail;
|
|
2248
|
-
constructor(budgetMs, outputTail) {
|
|
2249
|
-
super("host-boot-timeout", `dsh host did not become ready within ${budgetMs}ms${errorTail(outputTail)}`);
|
|
2250
|
-
this.budgetMs = budgetMs;
|
|
2251
|
-
this.outputTail = outputTail;
|
|
2252
|
-
}
|
|
2253
|
-
};
|
|
2254
|
-
HostDiedError = class HostDiedError extends HostLifecycleError {
|
|
2255
|
-
exitCode;
|
|
2256
|
-
signal;
|
|
2257
|
-
outputTail;
|
|
2258
|
-
constructor(exitCode, signal, outputTail) {
|
|
2259
|
-
super("host-died", `dsh host exited before readiness (code=${exitCode ?? "null"}, signal=${signal ?? "null"})${errorTail(outputTail)}`);
|
|
2260
|
-
this.exitCode = exitCode;
|
|
2261
|
-
this.signal = signal;
|
|
2262
|
-
this.outputTail = outputTail;
|
|
2263
|
-
}
|
|
2264
|
-
};
|
|
2265
|
-
HostNotServingError = class HostNotServingError extends HostLifecycleError {
|
|
2266
|
-
outputTail;
|
|
2267
|
-
budgetMs;
|
|
2268
|
-
constructor(outputTail, budgetMs = DEFAULT_SERVE_PROBE_BUDGET_MS) {
|
|
2269
|
-
super("host-not-serving", `dsh host is listening but never served the client mux (${budgetMs}ms budget)${errorTail(outputTail)}`);
|
|
2270
|
-
this.outputTail = outputTail;
|
|
2271
|
-
this.budgetMs = budgetMs;
|
|
2272
|
-
}
|
|
2273
|
-
};
|
|
2274
|
-
HostSpawnError = class HostSpawnError extends HostLifecycleError {
|
|
2275
|
-
cause;
|
|
2276
|
-
constructor(cause) {
|
|
2277
|
-
super("host-spawn-failed", `failed to start dsh host: ${cause.message}`);
|
|
2278
|
-
this.cause = cause;
|
|
2279
|
-
this.name = new.target.name;
|
|
3364
|
+
this.name = "WorkspaceConfigError";
|
|
2280
3365
|
}
|
|
2281
3366
|
};
|
|
2282
|
-
|
|
2283
|
-
|
|
2284
|
-
|
|
2285
|
-
constructor(
|
|
2286
|
-
super(
|
|
2287
|
-
this.
|
|
2288
|
-
this.
|
|
3367
|
+
WorkspaceConfigParseError = class WorkspaceConfigParseError extends WorkspaceConfigError {
|
|
3368
|
+
path;
|
|
3369
|
+
line;
|
|
3370
|
+
constructor(path, line, reason) {
|
|
3371
|
+
super(`${path}${line === undefined ? "" : `:${line}`}: ${reason}`);
|
|
3372
|
+
this.name = "WorkspaceConfigParseError";
|
|
3373
|
+
this.path = path;
|
|
3374
|
+
this.line = line;
|
|
2289
3375
|
}
|
|
2290
3376
|
};
|
|
2291
|
-
|
|
2292
|
-
|
|
2293
|
-
|
|
3377
|
+
WorkspaceConfigCredentialError = class WorkspaceConfigCredentialError extends WorkspaceConfigError {
|
|
3378
|
+
keyPath;
|
|
3379
|
+
constructor(keyPath, where) {
|
|
3380
|
+
super(`credential-like key "${keyPath}" in ${where} \u2014 workspace config must never hold credentials ` + "(the file lives next to the working tree and would leak into version control); remove it");
|
|
3381
|
+
this.name = "WorkspaceConfigCredentialError";
|
|
3382
|
+
this.keyPath = keyPath;
|
|
2294
3383
|
}
|
|
2295
3384
|
};
|
|
2296
|
-
|
|
2297
|
-
|
|
2298
|
-
|
|
2299
|
-
|
|
2300
|
-
|
|
2301
|
-
this.
|
|
2302
|
-
this.profileDir = profileDir;
|
|
3385
|
+
WorkspaceConfigWriteError = class WorkspaceConfigWriteError extends WorkspaceConfigError {
|
|
3386
|
+
path;
|
|
3387
|
+
constructor(path, message) {
|
|
3388
|
+
super(`${path}: ${message}`);
|
|
3389
|
+
this.name = "WorkspaceConfigWriteError";
|
|
3390
|
+
this.path = path;
|
|
2303
3391
|
}
|
|
2304
3392
|
};
|
|
2305
|
-
|
|
2306
|
-
|
|
2307
|
-
|
|
2308
|
-
|
|
3393
|
+
CREDENTIAL_KEY_DENYLIST = new Set([
|
|
3394
|
+
"apikey",
|
|
3395
|
+
"apisecret",
|
|
3396
|
+
"token",
|
|
3397
|
+
"accesstoken",
|
|
3398
|
+
"refreshtoken",
|
|
3399
|
+
"idtoken",
|
|
3400
|
+
"sessiontoken",
|
|
3401
|
+
"secret",
|
|
3402
|
+
"secretkey",
|
|
3403
|
+
"clientsecret",
|
|
3404
|
+
"privatekey",
|
|
3405
|
+
"password",
|
|
3406
|
+
"passwd",
|
|
3407
|
+
"credential",
|
|
3408
|
+
"credentials",
|
|
3409
|
+
"auth",
|
|
3410
|
+
"authorization",
|
|
3411
|
+
"cookie",
|
|
3412
|
+
"bearer",
|
|
3413
|
+
"sessionkey",
|
|
3414
|
+
"signingkey"
|
|
3415
|
+
]);
|
|
3416
|
+
MODEL_FIELDS = ["provider", "model", "reasoningEffort"];
|
|
3417
|
+
ATOMIC_SCALAR = /^(?:~|null|Null|NULL|true|True|TRUE|false|False|FALSE|yes|Yes|YES|no|No|NO|on|On|ON|off|Off|OFF|[-+]?(?:\d+|\d+\.\d+|\.\d+)(?:[eE][-+]?\d+)?|[-+]?(?:inf|Inf|INF)|\.nan|\.NaN|\.NAN)$/u;
|
|
3418
|
+
FILE_HEADER = `# dsh-opentui workspace-local config \u2014 theme + model preferences ONLY.
|
|
3419
|
+
` + `# Credentials and plugin installs must NEVER live in this file (it would
|
|
3420
|
+
` + `# leak into version control). Unknown keys are preserved on rewrite.
|
|
3421
|
+
`;
|
|
3422
|
+
});
|
|
3423
|
+
|
|
3424
|
+
// src/client/boot-shared.ts
|
|
3425
|
+
var exports_boot_shared = {};
|
|
3426
|
+
__export(exports_boot_shared, {
|
|
3427
|
+
BOOT_LABEL_BUDGET_MS: () => BOOT_LABEL_BUDGET_MS,
|
|
3428
|
+
ENV_MOTION: () => ENV_MOTION,
|
|
3429
|
+
ENV_THEME: () => ENV_THEME,
|
|
3430
|
+
SHUTDOWN_GRACE_MS: () => SHUTDOWN_GRACE_MS,
|
|
3431
|
+
SKIN_MIGRATION_NOTICE: () => SKIN_MIGRATION_NOTICE,
|
|
3432
|
+
SKIN_MIGRATION_THEME: () => SKIN_MIGRATION_THEME,
|
|
3433
|
+
bootCallOrder: () => bootCallOrder,
|
|
3434
|
+
clientErrorLogPath: () => clientErrorLogPath,
|
|
3435
|
+
defaultSpawnReaper: () => defaultSpawnReaper,
|
|
3436
|
+
hostLockPath: () => hostLockPath,
|
|
3437
|
+
installClientErrorLog: () => installClientErrorLog,
|
|
3438
|
+
installExitPaths: () => installExitPaths,
|
|
3439
|
+
motionFromConfig: () => motionFromConfig,
|
|
3440
|
+
resolveReaperScript: () => resolveReaperScript,
|
|
3441
|
+
skinMigrationPlan: () => skinMigrationPlan,
|
|
3442
|
+
spawnIdleReaper: () => spawnIdleReaper,
|
|
3443
|
+
themeModeFromConfig: () => themeModeFromConfig,
|
|
3444
|
+
themeNameFromConfig: () => themeNameFromConfig
|
|
3445
|
+
});
|
|
3446
|
+
import { join as join8 } from "path";
|
|
3447
|
+
import { appendFileSync, existsSync as existsSync4 } from "fs";
|
|
3448
|
+
import { spawn as spawn3 } from "child_process";
|
|
3449
|
+
function installExitPaths(shutdown, target = process, graceMs = SHUTDOWN_GRACE_MS) {
|
|
3450
|
+
const realExit = target.exit.bind(target);
|
|
3451
|
+
const exitAfterShutdown = (code) => {
|
|
3452
|
+
Promise.race([
|
|
3453
|
+
shutdown(),
|
|
3454
|
+
new Promise((resolve) => setTimeout(resolve, graceMs))
|
|
3455
|
+
]).then(() => realExit(code));
|
|
2309
3456
|
};
|
|
2310
|
-
|
|
2311
|
-
|
|
2312
|
-
|
|
2313
|
-
|
|
2314
|
-
|
|
2315
|
-
|
|
2316
|
-
|
|
2317
|
-
|
|
2318
|
-
|
|
2319
|
-
|
|
2320
|
-
|
|
3457
|
+
target.exit = (code) => exitAfterShutdown(code);
|
|
3458
|
+
for (const signal of ["SIGINT", "SIGTERM", "SIGHUP"]) {
|
|
3459
|
+
target.on(signal, () => exitAfterShutdown(0));
|
|
3460
|
+
}
|
|
3461
|
+
}
|
|
3462
|
+
function hostLockPath(dshHome, profile) {
|
|
3463
|
+
return join8(dshHome, `opentui-host.${profile}.json`);
|
|
3464
|
+
}
|
|
3465
|
+
function clientErrorLogPath(dshHome) {
|
|
3466
|
+
return join8(dshHome, "opentui-client.errors.log");
|
|
3467
|
+
}
|
|
3468
|
+
function installClientErrorLog(dshHome, target = process) {
|
|
3469
|
+
const logPath = clientErrorLogPath(dshHome);
|
|
3470
|
+
const record = (kind, error) => {
|
|
3471
|
+
const message = error instanceof Error ? error.stack ?? error.message : String(error);
|
|
3472
|
+
const line = `${new Date().toISOString()} kind=${kind} pid=${process.pid}
|
|
3473
|
+
${message}
|
|
3474
|
+
|
|
3475
|
+
`;
|
|
3476
|
+
try {
|
|
3477
|
+
appendFileSync(logPath, line);
|
|
3478
|
+
} catch {}
|
|
3479
|
+
try {
|
|
3480
|
+
process.stderr.write(`[dsh-opentui] ${kind}: ${message.split(`
|
|
3481
|
+
`)[0]}
|
|
3482
|
+
`);
|
|
3483
|
+
} catch {}
|
|
2321
3484
|
};
|
|
3485
|
+
target.on("unhandledRejection", (reason) => {
|
|
3486
|
+
record("unhandledRejection", reason);
|
|
3487
|
+
});
|
|
3488
|
+
target.on("uncaughtException", (error) => {
|
|
3489
|
+
record("uncaughtException", error);
|
|
3490
|
+
target.exit(1);
|
|
3491
|
+
});
|
|
3492
|
+
}
|
|
3493
|
+
function resolveReaperScript() {
|
|
3494
|
+
const candidates = [
|
|
3495
|
+
join8(import.meta.dir, "..", "scripts", "idle-reaper.mjs"),
|
|
3496
|
+
join8(import.meta.dir, "..", "..", "scripts", "idle-reaper.mjs")
|
|
3497
|
+
];
|
|
3498
|
+
for (const candidate of candidates) {
|
|
3499
|
+
if (existsSync4(candidate))
|
|
3500
|
+
return candidate;
|
|
3501
|
+
}
|
|
3502
|
+
throw new Error(`idle-reaper.mjs not found (looked in: ${candidates.join(", ")})`);
|
|
3503
|
+
}
|
|
3504
|
+
function defaultSpawnReaper(args) {
|
|
3505
|
+
const script = resolveReaperScript();
|
|
3506
|
+
const child = spawn3(process.execPath, [script, String(args.pid), String(args.port), args.lockPath, String(args.idleMs)], {
|
|
3507
|
+
detached: true,
|
|
3508
|
+
stdio: "ignore"
|
|
3509
|
+
});
|
|
3510
|
+
child.unref?.();
|
|
3511
|
+
}
|
|
3512
|
+
function spawnIdleReaper(host, idleMs, spawnReaper = defaultSpawnReaper) {
|
|
3513
|
+
if (!(idleMs > 0))
|
|
3514
|
+
return;
|
|
3515
|
+
try {
|
|
3516
|
+
spawnReaper({
|
|
3517
|
+
pid: host.pid,
|
|
3518
|
+
port: host.port,
|
|
3519
|
+
lockPath: hostLockPath(host.dshHome, host.profile),
|
|
3520
|
+
idleMs
|
|
3521
|
+
});
|
|
3522
|
+
} catch (error) {
|
|
3523
|
+
console.error("[client-entry] idle reaper spawn failed:", error);
|
|
3524
|
+
}
|
|
3525
|
+
}
|
|
3526
|
+
function themeNameFromConfig(session) {
|
|
3527
|
+
try {
|
|
3528
|
+
const theme = session.configLoad().theme;
|
|
3529
|
+
return typeof theme === "string" && theme ? theme : undefined;
|
|
3530
|
+
} catch {
|
|
3531
|
+
return;
|
|
3532
|
+
}
|
|
3533
|
+
}
|
|
3534
|
+
function themeModeFromConfig(session) {
|
|
3535
|
+
try {
|
|
3536
|
+
const mode = session.configLoad().themeMode;
|
|
3537
|
+
return mode === "dark" || mode === "light" ? mode : undefined;
|
|
3538
|
+
} catch {
|
|
3539
|
+
return;
|
|
3540
|
+
}
|
|
3541
|
+
}
|
|
3542
|
+
function motionFromConfig(session) {
|
|
3543
|
+
try {
|
|
3544
|
+
const motion = session.configLoad().motion;
|
|
3545
|
+
return typeof motion === "string" && motion ? motion : undefined;
|
|
3546
|
+
} catch {
|
|
3547
|
+
return;
|
|
3548
|
+
}
|
|
3549
|
+
}
|
|
3550
|
+
function storedTheme(value) {
|
|
3551
|
+
return typeof value === "string" && value.length > 0 ? value : undefined;
|
|
3552
|
+
}
|
|
3553
|
+
function skinMigrationPlan(input) {
|
|
3554
|
+
if (storedTheme(input.envTheme) !== undefined)
|
|
3555
|
+
return;
|
|
3556
|
+
if (input.profileConfig.skinMigration !== undefined)
|
|
3557
|
+
return;
|
|
3558
|
+
const workspaceTheme = storedTheme(input.workspaceConfig.theme);
|
|
3559
|
+
if (workspaceTheme !== undefined && workspaceTheme !== SKIN_MIGRATION_THEME) {
|
|
3560
|
+
return { layer: "workspace", theme: SKIN_MIGRATION_THEME, skinMigration: 1, notice: SKIN_MIGRATION_NOTICE };
|
|
3561
|
+
}
|
|
3562
|
+
const profileTheme = storedTheme(input.profileConfig.theme);
|
|
3563
|
+
if (profileTheme !== undefined && profileTheme !== SKIN_MIGRATION_THEME) {
|
|
3564
|
+
return { layer: "profile", theme: SKIN_MIGRATION_THEME, skinMigration: 1, notice: SKIN_MIGRATION_NOTICE };
|
|
3565
|
+
}
|
|
3566
|
+
return;
|
|
3567
|
+
}
|
|
3568
|
+
var SHUTDOWN_GRACE_MS = 2500, BOOT_LABEL_BUDGET_MS = 4000, bootCallOrder, ENV_MOTION = "DSH_OPENTUI_MOTION", SKIN_MIGRATION_THEME = "dsh-blue", SKIN_MIGRATION_NOTICE = "Theme switched to dsh-blue (new default). Use /theme to switch back.";
|
|
3569
|
+
var init_boot_shared = __esm(() => {
|
|
3570
|
+
init_workspace_config();
|
|
3571
|
+
bootCallOrder = [];
|
|
2322
3572
|
});
|
|
2323
3573
|
|
|
2324
3574
|
// ../../node_modules/.pnpm/@deepseek-ai+cosmokit@1.9.0/node_modules/@deepseek-ai/cosmokit/lib/index.js
|
|
@@ -6005,21 +7255,21 @@ class WaterfallAnswerer {
|
|
|
6005
7255
|
import {
|
|
6006
7256
|
chmodSync as chmodSync3,
|
|
6007
7257
|
closeSync,
|
|
6008
|
-
existsSync as
|
|
7258
|
+
existsSync as existsSync5,
|
|
6009
7259
|
openSync,
|
|
6010
|
-
readFileSync as
|
|
7260
|
+
readFileSync as readFileSync6,
|
|
6011
7261
|
readdirSync,
|
|
6012
7262
|
readSync,
|
|
6013
|
-
renameSync as
|
|
7263
|
+
renameSync as renameSync5,
|
|
6014
7264
|
statSync as statSync3,
|
|
6015
|
-
unlinkSync as
|
|
6016
|
-
writeFileSync as
|
|
7265
|
+
unlinkSync as unlinkSync4,
|
|
7266
|
+
writeFileSync as writeFileSync5
|
|
6017
7267
|
} from "fs";
|
|
6018
|
-
import { homedir as
|
|
6019
|
-
import { basename, dirname, join as
|
|
7268
|
+
import { homedir as homedir4 } from "os";
|
|
7269
|
+
import { basename, dirname as dirname2, join as join9 } from "path";
|
|
6020
7270
|
import * as nodeZlib from "zlib";
|
|
6021
7271
|
function resolveDshHome(explicit) {
|
|
6022
|
-
return explicit ?? (process.env.DSH_HOME ||
|
|
7272
|
+
return explicit ?? (process.env.DSH_HOME || join9(homedir4(), ".dsh"));
|
|
6023
7273
|
}
|
|
6024
7274
|
function stripQuotes(value) {
|
|
6025
7275
|
if (value.length >= 2) {
|
|
@@ -6110,15 +7360,15 @@ function listAgentFiles(explicitHome) {
|
|
|
6110
7360
|
const broken = [];
|
|
6111
7361
|
try {
|
|
6112
7362
|
const home = resolveDshHome(explicitHome);
|
|
6113
|
-
const dir =
|
|
6114
|
-
if (!
|
|
7363
|
+
const dir = join9(home, "agents");
|
|
7364
|
+
if (!existsSync5(dir))
|
|
6115
7365
|
return [];
|
|
6116
7366
|
for (const entry of readdirSync(dir, { withFileTypes: true })) {
|
|
6117
7367
|
if (!entry.isFile() || !entry.name.endsWith(".md"))
|
|
6118
7368
|
continue;
|
|
6119
|
-
const full =
|
|
7369
|
+
const full = join9(dir, entry.name);
|
|
6120
7370
|
try {
|
|
6121
|
-
const result = parseAgentMarkdown(
|
|
7371
|
+
const result = parseAgentMarkdown(readFileSync6(full, "utf8"), full);
|
|
6122
7372
|
if (result.ok)
|
|
6123
7373
|
agents.push(result.agent);
|
|
6124
7374
|
else
|
|
@@ -6141,7 +7391,7 @@ function listAgentFiles(explicitHome) {
|
|
|
6141
7391
|
function updateAgentFrontmatter(path, updates) {
|
|
6142
7392
|
let text;
|
|
6143
7393
|
try {
|
|
6144
|
-
text =
|
|
7394
|
+
text = readFileSync6(path, "utf8");
|
|
6145
7395
|
} catch (e) {
|
|
6146
7396
|
return `cannot read ${path}: ${String(e instanceof Error ? e.message : e)}`;
|
|
6147
7397
|
}
|
|
@@ -6194,7 +7444,7 @@ function updateAgentFrontmatter(path, updates) {
|
|
|
6194
7444
|
if (!changed)
|
|
6195
7445
|
return;
|
|
6196
7446
|
try {
|
|
6197
|
-
|
|
7447
|
+
writeFileSync5(path, lines.join(eol));
|
|
6198
7448
|
return;
|
|
6199
7449
|
} catch (e) {
|
|
6200
7450
|
return String(e instanceof Error ? e.message : e);
|
|
@@ -6202,7 +7452,7 @@ function updateAgentFrontmatter(path, updates) {
|
|
|
6202
7452
|
}
|
|
6203
7453
|
function setAgentField(name, field, value, explicitHome) {
|
|
6204
7454
|
const home = resolveDshHome(explicitHome);
|
|
6205
|
-
const file =
|
|
7455
|
+
const file = join9(home, "agents", `${name}.md`);
|
|
6206
7456
|
if (field === "deep") {
|
|
6207
7457
|
if (value !== null && !/^\d+$/.test(value)) {
|
|
6208
7458
|
return `expected a non-negative integer, got "${value}"`;
|
|
@@ -6230,8 +7480,8 @@ function repairScanSessions(explicitHome) {
|
|
|
6230
7480
|
const out = [];
|
|
6231
7481
|
try {
|
|
6232
7482
|
const home = resolveDshHome(explicitHome);
|
|
6233
|
-
const root =
|
|
6234
|
-
if (!
|
|
7483
|
+
const root = join9(home, "sessions");
|
|
7484
|
+
if (!existsSync5(root))
|
|
6235
7485
|
return ["no sessions directory"];
|
|
6236
7486
|
let total = 0;
|
|
6237
7487
|
let ok = 0;
|
|
@@ -6263,11 +7513,11 @@ function scanBrokenSessionLogs(explicitHome) {
|
|
|
6263
7513
|
const broken = [];
|
|
6264
7514
|
try {
|
|
6265
7515
|
const home = resolveDshHome(explicitHome);
|
|
6266
|
-
const root =
|
|
6267
|
-
if (!
|
|
7516
|
+
const root = join9(home, "sessions");
|
|
7517
|
+
if (!existsSync5(root))
|
|
6268
7518
|
return broken;
|
|
6269
7519
|
visitSessionLogs(root, 0, (full, name) => {
|
|
6270
|
-
const sessionId = /^session-(.+)$/.exec(basename(
|
|
7520
|
+
const sessionId = /^session-(.+)$/.exec(basename(dirname2(full)))?.[1];
|
|
6271
7521
|
const verdict = probeSessionLog(full, name);
|
|
6272
7522
|
if (verdict.broken)
|
|
6273
7523
|
broken.push({ path: full, name, reason: verdict.reason, sessionId });
|
|
@@ -6291,7 +7541,7 @@ function visitSessionLogs(dir, depth, onLog) {
|
|
|
6291
7541
|
return;
|
|
6292
7542
|
}
|
|
6293
7543
|
for (const entry of entries) {
|
|
6294
|
-
const full =
|
|
7544
|
+
const full = join9(dir, entry.name);
|
|
6295
7545
|
if (entry.isDirectory()) {
|
|
6296
7546
|
visitSessionLogs(full, depth + 1, onLog);
|
|
6297
7547
|
continue;
|
|
@@ -6357,7 +7607,7 @@ function probeZstdFrame(path) {
|
|
|
6357
7607
|
if (verify === undefined)
|
|
6358
7608
|
return { broken: false };
|
|
6359
7609
|
try {
|
|
6360
|
-
verify(
|
|
7610
|
+
verify(readFileSync6(path));
|
|
6361
7611
|
return { broken: false };
|
|
6362
7612
|
} catch {
|
|
6363
7613
|
return { broken: true, reason: `truncated or corrupt zstd frame${notRepairable}` };
|
|
@@ -6403,14 +7653,14 @@ function sleepSync2(ms) {
|
|
|
6403
7653
|
}
|
|
6404
7654
|
function repairSessionLogTail(path, options = {}) {
|
|
6405
7655
|
const delayFn = options.delayFn ?? sleepSync2;
|
|
6406
|
-
const writeFn = options.writeFn ??
|
|
6407
|
-
const renameFn = options.renameFn ??
|
|
7656
|
+
const writeFn = options.writeFn ?? writeFileSync5;
|
|
7657
|
+
const renameFn = options.renameFn ?? renameSync5;
|
|
6408
7658
|
if (!path.endsWith(".jsonl")) {
|
|
6409
7659
|
return { kind: "failed", detail: "not a plain jsonl log \u2014 client-side repair only truncates invalid jsonl tails" };
|
|
6410
7660
|
}
|
|
6411
7661
|
let text;
|
|
6412
7662
|
try {
|
|
6413
|
-
text =
|
|
7663
|
+
text = readFileSync6(path, "utf8");
|
|
6414
7664
|
} catch (e) {
|
|
6415
7665
|
return { kind: "failed", detail: `cannot read ${basename(path)}: ${String(e instanceof Error ? e.message : e)}` };
|
|
6416
7666
|
}
|
|
@@ -6453,11 +7703,11 @@ function repairSessionLogTail(path, options = {}) {
|
|
|
6453
7703
|
return { kind: "failed", detail: `cannot write the repaired copy: ${String(e instanceof Error ? e.message : e)}` };
|
|
6454
7704
|
}
|
|
6455
7705
|
try {
|
|
6456
|
-
if (
|
|
7706
|
+
if (readFileSync6(tmpPath, "utf8") !== repaired)
|
|
6457
7707
|
throw new Error("repaired copy content mismatch");
|
|
6458
7708
|
} catch (e) {
|
|
6459
7709
|
try {
|
|
6460
|
-
|
|
7710
|
+
unlinkSync4(tmpPath);
|
|
6461
7711
|
} catch {}
|
|
6462
7712
|
return {
|
|
6463
7713
|
kind: "failed",
|
|
@@ -6473,7 +7723,7 @@ function repairSessionLogTail(path, options = {}) {
|
|
|
6473
7723
|
renameFn(path, backupPath);
|
|
6474
7724
|
} catch (e) {
|
|
6475
7725
|
try {
|
|
6476
|
-
|
|
7726
|
+
unlinkSync4(tmpPath);
|
|
6477
7727
|
} catch {}
|
|
6478
7728
|
return { kind: "failed", detail: `cannot back up the original: ${String(e instanceof Error ? e.message : e)}` };
|
|
6479
7729
|
}
|
|
@@ -6481,7 +7731,7 @@ function repairSessionLogTail(path, options = {}) {
|
|
|
6481
7731
|
renameFn(tmpPath, path);
|
|
6482
7732
|
} catch (e) {
|
|
6483
7733
|
try {
|
|
6484
|
-
|
|
7734
|
+
unlinkSync4(tmpPath);
|
|
6485
7735
|
} catch {}
|
|
6486
7736
|
let restored = false;
|
|
6487
7737
|
try {
|
|
@@ -6505,10 +7755,10 @@ var init_remote_local_fs = __esm(() => {
|
|
|
6505
7755
|
});
|
|
6506
7756
|
|
|
6507
7757
|
// src/client/remote-agent-profiles.ts
|
|
6508
|
-
import { existsSync as
|
|
6509
|
-
import { dirname as
|
|
7758
|
+
import { existsSync as existsSync6, mkdirSync as mkdirSync5, readFileSync as readFileSync7, renameSync as renameSync6, rmSync as rmSync2, writeFileSync as writeFileSync6 } from "fs";
|
|
7759
|
+
import { dirname as dirname3, join as join10, resolve as resolve2 } from "path";
|
|
6510
7760
|
function modelProfilesPath(home) {
|
|
6511
|
-
return
|
|
7761
|
+
return join10(home, "model-profiles.json");
|
|
6512
7762
|
}
|
|
6513
7763
|
function narrowEntry(value) {
|
|
6514
7764
|
if (value === null || typeof value !== "object" || Array.isArray(value))
|
|
@@ -6549,7 +7799,7 @@ function seedModelProfilesDoc() {
|
|
|
6549
7799
|
function readModelProfilesDoc(home) {
|
|
6550
7800
|
let raw;
|
|
6551
7801
|
try {
|
|
6552
|
-
raw = JSON.parse(
|
|
7802
|
+
raw = JSON.parse(readFileSync7(modelProfilesPath(home), "utf8"));
|
|
6553
7803
|
} catch {
|
|
6554
7804
|
return seedModelProfilesDoc();
|
|
6555
7805
|
}
|
|
@@ -6590,17 +7840,17 @@ function parsePinText(text) {
|
|
|
6590
7840
|
return;
|
|
6591
7841
|
}
|
|
6592
7842
|
function readNearestProfilePin(startDir) {
|
|
6593
|
-
let current =
|
|
7843
|
+
let current = resolve2(startDir);
|
|
6594
7844
|
while (true) {
|
|
6595
|
-
const candidate =
|
|
7845
|
+
const candidate = join10(current, PROFILE_PIN_FILE);
|
|
6596
7846
|
try {
|
|
6597
|
-
if (
|
|
6598
|
-
const name = parsePinText(
|
|
7847
|
+
if (existsSync6(candidate)) {
|
|
7848
|
+
const name = parsePinText(readFileSync7(candidate, "utf8"));
|
|
6599
7849
|
if (name !== undefined)
|
|
6600
7850
|
return name;
|
|
6601
7851
|
}
|
|
6602
7852
|
} catch {}
|
|
6603
|
-
const parent =
|
|
7853
|
+
const parent = dirname3(current);
|
|
6604
7854
|
if (parent === current)
|
|
6605
7855
|
break;
|
|
6606
7856
|
current = parent;
|
|
@@ -6660,7 +7910,7 @@ function saveProfileAgentOverrides(home, profileName, agentName, edit) {
|
|
|
6660
7910
|
profiles: DEFAULT_PROFILE_NAMES.map((name) => ({ name, agents: {} }))
|
|
6661
7911
|
};
|
|
6662
7912
|
try {
|
|
6663
|
-
const parsed = JSON.parse(
|
|
7913
|
+
const parsed = JSON.parse(readFileSync7(path, "utf8"));
|
|
6664
7914
|
if (parsed !== null && typeof parsed === "object" && !Array.isArray(parsed)) {
|
|
6665
7915
|
const candidate = parsed;
|
|
6666
7916
|
if (candidate.version === MODEL_PROFILES_VERSION && Array.isArray(candidate.profiles))
|
|
@@ -6697,12 +7947,12 @@ function saveProfileAgentOverrides(home, profileName, agentName, edit) {
|
|
|
6697
7947
|
profile.agents = agents;
|
|
6698
7948
|
profiles[index] = profile;
|
|
6699
7949
|
const body = JSON.stringify(raw);
|
|
6700
|
-
const dir =
|
|
6701
|
-
const tmp =
|
|
7950
|
+
const dir = dirname3(path);
|
|
7951
|
+
const tmp = join10(dir, `.model-profiles.json.tmp-${process.pid}`);
|
|
6702
7952
|
try {
|
|
6703
|
-
|
|
6704
|
-
|
|
6705
|
-
|
|
7953
|
+
mkdirSync5(dir, { recursive: true });
|
|
7954
|
+
writeFileSync6(tmp, body);
|
|
7955
|
+
renameSync6(tmp, path);
|
|
6706
7956
|
return;
|
|
6707
7957
|
} catch (e) {
|
|
6708
7958
|
try {
|
|
@@ -6882,7 +8132,7 @@ var init_remote_attachments = __esm(() => {
|
|
|
6882
8132
|
});
|
|
6883
8133
|
|
|
6884
8134
|
// src/client/remote-btw.ts
|
|
6885
|
-
import { randomUUID as
|
|
8135
|
+
import { randomUUID as randomUUID4 } from "crypto";
|
|
6886
8136
|
import { appendFileSync as appendFileSync2 } from "fs";
|
|
6887
8137
|
function btwTrace(message) {
|
|
6888
8138
|
const line = `[btw ${new Date().toISOString().slice(11, 23)}] ${message}
|
|
@@ -6903,7 +8153,7 @@ async function askBtw(options) {
|
|
|
6903
8153
|
const timeoutMs = options.timeoutMs ?? 120000;
|
|
6904
8154
|
let sessionId = options.previousSessionId ?? "";
|
|
6905
8155
|
if (!sessionId) {
|
|
6906
|
-
const requested =
|
|
8156
|
+
const requested = randomUUID4();
|
|
6907
8157
|
const value = await options.rpc("session/create", {
|
|
6908
8158
|
request: {
|
|
6909
8159
|
cwd: options.cwd,
|
|
@@ -7000,7 +8250,7 @@ ${options.snapshot.join(`
|
|
|
7000
8250
|
` : "";
|
|
7001
8251
|
options.rpc("session/prompt", {
|
|
7002
8252
|
request: {
|
|
7003
|
-
requestId:
|
|
8253
|
+
requestId: randomUUID4(),
|
|
7004
8254
|
sessionId,
|
|
7005
8255
|
mode: "queue",
|
|
7006
8256
|
content: [{ type: "text", text: `${snap}Side question (answer in one or two sentences, do not use tools): ${options.question}` }]
|
|
@@ -7402,7 +8652,7 @@ function createSpinAttentionSource(options) {
|
|
|
7402
8652
|
var SPIN_JEV_MIN_INTERVAL_MS = 30000, SPIN_JEV_TIMEOUT_MS = 8000, SPIN_STATE_MAX_CHARS = 1000, SPIN_LABEL_MAX_CHARS = 40;
|
|
7403
8653
|
|
|
7404
8654
|
// src/client/remote-subagents.ts
|
|
7405
|
-
import { randomUUID as
|
|
8655
|
+
import { randomUUID as randomUUID5 } from "crypto";
|
|
7406
8656
|
|
|
7407
8657
|
class RemoteSubagentPanel {
|
|
7408
8658
|
#options;
|
|
@@ -7568,7 +8818,7 @@ class RemoteSubagentPanel {
|
|
|
7568
8818
|
try {
|
|
7569
8819
|
await this.#options.rpc("subagents/prompt", {
|
|
7570
8820
|
request: {
|
|
7571
|
-
requestId:
|
|
8821
|
+
requestId: randomUUID5(),
|
|
7572
8822
|
parentSessionId: parent,
|
|
7573
8823
|
childSessionId: id,
|
|
7574
8824
|
mode: "continuable",
|
|
@@ -7593,7 +8843,7 @@ class RemoteSubagentPanel {
|
|
|
7593
8843
|
try {
|
|
7594
8844
|
await this.#options.rpc("subagents/prompt", {
|
|
7595
8845
|
request: {
|
|
7596
|
-
requestId:
|
|
8846
|
+
requestId: randomUUID5(),
|
|
7597
8847
|
parentSessionId: parent,
|
|
7598
8848
|
childSessionId: id,
|
|
7599
8849
|
mode: "continuable",
|
|
@@ -7868,11 +9118,11 @@ var init_remote_subagents = __esm(() => {
|
|
|
7868
9118
|
});
|
|
7869
9119
|
|
|
7870
9120
|
// src/client/remote-restart.ts
|
|
7871
|
-
import { spawn as
|
|
7872
|
-
import { existsSync as
|
|
7873
|
-
import { join as
|
|
9121
|
+
import { spawn as spawn4 } from "child_process";
|
|
9122
|
+
import { existsSync as existsSync7, readFileSync as readFileSync8, renameSync as renameSync7, rmSync as rmSync3, unlinkSync as unlinkSync5, writeFileSync as writeFileSync7 } from "fs";
|
|
9123
|
+
import { join as join11 } from "path";
|
|
7874
9124
|
function defaultSpawnDsh2(argv, options) {
|
|
7875
|
-
const child =
|
|
9125
|
+
const child = spawn4("dsh", argv, {
|
|
7876
9126
|
cwd: options.cwd,
|
|
7877
9127
|
env: options.env,
|
|
7878
9128
|
detached: true,
|
|
@@ -7885,26 +9135,32 @@ function defaultSpawnDsh2(argv, options) {
|
|
|
7885
9135
|
return child;
|
|
7886
9136
|
}
|
|
7887
9137
|
function writeRestartedLock(home, profile, host) {
|
|
7888
|
-
const path =
|
|
9138
|
+
const path = join11(home, `opentui-host.${profile}.json`);
|
|
9139
|
+
const now = new Date().toISOString();
|
|
7889
9140
|
const payload = {
|
|
9141
|
+
version: 2,
|
|
9142
|
+
profile,
|
|
9143
|
+
home,
|
|
7890
9144
|
pid: host.pid,
|
|
7891
9145
|
port: host.port,
|
|
9146
|
+
phase: "ready",
|
|
9147
|
+
startedAt: now,
|
|
9148
|
+
updatedAt: now,
|
|
7892
9149
|
authority: host.authority,
|
|
7893
|
-
|
|
7894
|
-
profile
|
|
9150
|
+
clients: []
|
|
7895
9151
|
};
|
|
7896
9152
|
const tmp = `${path}.tmp`;
|
|
7897
|
-
|
|
9153
|
+
writeFileSync7(tmp, JSON.stringify(payload, null, 2) + `
|
|
7898
9154
|
`);
|
|
7899
|
-
|
|
9155
|
+
renameSync7(tmp, path);
|
|
7900
9156
|
}
|
|
7901
9157
|
async function restartSamePortHost(options = {}) {
|
|
7902
9158
|
const profile = options.profile ?? "opentui";
|
|
7903
9159
|
const home = resolveDshHome(options.dshHome);
|
|
7904
|
-
const lockPath =
|
|
9160
|
+
const lockPath = join11(home, `opentui-host.${profile}.json`);
|
|
7905
9161
|
let lock;
|
|
7906
9162
|
try {
|
|
7907
|
-
const raw = JSON.parse(
|
|
9163
|
+
const raw = JSON.parse(readFileSync8(lockPath, "utf8"));
|
|
7908
9164
|
if (typeof raw.pid === "number" && typeof raw.port === "number") {
|
|
7909
9165
|
lock = { pid: raw.pid, port: raw.port, ...raw.booting === true ? { booting: true } : {} };
|
|
7910
9166
|
}
|
|
@@ -7940,12 +9196,12 @@ async function restartSamePortHost(options = {}) {
|
|
|
7940
9196
|
await sleep2(POLL_MS);
|
|
7941
9197
|
}
|
|
7942
9198
|
try {
|
|
7943
|
-
const current = JSON.parse(
|
|
9199
|
+
const current = JSON.parse(readFileSync8(lockPath, "utf8"));
|
|
7944
9200
|
if (current.booting !== true && current.pid === pid && current.port === port)
|
|
7945
9201
|
rmSync3(lockPath, { force: true });
|
|
7946
9202
|
} catch {
|
|
7947
9203
|
try {
|
|
7948
|
-
|
|
9204
|
+
unlinkSync5(lockPath);
|
|
7949
9205
|
} catch {}
|
|
7950
9206
|
}
|
|
7951
9207
|
const quietDeadline = deadline(KILL_GRACE_MS2 + KILL_ESCALATE_MS2 + LISTEN_RELEASE_GRACE_MS);
|
|
@@ -7954,8 +9210,8 @@ async function restartSamePortHost(options = {}) {
|
|
|
7954
9210
|
if (await isListening(port)) {
|
|
7955
9211
|
throw new HostRestartError("port-held", `port ${port} is still held after the old host died \u2014 refusing to spawn into EADDRINUSE`);
|
|
7956
9212
|
}
|
|
7957
|
-
const profileDir =
|
|
7958
|
-
if (!
|
|
9213
|
+
const profileDir = join11(home, "profiles", profile);
|
|
9214
|
+
if (!existsSync7(profileDir)) {
|
|
7959
9215
|
throw new HostRestartError("profile-missing", `profile '${profile}' is not provisioned (${profileDir} missing)`);
|
|
7960
9216
|
}
|
|
7961
9217
|
const spawnDsh = options.spawnDsh ?? defaultSpawnDsh2;
|
|
@@ -8023,8 +9279,8 @@ __export(exports_remote_host_session, {
|
|
|
8023
9279
|
SPIN_REFRESH_TTL_MS: () => SPIN_REFRESH_TTL_MS,
|
|
8024
9280
|
openRemoteStream: () => openRemoteStream
|
|
8025
9281
|
});
|
|
8026
|
-
import { randomUUID as
|
|
8027
|
-
import { existsSync as
|
|
9282
|
+
import { randomUUID as randomUUID6 } from "crypto";
|
|
9283
|
+
import { existsSync as existsSync8, mkdirSync as mkdirSync6, readFileSync as readFileSync9, renameSync as renameSync8, rmSync as rmSync4, writeFileSync as writeFileSync8 } from "fs";
|
|
8028
9284
|
import { join as joinPath } from "path";
|
|
8029
9285
|
import WS3 from "ws";
|
|
8030
9286
|
function trace(message) {
|
|
@@ -8220,7 +9476,7 @@ class RemoteHostSession {
|
|
|
8220
9476
|
this.#contextMeter.notePending(userText);
|
|
8221
9477
|
await this.start();
|
|
8222
9478
|
const sessionId = await this.#ensureSession();
|
|
8223
|
-
const requestId =
|
|
9479
|
+
const requestId = randomUUID6();
|
|
8224
9480
|
const attachmentParts = this.#pendingUploads.map(imagePromptPart);
|
|
8225
9481
|
this.#pendingUploads = [];
|
|
8226
9482
|
await this.#rpc("session/prompt", {
|
|
@@ -8249,7 +9505,7 @@ class RemoteHostSession {
|
|
|
8249
9505
|
return;
|
|
8250
9506
|
this.#rpc("session/prompt", {
|
|
8251
9507
|
request: {
|
|
8252
|
-
requestId:
|
|
9508
|
+
requestId: randomUUID6(),
|
|
8253
9509
|
sessionId,
|
|
8254
9510
|
mode: "steer",
|
|
8255
9511
|
content: [{ type: "text", text: userText }]
|
|
@@ -8654,7 +9910,7 @@ class RemoteHostSession {
|
|
|
8654
9910
|
}
|
|
8655
9911
|
keybindingsLoad() {
|
|
8656
9912
|
try {
|
|
8657
|
-
return JSON.parse(
|
|
9913
|
+
return JSON.parse(readFileSync9(this.configPath("keybindings.json"), "utf8"));
|
|
8658
9914
|
} catch {
|
|
8659
9915
|
return {};
|
|
8660
9916
|
}
|
|
@@ -8667,14 +9923,14 @@ class RemoteHostSession {
|
|
|
8667
9923
|
configLoad() {
|
|
8668
9924
|
let base = {};
|
|
8669
9925
|
try {
|
|
8670
|
-
base = JSON.parse(
|
|
9926
|
+
base = JSON.parse(readFileSync9(this.configPath(), "utf8"));
|
|
8671
9927
|
} catch {}
|
|
8672
9928
|
const merged = mergeConfig(base, this.#overlayCache ?? {}, process.env);
|
|
8673
9929
|
return { ...base, ...merged };
|
|
8674
9930
|
}
|
|
8675
9931
|
configRaw() {
|
|
8676
9932
|
try {
|
|
8677
|
-
return JSON.parse(
|
|
9933
|
+
return JSON.parse(readFileSync9(this.configPath(), "utf8"));
|
|
8678
9934
|
} catch {
|
|
8679
9935
|
return {};
|
|
8680
9936
|
}
|
|
@@ -8707,14 +9963,14 @@ class RemoteHostSession {
|
|
|
8707
9963
|
if (Object.keys(rest).length > 0) {
|
|
8708
9964
|
const merged = { ...this.#readProfileConfig(), ...rest };
|
|
8709
9965
|
const profileDir = joinPath(this.#dshHome, "profiles", this.#profile);
|
|
8710
|
-
if (!
|
|
8711
|
-
|
|
9966
|
+
if (!existsSync8(profileDir))
|
|
9967
|
+
mkdirSync6(profileDir, { recursive: true });
|
|
8712
9968
|
const path = this.configPath();
|
|
8713
9969
|
const tmp = `${path}.${process.pid}.tmp`;
|
|
8714
9970
|
try {
|
|
8715
|
-
|
|
9971
|
+
writeFileSync8(tmp, JSON.stringify(merged, null, 2) + `
|
|
8716
9972
|
`);
|
|
8717
|
-
|
|
9973
|
+
renameSync8(tmp, path);
|
|
8718
9974
|
} catch (error) {
|
|
8719
9975
|
try {
|
|
8720
9976
|
rmSync4(tmp, { force: true });
|
|
@@ -8729,7 +9985,7 @@ class RemoteHostSession {
|
|
|
8729
9985
|
}
|
|
8730
9986
|
#readProfileConfig() {
|
|
8731
9987
|
try {
|
|
8732
|
-
return JSON.parse(
|
|
9988
|
+
return JSON.parse(readFileSync9(this.configPath(), "utf8"));
|
|
8733
9989
|
} catch {
|
|
8734
9990
|
return {};
|
|
8735
9991
|
}
|
|
@@ -9200,7 +10456,7 @@ class RemoteHostSession {
|
|
|
9200
10456
|
return this.#sessionId;
|
|
9201
10457
|
}
|
|
9202
10458
|
const resumed = this.#resumeId !== undefined;
|
|
9203
|
-
const requestedId = this.#resumeId ??
|
|
10459
|
+
const requestedId = this.#resumeId ?? randomUUID6();
|
|
9204
10460
|
this.#resumeId = undefined;
|
|
9205
10461
|
const request = { cwd: this.#cwd, sessionId: requestedId };
|
|
9206
10462
|
if (this.#presetId !== undefined)
|
|
@@ -12791,7 +14047,7 @@ var backEdges = 0, addBackEdge = () => {
|
|
|
12791
14047
|
};
|
|
12792
14048
|
|
|
12793
14049
|
// ../../node_modules/.pnpm/effect@4.1.0/node_modules/effect/dist/Predicate.js
|
|
12794
|
-
function
|
|
14050
|
+
function isString2(input) {
|
|
12795
14051
|
return typeof input === "string";
|
|
12796
14052
|
}
|
|
12797
14053
|
function isNumber2(input) {
|
|
@@ -12807,7 +14063,7 @@ function isSymbol(input) {
|
|
|
12807
14063
|
return typeof input === "symbol";
|
|
12808
14064
|
}
|
|
12809
14065
|
function isPropertyKey(u) {
|
|
12810
|
-
return
|
|
14066
|
+
return isString2(u) || isNumber2(u) || isSymbol(u);
|
|
12811
14067
|
}
|
|
12812
14068
|
function isFunction(input) {
|
|
12813
14069
|
return typeof input === "function";
|
|
@@ -14312,7 +15568,7 @@ var TypeId4 = "~effect/Duration", bigint0, bigint1, bigint2, bigint10, bigint1e3
|
|
|
14312
15568
|
return input;
|
|
14313
15569
|
if (Array.isArray(input)) {
|
|
14314
15570
|
if (input.length !== 2 || !input.every(isNumber2)) {
|
|
14315
|
-
return
|
|
15571
|
+
return invalid2(input);
|
|
14316
15572
|
}
|
|
14317
15573
|
if (Number.isNaN(input[0]) || Number.isNaN(input[1])) {
|
|
14318
15574
|
return zero;
|
|
@@ -14351,7 +15607,7 @@ var TypeId4 = "~effect/Duration", bigint0, bigint1, bigint2, bigint10, bigint1e3
|
|
|
14351
15607
|
return exact === undefined ? fromNanosNumber(nanos) : make4(exact);
|
|
14352
15608
|
}
|
|
14353
15609
|
}
|
|
14354
|
-
return
|
|
15610
|
+
return invalid2(input);
|
|
14355
15611
|
}, isIntegerOrUnset = (n) => !n || Number.isInteger(n), sumObjectNanos = (obj) => {
|
|
14356
15612
|
if (!isIntegerOrUnset(obj.weeks) || !isIntegerOrUnset(obj.days) || !isIntegerOrUnset(obj.hours) || !isIntegerOrUnset(obj.minutes) || !isIntegerOrUnset(obj.seconds) || !isIntegerOrUnset(obj.milliseconds) || !isIntegerOrUnset(obj.microseconds) || !isIntegerOrUnset(obj.nanoseconds))
|
|
14357
15613
|
return;
|
|
@@ -14373,7 +15629,7 @@ var TypeId4 = "~effect/Duration", bigint0, bigint1, bigint2, bigint10, bigint1e3
|
|
|
14373
15629
|
if (obj.nanoseconds)
|
|
14374
15630
|
nanos += BigInt(obj.nanoseconds);
|
|
14375
15631
|
return nanos;
|
|
14376
|
-
},
|
|
15632
|
+
}, invalid2 = (input) => {
|
|
14377
15633
|
throw new Error(`Invalid Input: ${input}`);
|
|
14378
15634
|
}, zeroDurationValue, infinityDurationValue, negativeInfinityDurationValue, DurationProto, make4 = (input) => {
|
|
14379
15635
|
const duration = Object.create(DurationProto);
|
|
@@ -16858,7 +18114,7 @@ var init_Redacted = __esm(() => {
|
|
|
16858
18114
|
return this.toString();
|
|
16859
18115
|
},
|
|
16860
18116
|
toString() {
|
|
16861
|
-
return `<redacted${
|
|
18117
|
+
return `<redacted${isString2(this.label) ? ":" + this.label : ""}>`;
|
|
16862
18118
|
},
|
|
16863
18119
|
[symbol]() {
|
|
16864
18120
|
return hash(redactedRegistry.get(this));
|
|
@@ -16870,14 +18126,14 @@ var init_Redacted = __esm(() => {
|
|
|
16870
18126
|
});
|
|
16871
18127
|
|
|
16872
18128
|
// ../../node_modules/.pnpm/effect@4.1.0/node_modules/effect/dist/internal/schema/annotations.js
|
|
16873
|
-
function
|
|
18129
|
+
function resolve3(ast) {
|
|
16874
18130
|
return ast.checks ? ast.checks[ast.checks.length - 1].annotations : ast.annotations;
|
|
16875
18131
|
}
|
|
16876
18132
|
var STRUCTURAL_ANNOTATION_KEY = "~structural", SENTINELS_ANNOTATION_KEY = "~sentinels", CONSTRUCTOR_ANNOTATION_KEY = "~constructor", getExpected;
|
|
16877
18133
|
var init_annotations = __esm(() => {
|
|
16878
18134
|
init_Function();
|
|
16879
18135
|
getExpected = /* @__PURE__ */ memoize((ast) => {
|
|
16880
|
-
const identifier =
|
|
18136
|
+
const identifier = resolve3(ast)?.identifier;
|
|
16881
18137
|
if (typeof identifier === "string")
|
|
16882
18138
|
return identifier;
|
|
16883
18139
|
return ast.getExpected(getExpected);
|
|
@@ -18497,7 +19753,7 @@ var init_SchemaAST = __esm(() => {
|
|
|
18497
19753
|
String5 = class extends ASTNodeImpl {
|
|
18498
19754
|
_tag = "String";
|
|
18499
19755
|
getParser() {
|
|
18500
|
-
return fromRefinement(this,
|
|
19756
|
+
return fromRefinement(this, isString2);
|
|
18501
19757
|
}
|
|
18502
19758
|
matchPart(s, options) {
|
|
18503
19759
|
const checks = this.checks;
|
|
@@ -19498,7 +20754,7 @@ function withDecode(fastDecode, decodeEffect) {
|
|
|
19498
20754
|
if (input !== missing) {
|
|
19499
20755
|
try {
|
|
19500
20756
|
const value = fastDecode(input, options);
|
|
19501
|
-
if (value !==
|
|
20757
|
+
if (value !== invalid3)
|
|
19502
20758
|
return value === input ? sameExit : succeed6(value);
|
|
19503
20759
|
} catch (error) {
|
|
19504
20760
|
return die3(error);
|
|
@@ -19515,20 +20771,20 @@ function lazyParser(resolve, ast, operation) {
|
|
|
19515
20771
|
let parser;
|
|
19516
20772
|
return (input, options) => (parser ??= entry[operation])(input, options);
|
|
19517
20773
|
}
|
|
19518
|
-
function
|
|
20774
|
+
function resolve4(ast) {
|
|
19519
20775
|
const cached = cache.get(ast);
|
|
19520
20776
|
if (cached !== undefined)
|
|
19521
20777
|
return cached;
|
|
19522
|
-
const entry = compiler === undefined ? new InterpretedEntry(ast) : new CompilerEntry(ast, compiler(ast,
|
|
20778
|
+
const entry = compiler === undefined ? new InterpretedEntry(ast) : new CompilerEntry(ast, compiler(ast, resolve4), resolve4);
|
|
19523
20779
|
cache.set(ast, entry);
|
|
19524
20780
|
return entry;
|
|
19525
20781
|
}
|
|
19526
|
-
var
|
|
20782
|
+
var invalid3, cache, compiler, compilerAdaptersEnabled = false, decodeChild = (ast) => compilerAdaptersEnabled ? lazyParser(resolve4, ast, "parser") : resolve4(ast).parser, makeChild = (ast) => compilerAdaptersEnabled ? lazyParser(resolve4, ast, "makeEffect") : resolve4(ast).makeEffect, makeField = (ast) => compileField(ast, makeChild), CompilerEntry;
|
|
19527
20783
|
var init_compilerRegistry = __esm(() => {
|
|
19528
20784
|
init_Effect();
|
|
19529
20785
|
init_interpreter();
|
|
19530
20786
|
init_parser();
|
|
19531
|
-
|
|
20787
|
+
invalid3 = /* @__PURE__ */ Symbol();
|
|
19532
20788
|
cache = /* @__PURE__ */ new WeakMap;
|
|
19533
20789
|
CompilerEntry = class CompilerEntry extends InterpretedEntry {
|
|
19534
20790
|
compiled;
|
|
@@ -19650,7 +20906,7 @@ function throwConstructorDefect(error) {
|
|
|
19650
20906
|
}
|
|
19651
20907
|
function makeConstructorSync(ast) {
|
|
19652
20908
|
let entry;
|
|
19653
|
-
return (input, options) => constructSync(entry ??=
|
|
20909
|
+
return (input, options) => constructSync(entry ??= resolve4(ast), input, options);
|
|
19654
20910
|
}
|
|
19655
20911
|
function constructSync(entry, input, options) {
|
|
19656
20912
|
const parseOptions = options?.disableChecks ? options.parseOptions ? {
|
|
@@ -19667,7 +20923,7 @@ function constructSync(entry, input, options) {
|
|
|
19667
20923
|
} catch (error) {
|
|
19668
20924
|
throwConstructorDefect(error);
|
|
19669
20925
|
}
|
|
19670
|
-
if (output !==
|
|
20926
|
+
if (output !== invalid3 && output !== missing)
|
|
19671
20927
|
return output;
|
|
19672
20928
|
}
|
|
19673
20929
|
return runSync2(parserResult(entry.makeEffect(input, parseOptions), input), constructorDefectMessage);
|
|
@@ -19680,7 +20936,7 @@ var mergeParseOptions = (options, overrideOptions) => overrideOptions ? {
|
|
|
19680
20936
|
return fail5(new InvalidValue);
|
|
19681
20937
|
}
|
|
19682
20938
|
return succeed5(value);
|
|
19683
|
-
}, constructorDefectMessage = "Constructor adapter can only throw schema issues", normalCompiler = (ast) =>
|
|
20939
|
+
}, constructorDefectMessage = "Constructor adapter can only throw schema issues", normalCompiler = (ast) => resolve4(ast).parser, constructorCompiler = (ast) => resolve4(ast).makeEffect;
|
|
19684
20940
|
var init_SchemaParser = __esm(() => {
|
|
19685
20941
|
init_Cause();
|
|
19686
20942
|
init_Effect();
|
|
@@ -32639,7 +33895,7 @@ var init_watch = () => {};
|
|
|
32639
33895
|
|
|
32640
33896
|
// ../tui-base/src/config/index.tsx
|
|
32641
33897
|
import path from "path";
|
|
32642
|
-
function
|
|
33898
|
+
function resolve5(input, options) {
|
|
32643
33899
|
const tabsMode = input.tabs?.mode ?? (input.tabs?.enabled === undefined ? "auto" : input.tabs.enabled ? "on" : "off");
|
|
32644
33900
|
const keybinds = {
|
|
32645
33901
|
...input.keybinds
|
|
@@ -32690,7 +33946,7 @@ function resolve4(input, options) {
|
|
|
32690
33946
|
function ConfigProvider2(props) {
|
|
32691
33947
|
const [config, setConfig] = createStore(props.config);
|
|
32692
33948
|
const host = props.service;
|
|
32693
|
-
const apply = (info) => setConfig(reconcile(
|
|
33949
|
+
const apply = (info) => setConfig(reconcile(resolve5(info, props.options ?? {
|
|
32694
33950
|
terminalSuspend: true
|
|
32695
33951
|
})));
|
|
32696
33952
|
const update = async (update) => {
|
|
@@ -33007,7 +34263,7 @@ var init_hash = __esm(() => {
|
|
|
33007
34263
|
// ../tui-base/src/vendor/util/src/flock.ts
|
|
33008
34264
|
import path2 from "path";
|
|
33009
34265
|
import os from "os";
|
|
33010
|
-
import { randomBytes, randomUUID as
|
|
34266
|
+
import { randomBytes, randomUUID as randomUUID7 } from "crypto";
|
|
33011
34267
|
import { mkdir, readFile as readFile2, rm, stat, utimes, writeFile } from "fs/promises";
|
|
33012
34268
|
var Flock;
|
|
33013
34269
|
var init_flock = __esm(() => {
|
|
@@ -33097,7 +34353,7 @@ var init_flock = __esm(() => {
|
|
|
33097
34353
|
return now - dir.mtimeMs > staleMs;
|
|
33098
34354
|
}
|
|
33099
34355
|
async function tryAcquireLockDir(lockDir, opts) {
|
|
33100
|
-
const token =
|
|
34356
|
+
const token = randomUUID7?.() ?? randomBytes(16).toString("hex");
|
|
33101
34357
|
const metaPath = path2.join(lockDir, "meta.json");
|
|
33102
34358
|
const heartbeatPath = path2.join(lockDir, "heartbeat");
|
|
33103
34359
|
try {
|
|
@@ -33706,9 +34962,9 @@ var init_theme3 = __esm(() => {
|
|
|
33706
34962
|
});
|
|
33707
34963
|
|
|
33708
34964
|
// ../i18n/src/registry.ts
|
|
33709
|
-
import { existsSync as
|
|
33710
|
-
import { homedir as
|
|
33711
|
-
import { dirname as
|
|
34965
|
+
import { existsSync as existsSync9, readdirSync as readdirSync2, readFileSync as readFileSync10 } from "fs";
|
|
34966
|
+
import { homedir as homedir5 } from "os";
|
|
34967
|
+
import { dirname as dirname4, join as join12 } from "path";
|
|
33712
34968
|
function validateLocaleFile(raw) {
|
|
33713
34969
|
if (typeof raw !== "object" || raw === null || Array.isArray(raw)) {
|
|
33714
34970
|
return { ok: false, errors: [{ key: "(file)", reason: "not a flat JSON object" }] };
|
|
@@ -33752,32 +35008,32 @@ function mergeTables(bundled, override) {
|
|
|
33752
35008
|
return { ...bundled, ...override };
|
|
33753
35009
|
}
|
|
33754
35010
|
function userLocalesDir(dshHome) {
|
|
33755
|
-
const home = dshHome ?? process.env.DSH_HOME ??
|
|
33756
|
-
return
|
|
35011
|
+
const home = dshHome ?? process.env.DSH_HOME ?? join12(homedir5(), ".dsh");
|
|
35012
|
+
return join12(home, "locales");
|
|
33757
35013
|
}
|
|
33758
35014
|
function bundledLocalesDir() {
|
|
33759
|
-
let dir =
|
|
35015
|
+
let dir = dirname4(new URL(import.meta.url).pathname);
|
|
33760
35016
|
for (let up = 0;up < 6; up++) {
|
|
33761
|
-
const candidate =
|
|
33762
|
-
if (
|
|
35017
|
+
const candidate = join12(dir, "locales");
|
|
35018
|
+
if (existsSync9(join12(candidate, `${DEFAULT_LANGUAGE}.json`)))
|
|
33763
35019
|
return candidate;
|
|
33764
|
-
const parent =
|
|
35020
|
+
const parent = dirname4(dir);
|
|
33765
35021
|
if (parent === dir)
|
|
33766
35022
|
break;
|
|
33767
35023
|
dir = parent;
|
|
33768
35024
|
}
|
|
33769
|
-
return
|
|
35025
|
+
return join12(dirname4(new URL(import.meta.url).pathname), "..", "locales");
|
|
33770
35026
|
}
|
|
33771
35027
|
function loadLocales(options) {
|
|
33772
35028
|
const bundledDir = options?.bundledDir ?? bundledLocalesDir();
|
|
33773
35029
|
const languages = new Map;
|
|
33774
35030
|
const warnings = [];
|
|
33775
|
-
if (
|
|
35031
|
+
if (existsSync9(bundledDir)) {
|
|
33776
35032
|
for (const entry of readdirSync2(bundledDir)) {
|
|
33777
35033
|
if (!entry.endsWith(".json"))
|
|
33778
35034
|
continue;
|
|
33779
35035
|
const id = entry.slice(0, -".json".length);
|
|
33780
|
-
const result = parseLocaleFile(
|
|
35036
|
+
const result = parseLocaleFile(readFileSync10(join12(bundledDir, entry), "utf8"));
|
|
33781
35037
|
if (!result.ok) {
|
|
33782
35038
|
warnings.push(`[i18n] bundled locale file rejected, skipping '${entry}': ${formatErrors(result.errors)}`);
|
|
33783
35039
|
continue;
|
|
@@ -33788,12 +35044,12 @@ function loadLocales(options) {
|
|
|
33788
35044
|
warnings.push(`[i18n] bundled locales dir not found: ${bundledDir}`);
|
|
33789
35045
|
}
|
|
33790
35046
|
const userDir = options?.userDir ?? userLocalesDir();
|
|
33791
|
-
if (
|
|
35047
|
+
if (existsSync9(userDir)) {
|
|
33792
35048
|
for (const entry of readdirSync2(userDir)) {
|
|
33793
35049
|
if (!entry.endsWith(".json"))
|
|
33794
35050
|
continue;
|
|
33795
35051
|
const id = entry.slice(0, -".json".length);
|
|
33796
|
-
const result = parseLocaleFile(
|
|
35052
|
+
const result = parseLocaleFile(readFileSync10(join12(userDir, entry), "utf8"));
|
|
33797
35053
|
if (!result.ok) {
|
|
33798
35054
|
warnings.push(`[i18n] user locale file rejected, skipping '${entry}': ${formatErrors(result.errors)}`);
|
|
33799
35055
|
continue;
|
|
@@ -35201,7 +36457,7 @@ function getActiveCommandView(state, host, conditions, focused) {
|
|
|
35201
36457
|
}
|
|
35202
36458
|
return collectActiveCommands(state.activeLayersCache, conditions, true);
|
|
35203
36459
|
}
|
|
35204
|
-
function
|
|
36460
|
+
function isPlainObject2(value) {
|
|
35205
36461
|
const prototype = Object.getPrototypeOf(value);
|
|
35206
36462
|
return prototype === Object.prototype || prototype === null;
|
|
35207
36463
|
}
|
|
@@ -35218,7 +36474,7 @@ function checkPlainData(value, identityKey, depth) {
|
|
|
35218
36474
|
if (typeof value !== "object" || value === null)
|
|
35219
36475
|
return true;
|
|
35220
36476
|
const isArray = Array.isArray(value);
|
|
35221
|
-
const plain = isArray ? Object.getPrototypeOf(value) === Array.prototype :
|
|
36477
|
+
const plain = isArray ? Object.getPrototypeOf(value) === Array.prototype : isPlainObject2(value);
|
|
35222
36478
|
if (!plain || !Object.isExtensible(value) || depth >= DEPTH_MAX)
|
|
35223
36479
|
return false;
|
|
35224
36480
|
return Reflect.ownKeys(value).every((key) => {
|
|
@@ -35256,7 +36512,7 @@ function markExternal(value, depth = 0) {
|
|
|
35256
36512
|
return;
|
|
35257
36513
|
external.add(value);
|
|
35258
36514
|
try {
|
|
35259
|
-
if (depth >= DEPTH_MAX || !(Array.isArray(value) ||
|
|
36515
|
+
if (depth >= DEPTH_MAX || !(Array.isArray(value) || isPlainObject2(value)))
|
|
35260
36516
|
return;
|
|
35261
36517
|
for (const key of Reflect.ownKeys(value)) {
|
|
35262
36518
|
const descriptor = Object.getOwnPropertyDescriptor(value, key);
|
|
@@ -35306,7 +36562,7 @@ function isPlainFunction(value) {
|
|
|
35306
36562
|
return Reflect.ownKeys(value).every((key) => PLAIN_FUNCTION_KEYS.has(key));
|
|
35307
36563
|
}
|
|
35308
36564
|
function isContainer(value) {
|
|
35309
|
-
return typeof value === "object" && value !== null && (Array.isArray(value) ||
|
|
36565
|
+
return typeof value === "object" && value !== null && (Array.isArray(value) || isPlainObject2(value));
|
|
35310
36566
|
}
|
|
35311
36567
|
function getErrorMessage(error, fallback) {
|
|
35312
36568
|
if (error instanceof Error && error.message) {
|
|
@@ -35332,7 +36588,7 @@ function snapshotDataValue(value, options) {
|
|
|
35332
36588
|
return freeze ? Object.freeze(cloned) : cloned;
|
|
35333
36589
|
}
|
|
35334
36590
|
if (value && typeof value === "object") {
|
|
35335
|
-
if (preserveNonPlainObjects && !
|
|
36591
|
+
if (preserveNonPlainObjects && !isPlainObject2(value)) {
|
|
35336
36592
|
return value;
|
|
35337
36593
|
}
|
|
35338
36594
|
const cloned = {};
|
|
@@ -41210,7 +42466,7 @@ var init_string_width = __esm(() => {
|
|
|
41210
42466
|
});
|
|
41211
42467
|
|
|
41212
42468
|
// ../tui-base/src/routes/session/composer-context.tsx
|
|
41213
|
-
import { homedir as
|
|
42469
|
+
import { homedir as homedir6 } from "os";
|
|
41214
42470
|
function truncateLeft(text, limit) {
|
|
41215
42471
|
if (limit <= 0)
|
|
41216
42472
|
return "";
|
|
@@ -41303,7 +42559,7 @@ function ComposerContext(props) {
|
|
|
41303
42559
|
}
|
|
41304
42560
|
function safeHome() {
|
|
41305
42561
|
try {
|
|
41306
|
-
return
|
|
42562
|
+
return homedir6();
|
|
41307
42563
|
} catch {
|
|
41308
42564
|
return;
|
|
41309
42565
|
}
|
|
@@ -52034,14 +53290,14 @@ var init_login = __esm(() => {
|
|
|
52034
53290
|
});
|
|
52035
53291
|
|
|
52036
53292
|
// ../tui-base/src/routes/session/export.ts
|
|
52037
|
-
import { homedir as
|
|
52038
|
-
import { resolve as
|
|
53293
|
+
import { homedir as homedir7 } from "os";
|
|
53294
|
+
import { resolve as resolve6 } from "path";
|
|
52039
53295
|
function exportTargetPath(sessionId, arg) {
|
|
52040
53296
|
const trimmed = arg?.trim();
|
|
52041
53297
|
if (trimmed)
|
|
52042
|
-
return
|
|
53298
|
+
return resolve6(trimmed);
|
|
52043
53299
|
const id8 = sessionId.slice(0, 8).replace(/[^A-Za-z0-9._-]/g, "-");
|
|
52044
|
-
return
|
|
53300
|
+
return resolve6(homedir7(), "Downloads", `dsh-session-${id8}.jsonl`);
|
|
52045
53301
|
}
|
|
52046
53302
|
function journalToJSONL(entries) {
|
|
52047
53303
|
if (entries.length === 0)
|
|
@@ -52054,7 +53310,7 @@ var init_export = () => {};
|
|
|
52054
53310
|
|
|
52055
53311
|
// ../tui-base/src/routes/session/commands.ts
|
|
52056
53312
|
import { mkdir as mkdir2, writeFile as writeFile2 } from "fs/promises";
|
|
52057
|
-
import { dirname as
|
|
53313
|
+
import { dirname as dirname5 } from "path";
|
|
52058
53314
|
function persistHints(seam) {
|
|
52059
53315
|
try {
|
|
52060
53316
|
seam.configSave?.({ footerHints: footerHints(), lang: hintsLocale() });
|
|
@@ -52651,7 +53907,7 @@ function coreCommands() {
|
|
|
52651
53907
|
try {
|
|
52652
53908
|
const entries = await ctx.seam.sessionJournal(sessionId);
|
|
52653
53909
|
const target = exportTargetPath(sessionId, argText);
|
|
52654
|
-
await mkdir2(
|
|
53910
|
+
await mkdir2(dirname5(target), { recursive: true });
|
|
52655
53911
|
await writeFile2(target, journalToJSONL(entries));
|
|
52656
53912
|
ctx.say(t("command.export.done", { count: entries.length, target }));
|
|
52657
53913
|
} catch (error) {
|
|
@@ -53183,29 +54439,29 @@ var init_slash_usage = __esm(() => {
|
|
|
53183
54439
|
});
|
|
53184
54440
|
|
|
53185
54441
|
// ../tui-base/src/routes/session/skills-source.ts
|
|
53186
|
-
import { existsSync as
|
|
53187
|
-
import { homedir as
|
|
53188
|
-
import { dirname as
|
|
54442
|
+
import { existsSync as existsSync10, readdirSync as readdirSync3, readFileSync as readFileSync11, statSync as statSync4 } from "fs";
|
|
54443
|
+
import { homedir as homedir8 } from "os";
|
|
54444
|
+
import { dirname as dirname6, join as join13, resolve as resolve7 } from "path";
|
|
53189
54445
|
import { TextAttributes as TextAttributes8 } from "@opentui/core";
|
|
53190
54446
|
function findProjectRoot(cwd) {
|
|
53191
|
-
let dir =
|
|
54447
|
+
let dir = resolve7(cwd);
|
|
53192
54448
|
for (let depth = 0;depth < 64; depth++) {
|
|
53193
|
-
if (
|
|
54449
|
+
if (existsSync10(join13(dir, ".git")))
|
|
53194
54450
|
return dir;
|
|
53195
|
-
const parent =
|
|
54451
|
+
const parent = dirname6(dir);
|
|
53196
54452
|
if (parent === dir)
|
|
53197
54453
|
break;
|
|
53198
54454
|
dir = parent;
|
|
53199
54455
|
}
|
|
53200
|
-
return
|
|
54456
|
+
return resolve7(cwd);
|
|
53201
54457
|
}
|
|
53202
54458
|
function resolveAgentsHome(explicit) {
|
|
53203
54459
|
if (typeof explicit === "string" && explicit.trim() !== "")
|
|
53204
|
-
return
|
|
54460
|
+
return resolve7(explicit);
|
|
53205
54461
|
const env = process.env.DSH_AGENTS_HOME;
|
|
53206
54462
|
if (typeof env === "string" && env.trim() !== "")
|
|
53207
|
-
return
|
|
53208
|
-
return
|
|
54463
|
+
return resolve7(env);
|
|
54464
|
+
return resolve7(join13(homedir8(), ".agents"));
|
|
53209
54465
|
}
|
|
53210
54466
|
function agentsHomeEnvWarning(env, configValue) {
|
|
53211
54467
|
const value = typeof env === "string" ? env : process.env.DSH_AGENTS_HOME;
|
|
@@ -53224,22 +54480,22 @@ function agentsHomeEnvWarning(env, configValue) {
|
|
|
53224
54480
|
function skillRoots(options) {
|
|
53225
54481
|
const roots = [];
|
|
53226
54482
|
const projectRoot = findProjectRoot(options.cwd);
|
|
53227
|
-
roots.push({ path:
|
|
53228
|
-
roots.push({ path:
|
|
54483
|
+
roots.push({ path: join13(projectRoot, ".dsh", "skills"), rank: 100, skipSystem: false });
|
|
54484
|
+
roots.push({ path: join13(projectRoot, ".agents", "skills"), rank: 200, skipSystem: false });
|
|
53229
54485
|
for (const dir of options.customSkillDirs ?? []) {
|
|
53230
54486
|
if (typeof dir === "string" && dir.trim() !== "") {
|
|
53231
|
-
roots.push({ path:
|
|
54487
|
+
roots.push({ path: resolve7(dir), rank: 300, skipSystem: false });
|
|
53232
54488
|
}
|
|
53233
54489
|
}
|
|
53234
54490
|
if (options.dshHome !== undefined) {
|
|
53235
|
-
roots.push({ path:
|
|
54491
|
+
roots.push({ path: join13(options.dshHome, "skills"), rank: 400, skipSystem: true });
|
|
53236
54492
|
}
|
|
53237
54493
|
const agentsHome = resolveAgentsHome(options.agentsHome);
|
|
53238
|
-
roots.push({ path:
|
|
54494
|
+
roots.push({ path: join13(agentsHome, "skills"), rank: 500, skipSystem: false });
|
|
53239
54495
|
const seen = new Set;
|
|
53240
54496
|
const deduped = [];
|
|
53241
54497
|
for (const root of roots.sort((a, b) => a.rank - b.rank)) {
|
|
53242
|
-
const key =
|
|
54498
|
+
const key = resolve7(root.path);
|
|
53243
54499
|
if (seen.has(key))
|
|
53244
54500
|
continue;
|
|
53245
54501
|
seen.add(key);
|
|
@@ -53299,7 +54555,7 @@ function oneLine(value) {
|
|
|
53299
54555
|
function readSkillFile(path) {
|
|
53300
54556
|
let raw;
|
|
53301
54557
|
try {
|
|
53302
|
-
raw =
|
|
54558
|
+
raw = readFileSync11(path, "utf8");
|
|
53303
54559
|
} catch {
|
|
53304
54560
|
return;
|
|
53305
54561
|
}
|
|
@@ -53336,7 +54592,7 @@ function discoverSkills(options) {
|
|
|
53336
54592
|
let isFile = entry.isFile();
|
|
53337
54593
|
if (entry.isSymbolicLink()) {
|
|
53338
54594
|
try {
|
|
53339
|
-
const target = statSync4(
|
|
54595
|
+
const target = statSync4(join13(root.path, entry.name));
|
|
53340
54596
|
isDirectory = target.isDirectory();
|
|
53341
54597
|
isFile = target.isFile();
|
|
53342
54598
|
} catch {
|
|
@@ -53345,9 +54601,9 @@ function discoverSkills(options) {
|
|
|
53345
54601
|
}
|
|
53346
54602
|
let file;
|
|
53347
54603
|
if (isDirectory)
|
|
53348
|
-
file =
|
|
54604
|
+
file = join13(root.path, entry.name, "SKILL.md");
|
|
53349
54605
|
else if (isFile && entry.name.endsWith(".md"))
|
|
53350
|
-
file =
|
|
54606
|
+
file = join13(root.path, entry.name);
|
|
53351
54607
|
if (file === undefined)
|
|
53352
54608
|
continue;
|
|
53353
54609
|
const row = readSkillFile(file);
|
|
@@ -53724,16 +54980,16 @@ var init_slash_palette = __esm(() => {
|
|
|
53724
54980
|
});
|
|
53725
54981
|
|
|
53726
54982
|
// ../tui-base/src/routes/session/skills-manage.ts
|
|
53727
|
-
import { existsSync as
|
|
54983
|
+
import { existsSync as existsSync11 } from "fs";
|
|
53728
54984
|
import { lstat, mkdir as mkdir3, readFile as readFile3, readdir, realpath, symlink, unlink } from "fs/promises";
|
|
53729
|
-
import { join as
|
|
54985
|
+
import { join as join14, sep } from "path";
|
|
53730
54986
|
function skillSymlinkPaths(publicDir, curatedDir, name) {
|
|
53731
|
-
const srcMd =
|
|
53732
|
-
if (
|
|
53733
|
-
return { src: srcMd, dest:
|
|
53734
|
-
const srcBundle =
|
|
53735
|
-
if (
|
|
53736
|
-
return { src: srcBundle, dest:
|
|
54987
|
+
const srcMd = join14(publicDir, `${name}.md`);
|
|
54988
|
+
if (existsSync11(srcMd))
|
|
54989
|
+
return { src: srcMd, dest: join14(curatedDir, `${name}.md`) };
|
|
54990
|
+
const srcBundle = join14(publicDir, name);
|
|
54991
|
+
if (existsSync11(srcBundle))
|
|
54992
|
+
return { src: srcBundle, dest: join14(curatedDir, name) };
|
|
53737
54993
|
return;
|
|
53738
54994
|
}
|
|
53739
54995
|
async function installSkillSymlink(src, dest) {
|
|
@@ -53797,8 +55053,8 @@ async function applyOneSkillChange(name, targetState, publicDir, curatedDir) {
|
|
|
53797
55053
|
}
|
|
53798
55054
|
}
|
|
53799
55055
|
try {
|
|
53800
|
-
const destMd =
|
|
53801
|
-
const destBundle =
|
|
55056
|
+
const destMd = join14(curatedDir, `${name}.md`);
|
|
55057
|
+
const destBundle = join14(curatedDir, name);
|
|
53802
55058
|
const mdStat = await lstat(destMd).catch(() => {
|
|
53803
55059
|
return;
|
|
53804
55060
|
});
|
|
@@ -53889,14 +55145,14 @@ async function scanAvailableSkills(publicDir, curatedDir) {
|
|
|
53889
55145
|
if (name.endsWith(".md")) {
|
|
53890
55146
|
skillNames.add(name.slice(0, -3));
|
|
53891
55147
|
} else if (!name.startsWith(".")) {
|
|
53892
|
-
if (
|
|
55148
|
+
if (existsSync11(join14(publicDir, name, "SKILL.md")))
|
|
53893
55149
|
skillNames.add(name);
|
|
53894
55150
|
}
|
|
53895
55151
|
}
|
|
53896
55152
|
const rows = [];
|
|
53897
55153
|
for (const name of skillNames) {
|
|
53898
|
-
const installed =
|
|
53899
|
-
const description = await readSkillDescription(
|
|
55154
|
+
const installed = existsSync11(join14(curatedDir, `${name}.md`)) || existsSync11(join14(curatedDir, name));
|
|
55155
|
+
const description = await readSkillDescription(existsSync11(join14(publicDir, name, "SKILL.md")) ? join14(publicDir, name, "SKILL.md") : join14(publicDir, `${name}.md`));
|
|
53900
55156
|
rows.push({ name, description, installed });
|
|
53901
55157
|
}
|
|
53902
55158
|
rows.sort((a, b) => a.name.localeCompare(b.name));
|
|
@@ -61162,7 +62418,7 @@ var init_subagents_viewer = __esm(() => {
|
|
|
61162
62418
|
import { TextAttributes as TextAttributes12 } from "@opentui/core";
|
|
61163
62419
|
function resolveVersion() {
|
|
61164
62420
|
try {
|
|
61165
|
-
return "0.
|
|
62421
|
+
return "0.19.0";
|
|
61166
62422
|
} catch {
|
|
61167
62423
|
return "dev";
|
|
61168
62424
|
}
|
|
@@ -63653,17 +64909,30 @@ var init_session_seam_adapter = __esm(() => {
|
|
|
63653
64909
|
});
|
|
63654
64910
|
|
|
63655
64911
|
// ../tui-base/examples/v2-entry.tsx
|
|
63656
|
-
import { join as
|
|
64912
|
+
import { join as join15 } from "path";
|
|
64913
|
+
import { existsSync as existsSync12 } from "fs";
|
|
64914
|
+
function resolveWatchdogScript() {
|
|
64915
|
+
const candidates = [
|
|
64916
|
+
join15(import.meta.dir, "..", "watchdog.mjs"),
|
|
64917
|
+
join15(import.meta.dir, "..", "..", "shell", "dist", "watchdog.mjs"),
|
|
64918
|
+
join15(import.meta.dir, "..", "..", "..", "shell", "dist", "watchdog.mjs")
|
|
64919
|
+
];
|
|
64920
|
+
for (const candidate of candidates)
|
|
64921
|
+
if (existsSync12(candidate))
|
|
64922
|
+
return candidate;
|
|
64923
|
+
return null;
|
|
64924
|
+
}
|
|
63657
64925
|
async function loadShell() {
|
|
63658
|
-
const [shared, lifecycle, transport, rhs, adapter, git] = await Promise.all([
|
|
64926
|
+
const [shared, lifecycle, clifecycle, transport, rhs, adapter, git] = await Promise.all([
|
|
63659
64927
|
Promise.resolve().then(() => (init_boot_shared(), exports_boot_shared)),
|
|
63660
64928
|
Promise.resolve().then(() => (init_lifecycle(), exports_lifecycle)),
|
|
64929
|
+
Promise.resolve().then(() => (init_client_lifecycle(), exports_client_lifecycle)),
|
|
63661
64930
|
Promise.resolve().then(() => (init_transport(), exports_transport)),
|
|
63662
64931
|
Promise.resolve().then(() => (init_remote_host_session(), exports_remote_host_session)),
|
|
63663
64932
|
Promise.resolve().then(() => (init_session_seam_adapter(), exports_session_seam_adapter)),
|
|
63664
64933
|
Promise.resolve().then(() => (init_remote_git(), exports_remote_git))
|
|
63665
64934
|
]);
|
|
63666
|
-
return { shared, lifecycle, transport, rhs, adapter, git };
|
|
64935
|
+
return { shared, lifecycle, clifecycle, transport, rhs, adapter, git };
|
|
63667
64936
|
}
|
|
63668
64937
|
function V2SessionPage(props) {
|
|
63669
64938
|
return createComponent2(DockProvider, {
|
|
@@ -64330,13 +65599,31 @@ function appendDiagnostic(line) {
|
|
|
64330
65599
|
} catch {}
|
|
64331
65600
|
}
|
|
64332
65601
|
async function bootClientV2(options = {}) {
|
|
64333
|
-
const { shared, lifecycle, transport, rhs, adapter, git } = await loadShell();
|
|
65602
|
+
const { shared, lifecycle, clifecycle, transport, rhs, adapter, git } = await loadShell();
|
|
64334
65603
|
const workspace = process.cwd();
|
|
64335
65604
|
const profile = lifecycle.DEFAULT_PROFILE;
|
|
64336
65605
|
const idleExitMs = lifecycle.resolveIdleExitMs();
|
|
64337
65606
|
const idleExitSec = idleExitMs / 1000;
|
|
64338
65607
|
shared.bootCallOrder.push("ensureHost");
|
|
64339
|
-
const host = await lifecycle.
|
|
65608
|
+
const host = await lifecycle.ensureV2Host({ profile, idleExitSec });
|
|
65609
|
+
let clientHeartbeat = null;
|
|
65610
|
+
let heartbeatRegistered = false;
|
|
65611
|
+
try {
|
|
65612
|
+
clientHeartbeat = clifecycle.registerHeartbeat(host.dshHome, { pid: process.pid, workspace });
|
|
65613
|
+
clientHeartbeat.start();
|
|
65614
|
+
heartbeatRegistered = true;
|
|
65615
|
+
} catch (error) {
|
|
65616
|
+
console.error("[v2-entry] heartbeat registration failed:", error);
|
|
65617
|
+
}
|
|
65618
|
+
if (heartbeatRegistered) {
|
|
65619
|
+
try {
|
|
65620
|
+
const scriptPath = resolveWatchdogScript();
|
|
65621
|
+
if (scriptPath)
|
|
65622
|
+
clifecycle.spawnWatchdog(host.dshHome, { scriptPath, profile });
|
|
65623
|
+
} catch (error) {
|
|
65624
|
+
console.error("[v2-entry] watchdog spawn failed:", error);
|
|
65625
|
+
}
|
|
65626
|
+
}
|
|
64340
65627
|
shared.bootCallOrder.push("connect");
|
|
64341
65628
|
const connection = new transport.ClientConnection({
|
|
64342
65629
|
authority: host.authority,
|
|
@@ -64386,8 +65673,8 @@ async function bootClientV2(options = {}) {
|
|
|
64386
65673
|
agentsHome: agentsHomeForSkills
|
|
64387
65674
|
});
|
|
64388
65675
|
const skillsManagerRoots = {
|
|
64389
|
-
source:
|
|
64390
|
-
curated:
|
|
65676
|
+
source: join15(agentsHomeForSkills, "skills"),
|
|
65677
|
+
curated: join15(host.dshHome, "skills")
|
|
64391
65678
|
};
|
|
64392
65679
|
const envTheme = process.env[shared.ENV_THEME];
|
|
64393
65680
|
const workspaceConfig = seam.workspaceConfig();
|
|
@@ -64423,8 +65710,17 @@ async function bootClientV2(options = {}) {
|
|
|
64423
65710
|
try {
|
|
64424
65711
|
await Promise.race([session.dispose(), new Promise((resolve) => setTimeout(resolve, shared.SHUTDOWN_GRACE_MS))]);
|
|
64425
65712
|
} catch {}
|
|
65713
|
+
if (clientHeartbeat) {
|
|
65714
|
+
clientHeartbeat.stop();
|
|
65715
|
+
clientHeartbeat.remove();
|
|
65716
|
+
try {
|
|
65717
|
+
await clifecycle.lastOneGracefulShutdown(host.dshHome, { profile, hooks: clifecycle.psKillHooks });
|
|
65718
|
+
} catch (error) {
|
|
65719
|
+
console.error("[v2-entry] last-one shutdown failed:", error);
|
|
65720
|
+
}
|
|
65721
|
+
}
|
|
64426
65722
|
host.release();
|
|
64427
|
-
if (host.refCount === 0 && idleExitMs > 0)
|
|
65723
|
+
if (host.v2Managed !== true && host.refCount === 0 && idleExitMs > 0)
|
|
64428
65724
|
shared.spawnIdleReaper(host, idleExitMs);
|
|
64429
65725
|
})();
|
|
64430
65726
|
return shutdownPromise;
|
|
@@ -64432,7 +65728,7 @@ async function bootClientV2(options = {}) {
|
|
|
64432
65728
|
shared.installExitPaths(shutdown);
|
|
64433
65729
|
shared.bootCallOrder.push("render");
|
|
64434
65730
|
render(() => createComponent2(ConfigProvider2, {
|
|
64435
|
-
config:
|
|
65731
|
+
config: resolve5({}, { terminalSuspend: true }),
|
|
64436
65732
|
get children() {
|
|
64437
65733
|
return createComponent2(Keymap2.Provider, {
|
|
64438
65734
|
get children() {
|
|
@@ -64580,11 +65876,26 @@ var init_v2_entry = __esm(() => {
|
|
|
64580
65876
|
});
|
|
64581
65877
|
|
|
64582
65878
|
// src/client-entry.tsx
|
|
65879
|
+
init_client_lifecycle();
|
|
64583
65880
|
init_boot_shared();
|
|
64584
65881
|
init_boot_shared();
|
|
64585
65882
|
init_lifecycle();
|
|
64586
65883
|
init_transport();
|
|
64587
65884
|
init_remote_host_session();
|
|
65885
|
+
import { existsSync as existsSync13 } from "fs";
|
|
65886
|
+
import { join as join16 } from "path";
|
|
65887
|
+
function resolveWatchdogScript2() {
|
|
65888
|
+
const candidates = [
|
|
65889
|
+
join16(import.meta.dir, "..", "watchdog.mjs"),
|
|
65890
|
+
join16(import.meta.dir, "..", "dist", "watchdog.mjs"),
|
|
65891
|
+
join16(import.meta.dir, "..", "scripts", "watchdog.mjs")
|
|
65892
|
+
];
|
|
65893
|
+
for (const candidate of candidates) {
|
|
65894
|
+
if (existsSync13(candidate))
|
|
65895
|
+
return candidate;
|
|
65896
|
+
}
|
|
65897
|
+
return null;
|
|
65898
|
+
}
|
|
64588
65899
|
async function waitForBootLabel(session, budgetMs) {
|
|
64589
65900
|
const deadline = Date.now() + budgetMs;
|
|
64590
65901
|
while (session.label === "dsh-host" && Date.now() < deadline) {
|
|
@@ -64617,11 +65928,36 @@ async function bootClient(options = {}) {
|
|
|
64617
65928
|
const idleExitMs = resolveIdleExitMs(options.idleExitSec);
|
|
64618
65929
|
const idleExitSec = idleExitMs / 1000;
|
|
64619
65930
|
bootCallOrder.push("ensureHost");
|
|
64620
|
-
const host = await (options.ensureHost ??
|
|
65931
|
+
const host = await (options.ensureHost ?? ensureV2Host)({
|
|
64621
65932
|
profile,
|
|
64622
65933
|
idleExitSec,
|
|
64623
65934
|
...options.dshHome !== undefined ? { dshHome: options.dshHome } : {}
|
|
64624
65935
|
});
|
|
65936
|
+
let heartbeat = null;
|
|
65937
|
+
if (options.heartbeat !== false) {
|
|
65938
|
+
let heartbeatRegistered = false;
|
|
65939
|
+
try {
|
|
65940
|
+
heartbeat = (options.registerHeartbeat ?? registerHeartbeat)(host.dshHome, {
|
|
65941
|
+
...options.clientId !== undefined ? { id: options.clientId } : {},
|
|
65942
|
+
pid: process.pid,
|
|
65943
|
+
workspace
|
|
65944
|
+
});
|
|
65945
|
+
heartbeat.start();
|
|
65946
|
+
heartbeatRegistered = true;
|
|
65947
|
+
} catch (error) {
|
|
65948
|
+
console.error("[client-entry] heartbeat registration failed:", error);
|
|
65949
|
+
}
|
|
65950
|
+
if (heartbeatRegistered) {
|
|
65951
|
+
try {
|
|
65952
|
+
const scriptPath = options.watchdogScriptPath ?? resolveWatchdogScript2();
|
|
65953
|
+
if (scriptPath) {
|
|
65954
|
+
(options.spawnLifecycleWatchdog ?? spawnWatchdog)(host.dshHome, { scriptPath, profile });
|
|
65955
|
+
}
|
|
65956
|
+
} catch (error) {
|
|
65957
|
+
console.error("[client-entry] watchdog spawn failed:", error);
|
|
65958
|
+
}
|
|
65959
|
+
}
|
|
65960
|
+
}
|
|
64625
65961
|
if (options.installErrorLog !== false) {
|
|
64626
65962
|
installClientErrorLog(host.dshHome);
|
|
64627
65963
|
}
|
|
@@ -64662,8 +65998,17 @@ async function bootClient(options = {}) {
|
|
|
64662
65998
|
new Promise((resolve) => setTimeout(resolve, SHUTDOWN_GRACE_MS))
|
|
64663
65999
|
]);
|
|
64664
66000
|
} catch {}
|
|
66001
|
+
if (heartbeat) {
|
|
66002
|
+
heartbeat.stop();
|
|
66003
|
+
heartbeat.remove();
|
|
66004
|
+
try {
|
|
66005
|
+
await (options.lastOneShutdown ?? lastOneGracefulShutdown)(host.dshHome, { profile, hooks: psKillHooks });
|
|
66006
|
+
} catch (error) {
|
|
66007
|
+
console.error("[client-entry] last-one shutdown failed:", error);
|
|
66008
|
+
}
|
|
66009
|
+
}
|
|
64665
66010
|
host.release();
|
|
64666
|
-
if (host.refCount === 0 && idleExitMs > 0) {
|
|
66011
|
+
if (host.v2Managed !== true && host.refCount === 0 && idleExitMs > 0) {
|
|
64667
66012
|
spawnIdleReaper(host, idleExitMs, options.spawnReaper ?? defaultSpawnReaper);
|
|
64668
66013
|
}
|
|
64669
66014
|
})();
|
|
@@ -64711,5 +66056,5 @@ export {
|
|
|
64711
66056
|
themeNameFromConfig
|
|
64712
66057
|
};
|
|
64713
66058
|
|
|
64714
|
-
//# debugId=
|
|
66059
|
+
//# debugId=5292F041178B90FD64756E2164756E21
|
|
64715
66060
|
//# sourceMappingURL=index.js.map
|