shellpuppet 0.0.1 → 0.2.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/LICENSE +202 -0
- package/NOTICE +31 -0
- package/README.md +499 -8
- 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.d.ts +13 -0
- package/dist/cli/index.js +846 -0
- package/dist/cli/index.js.map +1 -0
- package/dist/client/http.d.ts +143 -0
- package/dist/client/http.js +581 -0
- package/dist/client/http.js.map +1 -0
- package/dist/core/dialogs.d.ts +96 -0
- package/dist/core/dialogs.js +226 -0
- package/dist/core/dialogs.js.map +1 -0
- package/dist/core/echo.d.ts +71 -0
- package/dist/core/echo.js +249 -0
- package/dist/core/echo.js.map +1 -0
- package/dist/core/find.d.ts +34 -0
- package/dist/core/find.js +41 -0
- package/dist/core/find.js.map +1 -0
- package/dist/core/keys.d.ts +22 -0
- package/dist/core/keys.js +80 -0
- package/dist/core/keys.js.map +1 -0
- package/dist/core/manager.d.ts +96 -0
- package/dist/core/manager.js +271 -0
- package/dist/core/manager.js.map +1 -0
- package/dist/core/nativePty.d.ts +73 -0
- package/dist/core/nativePty.js +161 -0
- package/dist/core/nativePty.js.map +1 -0
- package/dist/core/policy.d.ts +61 -0
- package/dist/core/policy.js +143 -0
- package/dist/core/policy.js.map +1 -0
- package/dist/core/promptDetector.d.ts +109 -0
- package/dist/core/promptDetector.js +897 -0
- package/dist/core/promptDetector.js.map +1 -0
- package/dist/core/reasoning.d.ts +265 -0
- package/dist/core/reasoning.js +933 -0
- package/dist/core/reasoning.js.map +1 -0
- package/dist/core/regexBudget.d.ts +64 -0
- package/dist/core/regexBudget.js +103 -0
- package/dist/core/regexBudget.js.map +1 -0
- package/dist/core/renderer.d.ts +127 -0
- package/dist/core/renderer.js +316 -0
- package/dist/core/renderer.js.map +1 -0
- 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 +565 -0
- package/dist/core/session.js +1450 -0
- package/dist/core/session.js.map +1 -0
- package/dist/core/types.d.ts +316 -0
- package/dist/core/types.js +71 -0
- package/dist/core/types.js.map +1 -0
- package/dist/core/waiter.d.ts +94 -0
- package/dist/core/waiter.js +310 -0
- package/dist/core/waiter.js.map +1 -0
- 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 +161 -0
- package/dist/core/windowsPtyStart.js +236 -0
- package/dist/core/windowsPtyStart.js.map +1 -0
- package/dist/daemon/audit.d.ts +23 -0
- package/dist/daemon/audit.js +51 -0
- package/dist/daemon/audit.js.map +1 -0
- package/dist/daemon/auth.d.ts +197 -0
- package/dist/daemon/auth.js +366 -0
- package/dist/daemon/auth.js.map +1 -0
- package/dist/daemon/config.d.ts +119 -0
- package/dist/daemon/config.js +568 -0
- package/dist/daemon/config.js.map +1 -0
- 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.d.ts +7 -0
- package/dist/daemon/index.js +88 -0
- package/dist/daemon/index.js.map +1 -0
- 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 +36 -0
- package/dist/daemon/liveness.js +71 -0
- package/dist/daemon/liveness.js.map +1 -0
- package/dist/daemon/logger.d.ts +7 -0
- package/dist/daemon/logger.js +29 -0
- package/dist/daemon/logger.js.map +1 -0
- package/dist/daemon/meta.d.ts +9 -0
- package/dist/daemon/meta.js +24 -0
- package/dist/daemon/meta.js.map +1 -0
- package/dist/daemon/paths.d.ts +85 -0
- package/dist/daemon/paths.js +154 -0
- package/dist/daemon/paths.js.map +1 -0
- package/dist/daemon/screenshot.d.ts +144 -0
- package/dist/daemon/screenshot.js +402 -0
- package/dist/daemon/screenshot.js.map +1 -0
- package/dist/daemon/server.d.ts +453 -0
- package/dist/daemon/server.js +3954 -0
- package/dist/daemon/server.js.map +1 -0
- 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/terminalReports.d.ts +38 -0
- package/dist/daemon/terminalReports.js +84 -0
- package/dist/daemon/terminalReports.js.map +1 -0
- package/dist/daemon/viewerLauncher.d.ts +226 -0
- package/dist/daemon/viewerLauncher.js +562 -0
- package/dist/daemon/viewerLauncher.js.map +1 -0
- package/dist/daemon/viewerSync.d.ts +38 -0
- package/dist/daemon/viewerSync.js +83 -0
- package/dist/daemon/viewerSync.js.map +1 -0
- package/dist/mcp/config.d.ts +50 -0
- package/dist/mcp/config.js +95 -0
- package/dist/mcp/config.js.map +1 -0
- package/dist/mcp/index.d.ts +10 -0
- package/dist/mcp/index.js +78 -0
- package/dist/mcp/index.js.map +1 -0
- package/dist/mcp/tools.d.ts +66 -0
- package/dist/mcp/tools.js +638 -0
- package/dist/mcp/tools.js.map +1 -0
- 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 +1518 -0
- package/dist/viewer/icon-16.png +0 -0
- package/dist/viewer/icon-180.png +0 -0
- package/dist/viewer/icon-32.png +0 -0
- package/dist/viewer/icon-512.png +0 -0
- package/dist/viewer/icon.ico +0 -0
- package/dist/viewer/icon.svg +66 -0
- package/dist/viewer/index.html +61 -0
- package/dist/viewer/pane.js +736 -0
- package/dist/viewer/viewer.css +95 -0
- package/dist/viewer/viewer.js +84 -0
- package/package.json +66 -7
- package/index.js +0 -4
|
@@ -0,0 +1,846 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
/**
|
|
3
|
+
* ShellPuppet CLI: a thin, one-shot client over the daemon HTTP API
|
|
4
|
+
* (design §2.4). Every invocation makes its request(s), prints and EXITS:
|
|
5
|
+
* it never spawns anything it stays attached to. That one property is why the
|
|
6
|
+
* CLI can never hang a calling shell (the inherited-stdio hang, §2.2).
|
|
7
|
+
*
|
|
8
|
+
* stdout carries results; warnings and errors go to stderr. Exit codes:
|
|
9
|
+
* 0 success · 1 the operation failed · 2 the request itself was wrong, whether
|
|
10
|
+
* this CLI caught it or the daemon refused it with a 400 · 3 wait did not
|
|
11
|
+
* match, or find found nothing.
|
|
12
|
+
*/
|
|
13
|
+
import { writeFile } from 'node:fs/promises';
|
|
14
|
+
import { resolve } from 'node:path';
|
|
15
|
+
import process from 'node:process';
|
|
16
|
+
import { DaemonGoneError, discoverDaemon, ensureDaemon, request, waitForPendingDaemon } from '../client/http.js';
|
|
17
|
+
import { assertNodeVersion, packageVersion } from '../daemon/meta.js';
|
|
18
|
+
import { NO_MATCHES } from '../core/find.js';
|
|
19
|
+
import { resultRefusal } from '../core/reasoning.js';
|
|
20
|
+
import { readDaemonState, shellpuppetHome } from '../daemon/paths.js';
|
|
21
|
+
import { planPassedEnv } from '../mcp/config.js';
|
|
22
|
+
import { isEnvNamesProblem, readDaemonConfig } from '../daemon/config.js';
|
|
23
|
+
import { agentNameFor } from '../core/reasoning.js';
|
|
24
|
+
import { knownKeys } from '../core/keys.js';
|
|
25
|
+
import { listedState } from '../core/types.js';
|
|
26
|
+
import { installDesktopShortcut, uninstallDesktopShortcut, userShortcutOptions } from './desktopShortcut.js';
|
|
27
|
+
const USAGE = `ShellPuppet: drive a real terminal session; humans watch and type via the viewer.
|
|
28
|
+
|
|
29
|
+
Usage:
|
|
30
|
+
shellpuppet start [options] <command> [args...] Launch a program in a new session
|
|
31
|
+
--label <s> --purpose <s> --cols <n> --rows <n> --cwd <dir>
|
|
32
|
+
--ready-text <s> --ready-quiet <ms> --no-shell --hold --agent <name>
|
|
33
|
+
--env-name <NAME> (repeatable) --no-viewer
|
|
34
|
+
--no-viewer opens no dashboard or viewer window, for a short scripted session nobody
|
|
35
|
+
needs to watch; viewer-url still gives a link to it.
|
|
36
|
+
--cwd sets the folder the session starts in; it defaults to THIS shell's
|
|
37
|
+
working directory, and a relative --cwd is taken from there.
|
|
38
|
+
A session that runs as an agent CLI receives, from THIS shell's
|
|
39
|
+
environment, the variables listed for that agent in agents.passEnv in
|
|
40
|
+
config.json, with no flag. --env-name copies another variable, for a
|
|
41
|
+
program that is not an agent CLI: only names listed in envNames in
|
|
42
|
+
config.json pass, and any other name refuses the start. Values are
|
|
43
|
+
never printed or logged.
|
|
44
|
+
--agent names the agent CLI the session runs (claude, codex, muse, qoder...)
|
|
45
|
+
when it is reached through a shell or a launcher script, so that
|
|
46
|
+
--hide-reasoning and result can read its screen.
|
|
47
|
+
--cols/--rows say where to START; the human's viewer reshapes the grid to
|
|
48
|
+
its window unless --hold keeps it, which is for runs you compare against
|
|
49
|
+
a known width.
|
|
50
|
+
--purpose says what the session is FOR; it titles the viewer window.
|
|
51
|
+
--no-shell starts the command without a shell; on Windows it must then
|
|
52
|
+
be an .exe or .com, so start a script through the shell. A command with
|
|
53
|
+
a path separator is resolved from the session's working directory, and
|
|
54
|
+
a file name containing ':' is refused as an alternate data stream.
|
|
55
|
+
On Windows, the default uses cmd.exe /d /s /c. Arguments are joined as
|
|
56
|
+
shell text: quote spaces for cmd.exe, for example pass the one argument
|
|
57
|
+
'mcp_servers.x.command="C:/Program Files/nodejs/node.exe"' from Git Bash.
|
|
58
|
+
cmd.exe also expands %NAME% and interprets ^ & | < >. Use --no-shell
|
|
59
|
+
with an .exe or .com when each argument must arrive literally.
|
|
60
|
+
Options go BEFORE the command; everything after the command is passed
|
|
61
|
+
to the daemon unchanged (so its own --flags survive).
|
|
62
|
+
shellpuppet list [--waiting] [--hide-reasoning] List sessions, or only waiting prompts
|
|
63
|
+
shellpuppet snap <id> [--last <n>] [--hide-reasoning]
|
|
64
|
+
Print the rendered screen
|
|
65
|
+
--hide-reasoning leaves out an agent CLI's reasoning, each block as one
|
|
66
|
+
"[reasoning hidden: N lines]" line; a session whose agent has no
|
|
67
|
+
signature is refused (exit 2), never printed unfiltered.
|
|
68
|
+
shellpuppet result <id> [--hide-reasoning] Print the agent's latest answer
|
|
69
|
+
The answer that ends the latest turn, and its turn summary: never its
|
|
70
|
+
reasoning. --hide-reasoning is accepted but changes nothing: result
|
|
71
|
+
always leaves reasoning out. Exits 3, with the reason on stderr, while
|
|
72
|
+
the agent is still working or when no answer is recognised.
|
|
73
|
+
shellpuppet type <id> <text> [--enter] [--verify] Type text (--verify re-reads the screen,
|
|
74
|
+
for up to 15 s on long text)
|
|
75
|
+
shellpuppet key <id> <name> Press a key (enter, escape, ctrl+c, f1…)
|
|
76
|
+
shellpuppet wait <id> [--text <s>|--regex <r>|--quiet <ms>|--prompt]
|
|
77
|
+
[--timeout <ms>] [--debounce <ms>] [--match-after-input true|false]
|
|
78
|
+
[--hide-reasoning]
|
|
79
|
+
Wait for a condition, print the screen
|
|
80
|
+
--prompt waits until the session asks a permission question
|
|
81
|
+
(the one you just answered does not count until it has been
|
|
82
|
+
seen to go; --match-after-input false accepts any prompt)
|
|
83
|
+
--match-after-input true ignores text/regex matches at or
|
|
84
|
+
before the echo of what you last typed
|
|
85
|
+
--debounce waits for the condition to hold on every poll
|
|
86
|
+
for this many ms; a missed poll restarts it, while other
|
|
87
|
+
output such as a ticking timer does not; a match on the
|
|
88
|
+
final screen settles at once if the program exits
|
|
89
|
+
shellpuppet wait --prompt [id ...] [--now] [--timeout <ms>] [--hide-reasoning]
|
|
90
|
+
Wait for any listed session's prompt,
|
|
91
|
+
or every live session if no ids are given;
|
|
92
|
+
--now polls once without waiting
|
|
93
|
+
shellpuppet find <id> <pattern> [--hide-reasoning]
|
|
94
|
+
Regex-search the screen, with line numbers
|
|
95
|
+
Prints each matching line as <row>: <text>. Nothing matching prints
|
|
96
|
+
"No matches." on stderr, never the pattern, and exits 3 (with --json
|
|
97
|
+
too, after printing the empty result).
|
|
98
|
+
shellpuppet screenshot <id> [--out <f>] [--hide-reasoning]
|
|
99
|
+
[--width <n>] [--height <n>] [--timeout <ms>]
|
|
100
|
+
Photograph the viewer as a browser draws it
|
|
101
|
+
Defaults to shellpuppet-<id>.png at 1400x900, with 45 s for the whole
|
|
102
|
+
capture (--timeout, 1000 to 120000, for a slow or a hurried machine).
|
|
103
|
+
Needs a Chromium-family browser; it cannot type into the session or
|
|
104
|
+
change its size.
|
|
105
|
+
shellpuppet viewer-url <id> [--read-only] Mint a fresh viewer link (single use)
|
|
106
|
+
Links work once and expire after a few minutes; mint another whenever
|
|
107
|
+
the human needs one. --read-only grants watching without typing, and the
|
|
108
|
+
daemon enforces it rather than the page.
|
|
109
|
+
shellpuppet dashboard Open the dashboard in its own window
|
|
110
|
+
One window for every session, in ShellPuppet's isolated browser profile.
|
|
111
|
+
Prints whether a window opened, never the link.
|
|
112
|
+
shellpuppet desktop [--install|--uninstall] Start ShellPuppet and open its dashboard
|
|
113
|
+
Reuses a connected dashboard. --install adds or updates a per-user shortcut;
|
|
114
|
+
--uninstall removes that shortcut. Neither option starts the daemon.
|
|
115
|
+
shellpuppet resize <id> <cols> <rows> [--hold] Set screen geometry
|
|
116
|
+
Without --hold the human's window reshapes it again the moment they
|
|
117
|
+
move it, which is what lets the viewer fill.
|
|
118
|
+
shellpuppet kill <id> Kill the session and its process tree
|
|
119
|
+
shellpuppet daemon status|start|stop|restart Manage the shared daemon
|
|
120
|
+
start/restart: --direct starts without daemon.startWith.
|
|
121
|
+
stop/restart: --force to kill live sessions. status and stop never
|
|
122
|
+
start a daemon: one that has gone is reported as not running.
|
|
123
|
+
shellpuppet mcp Run the MCP stdio server (long-running)
|
|
124
|
+
shellpuppet --version | --help
|
|
125
|
+
|
|
126
|
+
Any verb accepts --json for the raw API response.
|
|
127
|
+
|
|
128
|
+
Exit codes: 0 ok · 1 the operation failed · 2 the request itself was wrong,
|
|
129
|
+
whether this CLI caught it (an unknown verb, a missing id or a flag without
|
|
130
|
+
its value) or the daemon refused it with a 400 (an unparsable --regex, a grid
|
|
131
|
+
outside the bounds) · 3 the wait did not match, or find found nothing, so
|
|
132
|
+
scripts can branch on either; result exits 3 when there is no answer yet.
|
|
133
|
+
Waiting for text you just typed matches its own echo, so pass
|
|
134
|
+
--match-after-input true, wait for output-only text or use --quiet.`;
|
|
135
|
+
/** Flags that take a value and may be given more than once. */
|
|
136
|
+
const REPEAT_FLAGS = new Set(['env-name']);
|
|
137
|
+
/** Flags that take a value; everything else `--x` is boolean. */
|
|
138
|
+
const VALUE_FLAGS = new Set([
|
|
139
|
+
'label',
|
|
140
|
+
'agent',
|
|
141
|
+
// Omitting a value-taking flag here does not fail loudly: the flag silently
|
|
142
|
+
// becomes boolean `true` and its VALUE becomes the first positional, i.e.
|
|
143
|
+
// the command to run, so `--purpose "Fix the failing login test"` would
|
|
144
|
+
// send that whole string to cmd.exe as a program name.
|
|
145
|
+
'purpose',
|
|
146
|
+
'cols',
|
|
147
|
+
'rows',
|
|
148
|
+
'cwd',
|
|
149
|
+
'ready-text',
|
|
150
|
+
'ready-quiet',
|
|
151
|
+
'last',
|
|
152
|
+
'text',
|
|
153
|
+
'regex',
|
|
154
|
+
'quiet',
|
|
155
|
+
'timeout',
|
|
156
|
+
'debounce',
|
|
157
|
+
'match-after-input',
|
|
158
|
+
'out',
|
|
159
|
+
'width',
|
|
160
|
+
'height',
|
|
161
|
+
]);
|
|
162
|
+
/**
|
|
163
|
+
* `stopAtFirstPositional` is how `start` avoids eating the target command's
|
|
164
|
+
* own flags: `shellpuppet start [options] <command> [args...]`. Once the
|
|
165
|
+
* command appears, everything after it (including `--version`, `--help`,
|
|
166
|
+
* anything) belongs to the command verbatim: `start goose --version` hands
|
|
167
|
+
* `--version` to Goose.
|
|
168
|
+
*/
|
|
169
|
+
function parseArgs(argv, stopAtFirstPositional = false) {
|
|
170
|
+
const positionals = [];
|
|
171
|
+
const flags = new Map();
|
|
172
|
+
const lists = new Map();
|
|
173
|
+
for (let i = 0; i < argv.length; i++) {
|
|
174
|
+
const arg = argv[i] ?? '';
|
|
175
|
+
if (!arg.startsWith('--') || (stopAtFirstPositional && positionals.length > 0)) {
|
|
176
|
+
positionals.push(arg);
|
|
177
|
+
continue;
|
|
178
|
+
}
|
|
179
|
+
const name = arg.slice(2);
|
|
180
|
+
if (REPEAT_FLAGS.has(name)) {
|
|
181
|
+
const value = argv[++i];
|
|
182
|
+
if (value === undefined)
|
|
183
|
+
fail(2, `--${name} needs a value.`);
|
|
184
|
+
lists.set(name, [...(lists.get(name) ?? []), value]);
|
|
185
|
+
}
|
|
186
|
+
else if (VALUE_FLAGS.has(name)) {
|
|
187
|
+
const value = argv[++i];
|
|
188
|
+
if (value === undefined)
|
|
189
|
+
fail(2, `--${name} needs a value.`);
|
|
190
|
+
flags.set(name, value);
|
|
191
|
+
}
|
|
192
|
+
else {
|
|
193
|
+
flags.set(name, true);
|
|
194
|
+
}
|
|
195
|
+
}
|
|
196
|
+
return { positionals, flags, lists };
|
|
197
|
+
}
|
|
198
|
+
function fail(code, message) {
|
|
199
|
+
console.error(message);
|
|
200
|
+
process.exit(code);
|
|
201
|
+
}
|
|
202
|
+
function intFlag(parsed, name) {
|
|
203
|
+
const raw = parsed.flags.get(name);
|
|
204
|
+
if (raw === undefined)
|
|
205
|
+
return undefined;
|
|
206
|
+
const value = Number(raw);
|
|
207
|
+
if (!Number.isInteger(value))
|
|
208
|
+
fail(2, `--${name} must be an integer.`);
|
|
209
|
+
return value;
|
|
210
|
+
}
|
|
211
|
+
const stderrLogger = {
|
|
212
|
+
debug: () => undefined,
|
|
213
|
+
info: () => undefined,
|
|
214
|
+
warn: (message) => console.error(`warning: ${message}`),
|
|
215
|
+
error: (message) => console.error(`error: ${message}`),
|
|
216
|
+
};
|
|
217
|
+
function surfaceWarnings(connection) {
|
|
218
|
+
for (const warning of connection.warnings)
|
|
219
|
+
console.error(`warning: ${warning}`);
|
|
220
|
+
}
|
|
221
|
+
async function call(connection, method, path, body, options = {}) {
|
|
222
|
+
const response = await request(connection, method, path, body, {
|
|
223
|
+
logger: stderrLogger,
|
|
224
|
+
actor: 'cli',
|
|
225
|
+
...options,
|
|
226
|
+
});
|
|
227
|
+
const payload = response.body;
|
|
228
|
+
if (response.status >= 400) {
|
|
229
|
+
const message = typeof payload['error'] === 'string' ? payload['error'] : 'request failed';
|
|
230
|
+
// A 400 is the daemon refusing THIS caller's own input: an unparsable
|
|
231
|
+
// `--regex`, a grid outside the bounds, a `cwd` that is not one. That is
|
|
232
|
+
// the same kind of mistake as a flag this CLI rejects itself, so it gets
|
|
233
|
+
// the same exit code, and a script can tell "I asked wrongly" from "it
|
|
234
|
+
// did not work" without reading the message. Everything else, meaning
|
|
235
|
+
// 401, 403, 404, 409, 5xx and any transport failure, is the operation
|
|
236
|
+
// failing and stays 1.
|
|
237
|
+
fail(response.status === 400 ? 2 : 1, `error (${String(response.status)}): ${message}`);
|
|
238
|
+
}
|
|
239
|
+
return payload;
|
|
240
|
+
}
|
|
241
|
+
function printJson(value) {
|
|
242
|
+
console.log(JSON.stringify(value, null, 2));
|
|
243
|
+
}
|
|
244
|
+
async function main() {
|
|
245
|
+
assertNodeVersion();
|
|
246
|
+
const argv = process.argv.slice(2);
|
|
247
|
+
const verb = argv[0];
|
|
248
|
+
const parsed = parseArgs(argv.slice(1), verb === 'start');
|
|
249
|
+
const wantJson = parsed.flags.get('json') === true;
|
|
250
|
+
// `--help` and `-h` as the FIRST argument are answered here, with `help` and
|
|
251
|
+
// `--version`, before any daemon contact: the unknown-verb branch runs
|
|
252
|
+
// AFTER ensureDaemon(), and asking for help must not start a daemon.
|
|
253
|
+
if (verb === undefined ||
|
|
254
|
+
verb === 'help' ||
|
|
255
|
+
verb === '--help' ||
|
|
256
|
+
verb === '-h' ||
|
|
257
|
+
parsed.flags.get('help') === true) {
|
|
258
|
+
console.log(USAGE);
|
|
259
|
+
process.exit(verb === undefined ? 2 : 0);
|
|
260
|
+
}
|
|
261
|
+
if (verb === '--version' || verb === 'version') {
|
|
262
|
+
console.log(packageVersion());
|
|
263
|
+
process.exit(0);
|
|
264
|
+
}
|
|
265
|
+
if (verb === 'mcp') {
|
|
266
|
+
// The one long-running verb: importing the MCP entry starts a stdio MCP
|
|
267
|
+
// server that owns the process until its client disconnects. Nothing may
|
|
268
|
+
// touch stdout before the transport does.
|
|
269
|
+
await import('../mcp/index.js');
|
|
270
|
+
return;
|
|
271
|
+
}
|
|
272
|
+
if (verb === 'daemon') {
|
|
273
|
+
await daemonVerb(parsed, wantJson);
|
|
274
|
+
process.exit(0);
|
|
275
|
+
}
|
|
276
|
+
if (verb === 'desktop' && (parsed.flags.has('install') || parsed.flags.has('uninstall'))) {
|
|
277
|
+
if (parsed.flags.has('install') && parsed.flags.has('uninstall'))
|
|
278
|
+
fail(2, 'Choose --install or --uninstall.');
|
|
279
|
+
if (parsed.positionals.length > 0)
|
|
280
|
+
fail(2, 'desktop takes no positional arguments.');
|
|
281
|
+
const options = userShortcutOptions();
|
|
282
|
+
console.log(parsed.flags.has('install') ? installDesktopShortcut(options) : uninstallDesktopShortcut(options));
|
|
283
|
+
process.exit(0);
|
|
284
|
+
}
|
|
285
|
+
const connection = await ensureDaemon({ logger: stderrLogger });
|
|
286
|
+
surfaceWarnings(connection);
|
|
287
|
+
switch (verb) {
|
|
288
|
+
case 'start': {
|
|
289
|
+
const command = parsed.positionals[0];
|
|
290
|
+
if (command === undefined)
|
|
291
|
+
fail(2, 'start needs a command. See --help.');
|
|
292
|
+
const body = {
|
|
293
|
+
command,
|
|
294
|
+
args: parsed.positionals.slice(1),
|
|
295
|
+
...(parsed.flags.has('label') ? { label: String(parsed.flags.get('label')) } : {}),
|
|
296
|
+
...(parsed.flags.has('purpose') ? { purpose: String(parsed.flags.get('purpose')) } : {}),
|
|
297
|
+
...(parsed.flags.has('agent') ? { agent: String(parsed.flags.get('agent')) } : {}),
|
|
298
|
+
...(intFlag(parsed, 'cols') !== undefined ? { cols: intFlag(parsed, 'cols') } : {}),
|
|
299
|
+
...(intFlag(parsed, 'rows') !== undefined ? { rows: intFlag(parsed, 'rows') } : {}),
|
|
300
|
+
// This shell's working directory, or --cwd taken from it: the daemon
|
|
301
|
+
// runs elsewhere, so a folder is always sent, and always absolute.
|
|
302
|
+
cwd: resolve(parsed.flags.has('cwd') ? String(parsed.flags.get('cwd')) : '.'),
|
|
303
|
+
...(parsed.flags.has('ready-text')
|
|
304
|
+
? { readyText: String(parsed.flags.get('ready-text')) }
|
|
305
|
+
: {}),
|
|
306
|
+
...(intFlag(parsed, 'ready-quiet') !== undefined
|
|
307
|
+
? { readyQuiet: intFlag(parsed, 'ready-quiet') }
|
|
308
|
+
: {}),
|
|
309
|
+
...(parsed.flags.get('no-shell') === true ? { shell: false } : {}),
|
|
310
|
+
...(parsed.flags.get('hold') === true ? { hold: true } : {}),
|
|
311
|
+
...(parsed.flags.get('no-viewer') === true ? { openViewer: false } : {}),
|
|
312
|
+
};
|
|
313
|
+
// The same lists and the same rules as terminal_start. The CLI reads
|
|
314
|
+
// config.json on every run, so a change to a list needs no restart here.
|
|
315
|
+
const daemonConfig = readDaemonConfig(shellpuppetHome());
|
|
316
|
+
const agent = agentNameFor(parsed.flags.has('agent') ? String(parsed.flags.get('agent')) : undefined, command, daemonConfig.config.agentSignatures ?? []);
|
|
317
|
+
const envNames = parsed.lists.get('env-name') ?? [];
|
|
318
|
+
if (envNames.length > 0) {
|
|
319
|
+
for (const problem of daemonConfig.problems.filter(isEnvNamesProblem))
|
|
320
|
+
console.error(`warning: ${problem}`);
|
|
321
|
+
}
|
|
322
|
+
const plan = planPassedEnv({
|
|
323
|
+
agent,
|
|
324
|
+
requested: envNames,
|
|
325
|
+
agentLists: daemonConfig.config.agentPassEnv ?? {},
|
|
326
|
+
adHoc: daemonConfig.config.envNames ?? [],
|
|
327
|
+
environment: process.env,
|
|
328
|
+
source: "this shell's environment",
|
|
329
|
+
});
|
|
330
|
+
if (plan.refusedForAgent.length > 0) {
|
|
331
|
+
const names = plan.refusedForAgent;
|
|
332
|
+
fail(2, `Not started: this session runs as ${String(agent)}, whose variables come from ` +
|
|
333
|
+
`agents.passEnv.${String(agent)} in ~/.shellpuppet/config.json, and ` +
|
|
334
|
+
`${names.join(', ')} ${names.length === 1 ? 'is' : 'are'} not on it. List ` +
|
|
335
|
+
`${names.length === 1 ? 'it' : 'them'} there, or start without --env-name.`);
|
|
336
|
+
}
|
|
337
|
+
if (plan.refused.length > 0) {
|
|
338
|
+
const names = plan.refused;
|
|
339
|
+
fail(2, `Not started: ${names.join(', ')} ${names.length === 1 ? 'is' : 'are'} not listed in ` +
|
|
340
|
+
`envNames in ~/.shellpuppet/config.json, the variables you allow to be passed into a ` +
|
|
341
|
+
`session. Add ${names.length === 1 ? 'it' : 'them'} to that list, or start without ` +
|
|
342
|
+
`${names.length === 1 ? 'it' : 'them'}.`);
|
|
343
|
+
}
|
|
344
|
+
if (agent !== null) {
|
|
345
|
+
for (const problem of daemonConfig.problems.filter((p) => p.startsWith('agents'))) {
|
|
346
|
+
console.error(`warning: ${problem}`);
|
|
347
|
+
}
|
|
348
|
+
}
|
|
349
|
+
if (Object.keys(plan.env).length > 0)
|
|
350
|
+
body['env'] = plan.env;
|
|
351
|
+
for (const note of plan.notes)
|
|
352
|
+
console.error(note);
|
|
353
|
+
const result = await call(connection, 'POST', '/sessions', body);
|
|
354
|
+
if (wantJson)
|
|
355
|
+
printJson(result);
|
|
356
|
+
else {
|
|
357
|
+
console.log(`${String(result['id'])} ${String(result['label'])}`);
|
|
358
|
+
const viewer = result['viewer'];
|
|
359
|
+
if (viewer?.mode === 'dashboard' && viewer.opened === true) {
|
|
360
|
+
console.log('viewer: opened in the dashboard');
|
|
361
|
+
}
|
|
362
|
+
else if (viewer?.mode === 'dashboard' && viewer.reason === 'a dashboard is connected') {
|
|
363
|
+
console.log('viewer: session is in the connected dashboard');
|
|
364
|
+
}
|
|
365
|
+
else if (viewer?.mode === 'dashboard' && viewer.reason === 'a dashboard window is opening') {
|
|
366
|
+
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)`);
|
|
367
|
+
}
|
|
368
|
+
else if (viewer?.opened === true) {
|
|
369
|
+
const how = viewer.reason !== undefined ? `, ${viewer.reason}` : '';
|
|
370
|
+
console.log(`viewer: window opened${how} (viewer-url ${String(result['id'])} mints a link)`);
|
|
371
|
+
}
|
|
372
|
+
else if (typeof result['viewerUrl'] === 'string') {
|
|
373
|
+
const why = viewer?.reason !== undefined ? ` (${viewer.reason})` : '';
|
|
374
|
+
console.log(`viewer: no window opened${why}; link: ${result['viewerUrl']}`);
|
|
375
|
+
}
|
|
376
|
+
else {
|
|
377
|
+
console.log(`viewer: no window opened (--no-viewer); viewer-url ${String(result['id'])} mints a link`);
|
|
378
|
+
}
|
|
379
|
+
if (result['ready'] !== true) {
|
|
380
|
+
console.log('ready: false. First paint is not readiness; wait before typing.');
|
|
381
|
+
}
|
|
382
|
+
}
|
|
383
|
+
break;
|
|
384
|
+
}
|
|
385
|
+
case 'list': {
|
|
386
|
+
const query = new URLSearchParams();
|
|
387
|
+
if (parsed.flags.get('hide-reasoning') === true)
|
|
388
|
+
query.set('hideReasoning', '1');
|
|
389
|
+
if (parsed.flags.get('waiting') === true)
|
|
390
|
+
query.set('waitingOnly', '1');
|
|
391
|
+
const result = await call(connection, 'GET', `/sessions${query.size > 0 ? `?${query.toString()}` : ''}`);
|
|
392
|
+
if (wantJson) {
|
|
393
|
+
printJson(result);
|
|
394
|
+
break;
|
|
395
|
+
}
|
|
396
|
+
const sessions = result['sessions'];
|
|
397
|
+
if (sessions.length === 0) {
|
|
398
|
+
console.log('no sessions');
|
|
399
|
+
break;
|
|
400
|
+
}
|
|
401
|
+
for (const s of sessions) {
|
|
402
|
+
if (parsed.flags.get('waiting') === true) {
|
|
403
|
+
const waiting = s;
|
|
404
|
+
console.log(`${waiting.id} ${waiting.label} WAITING ${String(Math.round(waiting.waitingMs / 1000))}s` + (waiting.question === undefined ? '' : `: ${waiting.question}`));
|
|
405
|
+
for (const [index, option] of (waiting.options ?? []).entries())
|
|
406
|
+
console.log(` ${index === waiting.selectedOption ? '* ' : ' '}${option}`);
|
|
407
|
+
continue;
|
|
408
|
+
}
|
|
409
|
+
console.log(`${s.id} ${listedState(s)} ` +
|
|
410
|
+
`${String(s.cols)}x${String(s.rows)} watchers:${String(s.watchers)} ` +
|
|
411
|
+
`${s.ready ? 'ready' : 'NOT-READY'} ${s.label}` +
|
|
412
|
+
(s.agent !== null && s.agent !== undefined ? ` agent:${s.agent}` : ''));
|
|
413
|
+
const waiting = s.waitingOnPrompt;
|
|
414
|
+
if (waiting !== undefined) {
|
|
415
|
+
console.log(` WAITING ${String(Math.round(waiting.waitingMs / 1000))}s on a prompt` +
|
|
416
|
+
(waiting.question === undefined ? '' : `: ${waiting.question}`));
|
|
417
|
+
if (waiting.selectedOption !== undefined)
|
|
418
|
+
console.log(` selectedOption: ${String(waiting.selectedOption)} (zero-based)`);
|
|
419
|
+
}
|
|
420
|
+
}
|
|
421
|
+
break;
|
|
422
|
+
}
|
|
423
|
+
case 'snap': {
|
|
424
|
+
const id = parsed.positionals[0] ?? fail(2, 'snap needs a session id.');
|
|
425
|
+
const last = intFlag(parsed, 'last');
|
|
426
|
+
const query = [
|
|
427
|
+
...(last !== undefined ? [`lastLines=${String(last)}`] : []),
|
|
428
|
+
...(parsed.flags.get('hide-reasoning') === true ? ['hideReasoning=1'] : []),
|
|
429
|
+
];
|
|
430
|
+
const path = `/sessions/${id}/snapshot${query.length > 0 ? `?${query.join('&')}` : ''}`;
|
|
431
|
+
const result = await call(connection, 'GET', path);
|
|
432
|
+
if (wantJson)
|
|
433
|
+
printJson(result);
|
|
434
|
+
else if (last !== undefined)
|
|
435
|
+
console.log(result['lastLines'].join('\n'));
|
|
436
|
+
else
|
|
437
|
+
console.log(String(result['screen']));
|
|
438
|
+
break;
|
|
439
|
+
}
|
|
440
|
+
case 'result': {
|
|
441
|
+
const id = parsed.positionals[0] ?? fail(2, 'result needs a session id.');
|
|
442
|
+
const result = await call(connection, 'GET', `/sessions/${id}/result`);
|
|
443
|
+
if (wantJson)
|
|
444
|
+
printJson(result);
|
|
445
|
+
else if (result['found'] === true) {
|
|
446
|
+
const lines = [
|
|
447
|
+
...(result['answer'] ?? []),
|
|
448
|
+
...(result['trailer'] ?? []),
|
|
449
|
+
];
|
|
450
|
+
for (const line of lines)
|
|
451
|
+
console.log(line);
|
|
452
|
+
// The prompt it answers, on stderr: stdout stays the answer alone.
|
|
453
|
+
if (typeof result['prompt'] === 'string')
|
|
454
|
+
console.error(`in answer to: ${result['prompt'].trim()}`);
|
|
455
|
+
}
|
|
456
|
+
else
|
|
457
|
+
console.error(resultRefusal(String(result['reason'])));
|
|
458
|
+
if (result['found'] !== true)
|
|
459
|
+
process.exit(3);
|
|
460
|
+
break;
|
|
461
|
+
}
|
|
462
|
+
case 'type': {
|
|
463
|
+
const id = parsed.positionals[0] ?? fail(2, 'type needs a session id.');
|
|
464
|
+
const text = parsed.positionals[1] ?? fail(2, 'type needs text.');
|
|
465
|
+
const data = parsed.flags.get('enter') === true ? `${text}\r` : text;
|
|
466
|
+
const result = await call(connection, 'POST', `/sessions/${id}/input`, {
|
|
467
|
+
data,
|
|
468
|
+
...(parsed.flags.get('verify') === true ? { verify: true } : {}),
|
|
469
|
+
});
|
|
470
|
+
if (wantJson)
|
|
471
|
+
printJson(result);
|
|
472
|
+
else if (result['verified'] === false) {
|
|
473
|
+
console.log('typed, but the text did NOT appear on screen. The app may still be ' +
|
|
474
|
+
'loading, a panel may have focus or, commonly with --enter, the app ' +
|
|
475
|
+
'accepted it and cleared the input box. Run `shellpuppet snap <id>` FIRST: ' +
|
|
476
|
+
'if the agent is working, it landed. Escape resets focus but is CANCEL in ' +
|
|
477
|
+
'agent CLIs, so do not reach for it before you have looked.');
|
|
478
|
+
process.exit(1);
|
|
479
|
+
}
|
|
480
|
+
else {
|
|
481
|
+
// Positive confirmation matters: with --verify the whole point is
|
|
482
|
+
// knowing the keystrokes landed, so say so rather than printing the
|
|
483
|
+
// same line as an unverified type.
|
|
484
|
+
console.log(`typed ${String(result['bytes'])} bytes` +
|
|
485
|
+
(result['verified'] === true ? ' (verified on screen).' : '.'));
|
|
486
|
+
}
|
|
487
|
+
break;
|
|
488
|
+
}
|
|
489
|
+
case 'key': {
|
|
490
|
+
const id = parsed.positionals[0] ?? fail(2, 'key needs a session id.');
|
|
491
|
+
const key = parsed.positionals[1] ?? fail(2, `key needs a key name: ${knownKeys().join(', ')}`);
|
|
492
|
+
const result = await call(connection, 'POST', `/sessions/${id}/key`, { key });
|
|
493
|
+
if (wantJson)
|
|
494
|
+
printJson(result);
|
|
495
|
+
else
|
|
496
|
+
console.log(`sent ${String(result['key'])}`);
|
|
497
|
+
break;
|
|
498
|
+
}
|
|
499
|
+
case 'wait': {
|
|
500
|
+
const multi = parsed.flags.get('prompt') === true && (parsed.positionals.length !== 1 || parsed.flags.get('now') === true);
|
|
501
|
+
if (multi) {
|
|
502
|
+
const params = new URLSearchParams({ prompt: 'true' });
|
|
503
|
+
for (const id of parsed.positionals)
|
|
504
|
+
params.append('session', id);
|
|
505
|
+
if (parsed.flags.get('now') === true)
|
|
506
|
+
params.set('now', 'true');
|
|
507
|
+
if (parsed.flags.has('timeout'))
|
|
508
|
+
params.set('timeout', String(parsed.flags.get('timeout')));
|
|
509
|
+
if (parsed.flags.get('hide-reasoning') === true)
|
|
510
|
+
params.set('hideReasoning', '1');
|
|
511
|
+
const result = await call(connection, 'GET', `/sessions/wait?${params.toString()}`);
|
|
512
|
+
if (wantJson)
|
|
513
|
+
printJson(result);
|
|
514
|
+
else {
|
|
515
|
+
for (const waiting of result['sessions']) {
|
|
516
|
+
console.log(`${waiting.id} ${waiting.label} WAITING ${String(Math.round(waiting.waitingMs / 1000))}s` + (waiting.question === undefined ? '' : `: ${waiting.question}`));
|
|
517
|
+
for (const [index, option] of (waiting.options ?? []).entries())
|
|
518
|
+
console.log(` ${index === waiting.selectedOption ? '* ' : ' '}${option}`);
|
|
519
|
+
}
|
|
520
|
+
console.error(`${result['matched'] === true ? 'matched' : 'NOT matched'} (${String(result['reason'])}, ${String(result['waitedMs'])} ms)`);
|
|
521
|
+
}
|
|
522
|
+
if (result['matched'] !== true && parsed.flags.get('now') !== true)
|
|
523
|
+
process.exit(3);
|
|
524
|
+
break;
|
|
525
|
+
}
|
|
526
|
+
const id = parsed.positionals[0] ?? fail(2, 'wait needs a session id.');
|
|
527
|
+
const params = new URLSearchParams();
|
|
528
|
+
for (const name of ['text', 'regex', 'quiet', 'timeout', 'debounce', 'prompt']) {
|
|
529
|
+
const value = parsed.flags.get(name);
|
|
530
|
+
if (value !== undefined)
|
|
531
|
+
params.set(name, String(value));
|
|
532
|
+
}
|
|
533
|
+
const afterInput = parsed.flags.get('match-after-input');
|
|
534
|
+
if (afterInput !== undefined)
|
|
535
|
+
params.set('matchAfterInput', String(afterInput));
|
|
536
|
+
if (parsed.flags.get('hide-reasoning') === true)
|
|
537
|
+
params.set('hideReasoning', '1');
|
|
538
|
+
const result = await call(connection, 'GET', `/sessions/${id}/wait?${params.toString()}`);
|
|
539
|
+
if (wantJson)
|
|
540
|
+
printJson(result);
|
|
541
|
+
else {
|
|
542
|
+
console.error(`${result['matched'] === true ? 'matched' : 'NOT matched'} ` +
|
|
543
|
+
`(${String(result['reason'])}, ${String(result['waitedMs'])} ms)`);
|
|
544
|
+
// The waiter's own explanation of a non-match ("has not painted
|
|
545
|
+
// anything yet"), when it has one. It goes to stderr, with the outcome
|
|
546
|
+
// line.
|
|
547
|
+
if (typeof result['detail'] === 'string')
|
|
548
|
+
console.error(result['detail']);
|
|
549
|
+
const detected = result['prompt'];
|
|
550
|
+
if (detected !== undefined) {
|
|
551
|
+
// stderr, like the outcome line: stdout stays the screen alone, so
|
|
552
|
+
// piping `wait` into a file or a diff keeps working unchanged.
|
|
553
|
+
console.error(`prompt: ${detected.question}`);
|
|
554
|
+
// No re-numbering: the options are captured verbatim and already
|
|
555
|
+
// carry the numbers the TUI drew, so counting again gives
|
|
556
|
+
// "1. 1. Allow once", and the number the human must press is the
|
|
557
|
+
// program's, not ours.
|
|
558
|
+
for (const option of detected.options)
|
|
559
|
+
console.error(` ${option}`);
|
|
560
|
+
if (detected.selectedOption !== undefined)
|
|
561
|
+
console.error(`selectedOption: ${String(detected.selectedOption)} (zero-based)`);
|
|
562
|
+
}
|
|
563
|
+
console.log(String(result['screen']));
|
|
564
|
+
}
|
|
565
|
+
if (result['matched'] !== true)
|
|
566
|
+
process.exit(3);
|
|
567
|
+
break;
|
|
568
|
+
}
|
|
569
|
+
case 'find': {
|
|
570
|
+
const id = parsed.positionals[0] ?? fail(2, 'find needs a session id.');
|
|
571
|
+
const pattern = parsed.positionals[1] ?? fail(2, 'find needs a pattern.');
|
|
572
|
+
const result = await call(connection, 'GET', `/sessions/${id}/find?pattern=${encodeURIComponent(pattern)}` +
|
|
573
|
+
(parsed.flags.get('hide-reasoning') === true ? '&hideReasoning=1' : ''));
|
|
574
|
+
const matches = result['matches'];
|
|
575
|
+
if (wantJson)
|
|
576
|
+
printJson(result);
|
|
577
|
+
else {
|
|
578
|
+
// stdout holds matching lines and nothing else, so a script reads the
|
|
579
|
+
// verdict from the exit code and never from the wording.
|
|
580
|
+
for (const m of matches)
|
|
581
|
+
console.log(`${String(m.line)}: ${m.text}`);
|
|
582
|
+
if (matches.length === 0)
|
|
583
|
+
console.error(NO_MATCHES);
|
|
584
|
+
if (result['truncated'] === true)
|
|
585
|
+
console.error('warning: matches truncated at 100');
|
|
586
|
+
}
|
|
587
|
+
if (matches.length === 0)
|
|
588
|
+
process.exit(3);
|
|
589
|
+
break;
|
|
590
|
+
}
|
|
591
|
+
case 'screenshot': {
|
|
592
|
+
const id = parsed.positionals[0] ?? fail(2, 'screenshot needs a session id.');
|
|
593
|
+
const out = parsed.flags.has('out')
|
|
594
|
+
? String(parsed.flags.get('out'))
|
|
595
|
+
: `shellpuppet-${id}.png`;
|
|
596
|
+
const result = await call(connection, 'POST', `/sessions/${id}/screenshot`, {
|
|
597
|
+
...(intFlag(parsed, 'width') !== undefined ? { width: intFlag(parsed, 'width') } : {}),
|
|
598
|
+
...(intFlag(parsed, 'height') !== undefined ? { height: intFlag(parsed, 'height') } : {}),
|
|
599
|
+
...(intFlag(parsed, 'timeout') !== undefined
|
|
600
|
+
? { timeoutMs: intFlag(parsed, 'timeout') }
|
|
601
|
+
: {}),
|
|
602
|
+
...(parsed.flags.get('hide-reasoning') === true ? { hideReasoning: true } : {}),
|
|
603
|
+
});
|
|
604
|
+
const png = Buffer.from(String(result['png']), 'base64');
|
|
605
|
+
await writeFile(out, png);
|
|
606
|
+
if (wantJson)
|
|
607
|
+
printJson({ ...result, png: `<${String(png.length)} bytes>`, path: resolve(out) });
|
|
608
|
+
else {
|
|
609
|
+
console.log(resolve(out));
|
|
610
|
+
console.log(`${String(result['width'])}x${String(result['height'])} px, ` +
|
|
611
|
+
`grid ${String(result['cols'])}x${String(result['rows'])}, ` +
|
|
612
|
+
`${String(png.length)} bytes`);
|
|
613
|
+
}
|
|
614
|
+
break;
|
|
615
|
+
}
|
|
616
|
+
case 'dashboard': {
|
|
617
|
+
const result = await call(connection, 'POST', '/dashboard/open', {});
|
|
618
|
+
if (wantJson)
|
|
619
|
+
printJson(result);
|
|
620
|
+
else
|
|
621
|
+
console.log('dashboard: window opened');
|
|
622
|
+
break;
|
|
623
|
+
}
|
|
624
|
+
case 'desktop': {
|
|
625
|
+
if (parsed.positionals.length > 0)
|
|
626
|
+
fail(2, 'desktop takes no positional arguments.');
|
|
627
|
+
const result = await call(connection, 'POST', '/desktop/open', {});
|
|
628
|
+
if (wantJson)
|
|
629
|
+
printJson(result);
|
|
630
|
+
else
|
|
631
|
+
console.log(result['alreadyOpen'] === true
|
|
632
|
+
? 'ShellPuppet is already open. If you cannot see it, run shellpuppet dashboard.'
|
|
633
|
+
: 'ShellPuppet desktop: window opened');
|
|
634
|
+
break;
|
|
635
|
+
}
|
|
636
|
+
case 'viewer-url': {
|
|
637
|
+
const id = parsed.positionals[0] ?? fail(2, 'viewer-url needs a session id.');
|
|
638
|
+
const readOnly = parsed.flags.get('read-only') === true;
|
|
639
|
+
const result = await call(connection, 'POST', `/sessions/${id}/viewer`, { readOnly });
|
|
640
|
+
if (wantJson)
|
|
641
|
+
printJson(result);
|
|
642
|
+
else {
|
|
643
|
+
const minutes = Math.round(Number(result['expiresInMs']) / 60_000);
|
|
644
|
+
console.log(String(result['viewerUrl']));
|
|
645
|
+
console.log(`${result['readOnly'] === true ? 'watch-only' : 'watch and type'}, single use, ` +
|
|
646
|
+
`expires in about ${String(minutes)} min`);
|
|
647
|
+
}
|
|
648
|
+
break;
|
|
649
|
+
}
|
|
650
|
+
case 'resize': {
|
|
651
|
+
const id = parsed.positionals[0] ?? fail(2, 'resize needs a session id.');
|
|
652
|
+
const cols = Number(parsed.positionals[1]);
|
|
653
|
+
const rows = Number(parsed.positionals[2]);
|
|
654
|
+
if (!Number.isInteger(cols) || !Number.isInteger(rows)) {
|
|
655
|
+
fail(2, 'resize needs integer cols and rows.');
|
|
656
|
+
}
|
|
657
|
+
const hold = parsed.flags.get('hold') === true;
|
|
658
|
+
const result = await call(connection, 'POST', `/sessions/${id}/resize`, {
|
|
659
|
+
cols,
|
|
660
|
+
rows,
|
|
661
|
+
hold,
|
|
662
|
+
});
|
|
663
|
+
if (wantJson)
|
|
664
|
+
printJson(result);
|
|
665
|
+
else {
|
|
666
|
+
console.log(`resized to ${String(result['cols'])}x${String(result['rows'])}` +
|
|
667
|
+
(result['geometryHeld'] === true ? ' (held against the viewer)' : ''));
|
|
668
|
+
}
|
|
669
|
+
break;
|
|
670
|
+
}
|
|
671
|
+
case 'kill': {
|
|
672
|
+
const id = parsed.positionals[0] ?? fail(2, 'kill needs a session id.');
|
|
673
|
+
const result = await call(connection, 'DELETE', `/sessions/${id}`);
|
|
674
|
+
if (wantJson)
|
|
675
|
+
printJson(result);
|
|
676
|
+
else
|
|
677
|
+
console.log(`killed ${String(result['killed'])} (whole process tree)`);
|
|
678
|
+
break;
|
|
679
|
+
}
|
|
680
|
+
default:
|
|
681
|
+
fail(2, `Unknown verb: ${verb}. See --help.`);
|
|
682
|
+
}
|
|
683
|
+
process.exit(0);
|
|
684
|
+
}
|
|
685
|
+
async function daemonVerb(parsed, wantJson) {
|
|
686
|
+
const sub = parsed.positionals[0];
|
|
687
|
+
const force = parsed.flags.get('force') === true;
|
|
688
|
+
const direct = parsed.flags.get('direct') === true;
|
|
689
|
+
if (direct && sub !== 'start' && sub !== 'restart')
|
|
690
|
+
fail(2, '--direct applies only to daemon start or restart.');
|
|
691
|
+
// Every request here passes `autoStart: false`: asking about or stopping a
|
|
692
|
+
// daemon must never start one, so a daemon that goes between being found
|
|
693
|
+
// and being asked is reported as not running.
|
|
694
|
+
const daemonOnly = { autoStart: false };
|
|
695
|
+
/** Stop the daemon, or say false when it had already gone. */
|
|
696
|
+
const stopRunning = async (connection) => {
|
|
697
|
+
let response;
|
|
698
|
+
try {
|
|
699
|
+
response = await request(connection, 'POST', '/daemon/shutdown', { force }, {
|
|
700
|
+
logger: stderrLogger,
|
|
701
|
+
actor: 'cli',
|
|
702
|
+
...daemonOnly,
|
|
703
|
+
});
|
|
704
|
+
}
|
|
705
|
+
catch (error) {
|
|
706
|
+
if (error instanceof DaemonGoneError)
|
|
707
|
+
return false;
|
|
708
|
+
throw error;
|
|
709
|
+
}
|
|
710
|
+
if (response.status === 409) {
|
|
711
|
+
fail(1, `${String(response.body['error'])} (use --force)`);
|
|
712
|
+
}
|
|
713
|
+
// Wait for the port to actually go quiet so restart cannot race it.
|
|
714
|
+
const deadline = Date.now() + 10_000;
|
|
715
|
+
while (Date.now() < deadline) {
|
|
716
|
+
try {
|
|
717
|
+
await fetch(`http://127.0.0.1:${String(connection.port)}/health`, {
|
|
718
|
+
signal: AbortSignal.timeout(400),
|
|
719
|
+
});
|
|
720
|
+
await new Promise((resolve) => setTimeout(resolve, 150));
|
|
721
|
+
}
|
|
722
|
+
catch {
|
|
723
|
+
return true;
|
|
724
|
+
}
|
|
725
|
+
}
|
|
726
|
+
fail(1, 'daemon did not stop within 10 s. Check daemon.log.');
|
|
727
|
+
};
|
|
728
|
+
switch (sub) {
|
|
729
|
+
case 'status': {
|
|
730
|
+
const notRunning = () => {
|
|
731
|
+
console.log(wantJson ? JSON.stringify({ running: false }) : 'not running');
|
|
732
|
+
};
|
|
733
|
+
const connection = await discoverDaemon({ logger: stderrLogger });
|
|
734
|
+
if (connection === null) {
|
|
735
|
+
notRunning();
|
|
736
|
+
return;
|
|
737
|
+
}
|
|
738
|
+
let sessions;
|
|
739
|
+
try {
|
|
740
|
+
sessions = await call(connection, 'GET', '/sessions', undefined, daemonOnly);
|
|
741
|
+
}
|
|
742
|
+
catch (error) {
|
|
743
|
+
if (error instanceof DaemonGoneError) {
|
|
744
|
+
notRunning();
|
|
745
|
+
return;
|
|
746
|
+
}
|
|
747
|
+
throw error;
|
|
748
|
+
}
|
|
749
|
+
surfaceWarnings(connection);
|
|
750
|
+
const list = sessions['sessions'];
|
|
751
|
+
const startedWrapped = readDaemonState(shellpuppetHome())?.startedWrapped === true;
|
|
752
|
+
// What sessions inherit (ADR-008). A daemon that cannot say is left out
|
|
753
|
+
// of the report rather than failing it.
|
|
754
|
+
const environment = await request(connection, 'GET', '/environment', undefined, {
|
|
755
|
+
logger: stderrLogger,
|
|
756
|
+
actor: 'cli',
|
|
757
|
+
...daemonOnly,
|
|
758
|
+
})
|
|
759
|
+
.then((response) => response.status === 200 ? response.body : undefined)
|
|
760
|
+
.catch(() => undefined);
|
|
761
|
+
if (wantJson) {
|
|
762
|
+
printJson({
|
|
763
|
+
running: true,
|
|
764
|
+
port: connection.port,
|
|
765
|
+
version: connection.version,
|
|
766
|
+
sessions: list,
|
|
767
|
+
startedWrapped,
|
|
768
|
+
...(environment !== undefined ? { sessionEnv: environment } : {}),
|
|
769
|
+
});
|
|
770
|
+
}
|
|
771
|
+
else {
|
|
772
|
+
console.log(`running on port ${String(connection.port)}, version ${connection.version}, ` +
|
|
773
|
+
`${String(list.length)} session(s), started wrapped: ${String(startedWrapped)}` +
|
|
774
|
+
(environment !== undefined ? `, session environment ${environment.mode}` : ''));
|
|
775
|
+
if (environment !== undefined && environment.exposed.length > 0) {
|
|
776
|
+
console.error(`warning: sessionEnv "passthrough" hands every session the daemon's whole ` +
|
|
777
|
+
`environment, including ${String(environment.exposed.length)} variable(s) ` +
|
|
778
|
+
`whose names look like credentials: ${environment.exposed.join(', ')}`);
|
|
779
|
+
}
|
|
780
|
+
}
|
|
781
|
+
return;
|
|
782
|
+
}
|
|
783
|
+
// `--help` says every verb accepts --json, so these three answer in JSON
|
|
784
|
+
// when asked, and a script driving the daemon need not parse English.
|
|
785
|
+
case 'start': {
|
|
786
|
+
const existing = await discoverDaemon({ logger: stderrLogger });
|
|
787
|
+
if (existing !== null) {
|
|
788
|
+
surfaceWarnings(existing);
|
|
789
|
+
if (wantJson) {
|
|
790
|
+
printJson({ running: true, port: existing.port, version: existing.version, startedWrapped: readDaemonState(shellpuppetHome())?.startedWrapped === true });
|
|
791
|
+
}
|
|
792
|
+
else
|
|
793
|
+
console.log(`already running on port ${String(existing.port)}`);
|
|
794
|
+
return;
|
|
795
|
+
}
|
|
796
|
+
const connection = await ensureDaemon({ logger: stderrLogger, direct });
|
|
797
|
+
surfaceWarnings(connection);
|
|
798
|
+
if (wantJson) {
|
|
799
|
+
printJson({ running: true, port: connection.port, version: connection.version, startedWrapped: readDaemonState(shellpuppetHome())?.startedWrapped === true });
|
|
800
|
+
}
|
|
801
|
+
else {
|
|
802
|
+
console.log(`started on port ${String(connection.port)}, version ${connection.version}`);
|
|
803
|
+
}
|
|
804
|
+
return;
|
|
805
|
+
}
|
|
806
|
+
case 'stop': {
|
|
807
|
+
const connection = await waitForPendingDaemon({ logger: stderrLogger });
|
|
808
|
+
// A daemon that went before it could be told to stop was not running.
|
|
809
|
+
if (connection === null || !(await stopRunning(connection))) {
|
|
810
|
+
// Nothing to stop IS the outcome asked for, so it reads the same to a
|
|
811
|
+
// script as a daemon that was stopped.
|
|
812
|
+
if (wantJson)
|
|
813
|
+
printJson({ running: false, stopped: true });
|
|
814
|
+
else
|
|
815
|
+
console.log('not running');
|
|
816
|
+
return;
|
|
817
|
+
}
|
|
818
|
+
if (wantJson)
|
|
819
|
+
printJson({ running: false, stopped: true });
|
|
820
|
+
else
|
|
821
|
+
console.log('stopped');
|
|
822
|
+
return;
|
|
823
|
+
}
|
|
824
|
+
case 'restart': {
|
|
825
|
+
// Only the start half may start a daemon.
|
|
826
|
+
const existing = await waitForPendingDaemon({ logger: stderrLogger });
|
|
827
|
+
if (existing !== null)
|
|
828
|
+
await stopRunning(existing);
|
|
829
|
+
const connection = await ensureDaemon({ logger: stderrLogger, direct });
|
|
830
|
+
surfaceWarnings(connection);
|
|
831
|
+
if (wantJson) {
|
|
832
|
+
printJson({ running: true, port: connection.port, version: connection.version, startedWrapped: readDaemonState(shellpuppetHome())?.startedWrapped === true });
|
|
833
|
+
}
|
|
834
|
+
else {
|
|
835
|
+
console.log(`restarted on port ${String(connection.port)}, version ${connection.version}`);
|
|
836
|
+
}
|
|
837
|
+
return;
|
|
838
|
+
}
|
|
839
|
+
default:
|
|
840
|
+
fail(2, 'daemon needs one of: status, start, stop [--force], restart [--force]');
|
|
841
|
+
}
|
|
842
|
+
}
|
|
843
|
+
main().catch((error) => {
|
|
844
|
+
fail(1, error instanceof Error ? error.message : String(error));
|
|
845
|
+
});
|
|
846
|
+
//# sourceMappingURL=index.js.map
|