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,311 @@
1
+ /**
2
+ * One PTY session: process + renderer + lifecycle (design §2.4).
3
+ *
4
+ * The session owns the real PTY (ConPTY on Windows), keeps the headless
5
+ * renderer current, serialises that renderer for viewers, tracks readiness
6
+ * and kills the whole process tree on demand (design §3.1), not just the PTY
7
+ * child.
8
+ *
9
+ * Shell wrapping happens HERE, after the caller has already made its policy
10
+ * decision against the pre-wrap command (design §4.3). Callers pass
11
+ * `goose session`; this module turns it into `cmd.exe /c goose session` on
12
+ * Windows because direct ConPTY spawns of single-file binaries hang (§7).
13
+ *
14
+ * No stdout/stderr: logging via the injected Logger only (lint-enforced).
15
+ */
16
+ import type { SerializeOptions, StyledLine } from './renderer.js';
17
+ import type { WaitTarget } from './waiter.js';
18
+ import type { Logger, ScreenSnapshot, SessionEnvMode, SessionOptions, SessionSummary, WaitCondition, WaitOptions, WaitResult } from './types.js';
19
+ /**
20
+ * Hard cap on `taskkill`. Without it a wedged kill never calls back, so
21
+ * `kill()` never resolves, `killAll()` never resolves and daemon shutdown
22
+ * never completes. The daemon then becomes an immortal, undiscoverable
23
+ * process the user can only end via Task Manager.
24
+ *
25
+ * **Why 30 s.** On a real Qoder CLI tree (78 descendants, because it spawns
26
+ * an MCP-server fleet) `taskkill /T /F` took **5,433 ms**. A cap tighter than
27
+ * a normal kill cuts the walk short and leaves the tree to the `pty.kill()`
28
+ * fallback below, the path that cannot reach console-detached descendants.
29
+ * The cap exists to bound the wedged case, not to be tighter than the normal
30
+ * case.
31
+ */
32
+ export declare const TREE_KILL_TIMEOUT_MS = 30000;
33
+ /** What a `taskkill` run reported when it did not simply succeed. */
34
+ export interface TreeKillFailure {
35
+ /** Our timeout fired and `taskkill` was terminated mid-walk. */
36
+ timedOut: boolean;
37
+ exitCode: number | string | null;
38
+ elapsedMs: number;
39
+ }
40
+ /**
41
+ * Tree-kill processes with one `taskkill /T /F` run (Windows). Resolves with
42
+ * null on success and with what went wrong otherwise; never rejects.
43
+ */
44
+ export type TreeKiller = (pids: readonly number[]) => Promise<TreeKillFailure | null>;
45
+ /**
46
+ * One `taskkill` run for any number of trees. Every run enumerates every
47
+ * process on the machine before it kills anything, and that is most of its
48
+ * cost. Measured on a Windows machine running about 2,700 processes: 9 to
49
+ * 13 s for one lone process; thirty concurrent runs, one per session, each
50
+ * overran the 30 s cap; one run given all thirty pids took 10 s. So daemon
51
+ * shutdown kills every tree in one run (`SessionManager.killAll`).
52
+ */
53
+ export declare const taskkillTrees: TreeKiller;
54
+ /**
55
+ * Whether the cursor is hidden after this chunk of program output, given
56
+ * whether it was before. The LAST transition in the chunk wins (a TUI
57
+ * re-asserts its modes on every redraw). A reset counts as showing, because
58
+ * both kinds show the cursor (see TERMINAL_RESET).
59
+ */
60
+ export declare function cursorHiddenAfter(scan: string, current: boolean): boolean;
61
+ /**
62
+ * Whether bracketed paste (DEC 2004) is on after this chunk of program
63
+ * output, given whether it was before. The twin of `cursorHiddenAfter`, and
64
+ * for the same reason: the emulator the daemon mirrors turns the mode OFF on
65
+ * a reset, so this scan does too. In @xterm/headless both RIS (`ESC c`) and
66
+ * DECSTR (`ESC [ ! p`) reach `CoreService.reset()`, which puts the DEC
67
+ * private modes back to their defaults, where bracketed paste is false.
68
+ *
69
+ * After a reset the program does not expect paste markers, and would read
70
+ * `ESC[200~` and `ESC[201~` around a long write as literal input. The last
71
+ * transition in the chunk wins, as above: a TUI re-asserts its modes on
72
+ * every redraw.
73
+ */
74
+ export declare function bracketedPasteAfter(scan: string, current: boolean): boolean;
75
+ /** A bare command name that is not on PATH: a caller error, mapped to 400. */
76
+ export declare class CommandNotFoundError extends Error {
77
+ constructor(message: string);
78
+ }
79
+ export interface SessionDeps {
80
+ logger?: Logger;
81
+ /** Platform override, for tests only. Defaults to `process.platform`. */
82
+ platform?: NodeJS.Platform;
83
+ /** Environment hygiene mode (design §4.6). Defaults to `DEFAULT_SESSION_ENV`. */
84
+ sessionEnv?: SessionEnvMode;
85
+ /** Windows tree killer override, for tests only. Defaults to `taskkillTrees`. */
86
+ treeKiller?: TreeKiller;
87
+ }
88
+ /**
89
+ * A session gets the clean baseline unless the configuration says otherwise
90
+ * (ADR-008): the daemon's environment is whatever the client that auto-started
91
+ * it had, so passing it on would hand that client's secrets to every session.
92
+ */
93
+ export declare const DEFAULT_SESSION_ENV: SessionEnvMode;
94
+ /**
95
+ * The names (never the values) of variables in `source` whose names look like
96
+ * credentials, sorted: part of what `passthrough` would hand every session.
97
+ */
98
+ export declare function credentialShapedNames(source?: NodeJS.ProcessEnv): string[];
99
+ /**
100
+ * Build the PTY environment for a session. Variable-name matching is
101
+ * case-insensitive on every platform: Windows environment names are, and a
102
+ * list in the configuration means the same wherever the daemon runs.
103
+ *
104
+ * An explicit allowlist is the CLEAN baseline plus the listed names: a bare
105
+ * list would strip system scaffolding that processes need to start at all
106
+ * (verified: node.exe aborts in CSPRNG initialisation without `SystemRoot` on
107
+ * Windows), and "functional minimum plus exactly what you name" is the intent
108
+ * of the mode: naming secrets in, not naming plumbing.
109
+ *
110
+ * `passed` is the session's own variables from the client that started it
111
+ * (`SessionOptions.env`), set on top of whatever the mode gave. On Windows a
112
+ * passed name replaces the inherited variable of the same name in any case,
113
+ * rather than sitting beside it as a second copy.
114
+ */
115
+ export declare function buildSessionEnv(mode: SessionEnvMode, platform: NodeJS.Platform, source?: NodeJS.ProcessEnv, passed?: Record<string, string>): Record<string, string>;
116
+ export declare class Session implements WaitTarget {
117
+ readonly id: string;
118
+ readonly label: string;
119
+ /** What this session is for, for the human watching it. */
120
+ readonly purpose: string;
121
+ /** The audit actor that started it: set by the daemon, not by the body. */
122
+ readonly startedBy: string;
123
+ /** The pre-wrap command as given by the caller. */
124
+ readonly command: string;
125
+ readonly args: string[];
126
+ /** The agent it was started as, which chooses how its screen is read. */
127
+ readonly agent: string | undefined;
128
+ readonly createdAt: Date;
129
+ private readonly pty;
130
+ private readonly renderer;
131
+ private readonly logger;
132
+ private readonly platform;
133
+ private readonly treeKiller;
134
+ /** Whether the program has bracketed paste (DEC 2004) enabled. See PASTE_START. */
135
+ private bracketedPaste;
136
+ /**
137
+ * Whether the most recent `write` took the bracketed-paste branch.
138
+ * Diagnostic only. A program that enabled bracketed paste can still report
139
+ * no markers, and from outside the two causes cannot be told apart: we
140
+ * wrapped and the transport stripped the markers off the input (ConPTY
141
+ * can), or the write raced ahead of the flag. This says which.
142
+ */
143
+ lastWriteWrapped: boolean | null;
144
+ /** Trailing output kept so a mode sequence split across PTY reads is still seen. */
145
+ private modeScanTail;
146
+ private readonly dataListeners;
147
+ private readonly exitListeners;
148
+ /** Whether the program has hidden the cursor (DECTCEM off), carried to viewers. */
149
+ private cursorHidden;
150
+ /** Serialises write() so chunked writes cannot interleave. See write(). */
151
+ private writeChain;
152
+ private lastChange;
153
+ /** Sticky: the rendered screen has shown something at least once. */
154
+ private painted;
155
+ /**
156
+ * The last input written, for the waiter's echo guard. Memory only, never
157
+ * logged: §4.5 keeps keystroke content out of the audit trail, and this
158
+ * is one string overwritten by the next write.
159
+ */
160
+ private lastInputData;
161
+ /** Which prompt the last input answered, and whether it has since gone. */
162
+ private readonly stalePrompts;
163
+ private exitedFlag;
164
+ private exitedAtValue;
165
+ private exitCodeValue;
166
+ private readyFlag;
167
+ private readyReasonValue;
168
+ private geometryHeldFlag;
169
+ private killed;
170
+ constructor(id: string, options: SessionOptions, deps?: SessionDeps);
171
+ /**
172
+ * Windows default: wrap in `cmd.exe` (§7: direct ConPTY spawns of
173
+ * single-file binaries hang). POSIX default: direct spawn; `shell: true`
174
+ * wraps in `/bin/sh -c`.
175
+ *
176
+ * The Windows form is `cmd.exe /d /s /c "<line>"` passed as a VERBATIM
177
+ * string (node-pty applies no quoting to string args). `/s` pins cmd's
178
+ * strip-first-and-last-quote behaviour so the outer quotes vanish cleanly
179
+ * and every quote inside `<line>` survives. Without it, a command path
180
+ * containing spaces (e.g. `C:\Program Files\nodejs\node.exe`) is split at
181
+ * the first space. This is the same invocation libuv uses for shell spawns.
182
+ */
183
+ private wrapCommand;
184
+ get pid(): number;
185
+ get cols(): number;
186
+ get rows(): number;
187
+ get ready(): boolean;
188
+ /** Why `ready` holds its value. See {@link SessionSummary.readyReason}. */
189
+ get readyReason(): SessionSummary['readyReason'];
190
+ /**
191
+ * True only when the grid is HELD: `hold` at start, or a resize that asked
192
+ * for it. A held grid keeps its size while viewports connect and reshape
193
+ * themselves around it; an unheld grid belongs to the controlling viewport,
194
+ * which fits it to the human's window (design §5).
195
+ */
196
+ get geometryHeld(): boolean;
197
+ get exited(): boolean;
198
+ /** Epoch ms of process exit: the manager's reap grace counts from here. */
199
+ get exitedAt(): number | null;
200
+ get exitCode(): number | null;
201
+ get watchers(): number;
202
+ getScreen(): string;
203
+ lastChangeAt(): number;
204
+ isExited(): boolean;
205
+ hasPainted(): boolean;
206
+ lastInput(): string | null;
207
+ observePrompt(signature: string | null): void;
208
+ isStalePrompt(signature: string): boolean;
209
+ /**
210
+ * Write to the PTY the way the program on the other end asked to be written
211
+ * to: as a bracketed paste when it enabled that mode, otherwise chunked.
212
+ *
213
+ * Anything under WRITE_CHUNK_CHARS goes straight through either way, so keys
214
+ * and human typing are unaffected. Above it the two paths diverge, and the
215
+ * divergence is the point. See PASTE_START for the evidence that chunking a
216
+ * TUI's input is what loses the front of a long prompt.
217
+ *
218
+ * **Writes are serialised.** The chunked path yields between pieces, and this
219
+ * tool's whole premise is that a human and an agent share one session. So
220
+ * without a queue a keystroke (or a multi-character paste, which is what xterm
221
+ * hands us for a clipboard drop) could land *between* an earlier write's
222
+ * chunks and interleave two inputs into gibberish. Making that ordering the
223
+ * caller's problem would be a trap; the queue keeps writes in call order,
224
+ * as a synchronous write would.
225
+ *
226
+ * Resolves with the screen as it was rendered just before this input went
227
+ * in, taken in the queue, so an earlier write still going in cannot be
228
+ * mistaken for this one's effect (`terminal_type`'s verify compares with it).
229
+ */
230
+ write(data: string): Promise<string>;
231
+ private writeInput;
232
+ /**
233
+ * Resize the PTY.
234
+ *
235
+ * Every caller arrives here, a viewport whose window changed shape and an
236
+ * agent asking for a specific grid alike, because the resize itself is the
237
+ * same act either way. What differs is only whether the caller also means to stop
238
+ * anyone else changing it, and that is said explicitly with `hold` rather
239
+ * than inferred from who is calling. Omitting `hold` leaves the current
240
+ * setting alone, so a viewport following a window cannot quietly release a
241
+ * hold that a scripted run is relying on.
242
+ */
243
+ resize(cols: number, rows: number, options?: {
244
+ hold?: boolean;
245
+ }): void;
246
+ /** Live raw-stream subscription (viewer mirroring). Returns unsubscribe. */
247
+ onData(listener: (data: string) => void): () => void;
248
+ onExit(listener: (exitCode: number) => void): () => void;
249
+ /**
250
+ * The rendered terminal as bytes that rebuild it in a fresh terminal of the
251
+ * same size (design §5): what a viewer receives on connect and after every
252
+ * grid change, in place of any slice of the raw stream. A slice starts
253
+ * mid-frame, and a program that only repaints what changed never puts the
254
+ * rest of its frame back. Every agent CLI repaints that way once its chrome
255
+ * is up, and on Windows every program does as ConPTY relays it. Resolves
256
+ * once every byte received before the call has been parsed, and includes
257
+ * nothing received after it.
258
+ */
259
+ viewerState(options?: SerializeOptions): Promise<string>;
260
+ snapshot(): Promise<ScreenSnapshot>;
261
+ /** Last N lines including scrollback (design §3). */
262
+ lastLines(count: number): Promise<string[]>;
263
+ /** Current viewport lines (for `terminal_find`). */
264
+ viewportLines(): Promise<string[]>;
265
+ /**
266
+ * The viewport with `above` lines of scrollback over it, as drawn
267
+ * (`reasoning.ts`). `firstVisible` is where the viewport begins.
268
+ */
269
+ styledScreen(above?: number): Promise<{
270
+ lines: StyledLine[];
271
+ firstVisible: number;
272
+ }>;
273
+ /**
274
+ * The last `count` lines, scrollback included, as drawn, with up to
275
+ * `context` more lines over them; `firstVisible` is where the `count` begin.
276
+ */
277
+ styledTail(count: number, context?: number): Promise<{
278
+ lines: StyledLine[];
279
+ firstVisible: number;
280
+ }>;
281
+ waitFor(condition: WaitCondition, options?: WaitOptions): Promise<WaitResult>;
282
+ summary(): SessionSummary;
283
+ /**
284
+ * Kill the whole process tree (design §3.1). Commands are shell-wrapped, so
285
+ * killing only the direct child (`cmd.exe`) strands the real application,
286
+ * and orphaned agent CLIs keep running and keep spending paid API tokens.
287
+ *
288
+ * Windows: `taskkill /T /F` walks and kills the tree; closing the ConPTY via
289
+ * `pty.kill()` also sends CTRL_CLOSE_EVENT to console-attached
290
+ * survivors. (The design's Job Object hardening needs a native module and is
291
+ * deferred. If the daemon itself dies, its ConPTY handles close, which gives
292
+ * console-attached descendants the same close signal.)
293
+ *
294
+ * POSIX: the PTY child is the session leader of its own process group, so
295
+ * signalling the negated pid takes the group down.
296
+ *
297
+ * The OS tree kill runs only while the root is still alive. A session whose
298
+ * program exited on its own is reaped fifteen minutes later, and by then the
299
+ * process group id may have been recycled, so an unconditional `kill(-pid)`
300
+ * could take down something unrelated; on Windows `taskkill` cannot walk a
301
+ * tree from a dead root either. So a grandchild that outlived its parent is
302
+ * left alone rather than guessed at, a residual risk stated in
303
+ * `docs/reference/security-model.md`.
304
+ */
305
+ kill(): Promise<void>;
306
+ /**
307
+ * Cheap liveness probe: signal 0 performs the permission and existence
308
+ * checks without delivering a signal, on Windows as well as POSIX.
309
+ */
310
+ private processAlive;
311
+ }