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.
Files changed (101) hide show
  1. package/README.md +210 -33
  2. package/dist/cli/desktopShortcut.d.ts +22 -0
  3. package/dist/cli/desktopShortcut.js +157 -0
  4. package/dist/cli/desktopShortcut.js.map +1 -0
  5. package/dist/cli/index.js +268 -59
  6. package/dist/cli/index.js.map +1 -1
  7. package/dist/client/http.d.ts +74 -3
  8. package/dist/client/http.js +560 -37
  9. package/dist/client/http.js.map +1 -1
  10. package/dist/core/dialogs.d.ts +20 -12
  11. package/dist/core/dialogs.js +31 -19
  12. package/dist/core/dialogs.js.map +1 -1
  13. package/dist/core/manager.d.ts +35 -5
  14. package/dist/core/manager.js +121 -8
  15. package/dist/core/manager.js.map +1 -1
  16. package/dist/core/nativePty.d.ts +9 -5
  17. package/dist/core/nativePty.js +11 -6
  18. package/dist/core/nativePty.js.map +1 -1
  19. package/dist/core/promptDetector.d.ts +37 -3
  20. package/dist/core/promptDetector.js +303 -12
  21. package/dist/core/promptDetector.js.map +1 -1
  22. package/dist/core/reasoning.d.ts +19 -6
  23. package/dist/core/reasoning.js +223 -30
  24. package/dist/core/reasoning.js.map +1 -1
  25. package/dist/core/regexBudget.d.ts +20 -0
  26. package/dist/core/regexBudget.js +25 -1
  27. package/dist/core/regexBudget.js.map +1 -1
  28. package/dist/core/renderer.d.ts +16 -1
  29. package/dist/core/renderer.js +97 -6
  30. package/dist/core/renderer.js.map +1 -1
  31. package/dist/core/selection.d.ts +6 -0
  32. package/dist/core/selection.js +48 -0
  33. package/dist/core/selection.js.map +1 -0
  34. package/dist/core/session.d.ts +267 -13
  35. package/dist/core/session.js +585 -101
  36. package/dist/core/session.js.map +1 -1
  37. package/dist/core/types.d.ts +53 -18
  38. package/dist/core/types.js +30 -6
  39. package/dist/core/types.js.map +1 -1
  40. package/dist/core/waiter.d.ts +12 -4
  41. package/dist/core/waiter.js +63 -70
  42. package/dist/core/waiter.js.map +1 -1
  43. package/dist/core/windowsConsoleHost.d.ts +147 -0
  44. package/dist/core/windowsConsoleHost.js +588 -0
  45. package/dist/core/windowsConsoleHost.js.map +1 -0
  46. package/dist/core/windowsPtyStart.d.ts +100 -29
  47. package/dist/core/windowsPtyStart.js +143 -36
  48. package/dist/core/windowsPtyStart.js.map +1 -1
  49. package/dist/daemon/auth.d.ts +72 -2
  50. package/dist/daemon/auth.js +128 -3
  51. package/dist/daemon/auth.js.map +1 -1
  52. package/dist/daemon/config.d.ts +44 -1
  53. package/dist/daemon/config.js +276 -9
  54. package/dist/daemon/config.js.map +1 -1
  55. package/dist/daemon/folderPicker.d.ts +27 -0
  56. package/dist/daemon/folderPicker.js +115 -0
  57. package/dist/daemon/folderPicker.js.map +1 -0
  58. package/dist/daemon/index.js +20 -19
  59. package/dist/daemon/index.js.map +1 -1
  60. package/dist/daemon/launchProfiles.d.ts +155 -0
  61. package/dist/daemon/launchProfiles.js +554 -0
  62. package/dist/daemon/launchProfiles.js.map +1 -0
  63. package/dist/daemon/liveness.d.ts +1 -1
  64. package/dist/daemon/liveness.js +2 -2
  65. package/dist/daemon/liveness.js.map +1 -1
  66. package/dist/daemon/paths.d.ts +4 -0
  67. package/dist/daemon/paths.js.map +1 -1
  68. package/dist/daemon/restartHold.d.ts +16 -0
  69. package/dist/daemon/restartHold.js +126 -0
  70. package/dist/daemon/restartHold.js.map +1 -0
  71. package/dist/daemon/screenshot.d.ts +58 -1
  72. package/dist/daemon/screenshot.js +172 -26
  73. package/dist/daemon/screenshot.js.map +1 -1
  74. package/dist/daemon/server.d.ts +220 -10
  75. package/dist/daemon/server.js +1975 -205
  76. package/dist/daemon/server.js.map +1 -1
  77. package/dist/daemon/sessionFeed.d.ts +48 -0
  78. package/dist/daemon/sessionFeed.js +101 -0
  79. package/dist/daemon/sessionFeed.js.map +1 -0
  80. package/dist/daemon/viewerLauncher.d.ts +100 -9
  81. package/dist/daemon/viewerLauncher.js +349 -67
  82. package/dist/daemon/viewerLauncher.js.map +1 -1
  83. package/dist/mcp/config.d.ts +7 -14
  84. package/dist/mcp/config.js +10 -21
  85. package/dist/mcp/config.js.map +1 -1
  86. package/dist/mcp/index.js +20 -11
  87. package/dist/mcp/index.js.map +1 -1
  88. package/dist/mcp/tools.d.ts +14 -7
  89. package/dist/mcp/tools.js +161 -60
  90. package/dist/mcp/tools.js.map +1 -1
  91. package/dist/viewer/dashboard-folders.js +20 -0
  92. package/dist/viewer/dashboard-layout.js +52 -0
  93. package/dist/viewer/dashboard.css +67 -0
  94. package/dist/viewer/dashboard.html +44 -0
  95. package/dist/viewer/dashboard.js +1523 -0
  96. package/dist/viewer/icon.ico +0 -0
  97. package/dist/viewer/index.html +12 -7
  98. package/dist/viewer/pane.js +736 -0
  99. package/dist/viewer/viewer.css +18 -7
  100. package/dist/viewer/viewer.js +47 -624
  101. package/package.json +13 -13
