shellpuppet 0.0.1 → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (112) hide show
  1. package/LICENSE +202 -0
  2. package/NOTICE +31 -0
  3. package/README.md +340 -8
  4. package/dist/cli/index.d.ts +13 -0
  5. package/dist/cli/index.js +693 -0
  6. package/dist/cli/index.js.map +1 -0
  7. package/dist/client/http.d.ts +82 -0
  8. package/dist/client/http.js +225 -0
  9. package/dist/client/http.js.map +1 -0
  10. package/dist/core/dialogs.d.ts +88 -0
  11. package/dist/core/dialogs.js +214 -0
  12. package/dist/core/dialogs.js.map +1 -0
  13. package/dist/core/echo.d.ts +71 -0
  14. package/dist/core/echo.js +249 -0
  15. package/dist/core/echo.js.map +1 -0
  16. package/dist/core/find.d.ts +34 -0
  17. package/dist/core/find.js +41 -0
  18. package/dist/core/find.js.map +1 -0
  19. package/dist/core/keys.d.ts +22 -0
  20. package/dist/core/keys.js +80 -0
  21. package/dist/core/keys.js.map +1 -0
  22. package/dist/core/manager.d.ts +66 -0
  23. package/dist/core/manager.js +158 -0
  24. package/dist/core/manager.js.map +1 -0
  25. package/dist/core/nativePty.d.ts +69 -0
  26. package/dist/core/nativePty.js +156 -0
  27. package/dist/core/nativePty.js.map +1 -0
  28. package/dist/core/policy.d.ts +61 -0
  29. package/dist/core/policy.js +143 -0
  30. package/dist/core/policy.js.map +1 -0
  31. package/dist/core/promptDetector.d.ts +75 -0
  32. package/dist/core/promptDetector.js +606 -0
  33. package/dist/core/promptDetector.js.map +1 -0
  34. package/dist/core/reasoning.d.ts +252 -0
  35. package/dist/core/reasoning.js +740 -0
  36. package/dist/core/reasoning.js.map +1 -0
  37. package/dist/core/regexBudget.d.ts +44 -0
  38. package/dist/core/regexBudget.js +79 -0
  39. package/dist/core/regexBudget.js.map +1 -0
  40. package/dist/core/renderer.d.ts +112 -0
  41. package/dist/core/renderer.js +225 -0
  42. package/dist/core/renderer.js.map +1 -0
  43. package/dist/core/session.d.ts +311 -0
  44. package/dist/core/session.js +966 -0
  45. package/dist/core/session.js.map +1 -0
  46. package/dist/core/types.d.ts +281 -0
  47. package/dist/core/types.js +47 -0
  48. package/dist/core/types.js.map +1 -0
  49. package/dist/core/waiter.d.ts +86 -0
  50. package/dist/core/waiter.js +317 -0
  51. package/dist/core/waiter.js.map +1 -0
  52. package/dist/core/windowsPtyStart.d.ts +90 -0
  53. package/dist/core/windowsPtyStart.js +129 -0
  54. package/dist/core/windowsPtyStart.js.map +1 -0
  55. package/dist/daemon/audit.d.ts +23 -0
  56. package/dist/daemon/audit.js +51 -0
  57. package/dist/daemon/audit.js.map +1 -0
  58. package/dist/daemon/auth.d.ts +127 -0
  59. package/dist/daemon/auth.js +241 -0
  60. package/dist/daemon/auth.js.map +1 -0
  61. package/dist/daemon/config.d.ts +76 -0
  62. package/dist/daemon/config.js +301 -0
  63. package/dist/daemon/config.js.map +1 -0
  64. package/dist/daemon/index.d.ts +7 -0
  65. package/dist/daemon/index.js +87 -0
  66. package/dist/daemon/index.js.map +1 -0
  67. package/dist/daemon/liveness.d.ts +36 -0
  68. package/dist/daemon/liveness.js +71 -0
  69. package/dist/daemon/liveness.js.map +1 -0
  70. package/dist/daemon/logger.d.ts +7 -0
  71. package/dist/daemon/logger.js +29 -0
  72. package/dist/daemon/logger.js.map +1 -0
  73. package/dist/daemon/meta.d.ts +9 -0
  74. package/dist/daemon/meta.js +24 -0
  75. package/dist/daemon/meta.js.map +1 -0
  76. package/dist/daemon/paths.d.ts +83 -0
  77. package/dist/daemon/paths.js +154 -0
  78. package/dist/daemon/paths.js.map +1 -0
  79. package/dist/daemon/screenshot.d.ts +87 -0
  80. package/dist/daemon/screenshot.js +256 -0
  81. package/dist/daemon/screenshot.js.map +1 -0
  82. package/dist/daemon/server.d.ts +244 -0
  83. package/dist/daemon/server.js +2187 -0
  84. package/dist/daemon/server.js.map +1 -0
  85. package/dist/daemon/terminalReports.d.ts +38 -0
  86. package/dist/daemon/terminalReports.js +84 -0
  87. package/dist/daemon/terminalReports.js.map +1 -0
  88. package/dist/daemon/viewerLauncher.d.ts +135 -0
  89. package/dist/daemon/viewerLauncher.js +280 -0
  90. package/dist/daemon/viewerLauncher.js.map +1 -0
  91. package/dist/daemon/viewerSync.d.ts +38 -0
  92. package/dist/daemon/viewerSync.js +83 -0
  93. package/dist/daemon/viewerSync.js.map +1 -0
  94. package/dist/mcp/config.d.ts +57 -0
  95. package/dist/mcp/config.js +106 -0
  96. package/dist/mcp/config.js.map +1 -0
  97. package/dist/mcp/index.d.ts +10 -0
  98. package/dist/mcp/index.js +69 -0
  99. package/dist/mcp/index.js.map +1 -0
  100. package/dist/mcp/tools.d.ts +59 -0
  101. package/dist/mcp/tools.js +537 -0
  102. package/dist/mcp/tools.js.map +1 -0
  103. package/dist/viewer/icon-16.png +0 -0
  104. package/dist/viewer/icon-180.png +0 -0
  105. package/dist/viewer/icon-32.png +0 -0
  106. package/dist/viewer/icon-512.png +0 -0
  107. package/dist/viewer/icon.svg +66 -0
  108. package/dist/viewer/index.html +56 -0
  109. package/dist/viewer/viewer.css +84 -0
  110. package/dist/viewer/viewer.js +661 -0
  111. package/package.json +66 -7
  112. package/index.js +0 -4
