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,317 @@
1
+ /**
2
+ * Wait predicates: block until a condition holds on a live screen.
3
+ *
4
+ * The single most important primitive for reliable terminal automation: stop
5
+ * guessing at sleeps (design §3.1). Supports text, regex and quiescence
6
+ * conditions, terminated by process exit or timeout.
7
+ *
8
+ * Pure logic over an abstract target. No I/O; timers only. The daemon adapts a
9
+ * session to `WaitTarget`.
10
+ */
11
+ import { DEFAULT_WAIT_TIMEOUT_MS, MAX_WAIT_TIMEOUT_MS, WAIT_POLL_INTERVAL_MS, } from './types.js';
12
+ import { detectPrompt } from './promptDetector.js';
13
+ import { echoEnd } from './echo.js';
14
+ import { RegexBudgetError, withRegexBudget } from './regexBudget.js';
15
+ /** Thrown for caller mistakes: bad condition shape or an unparsable regex. */
16
+ export class WaitConditionError extends Error {
17
+ constructor(message) {
18
+ super(message);
19
+ this.name = 'WaitConditionError';
20
+ }
21
+ }
22
+ /**
23
+ * Resolve when the condition holds, the process exits or the timeout lapses.
24
+ * Never rejects for runtime reasons: the result's `matched`/`reason` carry the
25
+ * outcome, because "it timed out" is an answer, not an error. It rejects only
26
+ * for the caller's own mistakes: a malformed condition, which throws
27
+ * synchronously, and a pattern that overruns its evaluation budget, which
28
+ * cannot be known until it is run and so rejects (`regexBudget.ts`). Both are
29
+ * `WaitConditionError`, which the daemon answers with a 400.
30
+ *
31
+ * Semantics worth knowing:
32
+ * - `text` is a case-insensitive substring match; `regex` is case-insensitive.
33
+ * - **The echo trap:** matching text you have just typed matches the *echo* of
34
+ * the input (measured at 0 ms), not the program's output. By default the
35
+ * waiter does not tell them apart, so wait on output-only text or use
36
+ * `quiet`. `matchAfterInput: true` closes the trap: matches at or before the
37
+ * echo of the last input are ignored (see `echo.ts` for how the echo is
38
+ * placed, and when it cannot be). Both behaviours are tested.
39
+ * - `quiet` holds once the program has PAINTED something and then produced no
40
+ * output for the given time. A program that has never painted is not quiet,
41
+ * it is not started: silence counted from session creation would report a
42
+ * CLI ready before its first byte, and a prompt typed on that false ready
43
+ * would be discarded. A test pins this.
44
+ * - `debounce` (text/regex/prompt): after the first match, keep polling until
45
+ * the screen has been stable for that long, so a mid-paint TUI can settle.
46
+ * The match is not re-checked after settling: it appeared, which is what
47
+ * was asked. The overall timeout still applies while settling.
48
+ * - `prompt` resolves as soon as a permission prompt is on screen, INCLUDING
49
+ * one already there when the wait began. It means "wait until a prompt is
50
+ * showing", not "wait for the next one". There is one exception, on by
51
+ * default: the prompt that was showing when the caller's last input was
52
+ * sent is treated as answered until the screen has been seen without it
53
+ * (`StalePromptGuard`). A supervision loop that has just answered one
54
+ * prompt gets the NEXT one, never the one it answered on a screen
55
+ * the program has not yet repainted. `matchAfterInput: false` restores the
56
+ * plain rule.
57
+ * - Match is checked before exit: an exited process whose final screen contains
58
+ * the target still reports the match.
59
+ */
60
+ export function waitFor(target, condition, options = {}) {
61
+ const provided = [
62
+ condition.text !== undefined,
63
+ condition.regex !== undefined,
64
+ condition.quiet !== undefined,
65
+ condition.prompt === true,
66
+ ].filter(Boolean).length;
67
+ if (provided !== 1) {
68
+ throw new WaitConditionError(`Exactly one of text, regex, quiet or prompt must be provided (got ${String(provided)}).`);
69
+ }
70
+ if (condition.quiet !== undefined && (!Number.isFinite(condition.quiet) || condition.quiet < 0)) {
71
+ throw new WaitConditionError('quiet must be a non-negative number of milliseconds.');
72
+ }
73
+ // timeout/debounce get the same scrutiny as quiet. A NaN timeout (the CLI's
74
+ // `--timeout abc` becomes Number('abc')) would make the deadline comparison
75
+ // below permanently false: the wait, and the one-shot client awaiting the
76
+ // HTTP response, would hang forever, the exact failure class this project
77
+ // exists to eliminate. A NaN debounce would instead never "settle" and
78
+ // mislabel a real match as a timeout.
79
+ if (options.timeout !== undefined &&
80
+ (!Number.isFinite(options.timeout) || options.timeout < 0)) {
81
+ throw new WaitConditionError('timeout must be a non-negative number of milliseconds.');
82
+ }
83
+ if (options.debounce !== undefined &&
84
+ (!Number.isFinite(options.debounce) || options.debounce < 0)) {
85
+ throw new WaitConditionError('debounce must be a non-negative number of milliseconds.');
86
+ }
87
+ // Both text and regex compile to a global, case-insensitive pattern so that
88
+ // a search can start at an offset (the echo guard below) without
89
+ // lowercasing the screen, which can change its length for some Unicode
90
+ // and misalign every offset. `text` is escaped, so it stays a plain
91
+ // substring match.
92
+ let pattern = null;
93
+ let patternReason = 'text';
94
+ /** What to name in a budget refusal: the caller's own words for it. */
95
+ let patternSource = condition.text ?? '';
96
+ if (condition.regex !== undefined) {
97
+ patternSource = condition.regex;
98
+ try {
99
+ // Multiline: the screen is lines joined with \n, and `^42` written by a
100
+ // caller means "a line starting with 42", the same per-line semantics
101
+ // terminal_find has. Without `m` the anchor silently binds to the start
102
+ // of the whole screen and never matches.
103
+ pattern = new RegExp(condition.regex, 'gim');
104
+ patternReason = 'regex';
105
+ }
106
+ catch (cause) {
107
+ throw new WaitConditionError(`Invalid regular expression: ${condition.regex} (${String(cause)})`);
108
+ }
109
+ }
110
+ else if (condition.text !== undefined) {
111
+ pattern = new RegExp(condition.text.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'), 'gi');
112
+ }
113
+ /**
114
+ * Index of the first match at or after `from`, or -1.
115
+ *
116
+ * A caller's own regex runs under a budget, because a pattern that
117
+ * backtracks catastrophically blocks the event loop for longer than this
118
+ * wait's own timeout: the poll timer that would give up never gets to run,
119
+ * and neither does anything else the daemon owes anyone (see
120
+ * `regexBudget.ts`). Per evaluation, not per wait: a screen the pattern
121
+ * copes with costs nothing, and one it does not is refused the moment it
122
+ * appears.
123
+ *
124
+ * A `text` condition is not bounded and does not need to be: it is escaped
125
+ * into a literal above, which has no quantifiers to backtrack through, and
126
+ * a wait can poll thousands of times before its deadline.
127
+ */
128
+ const bounded = condition.regex !== undefined;
129
+ const matchAt = (screen, from) => {
130
+ if (pattern === null)
131
+ return -1;
132
+ const search = () => {
133
+ pattern.lastIndex = from;
134
+ return pattern.exec(screen);
135
+ };
136
+ const found = bounded ? withRegexBudget(patternSource, search) : search();
137
+ return found === null ? -1 : found.index;
138
+ };
139
+ // Default: on for prompt (a supervisor never wants the question it has
140
+ // just answered handed back), off for text/regex (an opt-in guard).
141
+ const afterInput = options.matchAfterInput ?? condition.prompt === true;
142
+ const timeoutMs = Math.min(Math.max(options.timeout ?? DEFAULT_WAIT_TIMEOUT_MS, 0), MAX_WAIT_TIMEOUT_MS);
143
+ const debounceMs = Math.max(options.debounce ?? 0, 0);
144
+ const pollMs = options.pollIntervalMs ?? WAIT_POLL_INTERVAL_MS;
145
+ const startedAt = Date.now();
146
+ let matchedAt = null;
147
+ let matchedReason = null;
148
+ let matchedPrompt = null;
149
+ /** Last tick: the only prompt on screen was the one the last input answered. */
150
+ let staleOnly = false;
151
+ /** Last tick: matches existed, but only at or before the echo of the last input. */
152
+ let echoOnly = false;
153
+ return new Promise((resolve, reject) => {
154
+ /**
155
+ * The next poll, so an abort can cancel it rather than let it fire once
156
+ * more into a request nobody is reading.
157
+ */
158
+ let pollTimer = null;
159
+ const onAbort = () => {
160
+ if (pollTimer !== null)
161
+ clearTimeout(pollTimer);
162
+ pollTimer = null;
163
+ finish(false, 'aborted');
164
+ };
165
+ // Only a non-match carries an explanation, and only where the waiter
166
+ // knows one. Each is a different answer from "the condition never
167
+ // held", and the caller's next move depends on which it was.
168
+ const explain = () => {
169
+ if (condition.quiet !== undefined && !target.hasPainted()) {
170
+ return 'The program has not painted anything yet, so quiet cannot hold: it is still starting, or prints nothing.';
171
+ }
172
+ if (condition.prompt === true && staleOnly) {
173
+ return ('The prompt on screen is the one that was showing when your last input was sent, and the ' +
174
+ 'screen has not been seen without it since. The input may not have reached the program. ' +
175
+ 'Snapshot to check; pass matchAfterInput:false to accept it anyway.');
176
+ }
177
+ if (pattern !== null && echoOnly) {
178
+ return ('Matches were found only at or before the echo of your last input and were ignored ' +
179
+ '(matchAfterInput). If the output you expect repeats what you typed, wait for something ' +
180
+ 'else or use quiet.');
181
+ }
182
+ return undefined;
183
+ };
184
+ let settled = false;
185
+ const finish = (matched, reason) => {
186
+ if (settled)
187
+ return;
188
+ settled = true;
189
+ options.signal?.removeEventListener('abort', onAbort);
190
+ const detail = matched ? undefined : explain();
191
+ resolve({
192
+ matched,
193
+ reason,
194
+ waitedMs: Date.now() - startedAt,
195
+ screen: target.getScreen(),
196
+ ...(matchedPrompt !== null ? { prompt: matchedPrompt } : {}),
197
+ ...(detail !== undefined ? { detail } : {}),
198
+ });
199
+ };
200
+ const step = () => {
201
+ const now = Date.now();
202
+ const screen = target.getScreen();
203
+ if (matchedAt === null) {
204
+ if (pattern !== null) {
205
+ // The echo guard: with matchAfterInput, a match must lie after the
206
+ // echo of the last input, when that echo can be placed at all.
207
+ const from = afterInput ? (echoEnd(screen, target.lastInput() ?? '') ?? 0) : 0;
208
+ if (matchAt(screen, from) !== -1) {
209
+ matchedAt = now;
210
+ matchedReason = patternReason;
211
+ }
212
+ else {
213
+ echoOnly = from > 0 && matchAt(screen, 0) !== -1;
214
+ }
215
+ }
216
+ else if (condition.prompt === true) {
217
+ // Re-detected on every tick while settling below, because a
218
+ // mid-paint TUI can change WHICH prompt is drawn; the result must
219
+ // carry the prompt as it stands when the wait resolves, not a
220
+ // half-painted earlier read of it.
221
+ const detected = detectPrompt(screen);
222
+ target.observePrompt(detected?.signature ?? null);
223
+ if (detected === null) {
224
+ staleOnly = false;
225
+ }
226
+ else if (afterInput && target.isStalePrompt(detected.signature)) {
227
+ // The question the caller has just answered, on a screen the
228
+ // program has not repainted yet. Handing it back would have the
229
+ // supervisor answer it again, into whatever has focus by then.
230
+ staleOnly = true;
231
+ }
232
+ else {
233
+ staleOnly = false;
234
+ matchedAt = now;
235
+ matchedReason = 'prompt';
236
+ matchedPrompt = detected;
237
+ }
238
+ }
239
+ if (matchedAt !== null && debounceMs === 0) {
240
+ finish(true, matchedReason ?? 'text');
241
+ return;
242
+ }
243
+ }
244
+ else if (matchedReason === 'prompt') {
245
+ const stillThere = detectPrompt(screen);
246
+ target.observePrompt(stillThere?.signature ?? null);
247
+ if (stillThere === null) {
248
+ // The prompt went away while we were settling: answered by the
249
+ // human at the viewer, or redrawn past. Reporting `matched: true`
250
+ // with the remembered prompt would hand the caller a question that
251
+ // is no longer on screen, and a supervisor acting on it would answer
252
+ // a prompt that no longer exists. Retract the match and keep
253
+ // waiting: the condition asked for a prompt that is THERE.
254
+ matchedAt = null;
255
+ matchedPrompt = null;
256
+ matchedReason = null;
257
+ }
258
+ else {
259
+ matchedPrompt = stillThere;
260
+ }
261
+ }
262
+ if (matchedAt !== null) {
263
+ // Settling: resolve once the screen has been stable for debounceMs.
264
+ // An exited process's screen is final and so trivially settled, and the
265
+ // match must not be lost to the exit check below.
266
+ if (now - target.lastChangeAt() >= debounceMs || target.isExited()) {
267
+ finish(true, matchedReason ?? 'text');
268
+ return;
269
+ }
270
+ }
271
+ else if (condition.quiet !== undefined &&
272
+ // No paint, no quiet: silence from a program that has not drawn
273
+ // anything is "not started", not "finished and idle".
274
+ target.hasPainted() &&
275
+ now - target.lastChangeAt() >= condition.quiet) {
276
+ finish(true, 'quiet');
277
+ return;
278
+ }
279
+ if (target.isExited()) {
280
+ finish(false, 'exited');
281
+ return;
282
+ }
283
+ if (now - startedAt >= timeoutMs) {
284
+ finish(false, 'timeout');
285
+ return;
286
+ }
287
+ pollTimer = setTimeout(tick, pollMs);
288
+ };
289
+ /**
290
+ * A pattern that overruns its budget is the caller's mistake, so it is
291
+ * reported as one rather than left to escape from a timer callback, where
292
+ * nothing is listening and the daemon's uncaughtException handler would
293
+ * answer it by stopping.
294
+ */
295
+ const tick = () => {
296
+ try {
297
+ step();
298
+ }
299
+ catch (error) {
300
+ if (error instanceof RegexBudgetError) {
301
+ reject(new WaitConditionError(error.message));
302
+ return;
303
+ }
304
+ reject(error instanceof Error ? error : new Error(String(error)));
305
+ }
306
+ };
307
+ // Checked before the first look as well as after: a caller that has
308
+ // already gone is not owed one.
309
+ if (options.signal?.aborted === true) {
310
+ finish(false, 'aborted');
311
+ return;
312
+ }
313
+ options.signal?.addEventListener('abort', onAbort, { once: true });
314
+ tick();
315
+ });
316
+ }
317
+ //# sourceMappingURL=waiter.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"waiter.js","sourceRoot":"","sources":["../../src/core/waiter.ts"],"names":[],"mappings":"AAAA;;;;;;;;;GASG;AAEH,OAAO,EACL,uBAAuB,EACvB,mBAAmB,EACnB,qBAAqB,GACtB,MAAM,YAAY,CAAC;AAEpB,OAAO,EAAE,YAAY,EAAE,MAAM,qBAAqB,CAAC;AAEnD,OAAO,EAAE,OAAO,EAAE,MAAM,WAAW,CAAC;AACpC,OAAO,EAAE,gBAAgB,EAAE,eAAe,EAAE,MAAM,kBAAkB,CAAC;AAoCrE,8EAA8E;AAC9E,MAAM,OAAO,kBAAmB,SAAQ,KAAK;IAC3C,YAAY,OAAe;Q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KAAK,EAAE,SAAS,CAAC,CAAC;YACzB,OAAO;QACT,CAAC;QACD,OAAO,CAAC,MAAM,EAAE,gBAAgB,CAAC,OAAO,EAAE,OAAO,EAAE,EAAE,IAAI,EAAE,IAAI,EAAE,CAAC,CAAC;QACnE,IAAI,EAAE,CAAC;IACT,CAAC,CAAC,CAAC;AACL,CAAC"}
@@ -0,0 +1,90 @@
1
+ /**
2
+ * A Windows start that fails part-way releases what node-pty had built.
3
+ *
4
+ * node-pty 1.1.0 builds a Windows terminal in steps (`lib/windowsPtyAgent.js`):
5
+ * it creates the pseudoconsole, which is a `conhost.exe` and two pipes; it
6
+ * starts a worker thread that connects to the output pipe; it opens the input
7
+ * pipe; and only then does it create the process. When either of the last two
8
+ * steps throws, the constructor gives up without undoing the others. Opening
9
+ * the input pipe fails on every start under a sandbox that denies pipe access;
10
+ * creating the process fails for a file Windows cannot run, such as a script
11
+ * started with `shell: false`. The console host keeps running, and when the
12
+ * worker's own connect fails too, nothing listens for the worker's error, so
13
+ * it would reach the daemon as an uncaught exception.
14
+ *
15
+ * `releaseFailedStarts` wraps node-pty's Windows agent so that a failed start
16
+ * listens for the worker's error, ends the worker, destroys both sockets and,
17
+ * under ConPTY, closes the pseudoconsole, before the error reaches the caller.
18
+ * Windows builds before 18309 get winpty instead, which has no pseudoconsole
19
+ * and whose native kill takes other arguments, so there only that step is
20
+ * skipped. The wrapper reads node-pty's private fields, so it wraps version
21
+ * 1.1.0 only and leaves any other alone. The two pipe handles node-pty keeps
22
+ * for the pseudoconsole stay open: its native kill does not close them.
23
+ */
24
+ /** The fields of node-pty's `WindowsPtyAgent` that a failed start leaves set. */
25
+ export interface HalfBuiltAgent {
26
+ _useConpty?: boolean;
27
+ _pty?: number;
28
+ _useConptyDll?: boolean;
29
+ _ptyNative?: {
30
+ kill(pty: number, useConptyDll: boolean): void;
31
+ };
32
+ _inSocket?: {
33
+ destroy(): void;
34
+ };
35
+ _outSocket?: {
36
+ on(event: 'error', listener: () => void): unknown;
37
+ destroy(): void;
38
+ };
39
+ _conoutSocketWorker?: {
40
+ _worker?: {
41
+ on(event: 'error', listener: () => void): unknown;
42
+ terminate(): unknown;
43
+ };
44
+ };
45
+ }
46
+ type AgentConstructor = ((this: HalfBuiltAgent, ...args: unknown[]) => void) & {
47
+ prototype: object;
48
+ releasesFailedStarts?: true;
49
+ };
50
+ /** The shape of node-pty's `lib/windowsPtyAgent.js` exports that matter here. */
51
+ export interface AgentModule {
52
+ WindowsPtyAgent: AgentConstructor;
53
+ }
54
+ /**
55
+ * Replace the module's `WindowsPtyAgent` with one that releases a failed
56
+ * start. node-pty looks the constructor up on this module object each time it
57
+ * builds a terminal, so the replacement takes effect for every later start.
58
+ */
59
+ export declare function wrapWindowsPtyAgent(agents: AgentModule): void;
60
+ /**
61
+ * Wrap the installed node-pty's Windows agent, once. True when it is wrapped;
62
+ * false when the installed version is not the one this was written against.
63
+ */
64
+ export declare function releaseFailedStarts(): boolean;
65
+ /**
66
+ * Take the errors of the two streams of a live Windows terminal that node-pty
67
+ * 1.1.0 listens for nowhere, each of which would otherwise be an uncaught
68
+ * exception, on which the daemon shuts down with every session.
69
+ *
70
+ * - `input`: input reaches the pseudoconsole through a socket on its input
71
+ * pipe (`lib/windowsPtyAgent.js`). Once the console host has closed its end,
72
+ * a write the pipe refuses (`write EAGAIN`) is emitted as an 'error'; a
73
+ * viewer's focus report racing the session's exit does it.
74
+ * - `output`: a worker thread copies the output pipe to a local socket
75
+ * (`lib/worker/conoutSocketWorker.js`), and an error thrown there becomes
76
+ * the worker's 'error'.
77
+ *
78
+ * With the listener the stream fails as before and the daemon and its other
79
+ * sessions carry on. False when the installed node-pty is not the wrapped
80
+ * version or the terminal has neither stream.
81
+ */
82
+ export declare function listenForTerminalErrors(pty: unknown, listener: (error: Error, stream: 'input' | 'output') => void): boolean;
83
+ /**
84
+ * Wrap the agent module only for the node-pty version whose private fields
85
+ * `release` reads. Another version is left alone and its module not loaded:
86
+ * wrapping internals nobody has read could break every start, where leaving
87
+ * them alone costs only the release.
88
+ */
89
+ export declare function wrapIfKnownVersion(version: string, load: () => AgentModule): boolean;
90
+ export {};
@@ -0,0 +1,129 @@
1
+ /**
2
+ * A Windows start that fails part-way releases what node-pty had built.
3
+ *
4
+ * node-pty 1.1.0 builds a Windows terminal in steps (`lib/windowsPtyAgent.js`):
5
+ * it creates the pseudoconsole, which is a `conhost.exe` and two pipes; it
6
+ * starts a worker thread that connects to the output pipe; it opens the input
7
+ * pipe; and only then does it create the process. When either of the last two
8
+ * steps throws, the constructor gives up without undoing the others. Opening
9
+ * the input pipe fails on every start under a sandbox that denies pipe access;
10
+ * creating the process fails for a file Windows cannot run, such as a script
11
+ * started with `shell: false`. The console host keeps running, and when the
12
+ * worker's own connect fails too, nothing listens for the worker's error, so
13
+ * it would reach the daemon as an uncaught exception.
14
+ *
15
+ * `releaseFailedStarts` wraps node-pty's Windows agent so that a failed start
16
+ * listens for the worker's error, ends the worker, destroys both sockets and,
17
+ * under ConPTY, closes the pseudoconsole, before the error reaches the caller.
18
+ * Windows builds before 18309 get winpty instead, which has no pseudoconsole
19
+ * and whose native kill takes other arguments, so there only that step is
20
+ * skipped. The wrapper reads node-pty's private fields, so it wraps version
21
+ * 1.1.0 only and leaves any other alone. The two pipe handles node-pty keeps
22
+ * for the pseudoconsole stay open: its native kill does not close them.
23
+ */
24
+ import { createRequire } from 'node:module';
25
+ /** The node-pty version whose private fields this relies on. */
26
+ const WRAPPED_VERSION = '1.1.0';
27
+ /**
28
+ * Replace the module's `WindowsPtyAgent` with one that releases a failed
29
+ * start. node-pty looks the constructor up on this module object each time it
30
+ * builds a terminal, so the replacement takes effect for every later start.
31
+ */
32
+ export function wrapWindowsPtyAgent(agents) {
33
+ const Original = agents.WindowsPtyAgent;
34
+ if (Original.releasesFailedStarts === true)
35
+ return;
36
+ const Wrapped = function WindowsPtyAgent(...args) {
37
+ const agent = Object.create(Original.prototype);
38
+ try {
39
+ Original.apply(agent, args);
40
+ }
41
+ catch (error) {
42
+ release(agent);
43
+ throw error;
44
+ }
45
+ return agent;
46
+ };
47
+ Wrapped.prototype = Original.prototype;
48
+ Wrapped.releasesFailedStarts = true;
49
+ agents.WindowsPtyAgent = Wrapped;
50
+ }
51
+ /** Undo what a failed start built, as far as node-pty lets us. */
52
+ function release(agent) {
53
+ const worker = agent._conoutSocketWorker?._worker;
54
+ if (worker !== undefined) {
55
+ // The worker's connect may still fail after this, and an 'error' with no
56
+ // listener would reach the daemon as an uncaught exception.
57
+ worker.on('error', () => undefined);
58
+ void worker.terminate();
59
+ }
60
+ // The input socket exists only when the process could not be created.
61
+ agent._inSocket?.destroy();
62
+ // A 'ready' from the worker arriving after this would reconnect the output
63
+ // socket (connecting revives a destroyed socket), and its error would have
64
+ // no listener either.
65
+ agent._outSocket?.on('error', () => undefined);
66
+ agent._outSocket?.destroy();
67
+ // Only ConPTY has a pseudoconsole to close; winpty's kill takes a pid.
68
+ if (agent._useConpty === true && agent._pty !== undefined && agent._ptyNative !== undefined) {
69
+ try {
70
+ agent._ptyNative.kill(agent._pty, agent._useConptyDll ?? false);
71
+ }
72
+ catch {
73
+ // Best effort: the start has already failed and its caller is told.
74
+ }
75
+ }
76
+ }
77
+ let wrapped = false;
78
+ /**
79
+ * Wrap the installed node-pty's Windows agent, once. True when it is wrapped;
80
+ * false when the installed version is not the one this was written against.
81
+ */
82
+ export function releaseFailedStarts() {
83
+ if (wrapped)
84
+ return true;
85
+ const require = createRequire(import.meta.url);
86
+ const { version } = require('node-pty/package.json');
87
+ wrapped = wrapIfKnownVersion(version, () => require('node-pty/lib/windowsPtyAgent.js'));
88
+ return wrapped;
89
+ }
90
+ /**
91
+ * Take the errors of the two streams of a live Windows terminal that node-pty
92
+ * 1.1.0 listens for nowhere, each of which would otherwise be an uncaught
93
+ * exception, on which the daemon shuts down with every session.
94
+ *
95
+ * - `input`: input reaches the pseudoconsole through a socket on its input
96
+ * pipe (`lib/windowsPtyAgent.js`). Once the console host has closed its end,
97
+ * a write the pipe refuses (`write EAGAIN`) is emitted as an 'error'; a
98
+ * viewer's focus report racing the session's exit does it.
99
+ * - `output`: a worker thread copies the output pipe to a local socket
100
+ * (`lib/worker/conoutSocketWorker.js`), and an error thrown there becomes
101
+ * the worker's 'error'.
102
+ *
103
+ * With the listener the stream fails as before and the daemon and its other
104
+ * sessions carry on. False when the installed node-pty is not the wrapped
105
+ * version or the terminal has neither stream.
106
+ */
107
+ export function listenForTerminalErrors(pty, listener) {
108
+ if (!wrapped)
109
+ return false;
110
+ const agent = pty._agent;
111
+ const input = agent?.inSocket;
112
+ const output = agent?._conoutSocketWorker?._worker;
113
+ input?.on('error', (error) => listener(error, 'input'));
114
+ output?.on('error', (error) => listener(error, 'output'));
115
+ return input !== undefined || output !== undefined;
116
+ }
117
+ /**
118
+ * Wrap the agent module only for the node-pty version whose private fields
119
+ * `release` reads. Another version is left alone and its module not loaded:
120
+ * wrapping internals nobody has read could break every start, where leaving
121
+ * them alone costs only the release.
122
+ */
123
+ export function wrapIfKnownVersion(version, load) {
124
+ if (version !== WRAPPED_VERSION)
125
+ return false;
126
+ wrapWindowsPtyAgent(load());
127
+ return true;
128
+ }
129
+ //# sourceMappingURL=windowsPtyStart.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"windowsPtyStart.js","sourceRoot":"","sources":["../../src/core/windowsPtyStart.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;GAsBG;AAEH,OAAO,EAAE,aAAa,EAAE,MAAM,aAAa,CAAC;AAE5C,gEAAgE;AAChE,MAAM,eAAe,GAAG,OAAO,CAAC;AAyBhC;;;;GAIG;AACH,MAAM,UAAU,mBAAmB,CAAC,MAAmB;IACrD,MAAM,QAAQ,GAAG,MAAM,CAAC,eAAe,CAAC;IACxC,IAAI,QAAQ,CAAC,oBAAoB,KAAK,IAAI;QAAE,OAAO;IAEnD,MAAM,OAAO,GAAG,SAAS,eAAe,CAAgB,GAAG,IAAe;QACxE,MAAM,KAAK,GAAG,MAAM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KAAK,CAAC;IAC9C,mBAAmB,CAAC,IAAI,EAAE,CAAC,CAAC;IAC5B,OAAO,IAAI,CAAC;AACd,CAAC"}
@@ -0,0 +1,23 @@
1
+ /**
2
+ * Append-only action log at `~/.shellpuppet/audit.log` (design §4.5).
3
+ *
4
+ * THE RULE: typed content is never logged by default. Keystrokes are where the
5
+ * secrets are: an SSH passphrase or API key typed into a prompt must
6
+ * not end up in a plaintext log. Default entries record the action and the
7
+ * input LENGTH; the command line for `start` is recorded because commands are
8
+ * policy-visible by definition. Screen output is never logged.
9
+ *
10
+ * `audit.captureContent: true` in config.json opts into full input capture for
11
+ * debugging, and docs/reference/security-model.md documents it as secret-capturing.
12
+ */
13
+ import type { Logger } from '../core/types.js';
14
+ export interface Auditor {
15
+ readonly captureContent: boolean;
16
+ record(actor: string, action: string, session?: string, meta?: Record<string, unknown>): void;
17
+ }
18
+ export declare function auditLogPath(home: string): string;
19
+ /** An auditor that records nothing, used by unit-style tests. */
20
+ export declare const NULL_AUDITOR: Auditor;
21
+ export declare function createAuditor(home: string, options?: {
22
+ captureContent?: boolean;
23
+ }, logger?: Logger): Auditor;
@@ -0,0 +1,51 @@
1
+ /**
2
+ * Append-only action log at `~/.shellpuppet/audit.log` (design §4.5).
3
+ *
4
+ * THE RULE: typed content is never logged by default. Keystrokes are where the
5
+ * secrets are: an SSH passphrase or API key typed into a prompt must
6
+ * not end up in a plaintext log. Default entries record the action and the
7
+ * input LENGTH; the command line for `start` is recorded because commands are
8
+ * policy-visible by definition. Screen output is never logged.
9
+ *
10
+ * `audit.captureContent: true` in config.json opts into full input capture for
11
+ * debugging, and docs/reference/security-model.md documents it as secret-capturing.
12
+ */
13
+ import * as fs from 'node:fs';
14
+ import * as path from 'node:path';
15
+ import { NULL_LOGGER } from '../core/types.js';
16
+ export function auditLogPath(home) {
17
+ return path.join(home, 'audit.log');
18
+ }
19
+ /** An auditor that records nothing, used by unit-style tests. */
20
+ export const NULL_AUDITOR = {
21
+ captureContent: false,
22
+ record: () => undefined,
23
+ };
24
+ export function createAuditor(home, options = {}, logger = NULL_LOGGER) {
25
+ const file = auditLogPath(home);
26
+ let warned = false;
27
+ return {
28
+ captureContent: options.captureContent ?? false,
29
+ record(actor, action, session, meta) {
30
+ try {
31
+ const entry = {
32
+ time: new Date().toISOString(),
33
+ actor,
34
+ action,
35
+ ...(session !== undefined ? { session } : {}),
36
+ ...(meta !== undefined ? { meta } : {}),
37
+ };
38
+ fs.appendFileSync(file, JSON.stringify(entry) + '\n');
39
+ }
40
+ catch (error) {
41
+ if (!warned) {
42
+ warned = true;
43
+ logger.warn('audit log write failed: auditing disabled for this run', {
44
+ error: String(error),
45
+ });
46
+ }
47
+ }
48
+ },
49
+ };
50
+ }
51
+ //# sourceMappingURL=audit.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"audit.js","sourceRoot":"","sources":["../../src/daemon/audit.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;GAWG;AAEH,OAAO,KAAK,EAAE,MAAM,SAAS,CAAC;AAC9B,OAAO,KAAK,IAAI,MAAM,WAAW,CAAC;AAElC,OAAO,EAAE,WAAW,EAAE,MAAM,kBAAkB,CAAC;AAY/C,MAAM,UAAU,YAAY,CAAC,IAAY;IACvC,OAAO,IAAI,CAAC,IAAI,CAAC,IAAI,EAAE,WAAW,CAAC,CAAC;AACtC,CAAC;AAED,iEAAiE;AACjE,MAAM,CAAC,MAAM,YAAY,GAAY;IACnC,cAAc,EAAE,KAAK;IACrB,MAAM,EAAE,GAAG,EAAE,CAAC,SAAS;CACxB,CAAC;AAEF,MAAM,UAAU,aAAa,CAC3B,IAAY,EACZ,UAAwC,EAAE,EAC1C,SAAiB,WAAW;IAE5B,MAAM,IAAI,GAAG,YAAY,CAAC,IAAI,CAAC,CAAC;IAChC,IAAI,MAAM,GAAG,KAAK,CAAC;IACnB,OAAO;QACL,cAAc,EAAE,OAAO,CAAC,cAAc,IAAI,KAAK;QAC/C,MAAM,CAAC,KAAK,EAAE,MAAM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