package/dist/cli/index.js CHANGED
@@ -13,15 +13,18 @@
13
13
  import { writeFile } from 'node:fs/promises';
14
14
  import { resolve } from 'node:path';
15
15
  import process from 'node:process';
16
- import { discoverDaemon, ensureDaemon, request } from '../client/http.js';
16
+ import { DaemonGoneError, daemonStartMode, discoverDaemon, ensureDaemon, request, waitForPendingDaemon, withDaemonStartLock } from '../client/http.js';
17
17
  import { assertNodeVersion, packageVersion } from '../daemon/meta.js';
18
18
  import { NO_MATCHES } from '../core/find.js';
19
19
  import { resultRefusal } from '../core/reasoning.js';
20
- import { shellpuppetHome } from '../daemon/paths.js';
21
- import { readMcpConfig, planPassedEnv } from '../mcp/config.js';
22
- import { readDaemonConfig } from '../daemon/config.js';
20
+ import { inspectDaemonState, readDaemonState, shellpuppetHome } from '../daemon/paths.js';
21
+ import { clearRestartHold, readRestartHold, writeRestartHold } from '../daemon/restartHold.js';
22
+ import { planPassedEnv } from '../mcp/config.js';
23
+ import { isEnvNamesProblem, readDaemonConfig } from '../daemon/config.js';
23
24
  import { agentNameFor } from '../core/reasoning.js';
24
25
  import { knownKeys } from '../core/keys.js';