@@ -0,0 +1,693 @@
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 { discoverDaemon, ensureDaemon, request } 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 { shellpuppetHome } from '../daemon/paths.js';
21
+ import { readMcpConfig, planPassedEnv } from '../mcp/config.js';
22
+ import { readDaemonConfig } from '../daemon/config.js';
23
+ import { agentNameFor } from '../core/reasoning.js';
24
+ import { knownKeys } from '../core/keys.js';
25
+ const USAGE = `ShellPuppet: drive a real terminal session; humans watch and type via the viewer.
26
+
27
+ Usage:
28
+ shellpuppet start [options] <command> [args...] Launch a program in a new session
29
+ --label <s> --purpose <s> --cols <n> --rows <n> --cwd <dir>
30
+ --ready-text <s> --ready-quiet <ms> --no-shell --hold --agent <name>
31
+ --env-name <NAME> (repeatable) --no-viewer
32
+ --no-viewer opens no viewer window, for a short scripted session nobody
33
+ needs to watch; viewer-url still gives a link to it.
34
+ A session that runs as an agent CLI receives, from THIS shell's
35
+ environment, the variables listed for that agent in agents.passEnv in
36
+ 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...)
41
+ when it is reached through a shell or a launcher script, so that
42
+ --hide-reasoning and result can read its screen.
43
+ --cols/--rows say where to START; the human's viewer reshapes the grid to
44
+ its window unless --hold keeps it, which is for runs you compare against
45
+ a known width.
46
+ --purpose says what the session is FOR; it titles the viewer window.
47
+ 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
50
+ shellpuppet snap <id> [--last <n>] [--hide-reasoning]
51
+ Print the rendered screen
52
+ --hide-reasoning leaves out an agent CLI's reasoning, each block as one
53
+ "[reasoning hidden: N lines]" line; a session whose agent has no
54
+ signature is refused (exit 2), never printed unfiltered.
55
+ shellpuppet result <id> Print the agent's latest answer
56
+ 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.
59
+ shellpuppet type <id> <text> [--enter] [--verify] Type text (--verify re-reads the screen,
60
+ for up to 15 s on long text)
61
+ shellpuppet key <id> <name> Press a key (enter, escape, ctrl+c, f1…)
62
+ shellpuppet wait <id> [--text <s>|--regex <r>|--quiet <ms>|--prompt]
63
+ [--timeout <ms>] [--debounce <ms>] [--match-after-input true|false]
64
+ [--hide-reasoning]
65
+ Wait for a condition, print the screen
66
+ --prompt waits until the session asks a permission question
67
+ (the one you just answered does not count until it has been
68
+ seen to go; --match-after-input false accepts any prompt)
69
+ --match-after-input true ignores text/regex matches at or
70
+ before the echo of what you last typed
71
+ shellpuppet find <id> <pattern> [--hide-reasoning]
72
+ Regex-search the screen, with line numbers
73
+ Prints each matching line as <row>: <text>. Nothing matching prints
74
+ "No matches." on stderr, never the pattern, and exits 3 (with --json
75
+ too, after printing the empty result).
76
+ shellpuppet screenshot <id> [--out <f>] [--width <n>] [--height <n>]
77
+ [--timeout <ms>]
78
+ Photograph the viewer as a browser draws it
79
+ Defaults to shellpuppet-<id>.png at 1400x900, with 45 s for the whole
80
+ capture (--timeout, 1000 to 120000, for a slow or a hurried machine).
81
+ Needs a Chromium-family browser; it cannot type into the session or
82
+ change its size.
83
+ shellpuppet viewer-url <id> [--read-only] Mint a fresh viewer link (single use)
84
+ Links work once and expire after a few minutes; mint another whenever
85
+ the human needs one. --read-only grants watching without typing, and the
86
+ daemon enforces it rather than the page.
87
+ shellpuppet resize <id> <cols> <rows> [--hold] Set screen geometry
88
+ Without --hold the human's window reshapes it again the moment they
89
+ move it, which is what lets the viewer fill.
90
+ shellpuppet kill <id> Kill the session and its process tree
91
+ shellpuppet daemon status|start|stop|restart Manage the shared daemon
92
+ stop/restart: --force to kill live sessions
93
+ shellpuppet mcp Run the MCP stdio server (long-running)
94
+ shellpuppet --version | --help
95
+
96
+ Any verb accepts --json for the raw API response.
97
+
98
+ Exit codes: 0 ok · 1 the operation failed · 2 the request itself was wrong,
99
+ whether this CLI caught it (an unknown verb, a missing id or a flag without
100
+ its value) or the daemon refused it with a 400 (an unparsable --regex, a grid
101
+ outside the bounds) · 3 the wait did not match, or find found nothing, so
102
+ scripts can branch on either; result exits 3 when there is no answer yet.
103
+ Waiting for text you just typed matches its own echo, so pass
104
+ --match-after-input true, wait for output-only text or use --quiet.`;
105
+ /** Flags that take a value and may be given more than once. */
106
+ const REPEAT_FLAGS = new Set(['env-name']);
107
+ /** Flags that take a value; everything else `--x` is boolean. */
108
+ const VALUE_FLAGS = new Set([
109
+ 'label',
110
+ 'agent',
111
+ // Omitting a value-taking flag here does not fail loudly: the flag silently
112
+ // becomes boolean `true` and its VALUE becomes the first positional, i.e.
113
+ // the command to run, so `--purpose "Fix the failing login test"` would
114
+ // send that whole string to cmd.exe as a program name.
115
+ 'purpose',
116
+ 'cols',
117
+ 'rows',
118
+ 'cwd',
119
+ 'ready-text',
120
+ 'ready-quiet',
121
+ 'last',
122
+ 'text',
123
+ 'regex',
124
+ 'quiet',
125
+ 'timeout',
126
+ 'debounce',
127
+ 'match-after-input',
128
+ 'out',
129
+ 'width',
130
+ 'height',
131
+ ]);
132
+ /**
133
+ * `stopAtFirstPositional` is how `start` avoids eating the target command's
134
+ * own flags: `shellpuppet start [options] <command> [args...]`. Once the
135
+ * command appears, everything after it (including `--version`, `--help`,
136
+ * anything) belongs to the command verbatim: `start goose --version` hands
137
+ * `--version` to Goose.
138
+ */
139
+ function parseArgs(argv, stopAtFirstPositional = false) {
140
+ const positionals = [];
141
+ const flags = new Map();
142
+ const lists = new Map();
143
+ for (let i = 0; i < argv.length; i++) {
144
+ const arg = argv[i] ?? '';
145
+ if (!arg.startsWith('--') || (stopAtFirstPositional && positionals.length > 0)) {
146
+ positionals.push(arg);
147
+ continue;
148
+ }
149
+ const name = arg.slice(2);
150
+ if (REPEAT_FLAGS.has(name)) {
151
+ const value = argv[++i];
152
+ if (value === undefined)
153
+ fail(2, `--${name} needs a value.`);
154
+ lists.set(name, [...(lists.get(name) ?? []), value]);
155
+ }
156
+ else if (VALUE_FLAGS.has(name)) {
157
+ const value = argv[++i];
158
+ if (value === undefined)
159
+ fail(2, `--${name} needs a value.`);
160
+ flags.set(name, value);
161
+ }
162
+ else {
163
+ flags.set(name, true);
164
+ }
165
+ }
166
+ return { positionals, flags, lists };
167
+ }
168
+ function fail(code, message) {
169
+ console.error(message);
170
+ process.exit(code);
171
+ }
172
+ function intFlag(parsed, name) {
173
+ const raw = parsed.flags.get(name);
174
+ if (raw === undefined)
175
+ return undefined;
176
+ const value = Number(raw);
177
+ if (!Number.isInteger(value))
178
+ fail(2, `--${name} must be an integer.`);
179
+ return value;
180
+ }
181
+ const stderrLogger = {
182
+ debug: () => undefined,
183
+ info: () => undefined,
184
+ warn: (message) => console.error(`warning: ${message}`),
185
+ error: (message) => console.error(`error: ${message}`),
186
+ };
187
+ function surfaceWarnings(connection) {
188
+ for (const warning of connection.warnings)
189
+ console.error(`warning: ${warning}`);
190
+ }
191
+ async function call(connection, method, path, body) {
192
+ const response = await request(connection, method, path, body, {
193
+ logger: stderrLogger,
194
+ actor: 'cli',
195
+ });
196
+ const payload = response.body;
197
+ if (response.status >= 400) {
198
+ const message = typeof payload['error'] === 'string' ? payload['error'] : 'request failed';
199
+ // A 400 is the daemon refusing THIS caller's own input: an unparsable
200
+ // `--regex`, a grid outside the bounds, a `cwd` that is not one. That is
201
+ // the same kind of mistake as a flag this CLI rejects itself, so it gets
202
+ // the same exit code, and a script can tell "I asked wrongly" from "it
203
+ // did not work" without reading the message. Everything else, meaning
204
+ // 401, 403, 404, 409, 5xx and any transport failure, is the operation
205
+ // failing and stays 1.
206
+ fail(response.status === 400 ? 2 : 1, `error (${String(response.status)}): ${message}`);
207
+ }
208
+ return payload;
209
+ }
210
+ function printJson(value) {
211
+ console.log(JSON.stringify(value, null, 2));
212
+ }
213
+ async function main() {
214
+ assertNodeVersion();
215
+ const argv = process.argv.slice(2);
216
+ const verb = argv[0];
217
+ const parsed = parseArgs(argv.slice(1), verb === 'start');
218
+ const wantJson = parsed.flags.get('json') === true;
219
+ // `--help` and `-h` as the FIRST argument are answered here, with `help` and
220
+ // `--version`, before any daemon contact: the unknown-verb branch runs
221
+ // AFTER ensureDaemon(), and asking for help must not start a daemon.
222
+ if (verb === undefined ||
223
+ verb === 'help' ||
224
+ verb === '--help' ||
225
+ verb === '-h' ||
226
+ parsed.flags.get('help') === true) {
227
+ console.log(USAGE);
228
+ process.exit(verb === undefined ? 2 : 0);
229
+ }
230
+ if (verb === '--version' || verb === 'version') {
231
+ console.log(packageVersion());
232
+ process.exit(0);
233
+ }
234
+ if (verb === 'mcp') {
235
+ // The one long-running verb: importing the MCP entry starts a stdio MCP
236
+ // server that owns the process until its client disconnects. Nothing may
237
+ // touch stdout before the transport does.
238
+ await import('../mcp/index.js');
239
+ return;
240
+ }
241
+ if (verb === 'daemon') {
242
+ await daemonVerb(parsed, wantJson);
243
+ process.exit(0);
244
+ }
245
+ const connection = await ensureDaemon({ logger: stderrLogger });
246
+ surfaceWarnings(connection);
247
+ switch (verb) {
248
+ case 'start': {
249
+ const command = parsed.positionals[0];
250
+ if (command === undefined)
251
+ fail(2, 'start needs a command. See --help.');
252
+ const body = {
253
+ command,
254
+ args: parsed.positionals.slice(1),
255
+ ...(parsed.flags.has('label') ? { label: String(parsed.flags.get('label')) } : {}),
256
+ ...(parsed.flags.has('purpose') ? { purpose: String(parsed.flags.get('purpose')) } : {}),
257
+ ...(parsed.flags.has('agent') ? { agent: String(parsed.flags.get('agent')) } : {}),
258
+ ...(intFlag(parsed, 'cols') !== undefined ? { cols: intFlag(parsed, 'cols') } : {}),
259
+ ...(intFlag(parsed, 'rows') !== undefined ? { rows: intFlag(parsed, 'rows') } : {}),
260
+ ...(parsed.flags.has('cwd') ? { cwd: String(parsed.flags.get('cwd')) } : {}),
261
+ ...(parsed.flags.has('ready-text')
262
+ ? { readyText: String(parsed.flags.get('ready-text')) }
263
+ : {}),
264
+ ...(intFlag(parsed, 'ready-quiet') !== undefined
265
+ ? { readyQuiet: intFlag(parsed, 'ready-quiet') }
266
+ : {}),
267
+ ...(parsed.flags.get('no-shell') === true ? { shell: false } : {}),
268
+ ...(parsed.flags.get('hold') === true ? { hold: true } : {}),
269
+ ...(parsed.flags.get('no-viewer') === true ? { openViewer: false } : {}),
270
+ };
271
+ // The same lists and the same rules as terminal_start. The CLI reads
272
+ // 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 ?? []);
275
+ const envNames = parsed.lists.get('env-name') ?? [];
276
+ const plan = planPassedEnv({
277
+ agent,
278
+ requested: envNames,
279
+ agentLists: agentsConfig.config.agentPassEnv ?? {},
280
+ adHoc: envNames.length > 0 ? readMcpConfig(shellpuppetHome(), stderrLogger).passEnv : [],
281
+ environment: process.env,
282
+ source: "this shell's environment",
283
+ });
284
+ if (plan.refusedForAgent.length > 0) {
285
+ const names = plan.refusedForAgent;
286
+ fail(2, `Not started: this session runs as ${String(agent)}, whose variables come from ` +
287
+ `agents.passEnv.${String(agent)} in ~/.shellpuppet/config.json, and ` +
288
+ `${names.join(', ')} ${names.length === 1 ? 'is' : 'are'} not on it. List ` +
289
+ `${names.length === 1 ? 'it' : 'them'} there, or start without --env-name.`);
290
+ }
291
+ if (plan.refused.length > 0) {
292
+ 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'}.`);
297
+ }
298
+ if (agent !== null) {
299
+ for (const problem of agentsConfig.problems.filter((p) => p.startsWith('agents'))) {
300
+ console.error(`warning: ${problem}`);
301
+ }
302
+ }
303
+ if (Object.keys(plan.env).length > 0)
304
+ body['env'] = plan.env;
305
+ for (const note of plan.notes)
306
+ console.error(note);
307
+ const result = await call(connection, 'POST', '/sessions', body);
308
+ if (wantJson)
309
+ printJson(result);
310
+ else {
311
+ console.log(`${String(result['id'])} ${String(result['label'])}`);
312
+ const viewer = result['viewer'];
313
+ if (viewer?.opened === true) {
314
+ const how = viewer.reason !== undefined ? `, ${viewer.reason}` : '';
315
+ console.log(`viewer: window opened${how} (viewer-url ${String(result['id'])} mints a link)`);
316
+ }
317
+ else if (typeof result['viewerUrl'] === 'string') {
318
+ console.log(`viewer: ${result['viewerUrl']}`);
319
+ }
320
+ else {
321
+ console.log(`viewer: none opened (--no-viewer); viewer-url ${String(result['id'])} mints a link`);
322
+ }
323
+ if (result['ready'] !== true) {
324
+ console.log('ready: false. First paint is not readiness; wait before typing.');
325
+ }
326
+ }
327
+ break;
328
+ }
329
+ case 'list': {
330
+ const result = await call(connection, 'GET', '/sessions');
331
+ if (wantJson) {
332
+ printJson(result);
333
+ break;
334
+ }
335
+ const sessions = result['sessions'];
336
+ if (sessions.length === 0) {
337
+ console.log('no sessions');
338
+ break;
339
+ }
340
+ for (const s of sessions) {
341
+ console.log(`${s.id} ${s.exited ? `exited(${String(s.exitCode)})` : 'live'} ` +
342
+ `${String(s.cols)}x${String(s.rows)} watchers:${String(s.watchers)} ` +
343
+ `${s.ready ? 'ready' : 'NOT-READY'} ${s.label}` +
344
+ (s.agent !== null && s.agent !== undefined ? ` agent:${s.agent}` : ''));
345
+ const waiting = s.waitingOnPrompt;
346
+ if (waiting !== undefined) {
347
+ console.log(` WAITING ${String(Math.round(waiting.waitingMs / 1000))}s on a prompt: ` +
348
+ waiting.question);
349
+ }
350
+ }
351
+ break;
352
+ }
353
+ case 'snap': {
354
+ const id = parsed.positionals[0] ?? fail(2, 'snap needs a session id.');
355
+ const last = intFlag(parsed, 'last');
356
+ const query = [
357
+ ...(last !== undefined ? [`lastLines=${String(last)}`] : []),
358
+ ...(parsed.flags.get('hide-reasoning') === true ? ['hideReasoning=1'] : []),
359
+ ];
360
+ const path = `/sessions/${id}/snapshot${query.length > 0 ? `?${query.join('&')}` : ''}`;
361
+ const result = await call(connection, 'GET', path);
362
+ if (wantJson)
363
+ printJson(result);
364
+ else if (last !== undefined)
365
+ console.log(result['lastLines'].join('\n'));
366
+ else
367
+ console.log(String(result['screen']));
368
+ break;
369
+ }
370
+ case 'result': {
371
+ const id = parsed.positionals[0] ?? fail(2, 'result needs a session id.');
372
+ const result = await call(connection, 'GET', `/sessions/${id}/result`);
373
+ if (wantJson)
374
+ printJson(result);
375
+ else if (result['found'] === true) {
376
+ const lines = [
377
+ ...(result['answer'] ?? []),
378
+ ...(result['trailer'] ?? []),
379
+ ];
380
+ for (const line of lines)
381
+ console.log(line);
382
+ // The prompt it answers, on stderr: stdout stays the answer alone.
383
+ if (typeof result['prompt'] === 'string')
384
+ console.error(`in answer to: ${result['prompt'].trim()}`);
385
+ }
386
+ else
387
+ console.error(resultRefusal(String(result['reason'])));
388
+ if (result['found'] !== true)
389
+ process.exit(3);
390
+ break;
391
+ }
392
+ case 'type': {
393
+ const id = parsed.positionals[0] ?? fail(2, 'type needs a session id.');
394
+ const text = parsed.positionals[1] ?? fail(2, 'type needs text.');
395
+ const data = parsed.flags.get('enter') === true ? `${text}\r` : text;
396
+ const result = await call(connection, 'POST', `/sessions/${id}/input`, {
397
+ data,
398
+ ...(parsed.flags.get('verify') === true ? { verify: true } : {}),
399
+ });
400
+ if (wantJson)
401
+ printJson(result);
402
+ else if (result['verified'] === false) {
403
+ console.log('typed, but the text did NOT appear on screen. The app may still be ' +
404
+ 'loading, a panel may have focus or, commonly with --enter, the app ' +
405
+ 'accepted it and cleared the input box. Run `shellpuppet snap <id>` FIRST: ' +
406
+ 'if the agent is working, it landed. Escape resets focus but is CANCEL in ' +
407
+ 'agent CLIs, so do not reach for it before you have looked.');
408
+ process.exit(1);
409
+ }
410
+ else {
411
+ // Positive confirmation matters: with --verify the whole point is
412
+ // knowing the keystrokes landed, so say so rather than printing the
413
+ // same line as an unverified type.
414
+ console.log(`typed ${String(result['bytes'])} bytes` +
415
+ (result['verified'] === true ? ' (verified on screen).' : '.'));
416
+ }
417
+ break;
418
+ }
419
+ case 'key': {
420
+ const id = parsed.positionals[0] ?? fail(2, 'key needs a session id.');
421
+ const key = parsed.positionals[1] ?? fail(2, `key needs a key name: ${knownKeys().join(', ')}`);
422
+ const result = await call(connection, 'POST', `/sessions/${id}/key`, { key });
423
+ if (wantJson)
424
+ printJson(result);
425
+ else
426
+ console.log(`sent ${String(result['key'])}`);
427
+ break;
428
+ }
429
+ case 'wait': {
430
+ const id = parsed.positionals[0] ?? fail(2, 'wait needs a session id.');
431
+ const params = new URLSearchParams();
432
+ for (const name of ['text', 'regex', 'quiet', 'timeout', 'debounce', 'prompt']) {
433
+ const value = parsed.flags.get(name);
434
+ if (value !== undefined)
435
+ params.set(name, String(value));
436
+ }
437
+ const afterInput = parsed.flags.get('match-after-input');
438
+ if (afterInput !== undefined)
439
+ params.set('matchAfterInput', String(afterInput));
440
+ if (parsed.flags.get('hide-reasoning') === true)
441
+ params.set('hideReasoning', '1');
442
+ const result = await call(connection, 'GET', `/sessions/${id}/wait?${params.toString()}`);
443
+ if (wantJson)
444
+ printJson(result);
445
+ else {
446
+ console.error(`${result['matched'] === true ? 'matched' : 'NOT matched'} ` +
447
+ `(${String(result['reason'])}, ${String(result['waitedMs'])} ms)`);
448
+ // The waiter's own explanation of a non-match ("has not painted
449
+ // anything yet"), when it has one. It goes to stderr, with the outcome
450
+ // line.
451
+ if (typeof result['detail'] === 'string')
452
+ console.error(result['detail']);
453
+ const detected = result['prompt'];
454
+ if (detected !== undefined) {
455
+ // stderr, like the outcome line: stdout stays the screen alone, so
456
+ // piping `wait` into a file or a diff keeps working unchanged.
457
+ console.error(`prompt: ${detected.question}`);
458
+ // No re-numbering: the options are captured verbatim and already
459
+ // carry the numbers the TUI drew, so counting again gives
460
+ // "1. 1. Allow once", and the number the human must press is the
461
+ // program's, not ours.
462
+ for (const option of detected.options)
463
+ console.error(` ${option}`);
464
+ }
465
+ console.log(String(result['screen']));
466
+ }
467
+ if (result['matched'] !== true)
468
+ process.exit(3);
469
+ break;
470
+ }
471
+ case 'find': {
472
+ const id = parsed.positionals[0] ?? fail(2, 'find needs a session id.');
473
+ const pattern = parsed.positionals[1] ?? fail(2, 'find needs a pattern.');
474
+ const result = await call(connection, 'GET', `/sessions/${id}/find?pattern=${encodeURIComponent(pattern)}` +
475
+ (parsed.flags.get('hide-reasoning') === true ? '&hideReasoning=1' : ''));
476
+ const matches = result['matches'];
477
+ if (wantJson)
478
+ printJson(result);
479
+ else {
480
+ // stdout holds matching lines and nothing else, so a script reads the
481
+ // verdict from the exit code and never from the wording.
482
+ for (const m of matches)
483
+ console.log(`${String(m.line)}: ${m.text}`);
484
+ if (matches.length === 0)
485
+ console.error(NO_MATCHES);
486
+ if (result['truncated'] === true)
487
+ console.error('warning: matches truncated at 100');
488
+ }
489
+ if (matches.length === 0)
490
+ process.exit(3);
491
+ break;
492
+ }
493
+ case 'screenshot': {
494
+ const id = parsed.positionals[0] ?? fail(2, 'screenshot needs a session id.');
495
+ const out = parsed.flags.has('out')
496
+ ? String(parsed.flags.get('out'))
497
+ : `shellpuppet-${id}.png`;
498
+ const result = await call(connection, 'POST', `/sessions/${id}/screenshot`, {
499
+ ...(intFlag(parsed, 'width') !== undefined ? { width: intFlag(parsed, 'width') } : {}),
500
+ ...(intFlag(parsed, 'height') !== undefined ? { height: intFlag(parsed, 'height') } : {}),
501
+ ...(intFlag(parsed, 'timeout') !== undefined
502
+ ? { timeoutMs: intFlag(parsed, 'timeout') }
503
+ : {}),
504
+ });
505
+ const png = Buffer.from(String(result['png']), 'base64');
506
+ await writeFile(out, png);
507
+ if (wantJson)
508
+ printJson({ ...result, png: `<${String(png.length)} bytes>`, path: resolve(out) });
509
+ else {
510
+ console.log(resolve(out));
511
+ console.log(`${String(result['width'])}x${String(result['height'])} px, ` +
512
+ `grid ${String(result['cols'])}x${String(result['rows'])}, ` +
513
+ `${String(png.length)} bytes`);
514
+ }
515
+ break;
516
+ }
517
+ case 'viewer-url': {
518
+ const id = parsed.positionals[0] ?? fail(2, 'viewer-url needs a session id.');
519
+ const readOnly = parsed.flags.get('read-only') === true;
520
+ const result = await call(connection, 'POST', `/sessions/${id}/viewer`, { readOnly });
521
+ if (wantJson)
522
+ printJson(result);
523
+ else {
524
+ const minutes = Math.round(Number(result['expiresInMs']) / 60_000);
525
+ console.log(String(result['viewerUrl']));
526
+ console.log(`${result['readOnly'] === true ? 'watch-only' : 'watch and type'}, single use, ` +
527
+ `expires in about ${String(minutes)} min`);
528
+ }
529
+ break;
530
+ }
531
+ case 'resize': {
532
+ const id = parsed.positionals[0] ?? fail(2, 'resize needs a session id.');
533
+ const cols = Number(parsed.positionals[1]);
534
+ const rows = Number(parsed.positionals[2]);
535
+ if (!Number.isInteger(cols) || !Number.isInteger(rows)) {
536
+ fail(2, 'resize needs integer cols and rows.');
537
+ }
538
+ const hold = parsed.flags.get('hold') === true;
539
+ const result = await call(connection, 'POST', `/sessions/${id}/resize`, {
540
+ cols,
541
+ rows,
542
+ hold,
543
+ });
544
+ if (wantJson)
545
+ printJson(result);
546
+ else {
547
+ console.log(`resized to ${String(result['cols'])}x${String(result['rows'])}` +
548
+ (result['geometryHeld'] === true ? ' (held against the viewer)' : ''));
549
+ }
550
+ break;
551
+ }
552
+ case 'kill': {
553
+ const id = parsed.positionals[0] ?? fail(2, 'kill needs a session id.');
554
+ const result = await call(connection, 'DELETE', `/sessions/${id}`);
555
+ if (wantJson)
556
+ printJson(result);
557
+ else
558
+ console.log(`killed ${String(result['killed'])} (whole process tree)`);
559
+ break;
560
+ }
561
+ default:
562
+ fail(2, `Unknown verb: ${verb}. See --help.`);
563
+ }
564
+ process.exit(0);
565
+ }
566
+ async function daemonVerb(parsed, wantJson) {
567
+ const sub = parsed.positionals[0];
568
+ const force = parsed.flags.get('force') === true;
569
+ const stopRunning = async (connection) => {
570
+ const response = await request(connection, 'POST', '/daemon/shutdown', { force }, {
571
+ logger: stderrLogger,
572
+ actor: 'cli',
573
+ });
574
+ if (response.status === 409) {
575
+ fail(1, `${String(response.body['error'])} (use --force)`);
576
+ }
577
+ // Wait for the port to actually go quiet so restart cannot race it.
578
+ const deadline = Date.now() + 10_000;
579
+ while (Date.now() < deadline) {
580
+ try {
581
+ await fetch(`http://127.0.0.1:${String(connection.port)}/health`, {
582
+ signal: AbortSignal.timeout(400),
583
+ });
584
+ await new Promise((resolve) => setTimeout(resolve, 150));
585
+ }
586
+ catch {
587
+ return;
588
+ }
589
+ }
590
+ fail(1, 'daemon did not stop within 10 s. Check daemon.log.');
591
+ };
592
+ switch (sub) {
593
+ case 'status': {
594
+ const connection = await discoverDaemon({ logger: stderrLogger });
595
+ if (connection === null) {
596
+ console.log(wantJson ? JSON.stringify({ running: false }) : 'not running');
597
+ return;
598
+ }
599
+ surfaceWarnings(connection);
600
+ const sessions = await call(connection, 'GET', '/sessions');
601
+ const list = sessions['sessions'];
602
+ // What sessions inherit (ADR-008). A daemon that cannot say is left out
603
+ // of the report rather than failing it.
604
+ const environment = await request(connection, 'GET', '/environment', undefined, {
605
+ logger: stderrLogger,
606
+ actor: 'cli',
607
+ })
608
+ .then((response) => response.status === 200 ? response.body : undefined)
609
+ .catch(() => undefined);
610
+ if (wantJson) {
611
+ printJson({
612
+ running: true,
613
+ port: connection.port,
614
+ version: connection.version,
615
+ sessions: list,
616
+ ...(environment !== undefined ? { sessionEnv: environment } : {}),
617
+ });
618
+ }
619
+ else {
620
+ console.log(`running on port ${String(connection.port)}, version ${connection.version}, ` +
621
+ `${String(list.length)} session(s)` +
622
+ (environment !== undefined ? `, session environment ${environment.mode}` : ''));
623
+ if (environment !== undefined && environment.exposed.length > 0) {
624
+ console.error(`warning: sessionEnv "passthrough" hands every session the daemon's whole ` +
625
+ `environment, including ${String(environment.exposed.length)} variable(s) ` +
626
+ `whose names look like credentials: ${environment.exposed.join(', ')}`);
627
+ }
628
+ }
629
+ return;
630
+ }
631
+ // `--help` says every verb accepts --json, so these three answer in JSON
632
+ // when asked, and a script driving the daemon need not parse English.
633
+ case 'start': {
634
+ const existing = await discoverDaemon({ logger: stderrLogger });
635
+ if (existing !== null) {
636
+ surfaceWarnings(existing);
637
+ if (wantJson) {
638
+ printJson({ running: true, port: existing.port, version: existing.version });
639
+ }
640
+ else
641
+ console.log(`already running on port ${String(existing.port)}`);
642
+ return;
643
+ }
644
+ const connection = await ensureDaemon({ logger: stderrLogger });
645
+ surfaceWarnings(connection);
646
+ if (wantJson) {
647
+ printJson({ running: true, port: connection.port, version: connection.version });
648
+ }
649
+ else {
650
+ console.log(`started on port ${String(connection.port)}, version ${connection.version}`);
651
+ }
652
+ return;
653
+ }
654
+ case 'stop': {
655
+ const connection = await discoverDaemon({ logger: stderrLogger });
656
+ if (connection === null) {
657
+ // Nothing to stop IS the outcome asked for, so it reads the same to a
658
+ // script as a daemon that was stopped.
659
+ if (wantJson)
660
+ printJson({ running: false, stopped: true });
661
+ else
662
+ console.log('not running');
663
+ return;
664
+ }
665
+ await stopRunning(connection);
666
+ if (wantJson)
667
+ printJson({ running: false, stopped: true });
668
+ else
669
+ console.log('stopped');
670
+ return;
671
+ }
672
+ case 'restart': {
673
+ const existing = await discoverDaemon({ logger: stderrLogger });
674
+ if (existing !== null)
675
+ await stopRunning(existing);
676
+ const connection = await ensureDaemon({ logger: stderrLogger });
677
+ surfaceWarnings(connection);
678
+ if (wantJson) {
679
+ printJson({ running: true, port: connection.port, version: connection.version });
680
+ }
681
+ else {
682
+ console.log(`restarted on port ${String(connection.port)}, version ${connection.version}`);
683
+ }
684
+ return;
685
+ }
686
+ default:
687
+ fail(2, 'daemon needs one of: status, start, stop [--force], restart [--force]');
688
+ }
689
+ }
690
+ main().catch((error) => {
691
+ fail(1, error instanceof Error ? error.message : String(error));
692
+ });
693
+ //# sourceMappingURL=index.js.map