shellpuppet 0.1.0 → 0.2.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +210 -33
- package/dist/cli/desktopShortcut.d.ts +22 -0
- package/dist/cli/desktopShortcut.js +157 -0
- package/dist/cli/desktopShortcut.js.map +1 -0
- package/dist/cli/index.js +268 -59
- package/dist/cli/index.js.map +1 -1
- package/dist/client/http.d.ts +74 -3
- package/dist/client/http.js +560 -37
- package/dist/client/http.js.map +1 -1
- package/dist/core/dialogs.d.ts +20 -12
- package/dist/core/dialogs.js +31 -19
- package/dist/core/dialogs.js.map +1 -1
- package/dist/core/manager.d.ts +35 -5
- package/dist/core/manager.js +121 -8
- package/dist/core/manager.js.map +1 -1
- package/dist/core/nativePty.d.ts +9 -5
- package/dist/core/nativePty.js +11 -6
- package/dist/core/nativePty.js.map +1 -1
- package/dist/core/promptDetector.d.ts +37 -3
- package/dist/core/promptDetector.js +303 -12
- package/dist/core/promptDetector.js.map +1 -1
- package/dist/core/reasoning.d.ts +19 -6
- package/dist/core/reasoning.js +223 -30
- package/dist/core/reasoning.js.map +1 -1
- package/dist/core/regexBudget.d.ts +20 -0
- package/dist/core/regexBudget.js +25 -1
- package/dist/core/regexBudget.js.map +1 -1
- package/dist/core/renderer.d.ts +16 -1
- package/dist/core/renderer.js +97 -6
- package/dist/core/renderer.js.map +1 -1
- package/dist/core/selection.d.ts +6 -0
- package/dist/core/selection.js +48 -0
- package/dist/core/selection.js.map +1 -0
- package/dist/core/session.d.ts +267 -13
- package/dist/core/session.js +585 -101
- package/dist/core/session.js.map +1 -1
- package/dist/core/types.d.ts +53 -18
- package/dist/core/types.js +30 -6
- package/dist/core/types.js.map +1 -1
- package/dist/core/waiter.d.ts +12 -4
- package/dist/core/waiter.js +63 -70
- package/dist/core/waiter.js.map +1 -1
- package/dist/core/windowsConsoleHost.d.ts +147 -0
- package/dist/core/windowsConsoleHost.js +588 -0
- package/dist/core/windowsConsoleHost.js.map +1 -0
- package/dist/core/windowsPtyStart.d.ts +100 -29
- package/dist/core/windowsPtyStart.js +143 -36
- package/dist/core/windowsPtyStart.js.map +1 -1
- package/dist/daemon/auth.d.ts +72 -2
- package/dist/daemon/auth.js +128 -3
- package/dist/daemon/auth.js.map +1 -1
- package/dist/daemon/config.d.ts +44 -1
- package/dist/daemon/config.js +276 -9
- package/dist/daemon/config.js.map +1 -1
- package/dist/daemon/folderPicker.d.ts +27 -0
- package/dist/daemon/folderPicker.js +115 -0
- package/dist/daemon/folderPicker.js.map +1 -0
- package/dist/daemon/index.js +20 -19
- package/dist/daemon/index.js.map +1 -1
- package/dist/daemon/launchProfiles.d.ts +155 -0
- package/dist/daemon/launchProfiles.js +554 -0
- package/dist/daemon/launchProfiles.js.map +1 -0
- package/dist/daemon/liveness.d.ts +1 -1
- package/dist/daemon/liveness.js +2 -2
- package/dist/daemon/liveness.js.map +1 -1
- package/dist/daemon/paths.d.ts +4 -0
- package/dist/daemon/paths.js.map +1 -1
- package/dist/daemon/restartHold.d.ts +16 -0
- package/dist/daemon/restartHold.js +126 -0
- package/dist/daemon/restartHold.js.map +1 -0
- package/dist/daemon/screenshot.d.ts +58 -1
- package/dist/daemon/screenshot.js +172 -26
- package/dist/daemon/screenshot.js.map +1 -1
- package/dist/daemon/server.d.ts +220 -10
- package/dist/daemon/server.js +1975 -205
- package/dist/daemon/server.js.map +1 -1
- package/dist/daemon/sessionFeed.d.ts +48 -0
- package/dist/daemon/sessionFeed.js +101 -0
- package/dist/daemon/sessionFeed.js.map +1 -0
- package/dist/daemon/viewerLauncher.d.ts +100 -9
- package/dist/daemon/viewerLauncher.js +349 -67
- package/dist/daemon/viewerLauncher.js.map +1 -1
- package/dist/mcp/config.d.ts +7 -14
- package/dist/mcp/config.js +10 -21
- package/dist/mcp/config.js.map +1 -1
- package/dist/mcp/index.js +20 -11
- package/dist/mcp/index.js.map +1 -1
- package/dist/mcp/tools.d.ts +14 -7
- package/dist/mcp/tools.js +161 -60
- package/dist/mcp/tools.js.map +1 -1
- package/dist/viewer/dashboard-folders.js +20 -0
- package/dist/viewer/dashboard-layout.js +52 -0
- package/dist/viewer/dashboard.css +67 -0
- package/dist/viewer/dashboard.html +44 -0
- package/dist/viewer/dashboard.js +1523 -0
- package/dist/viewer/icon.ico +0 -0
- package/dist/viewer/index.html +12 -7
- package/dist/viewer/pane.js +736 -0
- package/dist/viewer/viewer.css +18 -7
- package/dist/viewer/viewer.js +47 -624
- package/package.json +13 -13
package/dist/client/http.js
CHANGED
|
@@ -16,12 +16,25 @@
|
|
|
16
16
|
* stdout or stderr (the MCP adapter loads it in-process).
|
|
17
17
|
*/
|
|
18
18
|
import { spawn } from 'node:child_process';
|
|
19
|
+
import { createHash } from 'node:crypto';
|
|
20
|
+
import * as fs from 'node:fs';
|
|
21
|
+
import * as net from 'node:net';
|
|
22
|
+
import * as os from 'node:os';
|
|
23
|
+
import * as path from 'node:path';
|
|
19
24
|
import { fileURLToPath } from 'node:url';
|
|
20
|
-
import {
|
|
25
|
+
import { readDaemonConfig } from '../daemon/config.js';
|
|
26
|
+
import { resolveLaunchCommand } from '../daemon/launchProfiles.js';
|
|
27
|
+
import { daemonStatePath, ensureHome, readDaemonState, removeDaemonStateIf, shellpuppetHome, } from '../daemon/paths.js';
|
|
21
28
|
import { daemonRunning } from '../daemon/liveness.js';
|
|
22
29
|
import { packageVersion } from '../daemon/meta.js';
|
|
30
|
+
import { readRestartHold, restartHoldError } from '../daemon/restartHold.js';
|
|
23
31
|
import { NULL_LOGGER } from '../core/types.js';
|
|
32
|
+
import { taskkillTrees } from '../core/session.js';
|
|
24
33
|
const AUTO_START_TIMEOUT_MS = 10_000;
|
|
34
|
+
/** A restart may spend ten seconds stopping, then a full direct or wrapped start bound. */
|
|
35
|
+
const RESTART_STOP_TIMEOUT_MS = 10_000;
|
|
36
|
+
/** A person may need time to unlock a configured secrets wrapper. */
|
|
37
|
+
export const WRAPPED_START_TIMEOUT_MS = 120_000;
|
|
25
38
|
const AUTO_START_POLL_MS = 150;
|
|
26
39
|
const HEALTH_TIMEOUT_MS = 1_500;
|
|
27
40
|
/**
|
|
@@ -30,6 +43,16 @@ const HEALTH_TIMEOUT_MS = 1_500;
|
|
|
30
43
|
* caller is told it is busy.
|
|
31
44
|
*/
|
|
32
45
|
const PATIENT_HEALTH_TIMEOUTS_MS = [3_000, 5_000];
|
|
46
|
+
const EARLY_WRAPPER_EXIT_GRACE_MS = 10_000;
|
|
47
|
+
/** A failed wrapper gets at most this long for process-tree cleanup. */
|
|
48
|
+
const WRAPPER_CLEANUP_TIMEOUT_MS = 15_000;
|
|
49
|
+
const WRAPPER_TREE_KILL_TIMEOUT_MS = 8_000;
|
|
50
|
+
const START_LOCK_SOCKET = 'daemon-start.sock';
|
|
51
|
+
/** sockaddr_un.sun_path includes the terminating NUL byte. */
|
|
52
|
+
const POSIX_SOCKET_PATH_BYTES = { darwin: 104, other: 108 };
|
|
53
|
+
const UNCOORDINATED_START = Symbol('uncoordinated daemon start');
|
|
54
|
+
let warnedInvalidDirect = false;
|
|
55
|
+
const reportedStartConfigProblems = new Set();
|
|
33
56
|
/**
|
|
34
57
|
* The daemon named in the state file is running but did not answer its health
|
|
35
58
|
* check in time. It holds its sessions still, so it is neither cleared nor
|
|
@@ -52,6 +75,20 @@ export class DaemonNotAnsweringError extends Error {
|
|
|
52
75
|
this.name = 'DaemonNotAnsweringError';
|
|
53
76
|
}
|
|
54
77
|
}
|
|
78
|
+
/**
|
|
79
|
+
* The daemon a request went to has gone, and the caller asked for no other to
|
|
80
|
+
* be started in its place (`autoStart: false`).
|
|
81
|
+
*/
|
|
82
|
+
export class DaemonGoneError extends Error {
|
|
83
|
+
pid;
|
|
84
|
+
port;
|
|
85
|
+
constructor(pid, port, options) {
|
|
86
|
+
super(`The ShellPuppet daemon (pid ${String(pid)}, port ${String(port)}) has stopped.`, options);
|
|
87
|
+
this.pid = pid;
|
|
88
|
+
this.port = port;
|
|
89
|
+
this.name = 'DaemonGoneError';
|
|
90
|
+
}
|
|
91
|
+
}
|
|
55
92
|
async function health(port, timeoutMs = HEALTH_TIMEOUT_MS) {
|
|
56
93
|
try {
|
|
57
94
|
const response = await fetch(`http://127.0.0.1:${String(port)}/health`, {
|
|
@@ -72,10 +109,347 @@ async function health(port, timeoutMs = HEALTH_TIMEOUT_MS) {
|
|
|
72
109
|
return null;
|
|
73
110
|
}
|
|
74
111
|
}
|
|
112
|
+
/**
|
|
113
|
+
* The folder the daemon runs in: the user's home directory, whichever client
|
|
114
|
+
* starts it. A process holds its working directory open, so on Windows a
|
|
115
|
+
* daemon started in the first client's folder would keep that folder from
|
|
116
|
+
* being deleted or renamed for as long as it ran. Not the ShellPuppet home:
|
|
117
|
+
* the daemon or its starting client creates and hardens that separately
|
|
118
|
+
* (design §4.1). Undefined, and so inherited, only where the home directory
|
|
119
|
+
* is not there to run in.
|
|
120
|
+
*/
|
|
121
|
+
export function daemonWorkingDirectory() {
|
|
122
|
+
const home = os.homedir();
|
|
123
|
+
try {
|
|
124
|
+
return fs.statSync(home).isDirectory() ? home : undefined;
|
|
125
|
+
}
|
|
126
|
+
catch {
|
|
127
|
+
return undefined;
|
|
128
|
+
}
|
|
129
|
+
}
|
|
75
130
|
function defaultDaemonEntry() {
|
|
76
131
|
// From dist/client/http.js this resolves to dist/daemon/index.js.
|
|
77
132
|
return fileURLToPath(new URL('../daemon/index.js', import.meta.url));
|
|
78
133
|
}
|
|
134
|
+
/** Resolve a configured wrapper without a shell or joined argument string. */
|
|
135
|
+
export function planDaemonStart(wrapper, entry, cwd, env) {
|
|
136
|
+
const program = wrapper[0] ?? '';
|
|
137
|
+
const name = path.basename(program);
|
|
138
|
+
const resolved = resolveLaunchCommand(program, cwd, env);
|
|
139
|
+
if ('error' in resolved) {
|
|
140
|
+
throw new Error(`daemon.startWith program ${name} could not be started: program not found.`);
|
|
141
|
+
}
|
|
142
|
+
if (process.platform === 'win32' && !/\.(exe|com)$/i.test(resolved.file)) {
|
|
143
|
+
throw new Error(`daemon.startWith program ${name} cannot start directly on Windows; point it at the program itself (.exe or .com).`);
|
|
144
|
+
}
|
|
145
|
+
return { command: resolved.file, args: [...wrapper.slice(1), process.execPath, entry] };
|
|
146
|
+
}
|
|
147
|
+
/** End only the process tree rooted at the child this client spawned. */
|
|
148
|
+
async function endSpawnedWrapper(child, logger) {
|
|
149
|
+
const pid = child.pid;
|
|
150
|
+
if (pid === undefined || pid <= 0)
|
|
151
|
+
return;
|
|
152
|
+
// Until Node observes the exit it holds the Windows process handle, so the
|
|
153
|
+
// pid cannot be reused. On POSIX it has not reaped the child, so neither
|
|
154
|
+
// its pid nor the process group id can be reused.
|
|
155
|
+
if (child.exitCode !== null || child.signalCode !== null)
|
|
156
|
+
return;
|
|
157
|
+
if (process.platform === 'win32') {
|
|
158
|
+
const began = Date.now();
|
|
159
|
+
let timer;
|
|
160
|
+
const failure = await Promise.race([
|
|
161
|
+
taskkillTrees([pid], WRAPPER_TREE_KILL_TIMEOUT_MS),
|
|
162
|
+
new Promise((resolve) => {
|
|
163
|
+
timer = setTimeout(() => resolve({ timedOut: true, exitCode: null,
|
|
164
|
+
elapsedMs: Date.now() - began }), WRAPPER_TREE_KILL_TIMEOUT_MS + 1_000);
|
|
165
|
+
}),
|
|
166
|
+
]);
|
|
167
|
+
if (timer !== undefined)
|
|
168
|
+
clearTimeout(timer);
|
|
169
|
+
if (failure !== null) {
|
|
170
|
+
// If the tree walk timed out, end the still-live root through its held
|
|
171
|
+
// child handle. The warning says descendants may need attention.
|
|
172
|
+
if (child.exitCode === null && child.signalCode === null)
|
|
173
|
+
child.kill('SIGKILL');
|
|
174
|
+
logger.warn('daemon.startWith process tree cleanup did not complete', { pid, timedOut: failure.timedOut });
|
|
175
|
+
}
|
|
176
|
+
while (child.exitCode === null && child.signalCode === null && Date.now() - began < WRAPPER_CLEANUP_TIMEOUT_MS) {
|
|
177
|
+
await new Promise((resolve) => setTimeout(resolve, Math.min(50, WRAPPER_CLEANUP_TIMEOUT_MS - (Date.now() - began))));
|
|
178
|
+
}
|
|
179
|
+
}
|
|
180
|
+
else {
|
|
181
|
+
const began = Date.now();
|
|
182
|
+
try {
|
|
183
|
+
process.kill(-pid, 'SIGKILL');
|
|
184
|
+
}
|
|
185
|
+
catch {
|
|
186
|
+
// The group may already be gone; still end the child if it is live.
|
|
187
|
+
if (child.exitCode === null && child.signalCode === null)
|
|
188
|
+
child.kill('SIGKILL');
|
|
189
|
+
}
|
|
190
|
+
// A signal only requests termination. Wait for Node to reap this child so
|
|
191
|
+
// callers do not observe its zombie pid as a live wrapper on POSIX.
|
|
192
|
+
while (child.exitCode === null && child.signalCode === null && Date.now() - began < WRAPPER_CLEANUP_TIMEOUT_MS) {
|
|
193
|
+
await new Promise((resolve) => setTimeout(resolve, Math.min(50, WRAPPER_CLEANUP_TIMEOUT_MS - (Date.now() - began))));
|
|
194
|
+
}
|
|
195
|
+
if (child.exitCode === null && child.signalCode === null) {
|
|
196
|
+
logger.warn('daemon.startWith wrapper cleanup did not complete', { pid, timedOut: true });
|
|
197
|
+
}
|
|
198
|
+
}
|
|
199
|
+
}
|
|
200
|
+
/** The fixed reasons a start socket folder is refused; each names one guard. */
|
|
201
|
+
export const START_FOLDER_PROBLEMS = [
|
|
202
|
+
'temporary folder is not a real folder',
|
|
203
|
+
'temporary folder belongs to another user',
|
|
204
|
+
'temporary folder is shared without the sticky bit',
|
|
205
|
+
'short folder is a link',
|
|
206
|
+
'short folder is not a real folder',
|
|
207
|
+
'short folder belongs to another user',
|
|
208
|
+
'short folder is open to others',
|
|
209
|
+
];
|
|
210
|
+
/**
|
|
211
|
+
* The short socket folder is checked once and then used by name, so nobody else
|
|
212
|
+
* may be able to rename or replace it afterwards. Renaming an entry needs write
|
|
213
|
+
* access to its parent, so a parent that group or others can write to must carry
|
|
214
|
+
* the sticky bit (as /tmp does). The sticky bit still lets the parent's owner
|
|
215
|
+
* rename entries, so the parent must also belong to root or to this user.
|
|
216
|
+
* Ancestors above the parent are not checked; that limit is documented.
|
|
217
|
+
*/
|
|
218
|
+
export function temporaryParentProblem(parent, uid) {
|
|
219
|
+
if (!parent.isDirectory() || parent.isSymbolicLink())
|
|
220
|
+
return 'temporary folder is not a real folder';
|
|
221
|
+
if (parent.uid !== 0 && parent.uid !== uid)
|
|
222
|
+
return 'temporary folder belongs to another user';
|
|
223
|
+
if ((parent.mode & 0o022) !== 0 && (parent.mode & 0o1000) === 0)
|
|
224
|
+
return 'temporary folder is shared without the sticky bit';
|
|
225
|
+
return null;
|
|
226
|
+
}
|
|
227
|
+
/** The short folder must be a real folder of this user's with no access for others. */
|
|
228
|
+
export function shortFolderProblem(folder, uid) {
|
|
229
|
+
if (folder.isSymbolicLink())
|
|
230
|
+
return 'short folder is a link';
|
|
231
|
+
if (!folder.isDirectory())
|
|
232
|
+
return 'short folder is not a real folder';
|
|
233
|
+
if (folder.uid !== uid)
|
|
234
|
+
return 'short folder belongs to another user';
|
|
235
|
+
if ((folder.mode & 0o077) !== 0)
|
|
236
|
+
return 'short folder is open to others';
|
|
237
|
+
return null;
|
|
238
|
+
}
|
|
239
|
+
function startLockEndpoint(home) {
|
|
240
|
+
if (process.platform !== 'win32') {
|
|
241
|
+
const inHome = path.join(home, START_LOCK_SOCKET);
|
|
242
|
+
const limit = process.platform === 'darwin' ? POSIX_SOCKET_PATH_BYTES.darwin : POSIX_SOCKET_PATH_BYTES.other;
|
|
243
|
+
if (Buffer.byteLength(inHome) + 1 <= limit)
|
|
244
|
+
return inHome;
|
|
245
|
+
const uid = process.getuid?.();
|
|
246
|
+
if (uid === undefined)
|
|
247
|
+
throw new Error('user id unavailable');
|
|
248
|
+
const parent = os.tmpdir();
|
|
249
|
+
const parentProblem = temporaryParentProblem(fs.lstatSync(parent), uid);
|
|
250
|
+
if (parentProblem !== null)
|
|
251
|
+
throw new Error(parentProblem);
|
|
252
|
+
const folder = path.join(parent, `shellpuppet-${String(uid)}`);
|
|
253
|
+
try {
|
|
254
|
+
fs.mkdirSync(folder, { mode: 0o700 });
|
|
255
|
+
}
|
|
256
|
+
catch (error) {
|
|
257
|
+
if (error.code !== 'EEXIST')
|
|
258
|
+
throw error;
|
|
259
|
+
}
|
|
260
|
+
const folderProblem = shortFolderProblem(fs.lstatSync(folder), uid);
|
|
261
|
+
if (folderProblem !== null)
|
|
262
|
+
throw new Error(folderProblem);
|
|
263
|
+
const hash = createHash('sha256').update(path.resolve(home)).digest('hex').slice(0, 16);
|
|
264
|
+
const endpoint = path.join(folder, `start-${hash}.sock`);
|
|
265
|
+
if (Buffer.byteLength(endpoint) + 1 > limit)
|
|
266
|
+
throw new Error('short socket path exceeds platform limit');
|
|
267
|
+
return endpoint;
|
|
268
|
+
}
|
|
269
|
+
const hash = createHash('sha256').update(path.resolve(home)).update('\0')
|
|
270
|
+
.update(os.userInfo().username).digest('hex').slice(0, 32);
|
|
271
|
+
return `\\\\.\\pipe\\shellpuppet-start-${hash}`;
|
|
272
|
+
}
|
|
273
|
+
function listenStartLock(server, endpoint) {
|
|
274
|
+
return new Promise((resolve, reject) => {
|
|
275
|
+
const onError = (error) => {
|
|
276
|
+
if (error.code === 'EADDRINUSE')
|
|
277
|
+
resolve(false);
|
|
278
|
+
else
|
|
279
|
+
reject(error);
|
|
280
|
+
};
|
|
281
|
+
server.once('error', onError);
|
|
282
|
+
server.listen(endpoint, () => { server.off('error', onError); resolve(true); });
|
|
283
|
+
});
|
|
284
|
+
}
|
|
285
|
+
function socketRefused(endpoint) {
|
|
286
|
+
return new Promise((resolve) => {
|
|
287
|
+
const socket = net.createConnection(endpoint);
|
|
288
|
+
socket.setTimeout(500, () => { socket.destroy(); resolve(false); });
|
|
289
|
+
socket.once('connect', () => { socket.destroy(); resolve(false); });
|
|
290
|
+
socket.once('error', (error) => resolve(error.code === 'ECONNREFUSED'));
|
|
291
|
+
});
|
|
292
|
+
}
|
|
293
|
+
function startLockFailureReason(error) {
|
|
294
|
+
const code = error instanceof Error ? error.code : undefined;
|
|
295
|
+
if (typeof code === 'string' && /^[A-Z0-9_]+$/.test(code))
|
|
296
|
+
return code;
|
|
297
|
+
const message = error instanceof Error ? error.message : '';
|
|
298
|
+
if (START_FOLDER_PROBLEMS.includes(message) || message === 'user id unavailable' ||
|
|
299
|
+
message === 'short socket path exceeds platform limit')
|
|
300
|
+
return message;
|
|
301
|
+
return 'endpoint preparation failed';
|
|
302
|
+
}
|
|
303
|
+
/** The listening endpoint is the lock: the OS releases it when this client dies. */
|
|
304
|
+
async function claimStartLock(home, logger) {
|
|
305
|
+
let endpoint;
|
|
306
|
+
try {
|
|
307
|
+
endpoint = startLockEndpoint(home);
|
|
308
|
+
}
|
|
309
|
+
catch (error) {
|
|
310
|
+
logger.warn(`daemon start coordination unavailable (${startLockFailureReason(error)}); starting without it`);
|
|
311
|
+
return UNCOORDINATED_START;
|
|
312
|
+
}
|
|
313
|
+
for (let attempt = 0; attempt < 2; attempt++) {
|
|
314
|
+
const server = net.createServer((socket) => socket.destroy());
|
|
315
|
+
try {
|
|
316
|
+
if (await listenStartLock(server, endpoint))
|
|
317
|
+
return server;
|
|
318
|
+
}
|
|
319
|
+
catch (error) {
|
|
320
|
+
logger.warn(`daemon start coordination unavailable (${startLockFailureReason(error)}); starting without it`);
|
|
321
|
+
return UNCOORDINATED_START;
|
|
322
|
+
}
|
|
323
|
+
if (process.platform === 'win32' || !(await socketRefused(endpoint)))
|
|
324
|
+
return null;
|
|
325
|
+
// A POSIX socket pathname may survive a crash. Never follow or remove a
|
|
326
|
+
// symlink or a regular file at this path.
|
|
327
|
+
try {
|
|
328
|
+
const stat = fs.lstatSync(endpoint);
|
|
329
|
+
if (!stat.isSocket() || stat.uid !== process.getuid?.()) {
|
|
330
|
+
logger.warn('daemon start coordination unavailable (unsafe stale socket); starting without it');
|
|
331
|
+
return UNCOORDINATED_START;
|
|
332
|
+
}
|
|
333
|
+
fs.unlinkSync(endpoint);
|
|
334
|
+
}
|
|
335
|
+
catch (error) {
|
|
336
|
+
if (error.code !== 'ENOENT') {
|
|
337
|
+
logger.warn(`daemon start coordination unavailable (${startLockFailureReason(error)}); starting without it`);
|
|
338
|
+
return UNCOORDINATED_START;
|
|
339
|
+
}
|
|
340
|
+
}
|
|
341
|
+
}
|
|
342
|
+
logger.warn('daemon start coordination unavailable (stale socket remained); starting without it');
|
|
343
|
+
return UNCOORDINATED_START;
|
|
344
|
+
}
|
|
345
|
+
function releaseStartLock(server) {
|
|
346
|
+
return new Promise((resolve) => server.close(() => resolve()));
|
|
347
|
+
}
|
|
348
|
+
function startWaitBound(home, mode) {
|
|
349
|
+
if (mode !== undefined)
|
|
350
|
+
return mode === 'wrapped' ? WRAPPED_START_TIMEOUT_MS : AUTO_START_TIMEOUT_MS;
|
|
351
|
+
return readDaemonConfig(home).config.daemon?.startWith === undefined ? AUTO_START_TIMEOUT_MS : WRAPPED_START_TIMEOUT_MS;
|
|
352
|
+
}
|
|
353
|
+
/** Select the same start path that ensureDaemon will use for this environment. */
|
|
354
|
+
export function daemonStartMode(home, direct, env = process.env) {
|
|
355
|
+
const configured = readDaemonConfig(home).config.daemon;
|
|
356
|
+
const condition = configured?.startWithOnlyIfEnvContains;
|
|
357
|
+
return direct !== true && env['SHELLPUPPET_DAEMON_DIRECT'] !== '1' &&
|
|
358
|
+
configured?.startWith !== undefined &&
|
|
359
|
+
(condition === undefined || Object.values(env).some((value) => value?.includes(condition))) ? 'wrapped' : 'direct';
|
|
360
|
+
}
|
|
361
|
+
function callDeadline(home, logger) {
|
|
362
|
+
const arrived = Date.now();
|
|
363
|
+
const hold = readRestartHold(home, logger);
|
|
364
|
+
return arrived + (hold?.replacing === undefined ? startWaitBound(home) :
|
|
365
|
+
RESTART_STOP_TIMEOUT_MS + startWaitBound(home, hold.replacing.startMode));
|
|
366
|
+
}
|
|
367
|
+
/** Hold the start endpoint while a daemon verb stops and replaces a daemon. */
|
|
368
|
+
export async function withDaemonStartLock(options, action) {
|
|
369
|
+
const home = options.home ?? shellpuppetHome();
|
|
370
|
+
const homeResult = await ensureHome(home);
|
|
371
|
+
if (homeResult.warning !== undefined)
|
|
372
|
+
(options.logger ?? NULL_LOGGER).warn(homeResult.warning);
|
|
373
|
+
const deadline = Date.now() + startWaitBound(home);
|
|
374
|
+
let lock = null;
|
|
375
|
+
while (Date.now() < deadline) {
|
|
376
|
+
lock = await claimStartLock(home, options.logger ?? NULL_LOGGER);
|
|
377
|
+
if (lock !== null)
|
|
378
|
+
break;
|
|
379
|
+
await new Promise((resolve) => setTimeout(resolve, AUTO_START_POLL_MS));
|
|
380
|
+
}
|
|
381
|
+
if (lock === null)
|
|
382
|
+
throw new Error('A pending daemon start did not settle within its health bound.');
|
|
383
|
+
try {
|
|
384
|
+
return await action(lock);
|
|
385
|
+
}
|
|
386
|
+
finally {
|
|
387
|
+
if (lock !== UNCOORDINATED_START)
|
|
388
|
+
await releaseStartLock(lock);
|
|
389
|
+
}
|
|
390
|
+
}
|
|
391
|
+
function replacingDaemon(hold, connection) {
|
|
392
|
+
// Older daemons have no identity. Any id-less health response is still the
|
|
393
|
+
// daemon being replaced; every new daemon has an id.
|
|
394
|
+
return hold.replacing !== undefined &&
|
|
395
|
+
(connection.instanceId === undefined || connection.instanceId === hold.replacing.instanceId);
|
|
396
|
+
}
|
|
397
|
+
/** A removed or expired hold returns control to the caller's ordinary start loop. */
|
|
398
|
+
async function waitForHeldDaemon(options, home, deadline) {
|
|
399
|
+
while (Date.now() < deadline) {
|
|
400
|
+
const hold = readRestartHold(home, options.logger ?? NULL_LOGGER);
|
|
401
|
+
if (hold === null)
|
|
402
|
+
return null;
|
|
403
|
+
const existing = await discoverDaemon(options, deadline);
|
|
404
|
+
const currentHold = readRestartHold(home, options.logger ?? NULL_LOGGER);
|
|
405
|
+
if (currentHold === null)
|
|
406
|
+
return null;
|
|
407
|
+
if (existing !== null && !replacingDaemon(currentHold, existing))
|
|
408
|
+
return existing;
|
|
409
|
+
await new Promise((resolve) => setTimeout(resolve, Math.min(AUTO_START_POLL_MS, Math.max(1, deadline - Date.now()))));
|
|
410
|
+
}
|
|
411
|
+
const hold = readRestartHold(home, options.logger ?? NULL_LOGGER);
|
|
412
|
+
if (hold === null)
|
|
413
|
+
return null;
|
|
414
|
+
throw restartHoldError(hold);
|
|
415
|
+
}
|
|
416
|
+
/** Let daemon stop and restart wait for a pending start without starting one. */
|
|
417
|
+
export async function waitForPendingDaemon(options = {}) {
|
|
418
|
+
const home = options.home ?? shellpuppetHome();
|
|
419
|
+
if (!fs.existsSync(home))
|
|
420
|
+
return discoverDaemon(options);
|
|
421
|
+
const deadline = callDeadline(home, options.logger ?? NULL_LOGGER);
|
|
422
|
+
while (Date.now() < deadline) {
|
|
423
|
+
const pendingHold = readRestartHold(home, options.logger ?? NULL_LOGGER);
|
|
424
|
+
if (pendingHold !== null) {
|
|
425
|
+
const existing = await waitForHeldDaemon(options, home, deadline);
|
|
426
|
+
if (existing !== null)
|
|
427
|
+
return existing;
|
|
428
|
+
continue;
|
|
429
|
+
}
|
|
430
|
+
const lock = await claimStartLock(home, options.logger ?? NULL_LOGGER);
|
|
431
|
+
if (lock !== null) {
|
|
432
|
+
try {
|
|
433
|
+
if (readRestartHold(home, options.logger ?? NULL_LOGGER) !== null)
|
|
434
|
+
continue;
|
|
435
|
+
const existing = await discoverDaemon(options, deadline);
|
|
436
|
+
const currentHold = readRestartHold(home, options.logger ?? NULL_LOGGER);
|
|
437
|
+
if (currentHold !== null) {
|
|
438
|
+
if (existing !== null && !replacingDaemon(currentHold, existing))
|
|
439
|
+
return existing;
|
|
440
|
+
continue;
|
|
441
|
+
}
|
|
442
|
+
return existing;
|
|
443
|
+
}
|
|
444
|
+
finally {
|
|
445
|
+
if (lock !== UNCOORDINATED_START)
|
|
446
|
+
await releaseStartLock(lock);
|
|
447
|
+
}
|
|
448
|
+
}
|
|
449
|
+
await new Promise((resolve) => setTimeout(resolve, Math.min(AUTO_START_POLL_MS, Math.max(1, deadline - Date.now()))));
|
|
450
|
+
}
|
|
451
|
+
throw new Error('A pending daemon start did not settle within its health bound.');
|
|
452
|
+
}
|
|
79
453
|
function versionWarnings(daemonVersion) {
|
|
80
454
|
const own = packageVersion();
|
|
81
455
|
if (daemonVersion === own)
|
|
@@ -97,24 +471,30 @@ function versionWarnings(daemonVersion) {
|
|
|
97
471
|
* `DaemonNotAnsweringError`. Its record stays, so no second daemon starts
|
|
98
472
|
* beside it.
|
|
99
473
|
*/
|
|
100
|
-
export async function discoverDaemon(options = {}) {
|
|
474
|
+
export async function discoverDaemon(options = {}, deadline) {
|
|
101
475
|
const home = options.home ?? shellpuppetHome();
|
|
102
476
|
const state = readDaemonState(home);
|
|
103
477
|
if (state === null)
|
|
104
478
|
return null;
|
|
479
|
+
const remaining = () => deadline === undefined ? Number.POSITIVE_INFINITY : deadline - Date.now();
|
|
105
480
|
const clearedAsGone = async () => {
|
|
106
|
-
|
|
481
|
+
const left = remaining();
|
|
482
|
+
if (left <= 0 || await daemonRunning(state, Math.min(5_000, left)))
|
|
107
483
|
return false;
|
|
108
484
|
(options.logger ?? NULL_LOGGER).info('clearing stale daemon.json', { pid: state.pid });
|
|
109
485
|
removeDaemonStateIf(home, state);
|
|
110
486
|
return true;
|
|
111
487
|
};
|
|
112
|
-
|
|
488
|
+
const firstHealthTimeout = remaining();
|
|
489
|
+
let alive = firstHealthTimeout > 0 ? await health(state.port, Math.min(HEALTH_TIMEOUT_MS, firstHealthTimeout)) : null;
|
|
113
490
|
if (alive === null) {
|
|
114
491
|
if (await clearedAsGone())
|
|
115
492
|
return null;
|
|
116
493
|
for (const timeoutMs of PATIENT_HEALTH_TIMEOUTS_MS) {
|
|
117
|
-
|
|
494
|
+
const left = remaining();
|
|
495
|
+
if (left <= 0)
|
|
496
|
+
break;
|
|
497
|
+
alive = await health(state.port, Math.min(timeoutMs, left));
|
|
118
498
|
if (alive !== null)
|
|
119
499
|
break;
|
|
120
500
|
}
|
|
@@ -130,6 +510,7 @@ export async function discoverDaemon(options = {}) {
|
|
|
130
510
|
token: state.token,
|
|
131
511
|
pid: state.pid,
|
|
132
512
|
version: alive.version,
|
|
513
|
+
instanceId: alive.instanceId,
|
|
133
514
|
warnings: versionWarnings(alive.version),
|
|
134
515
|
};
|
|
135
516
|
}
|
|
@@ -139,47 +520,186 @@ export async function discoverDaemon(options = {}) {
|
|
|
139
520
|
* only: a running daemon that does not answer (`DaemonNotAnsweringError`), and
|
|
140
521
|
* a started daemon that does not become healthy within the polling cap.
|
|
141
522
|
*/
|
|
142
|
-
export async function ensureDaemon(options = {}) {
|
|
523
|
+
export async function ensureDaemon(options = {}, heldLock) {
|
|
524
|
+
const home = options.home ?? shellpuppetHome();
|
|
525
|
+
return ensureDaemonUntil(options, heldLock, callDeadline(home, options.logger ?? NULL_LOGGER));
|
|
526
|
+
}
|
|
527
|
+
async function ensureDaemonUntil(options, heldLock, waitDeadline) {
|
|
143
528
|
const logger = options.logger ?? NULL_LOGGER;
|
|
144
529
|
const home = options.home ?? shellpuppetHome();
|
|
145
|
-
const
|
|
146
|
-
if (
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
const
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
530
|
+
const directValue = process.env['SHELLPUPPET_DAEMON_DIRECT'];
|
|
531
|
+
if (directValue !== undefined && directValue !== '1' && !warnedInvalidDirect) {
|
|
532
|
+
logger.warn('ignoring invalid SHELLPUPPET_DAEMON_DIRECT; only 1 is recognised');
|
|
533
|
+
warnedInvalidDirect = true;
|
|
534
|
+
}
|
|
535
|
+
const homeResult = await ensureHome(home);
|
|
536
|
+
if (homeResult.warning !== undefined)
|
|
537
|
+
logger.warn(homeResult.warning);
|
|
538
|
+
let lock = heldLock ?? null;
|
|
539
|
+
while (heldLock === undefined && Date.now() < waitDeadline) {
|
|
540
|
+
const hold = readRestartHold(home, logger);
|
|
541
|
+
if (hold !== null) {
|
|
542
|
+
// A peer can arrive at the start of a ten-second stop, followed by a
|
|
543
|
+
// ten-second direct start or a two-minute configured startWith.
|
|
544
|
+
const replacement = await waitForHeldDaemon(options, home, waitDeadline);
|
|
545
|
+
if (replacement !== null)
|
|
546
|
+
return replacement;
|
|
547
|
+
continue;
|
|
548
|
+
}
|
|
549
|
+
const existing = await discoverDaemon(options, waitDeadline);
|
|
550
|
+
const currentHold = readRestartHold(home, logger);
|
|
551
|
+
if (currentHold !== null) {
|
|
552
|
+
if (existing !== null && !replacingDaemon(currentHold, existing))
|
|
553
|
+
return existing;
|
|
554
|
+
continue;
|
|
555
|
+
}
|
|
556
|
+
if (existing !== null)
|
|
557
|
+
return existing;
|
|
558
|
+
lock = await claimStartLock(home, logger);
|
|
559
|
+
if (lock !== null) {
|
|
560
|
+
const claimedHold = readRestartHold(home, logger);
|
|
561
|
+
if (claimedHold === null)
|
|
562
|
+
break;
|
|
563
|
+
if (lock !== UNCOORDINATED_START)
|
|
564
|
+
await releaseStartLock(lock);
|
|
565
|
+
lock = null;
|
|
566
|
+
continue;
|
|
567
|
+
}
|
|
568
|
+
await new Promise((resolve) => setTimeout(resolve, Math.min(AUTO_START_POLL_MS, Math.max(1, waitDeadline - Date.now()))));
|
|
569
|
+
}
|
|
570
|
+
if (lock === null)
|
|
571
|
+
throw new Error('A pending daemon start did not settle within its health bound.');
|
|
572
|
+
try {
|
|
573
|
+
if (heldLock === undefined) {
|
|
574
|
+
const hold = readRestartHold(home, logger);
|
|
575
|
+
if (hold !== null) {
|
|
576
|
+
// An uncoordinated holder could publish a hold after our final check.
|
|
577
|
+
// Release our endpoint before waiting so an explicit start can use it.
|
|
578
|
+
if (lock !== UNCOORDINATED_START)
|
|
579
|
+
await releaseStartLock(lock);
|
|
580
|
+
lock = UNCOORDINATED_START;
|
|
581
|
+
const replacement = await waitForHeldDaemon(options, home, waitDeadline);
|
|
582
|
+
if (replacement !== null)
|
|
583
|
+
return replacement;
|
|
584
|
+
return ensureDaemonUntil(options, undefined, waitDeadline);
|
|
172
585
|
}
|
|
173
586
|
}
|
|
174
|
-
|
|
587
|
+
const wonWhileClaiming = await discoverDaemon(options, waitDeadline);
|
|
588
|
+
if (wonWhileClaiming !== null)
|
|
589
|
+
return wonWhileClaiming;
|
|
590
|
+
if (heldLock === undefined && Date.now() >= waitDeadline) {
|
|
591
|
+
throw new Error('A pending daemon start did not settle within its health bound.');
|
|
592
|
+
}
|
|
593
|
+
const entry = options.daemonEntry ?? defaultDaemonEntry();
|
|
594
|
+
const cwd = daemonWorkingDirectory();
|
|
595
|
+
const env = { ...process.env, SHELLPUPPET_HOME: home };
|
|
596
|
+
const parsed = readDaemonConfig(home);
|
|
597
|
+
for (const problem of parsed.problems) {
|
|
598
|
+
if ((problem.startsWith('daemon.') || problem.startsWith('daemon must') || problem.startsWith('daemon has')) &&
|
|
599
|
+
!reportedStartConfigProblems.has(problem)) {
|
|
600
|
+
logger.warn(problem);
|
|
601
|
+
reportedStartConfigProblems.add(problem);
|
|
602
|
+
}
|
|
603
|
+
}
|
|
604
|
+
const configured = parsed.config.daemon;
|
|
605
|
+
const wrapped = daemonStartMode(home, options.direct, env) === 'wrapped';
|
|
606
|
+
const wrapper = wrapped ? configured?.startWith : undefined;
|
|
607
|
+
const program = wrapper?.[0];
|
|
608
|
+
const programName = program === undefined ? undefined : path.basename(program);
|
|
609
|
+
let command = process.execPath;
|
|
610
|
+
let args = [entry];
|
|
611
|
+
if (program !== undefined) {
|
|
612
|
+
try {
|
|
613
|
+
({ command, args } = planDaemonStart(wrapper ?? [], entry, cwd ?? process.cwd(), env));
|
|
614
|
+
}
|
|
615
|
+
catch (error) {
|
|
616
|
+
const raced = await discoverDaemon(options, waitDeadline);
|
|
617
|
+
if (raced !== null)
|
|
618
|
+
return raced;
|
|
619
|
+
throw error;
|
|
620
|
+
}
|
|
621
|
+
}
|
|
622
|
+
env['SHELLPUPPET_DAEMON_STARTED_WRAPPED'] = wrapped ? '1' : '0';
|
|
623
|
+
logger.info('auto-starting daemon', { wrapped });
|
|
624
|
+
let startError = false;
|
|
625
|
+
let childExitAt = null;
|
|
626
|
+
let child;
|
|
627
|
+
try {
|
|
628
|
+
child = spawn(command, args, {
|
|
629
|
+
detached: true,
|
|
630
|
+
stdio: 'ignore', // MUST be 'ignore': inherited handles hang the caller (§2.2)
|
|
631
|
+
windowsHide: true,
|
|
632
|
+
shell: false,
|
|
633
|
+
env,
|
|
634
|
+
...(cwd !== undefined ? { cwd } : {}),
|
|
635
|
+
});
|
|
636
|
+
}
|
|
637
|
+
catch {
|
|
638
|
+
if (programName !== undefined) {
|
|
639
|
+
throw new Error(`daemon.startWith program ${programName} could not be started.`);
|
|
640
|
+
}
|
|
641
|
+
throw new Error('The ShellPuppet daemon process could not be started.');
|
|
642
|
+
}
|
|
643
|
+
// A process that cannot start reports it as an 'error' event, which with no
|
|
644
|
+
// listener would end this client. The poll below reports the failure.
|
|
645
|
+
child.on('error', (error) => {
|
|
646
|
+
startError = true;
|
|
647
|
+
childExitAt = Date.now();
|
|
648
|
+
logger.warn(programName === undefined ? 'the daemon process did not start' :
|
|
649
|
+
`daemon.startWith program ${programName} did not start`, { code: error.code });
|
|
650
|
+
});
|
|
651
|
+
child.on('exit', () => { childExitAt = Date.now(); });
|
|
652
|
+
child.unref();
|
|
653
|
+
// A healthy /health response is success regardless of what happened to the
|
|
654
|
+
// child we spawned (§2.2). Only the poll timing out is failure.
|
|
655
|
+
const timeoutMs = wrapped ? (options.wrappedStartTimeoutMs ?? WRAPPED_START_TIMEOUT_MS) : AUTO_START_TIMEOUT_MS;
|
|
656
|
+
const deadline = heldLock === undefined ? Math.min(Date.now() + timeoutMs, waitDeadline) : Date.now() + timeoutMs;
|
|
657
|
+
while (Date.now() < deadline) {
|
|
658
|
+
const state = readDaemonState(home);
|
|
659
|
+
if (state !== null) {
|
|
660
|
+
const alive = await health(state.port, Math.min(HEALTH_TIMEOUT_MS, Math.max(1, deadline - Date.now())));
|
|
661
|
+
if (alive !== null) {
|
|
662
|
+
return {
|
|
663
|
+
port: state.port,
|
|
664
|
+
token: state.token,
|
|
665
|
+
pid: state.pid,
|
|
666
|
+
version: alive.version,
|
|
667
|
+
instanceId: alive.instanceId,
|
|
668
|
+
warnings: versionWarnings(alive.version),
|
|
669
|
+
};
|
|
670
|
+
}
|
|
671
|
+
}
|
|
672
|
+
if (wrapped && childExitAt !== null && Date.now() - childExitAt >= EARLY_WRAPPER_EXIT_GRACE_MS)
|
|
673
|
+
break;
|
|
674
|
+
await new Promise((resolve) => setTimeout(resolve, Math.min(AUTO_START_POLL_MS, Math.max(1, deadline - Date.now()))));
|
|
675
|
+
}
|
|
676
|
+
if (heldLock === undefined && Date.now() >= waitDeadline) {
|
|
677
|
+
// Keep the start endpoint until a live wrapper has been ended or its
|
|
678
|
+
// cleanup bound passes. A peer cannot start a second wrapper meanwhile.
|
|
679
|
+
if (wrapped)
|
|
680
|
+
await endSpawnedWrapper(child, logger);
|
|
681
|
+
else if (child.exitCode === null && child.signalCode === null)
|
|
682
|
+
child.kill('SIGKILL');
|
|
683
|
+
throw new Error('A pending daemon start did not settle within its health bound.');
|
|
684
|
+
}
|
|
685
|
+
if (programName !== undefined) {
|
|
686
|
+
await endSpawnedWrapper(child, logger);
|
|
687
|
+
throw new Error(`daemon.startWith program ${programName} ${startError ? 'could not be started' :
|
|
688
|
+
childExitAt !== null && Date.now() < deadline ? 'exited before the daemon became healthy' :
|
|
689
|
+
`did not produce a healthy daemon within ${String(timeoutMs / 1_000)} s`}. Check daemon.log.`);
|
|
690
|
+
}
|
|
691
|
+
throw new Error(`The ShellPuppet daemon did not become healthy within ${String(timeoutMs / 1_000)} s. Check ${home}/daemon.log.`);
|
|
692
|
+
}
|
|
693
|
+
finally {
|
|
694
|
+
if (heldLock === undefined && lock !== UNCOORDINATED_START)
|
|
695
|
+
await releaseStartLock(lock);
|
|
175
696
|
}
|
|
176
|
-
throw new Error(`The ShellPuppet daemon did not become healthy within ` +
|
|
177
|
-
`${String(AUTO_START_TIMEOUT_MS / 1_000)} s. Check ${home}/daemon.log.`);
|
|
178
697
|
}
|
|
179
698
|
/**
|
|
180
699
|
* One authenticated JSON request. If the daemon has gone since discovery
|
|
181
700
|
* (stale state), re-ensure once and retry, because one-shot clients meet this
|
|
182
|
-
* whenever the daemon idle-stopped moments earlier
|
|
701
|
+
* whenever the daemon idle-stopped moments earlier; with `autoStart: false`,
|
|
702
|
+
* throw `DaemonGoneError` instead.
|
|
183
703
|
*
|
|
184
704
|
* A request that fails while its daemon is still running is reported, never
|
|
185
705
|
* retried against another daemon. The caller holds session ids from this
|
|
@@ -214,6 +734,9 @@ export async function request(connection, method, path, body, options = {}) {
|
|
|
214
734
|
`it is not, restart this client, first deleting ${statePath} if it still names pid ` +
|
|
215
735
|
`${pid}.`, { cause: error });
|
|
216
736
|
}
|
|
737
|
+
if (options.autoStart === false) {
|
|
738
|
+
throw new DaemonGoneError(connection.pid, connection.port, { cause: error });
|
|
739
|
+
}
|
|
217
740
|
const fresh = await ensureDaemon(options);
|
|
218
741
|
connection.port = fresh.port;
|
|
219
742
|
connection.token = fresh.token;
|