26
+ import { listedState } from '../core/types.js';
27
+ import { installDesktopShortcut, uninstallDesktopShortcut, userShortcutOptions } from './desktopShortcut.js';
25
28
  const USAGE = `ShellPuppet: drive a real terminal session; humans watch and type via the viewer.
26
29
 
27
30
  Usage:
@@ -29,33 +32,45 @@ Usage:
29
32
  --label <s> --purpose <s> --cols <n> --rows <n> --cwd <dir>
30
33
  --ready-text <s> --ready-quiet <ms> --no-shell --hold --agent <name>
31
34
  --env-name <NAME> (repeatable) --no-viewer
32
- --no-viewer opens no viewer window, for a short scripted session nobody
35
+ --no-viewer opens no dashboard or viewer window, for a short scripted session nobody
33
36
  needs to watch; viewer-url still gives a link to it.
37
+ --cwd sets the folder the session starts in; it defaults to THIS shell's
38
+ working directory, and a relative --cwd is taken from there.
34
39
  A session that runs as an agent CLI receives, from THIS shell's
35
40
  environment, the variables listed for that agent in agents.passEnv in
36
41
  config.json, with no flag. --env-name copies another variable, for a
37
- program that is not an agent CLI: only names listed in mcp.passEnv
38
- pass, and any other name refuses the start. Values are never printed
39
- or logged.
40
- --agent names the agent CLI the session runs (claude, codex, qoder...)
42
+ program that is not an agent CLI: only names listed in envNames in
43
+ config.json pass, and any other name refuses the start. Values are
44
+ never printed or logged.
45
+ --agent names the agent CLI the session runs (claude, codex, muse, qoder...)
41
46
  when it is reached through a shell or a launcher script, so that
42
47
  --hide-reasoning and result can read its screen.
43
48
  --cols/--rows say where to START; the human's viewer reshapes the grid to
44
49
  its window unless --hold keeps it, which is for runs you compare against
45
50
  a known width.
46
51
  --purpose says what the session is FOR; it titles the viewer window.
52
+ --no-shell starts the command without a shell; on Windows it must then
53
+ be an .exe or .com, so start a script through the shell. A command with
54
+ a path separator is resolved from the session's working directory, and
55
+ a file name containing ':' is refused as an alternate data stream.
56
+ On Windows, the default uses cmd.exe /d /s /c. Arguments are joined as
57
+ shell text: quote spaces for cmd.exe, for example pass the one argument
58
+ 'mcp_servers.x.command="C:/Program Files/nodejs/node.exe"' from Git Bash.
59
+ cmd.exe also expands %NAME% and interprets ^ & | < >. Use --no-shell
60
+ with an .exe or .com when each argument must arrive literally.
47
61
  Options go BEFORE the command; everything after the command is passed
48
- to it verbatim (so its own --flags survive).
49
- shellpuppet list List sessions
62
+ to the daemon unchanged (so its own --flags survive).
63
+ shellpuppet list [--waiting] [--hide-reasoning] List sessions, or only waiting prompts
50
64
  shellpuppet snap <id> [--last <n>] [--hide-reasoning]
51
65
  Print the rendered screen
52
66
  --hide-reasoning leaves out an agent CLI's reasoning, each block as one
53
67
  "[reasoning hidden: N lines]" line; a session whose agent has no
54
68
  signature is refused (exit 2), never printed unfiltered.
55
- shellpuppet result <id> Print the agent's latest answer
69
+ shellpuppet result <id> [--hide-reasoning] Print the agent's latest answer
56
70
  The answer that ends the latest turn, and its turn summary: never its
57
- reasoning. Exits 3, with the reason on stderr, while the agent is
58
- still working or when no answer is recognised.
71
+ reasoning. --hide-reasoning is accepted but changes nothing: result
72
+ always leaves reasoning out. Exits 3, with the reason on stderr, while
73
+ the agent is still working or when no answer is recognised.
59
74
  shellpuppet type <id> <text> [--enter] [--verify] Type text (--verify re-reads the screen,
60
75
  for up to 15 s on long text)
61
76
  shellpuppet key <id> <name> Press a key (enter, escape, ctrl+c, f1…)
@@ -68,13 +83,21 @@ Usage:
68
83
  seen to go; --match-after-input false accepts any prompt)
69
84
  --match-after-input true ignores text/regex matches at or
70
85
  before the echo of what you last typed
86
+ --debounce waits for the condition to hold on every poll
87
+ for this many ms; a missed poll restarts it, while other
88
+ output such as a ticking timer does not; a match on the
89
+ final screen settles at once if the program exits
90
+ shellpuppet wait --prompt [id ...] [--now] [--timeout <ms>] [--hide-reasoning]
91
+ Wait for any listed session's prompt,
92
+ or every live session if no ids are given;
93
+ --now polls once without waiting
71
94
  shellpuppet find <id> <pattern> [--hide-reasoning]
72
95
  Regex-search the screen, with line numbers
73
96
  Prints each matching line as <row>: <text>. Nothing matching prints
74
97
  "No matches." on stderr, never the pattern, and exits 3 (with --json
75
98
  too, after printing the empty result).
76
- shellpuppet screenshot <id> [--out <f>] [--width <n>] [--height <n>]
77
- [--timeout <ms>]
99
+ shellpuppet screenshot <id> [--out <f>] [--hide-reasoning]
100
+ [--width <n>] [--height <n>] [--timeout <ms>]
78
101
  Photograph the viewer as a browser draws it
79
102
  Defaults to shellpuppet-<id>.png at 1400x900, with 45 s for the whole
80
103
  capture (--timeout, 1000 to 120000, for a slow or a hurried machine).
@@ -84,12 +107,21 @@ Usage:
84
107
  Links work once and expire after a few minutes; mint another whenever
85
108
  the human needs one. --read-only grants watching without typing, and the
86
109
  daemon enforces it rather than the page.
110
+ shellpuppet dashboard Open the dashboard in its own window
111
+ One window for every session, in ShellPuppet's isolated browser profile.
112
+ Prints whether a window opened, never the link.
113
+ shellpuppet desktop [--install|--uninstall] Start ShellPuppet and open its dashboard
114
+ Reuses a connected dashboard. --install adds or updates a per-user shortcut;
115
+ --uninstall removes that shortcut. Neither option starts the daemon.
87
116
  shellpuppet resize <id> <cols> <rows> [--hold] Set screen geometry
88
117
  Without --hold the human's window reshapes it again the moment they
89
118
  move it, which is what lets the viewer fill.
90
119
  shellpuppet kill <id> Kill the session and its process tree
91
120
  shellpuppet daemon status|start|stop|restart Manage the shared daemon
92
- stop/restart: --force to kill live sessions
121
+ start/restart: --direct starts without daemon.startWith.
122
+ stop/restart: --force to kill live sessions. status and stop never
123
+ start a daemon: one that has gone is reported as not running.
124
+ stop: --hold [seconds] prevents auto-start for 120 s by default (1 to 600).
93
125
  shellpuppet mcp Run the MCP stdio server (long-running)
94
126
  shellpuppet --version | --help
95
127
 
@@ -153,6 +185,9 @@ function parseArgs(argv, stopAtFirstPositional = false) {
153
185
  fail(2, `--${name} needs a value.`);
154
186
  lists.set(name, [...(lists.get(name) ?? []), value]);
155
187
  }
188
+ else if (name === 'hold' && argv[0] === 'stop' && argv[i + 1] !== undefined && !argv[i + 1]?.startsWith('--')) {
189
+ flags.set(name, argv[++i] ?? '');
190
+ }
156
191
  else if (VALUE_FLAGS.has(name)) {
157
192
  const value = argv[++i];
158
193
  if (value === undefined)
@@ -188,10 +223,11 @@ function surfaceWarnings(connection) {
188
223
  for (const warning of connection.warnings)
189
224
  console.error(`warning: ${warning}`);
190
225
  }
191
- async function call(connection, method, path, body) {
226
+ async function call(connection, method, path, body, options = {}) {
192
227
  const response = await request(connection, method, path, body, {
193
228
  logger: stderrLogger,
194
229
  actor: 'cli',
230
+ ...options,
195
231
  });
196
232
  const payload = response.body;
197
233
  if (response.status >= 400) {
@@ -242,6 +278,15 @@ async function main() {
242
278
  await daemonVerb(parsed, wantJson);
243
279
  process.exit(0);
244
280
  }
281
+ if (verb === 'desktop' && (parsed.flags.has('install') || parsed.flags.has('uninstall'))) {
282
+ if (parsed.flags.has('install') && parsed.flags.has('uninstall'))
283
+ fail(2, 'Choose --install or --uninstall.');
284
+ if (parsed.positionals.length > 0)
285
+ fail(2, 'desktop takes no positional arguments.');
286
+ const options = userShortcutOptions();
287
+ console.log(parsed.flags.has('install') ? installDesktopShortcut(options) : uninstallDesktopShortcut(options));
288
+ process.exit(0);
289
+ }
245
290
  const connection = await ensureDaemon({ logger: stderrLogger });
246
291
  surfaceWarnings(connection);
247
292
  switch (verb) {
@@ -257,7 +302,9 @@ async function main() {
257
302
  ...(parsed.flags.has('agent') ? { agent: String(parsed.flags.get('agent')) } : {}),
258
303
  ...(intFlag(parsed, 'cols') !== undefined ? { cols: intFlag(parsed, 'cols') } : {}),
259
304
  ...(intFlag(parsed, 'rows') !== undefined ? { rows: intFlag(parsed, 'rows') } : {}),
260
- ...(parsed.flags.has('cwd') ? { cwd: String(parsed.flags.get('cwd')) } : {}),
305
+ // This shell's working directory, or --cwd taken from it: the daemon
306
+ // runs elsewhere, so a folder is always sent, and always absolute.
307
+ cwd: resolve(parsed.flags.has('cwd') ? String(parsed.flags.get('cwd')) : '.'),
261
308
  ...(parsed.flags.has('ready-text')
262
309
  ? { readyText: String(parsed.flags.get('ready-text')) }
263
310
  : {}),
@@ -270,14 +317,18 @@ async function main() {
270
317
  };
271
318
  // The same lists and the same rules as terminal_start. The CLI reads
272
319
  // config.json on every run, so a change to a list needs no restart here.
273
- const agentsConfig = readDaemonConfig(shellpuppetHome());
274
- const agent = agentNameFor(parsed.flags.has('agent') ? String(parsed.flags.get('agent')) : undefined, command, agentsConfig.config.agentSignatures ?? []);
320
+ const daemonConfig = readDaemonConfig(shellpuppetHome());
321
+ const agent = agentNameFor(parsed.flags.has('agent') ? String(parsed.flags.get('agent')) : undefined, command, daemonConfig.config.agentSignatures ?? []);
275
322
  const envNames = parsed.lists.get('env-name') ?? [];
323
+ if (envNames.length > 0) {
324
+ for (const problem of daemonConfig.problems.filter(isEnvNamesProblem))
325
+ console.error(`warning: ${problem}`);
326
+ }
276
327
  const plan = planPassedEnv({
277
328
  agent,
278
329
  requested: envNames,
279
- agentLists: agentsConfig.config.agentPassEnv ?? {},
280
- adHoc: envNames.length > 0 ? readMcpConfig(shellpuppetHome(), stderrLogger).passEnv : [],
330
+ agentLists: daemonConfig.config.agentPassEnv ?? {},
331
+ adHoc: daemonConfig.config.envNames ?? [],
281
332
  environment: process.env,
282
333
  source: "this shell's environment",
283
334
  });
@@ -290,13 +341,13 @@ async function main() {
290
341
  }
291
342
  if (plan.refused.length > 0) {
292
343
  const names = plan.refused;
293
- fail(2, `Not started: ${names.join(', ')} ${names.length === 1 ? 'is' : 'are'} not in ` +
294
- `mcp.passEnv, the list of variables you allow to be passed into a session. Add ` +
295
- `${names.length === 1 ? 'it' : 'them'} to ~/.shellpuppet/config.json, or start ` +
296
- `without ${names.length === 1 ? 'it' : 'them'}.`);
344
+ fail(2, `Not started: ${names.join(', ')} ${names.length === 1 ? 'is' : 'are'} not listed in ` +
345
+ `envNames in ~/.shellpuppet/config.json, the variables you allow to be passed into a ` +
346
+ `session. Add ${names.length === 1 ? 'it' : 'them'} to that list, or start without ` +
347
+ `${names.length === 1 ? 'it' : 'them'}.`);
297
348
  }
298
349
  if (agent !== null) {
299
- for (const problem of agentsConfig.problems.filter((p) => p.startsWith('agents'))) {
350
+ for (const problem of daemonConfig.problems.filter((p) => p.startsWith('agents'))) {
300
351
  console.error(`warning: ${problem}`);
301
352
  }
302
353
  }
@@ -310,15 +361,25 @@ async function main() {
310
361
  else {
311
362
  console.log(`${String(result['id'])} ${String(result['label'])}`);
312
363
  const viewer = result['viewer'];
313
- if (viewer?.opened === true) {
364
+ if (viewer?.mode === 'dashboard' && viewer.opened === true) {
365
+ console.log('viewer: opened in the dashboard');
366
+ }
367
+ else if (viewer?.mode === 'dashboard' && viewer.reason === 'a dashboard is connected') {
368
+ console.log('viewer: session is in the connected dashboard');
369
+ }
370
+ else if (viewer?.mode === 'dashboard' && viewer.reason === 'a dashboard window is opening') {
371
+ console.log(`viewer: dashboard window launch is in progress (if it does not show the session, run shellpuppet viewer-url ${String(result['id'])} for a link)`);
372
+ }
373
+ else if (viewer?.opened === true) {
314
374
  const how = viewer.reason !== undefined ? `, ${viewer.reason}` : '';
315
375
  console.log(`viewer: window opened${how} (viewer-url ${String(result['id'])} mints a link)`);
316
376
  }
317
377
  else if (typeof result['viewerUrl'] === 'string') {
318
- console.log(`viewer: ${result['viewerUrl']}`);
378
+ const why = viewer?.reason !== undefined ? ` (${viewer.reason})` : '';
379
+ console.log(`viewer: no window opened${why}; link: ${result['viewerUrl']}`);
319
380
  }
320
381
  else {
321
- console.log(`viewer: none opened (--no-viewer); viewer-url ${String(result['id'])} mints a link`);
382
+ console.log(`viewer: no window opened (--no-viewer); viewer-url ${String(result['id'])} mints a link`);
322
383
  }
323
384
  if (result['ready'] !== true) {
324
385
  console.log('ready: false. First paint is not readiness; wait before typing.');
@@ -327,7 +388,12 @@ async function main() {
327
388
  break;
328
389
  }
329
390
  case 'list': {
330
- const result = await call(connection, 'GET', '/sessions');
391
+ const query = new URLSearchParams();
392
+ if (parsed.flags.get('hide-reasoning') === true)
393
+ query.set('hideReasoning', '1');
394
+ if (parsed.flags.get('waiting') === true)
395
+ query.set('waitingOnly', '1');
396
+ const result = await call(connection, 'GET', `/sessions${query.size > 0 ? `?${query.toString()}` : ''}`);
331
397
  if (wantJson) {
332
398
  printJson(result);
333
399
  break;
@@ -338,14 +404,23 @@ async function main() {
338
404
  break;
339
405
  }
340
406
  for (const s of sessions) {
341
- console.log(`${s.id} ${s.exited ? `exited(${String(s.exitCode)})` : 'live'} ` +
407
+ if (parsed.flags.get('waiting') === true) {
408
+ const waiting = s;
409
+ console.log(`${waiting.id} ${waiting.label} WAITING ${String(Math.round(waiting.waitingMs / 1000))}s` + (waiting.question === undefined ? '' : `: ${waiting.question}`));
410
+ for (const [index, option] of (waiting.options ?? []).entries())
411
+ console.log(` ${index === waiting.selectedOption ? '* ' : ' '}${option}`);
412
+ continue;
413
+ }
414
+ console.log(`${s.id} ${listedState(s)} ` +
342
415
  `${String(s.cols)}x${String(s.rows)} watchers:${String(s.watchers)} ` +
343
416
  `${s.ready ? 'ready' : 'NOT-READY'} ${s.label}` +
344
417
  (s.agent !== null && s.agent !== undefined ? ` agent:${s.agent}` : ''));
345
418
  const waiting = s.waitingOnPrompt;
346
419
  if (waiting !== undefined) {
347
- console.log(` WAITING ${String(Math.round(waiting.waitingMs / 1000))}s on a prompt: ` +
348
- waiting.question);
420
+ console.log(` WAITING ${String(Math.round(waiting.waitingMs / 1000))}s on a prompt` +
421
+ (waiting.question === undefined ? '' : `: ${waiting.question}`));
422
+ if (waiting.selectedOption !== undefined)
423
+ console.log(` selectedOption: ${String(waiting.selectedOption)} (zero-based)`);
349
424
  }
350
425
  }
351
426
  break;
@@ -427,6 +502,32 @@ async function main() {
427
502
  break;
428
503
  }
429
504
  case 'wait': {
505
+ const multi = parsed.flags.get('prompt') === true && (parsed.positionals.length !== 1 || parsed.flags.get('now') === true);
506
+ if (multi) {
507
+ const params = new URLSearchParams({ prompt: 'true' });
508
+ for (const id of parsed.positionals)
509
+ params.append('session', id);
510
+ if (parsed.flags.get('now') === true)
511
+ params.set('now', 'true');
512
+ if (parsed.flags.has('timeout'))
513
+ params.set('timeout', String(parsed.flags.get('timeout')));
514
+ if (parsed.flags.get('hide-reasoning') === true)
515
+ params.set('hideReasoning', '1');
516
+ const result = await call(connection, 'GET', `/sessions/wait?${params.toString()}`);
517
+ if (wantJson)
518
+ printJson(result);
519
+ else {
520
+ for (const waiting of result['sessions']) {
521
+ console.log(`${waiting.id} ${waiting.label} WAITING ${String(Math.round(waiting.waitingMs / 1000))}s` + (waiting.question === undefined ? '' : `: ${waiting.question}`));
522
+ for (const [index, option] of (waiting.options ?? []).entries())
523
+ console.log(` ${index === waiting.selectedOption ? '* ' : ' '}${option}`);
524
+ }
525
+ console.error(`${result['matched'] === true ? 'matched' : 'NOT matched'} (${String(result['reason'])}, ${String(result['waitedMs'])} ms)`);
526
+ }
527
+ if (result['matched'] !== true && parsed.flags.get('now') !== true)
528
+ process.exit(3);
529
+ break;
530
+ }
430
531
  const id = parsed.positionals[0] ?? fail(2, 'wait needs a session id.');
431
532
  const params = new URLSearchParams();
432
533
  for (const name of ['text', 'regex', 'quiet', 'timeout', 'debounce', 'prompt']) {
@@ -461,6 +562,8 @@ async function main() {
461
562
  // program's, not ours.
462
563
  for (const option of detected.options)
463
564
  console.error(` ${option}`);
565
+ if (detected.selectedOption !== undefined)
566
+ console.error(`selectedOption: ${String(detected.selectedOption)} (zero-based)`);
464
567
  }
465
568
  console.log(String(result['screen']));
466
569
  }
@@ -501,6 +604,7 @@ async function main() {
501
604
  ...(intFlag(parsed, 'timeout') !== undefined
502
605
  ? { timeoutMs: intFlag(parsed, 'timeout') }
503
606
  : {}),
607
+ ...(parsed.flags.get('hide-reasoning') === true ? { hideReasoning: true } : {}),
504
608
  });
505
609
  const png = Buffer.from(String(result['png']), 'base64');
506
610
  await writeFile(out, png);
@@ -514,6 +618,26 @@ async function main() {
514
618
  }
515
619
  break;
516
620
  }
621
+ case 'dashboard': {
622
+ const result = await call(connection, 'POST', '/dashboard/open', {});
623
+ if (wantJson)
624
+ printJson(result);
625
+ else
626
+ console.log('dashboard: window opened');
627
+ break;
628
+ }
629
+ case 'desktop': {
630
+ if (parsed.positionals.length > 0)
631
+ fail(2, 'desktop takes no positional arguments.');
632
+ const result = await call(connection, 'POST', '/desktop/open', {});
633
+ if (wantJson)
634
+ printJson(result);
635
+ else
636
+ console.log(result['alreadyOpen'] === true
637
+ ? 'ShellPuppet is already open. If you cannot see it, run shellpuppet dashboard.'
638
+ : 'ShellPuppet desktop: window opened');
639
+ break;
640
+ }
517
641
  case 'viewer-url': {
518
642
  const id = parsed.positionals[0] ?? fail(2, 'viewer-url needs a session id.');
519
643
  const readOnly = parsed.flags.get('read-only') === true;
@@ -566,11 +690,35 @@ async function main() {
566
690
  async function daemonVerb(parsed, wantJson) {
567
691
  const sub = parsed.positionals[0];
568
692
  const force = parsed.flags.get('force') === true;
693
+ const direct = parsed.flags.get('direct') === true;
694
+ if (direct && sub !== 'start' && sub !== 'restart')
695
+ fail(2, '--direct applies only to daemon start or restart.');
696
+ const holdFlag = parsed.flags.get('hold');
697
+ if (holdFlag !== undefined && sub !== 'stop')
698
+ fail(2, '--hold applies only to daemon stop.');
699
+ const holdSeconds = holdFlag === undefined ? undefined : holdFlag === true ? 120 : Number(holdFlag);
700
+ if (holdSeconds !== undefined && (!Number.isInteger(holdSeconds) || holdSeconds < 1 || holdSeconds > 600)) {
701
+ fail(2, '--hold needs a whole number of seconds from 1 to 600.');
702
+ }
703
+ // Every request here passes `autoStart: false`: asking about or stopping a
704
+ // daemon must never start one, so a daemon that goes between being found
705
+ // and being asked is reported as not running.
706
+ const daemonOnly = { autoStart: false };
707
+ /** Stop the daemon, or say false when it had already gone. */
569
708
  const stopRunning = async (connection) => {
570
- const response = await request(connection, 'POST', '/daemon/shutdown', { force }, {
571
- logger: stderrLogger,
572
- actor: 'cli',
573
- });
709
+ let response;
710
+ try {
711
+ response = await request(connection, 'POST', '/daemon/shutdown', { force }, {
712
+ logger: stderrLogger,
713
+ actor: 'cli',
714
+ ...daemonOnly,
715
+ });
716
+ }
717
+ catch (error) {
718
+ if (error instanceof DaemonGoneError)
719
+ return false;
720
+ throw error;
721
+ }
574
722
  if (response.status === 409) {
575
723
  fail(1, `${String(response.body['error'])} (use --force)`);
576
724
  }
@@ -584,26 +732,44 @@ async function daemonVerb(parsed, wantJson) {
584
732
  await new Promise((resolve) => setTimeout(resolve, 150));
585
733
  }
586
734
  catch {
587
- return;
735
+ return true;
588
736
  }
589
737
  }
590
738
  fail(1, 'daemon did not stop within 10 s. Check daemon.log.');
591
739
  };
592
740
  switch (sub) {
593
741
  case 'status': {
742
+ const hold = readRestartHold(shellpuppetHome(), stderrLogger);
743
+ const holdRemainingSeconds = hold === null ? undefined : Math.max(1, Math.ceil((hold.expiresAt - Date.now()) / 1000));
744
+ const notRunning = () => {
745
+ console.log(wantJson ? JSON.stringify({ running: false, ...(holdRemainingSeconds !== undefined ? { holdRemainingSeconds } : {}) }) :
746
+ `not running${holdRemainingSeconds === undefined ? '' : `; restart hold ends in ${String(holdRemainingSeconds)} s`}`);
747
+ };
594
748
  const connection = await discoverDaemon({ logger: stderrLogger });
595
749
  if (connection === null) {
596
- console.log(wantJson ? JSON.stringify({ running: false }) : 'not running');
750
+ notRunning();
597
751
  return;
598
752
  }
753
+ let sessions;
754
+ try {
755
+ sessions = await call(connection, 'GET', '/sessions', undefined, daemonOnly);
756
+ }
757
+ catch (error) {
758
+ if (error instanceof DaemonGoneError) {
759
+ notRunning();
760
+ return;
761
+ }
762
+ throw error;
763
+ }
599
764
  surfaceWarnings(connection);
600
- const sessions = await call(connection, 'GET', '/sessions');
601
765
  const list = sessions['sessions'];
766
+ const startedWrapped = readDaemonState(shellpuppetHome())?.startedWrapped === true;
602
767
  // What sessions inherit (ADR-008). A daemon that cannot say is left out
603
768
  // of the report rather than failing it.
604
769
  const environment = await request(connection, 'GET', '/environment', undefined, {
605
770
  logger: stderrLogger,
606
771
  actor: 'cli',
772
+ ...daemonOnly,
607
773
  })
608
774
  .then((response) => response.status === 200 ? response.body : undefined)
609
775
  .catch(() => undefined);
@@ -613,12 +779,15 @@ async function daemonVerb(parsed, wantJson) {
613
779
  port: connection.port,
614
780
  version: connection.version,
615
781
  sessions: list,
782
+ startedWrapped,
783
+ ...(holdRemainingSeconds !== undefined ? { holdRemainingSeconds } : {}),
616
784
  ...(environment !== undefined ? { sessionEnv: environment } : {}),
617
785
  });
618
786
  }
619
787
  else {
620
788
  console.log(`running on port ${String(connection.port)}, version ${connection.version}, ` +
621
- `${String(list.length)} session(s)` +
789
+ `${String(list.length)} session(s), started wrapped: ${String(startedWrapped)}` +
790
+ (holdRemainingSeconds !== undefined ? `, restart hold ends in ${String(holdRemainingSeconds)} s` : '') +
622
791
  (environment !== undefined ? `, session environment ${environment.mode}` : ''));
623
792
  if (environment !== undefined && environment.exposed.length > 0) {
624
793
  console.error(`warning: sessionEnv "passthrough" hands every session the daemon's whole ` +
@@ -631,20 +800,24 @@ async function daemonVerb(parsed, wantJson) {
631
800
  // `--help` says every verb accepts --json, so these three answer in JSON
632
801
  // when asked, and a script driving the daemon need not parse English.
633
802
  case 'start': {
634
- const existing = await discoverDaemon({ logger: stderrLogger });
635
- if (existing !== null) {
636
- surfaceWarnings(existing);
803
+ const { connection, alreadyRunning } = await withDaemonStartLock({ logger: stderrLogger }, async (lock) => {
804
+ clearRestartHold(shellpuppetHome());
805
+ const existing = await discoverDaemon({ logger: stderrLogger });
806
+ return existing !== null ? { connection: existing, alreadyRunning: true } :
807
+ { connection: await ensureDaemon({ logger: stderrLogger, direct }, lock), alreadyRunning: false };
808
+ });
809
+ if (alreadyRunning) {
810
+ surfaceWarnings(connection);
637
811
  if (wantJson) {
638
- printJson({ running: true, port: existing.port, version: existing.version });
812
+ printJson({ running: true, port: connection.port, version: connection.version, startedWrapped: readDaemonState(shellpuppetHome())?.startedWrapped === true });
639
813
  }
640
814
  else
641
- console.log(`already running on port ${String(existing.port)}`);
815
+ console.log(`already running on port ${String(connection.port)}`);
642
816
  return;
643
817
  }
644
- const connection = await ensureDaemon({ logger: stderrLogger });
645
818
  surfaceWarnings(connection);
646
819
  if (wantJson) {
647
- printJson({ running: true, port: connection.port, version: connection.version });
820
+ printJson({ running: true, port: connection.port, version: connection.version, startedWrapped: readDaemonState(shellpuppetHome())?.startedWrapped === true });
648
821
  }
649
822
  else {
650
823
  console.log(`started on port ${String(connection.port)}, version ${connection.version}`);
@@ -652,8 +825,23 @@ async function daemonVerb(parsed, wantJson) {
652
825
  return;
653
826
  }
654
827
  case 'stop': {
655
- const connection = await discoverDaemon({ logger: stderrLogger });
656
- if (connection === null) {
828
+ if (holdSeconds !== undefined) {
829
+ const stopped = await withDaemonStartLock({ logger: stderrLogger }, async () => {
830
+ const existing = await discoverDaemon({ logger: stderrLogger });
831
+ const didStop = existing !== null && await stopRunning(existing);
832
+ writeRestartHold(shellpuppetHome(), holdSeconds);
833
+ return didStop;
834
+ });
835
+ if (wantJson)
836
+ printJson({ running: false, stopped: true, holdRemainingSeconds: holdSeconds });
837
+ else
838
+ console.log(stopped ? `stopped; restart hold ends in ${String(holdSeconds)} s` :
839
+ `not running; restart hold ends in ${String(holdSeconds)} s`);
840
+ return;
841
+ }
842
+ const connection = await waitForPendingDaemon({ logger: stderrLogger });
843
+ // A daemon that went before it could be told to stop was not running.
844
+ if (connection === null || !(await stopRunning(connection))) {
657
845
  // Nothing to stop IS the outcome asked for, so it reads the same to a
658
846
  // script as a daemon that was stopped.
659
847
  if (wantJson)
@@ -662,7 +850,6 @@ async function daemonVerb(parsed, wantJson) {
662
850
  console.log('not running');
663
851
  return;
664
852
  }
665
- await stopRunning(connection);
666
853
  if (wantJson)
667
854
  printJson({ running: false, stopped: true });
668
855
  else
@@ -670,13 +857,35 @@ async function daemonVerb(parsed, wantJson) {
670
857
  return;
671
858
  }
672
859
  case 'restart': {
673
- const existing = await discoverDaemon({ logger: stderrLogger });
674
- if (existing !== null)
675
- await stopRunning(existing);
676
- const connection = await ensureDaemon({ logger: stderrLogger });
860
+ const connection = await withDaemonStartLock({ logger: stderrLogger }, async (lock) => {
861
+ const home = shellpuppetHome();
862
+ clearRestartHold(home);
863
+ const record = inspectDaemonState(home);
864
+ if (record.kind !== 'record') {
865
+ throw new Error('Cannot restart without a readable daemon record. Wait about 15 seconds and run `shellpuppet daemon restart` again. If the record is still missing, the daemon is usually stopped; check that no ShellPuppet daemon process is running before `shellpuppet daemon start`.');
866
+ }
867
+ const existing = await discoverDaemon({ logger: stderrLogger });
868
+ if (existing === null)
869
+ return ensureDaemon({ logger: stderrLogger, direct }, lock);
870
+ const state = readDaemonState(home);
871
+ if (state === null || state.pid !== existing.pid || state.instanceId !== existing.instanceId) {
872
+ throw new Error('The daemon changed while preparing its restart. Try again.');
873
+ }
874
+ // Publish the daemon being replaced before the shutdown request. Peers
875
+ // can still see its healthy port until the stop completes.
876
+ writeRestartHold(home, 140, { ...(existing.instanceId === undefined ? {} : { instanceId: existing.instanceId }),
877
+ pid: existing.pid, port: existing.port, startMode: daemonStartMode(home, direct) });
878
+ try {
879
+ await stopRunning(existing);
880
+ return await ensureDaemon({ logger: stderrLogger, direct }, lock);
881
+ }
882
+ finally {
883
+ clearRestartHold(home);
884
+ }
885
+ });
677
886
  surfaceWarnings(connection);
678
887
  if (wantJson) {
679
- printJson({ running: true, port: connection.port, version: connection.version });
888
+ printJson({ running: true, port: connection.port, version: connection.version, startedWrapped: readDaemonState(shellpuppetHome())?.startedWrapped === true });
680
889
  }
681
890
  else {
682
891
  console.log(`restarted on port ${String(connection.port)}, version ${connection.version}`);
@@ -684,7 +893,7 @@ async function daemonVerb(parsed, wantJson) {
684
893
  return;
685
894
  }
686
895
  default:
687
- fail(2, 'daemon needs one of: status, start, stop [--force], restart [--force]');
896
+ fail(2, 'daemon needs one of: status, start, stop [--force] [--hold [seconds]], restart [--force]');
688
897
  }
689
898
  }
690
899
  main().catch((error) => {