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,280 @@
1
+ /**
2
+ * Opening the viewer in its own browser window.
3
+ *
4
+ * Two problems with handing the URL to the default browser
5
+ * (`launchMode: "default-browser"`), which opens it in the user's normal
6
+ * profile:
7
+ *
8
+ * 1. The viewer then shares a browsing context with every other page that
9
+ * profile has open: cookie jar, storage and history. Loopback is not a boundary
10
+ * against the browser itself. The daemon's Host/Origin checks and bearer
11
+ * auth (§4.2) are what holds this; a separate profile removes the exposure
12
+ * rather than defending it.
13
+ * 2. The viewer grant is in the URL, so it lands in that profile's history.
14
+ *
15
+ * **Why no bundled browser.** The viewer IS a web page: a browser is already a
16
+ * hard prerequisite for ShellPuppet to be usable at all. Bundling one
17
+ * (Playwright's ~130 MB download, or Electron) adds a very large dependency to
18
+ * solve a problem every user already has a browser for. Playwright is the
19
+ * wrong shape besides, being built to DRIVE a page while here a human does.
20
+ * So: detect an installed Chromium-family browser, and degrade gracefully when
21
+ * there is none. `chrome-launcher` (Apache-2.0, ~140 KB) does the fiddly
22
+ * cross-platform detection, which is exactly the part that would otherwise
23
+ * be machine-specific guesswork: Windows registry and Program Files, macOS
24
+ * LSRegister, Linux PATH. We spawn the process ourselves, because the
25
+ * detachment discipline below is not negotiable.
26
+ *
27
+ * Nothing here may ever fail a session start. A browser that will not launch is
28
+ * an inconvenience: the launcher reports that nothing opened, the daemon hands
29
+ * the caller the URL instead, and the human can open it themselves. That report
30
+ * has to be truthful, because the caller is told the human needs no link when a
31
+ * window opened: a spawn settles on the child's `spawn` or `error` event, and
32
+ * the system's opener (`start`, `open`, `xdg-open`) on its exit code.
33
+ */
34
+ import { spawn } from 'node:child_process';
35
+ import * as fs from 'node:fs';
36
+ import * as path from 'node:path';
37
+ /**
38
+ * Chromium-family browsers that `chrome-launcher` does NOT look for, checked
39
+ * after it. Edge earns its place: it ships with Windows, so including it means
40
+ * a Windows machine effectively always has a usable browser even with no
41
+ * Chrome installed. Paths only, never a bare name, because a bare name would
42
+ * resolve against PATH and PATH is attacker-influenced on a shared machine.
43
+ */
44
+ export function extraBrowserCandidates() {
45
+ const env = process.env;
46
+ if (process.platform === 'win32') {
47
+ const roots = [env['PROGRAMFILES(X86)'], env['PROGRAMFILES'], env['LOCALAPPDATA']].filter((value) => typeof value === 'string' && value !== '');
48
+ const relative = [
49
+ path.join('Microsoft', 'Edge', 'Application', 'msedge.exe'),
50
+ path.join('BraveSoftware', 'Brave-Browser', 'Application', 'brave.exe'),
51
+ path.join('Vivaldi', 'Application', 'vivaldi.exe'),
52
+ ];
53
+ return roots.flatMap((root) => relative.map((rel) => path.join(root, rel)));
54
+ }
55
+ if (process.platform === 'darwin') {
56
+ return [
57
+ '/Applications/Microsoft Edge.app/Contents/MacOS/Microsoft Edge',
58
+ '/Applications/Brave Browser.app/Contents/MacOS/Brave Browser',
59
+ '/Applications/Vivaldi.app/Contents/MacOS/Vivaldi',
60
+ ];
61
+ }
62
+ return [
63
+ '/usr/bin/microsoft-edge',
64
+ '/usr/bin/brave-browser',
65
+ '/usr/bin/vivaldi',
66
+ '/usr/bin/chromium',
67
+ '/usr/bin/chromium-browser',
68
+ ];
69
+ }
70
+ /**
71
+ * Find a Chromium-family browser, or null. `chrome-launcher` is imported
72
+ * dynamically and inside a try: a detection library must never be able to stop
73
+ * the daemon from serving sessions, and its Windows path pokes the registry.
74
+ */
75
+ export async function findBrowser(explicitPath) {
76
+ if (explicitPath !== undefined && explicitPath !== '') {
77
+ // Never cached: an operator who names a binary means that binary, and the
78
+ // answer is a single existsSync anyway.
79
+ return fs.existsSync(explicitPath) ? explicitPath : null;
80
+ }
81
+ // Detection is memoised for the daemon's lifetime because it is NOT cheap:
82
+ // chrome-launcher's macOS path (an LSRegister query) took 5.7 s and 9.7 s
83
+ // on macOS CI runners. A session start waits for the launch, so the daemon
84
+ // looks once as it starts (server.ts) and every start after that finds the
85
+ // answer ready; it changes only when someone installs a browser. A daemon
86
+ // restart re-detects.
87
+ // The promise is memoised, not the value, so a caller that arrives while
88
+ // detection is still running waits for the rest of it instead of starting
89
+ // a second detection of its own.
90
+ cachedDetection ??= detectBrowser();
91
+ return cachedDetection;
92
+ }
93
+ /** Memoised detection; `undefined` means "not looked yet". */
94
+ let cachedDetection;
95
+ /** Test hook: forget the memoised browser so detection runs again. */
96
+ export function resetBrowserCache() {
97
+ cachedDetection = undefined;
98
+ }
99
+ async function detectBrowser() {
100
+ try {
101
+ const { Launcher } = await import('chrome-launcher');
102
+ const installations = Launcher.getInstallations();
103
+ if (installations.length > 0 && installations[0] !== undefined)
104
+ return installations[0];
105
+ }
106
+ catch {
107
+ // No Chrome/Chromium found, or detection threw: fall through to the
108
+ // supplementary list rather than giving up.
109
+ }
110
+ for (const candidate of extraBrowserCandidates()) {
111
+ if (fs.existsSync(candidate))
112
+ return candidate;
113
+ }
114
+ return null;
115
+ }
116
+ export async function launchViewer(url, home, config, logger, deps = {}) {
117
+ const mode = config.launchMode ?? 'none';
118
+ if (mode === 'none')
119
+ return { launched: false, mode, reason: 'viewer.launchMode is "none"' };
120
+ if (mode === 'isolated-app') {
121
+ const browser = await findBrowser(config.browserPath);
122
+ if (browser === null) {
123
+ // Degrade rather than fail: the system's opener is tried, and when
124
+ // nothing opens the daemon hands the caller the URL.
125
+ logger.warn('no Chromium-family browser found for the isolated viewer window', {
126
+ hint: 'set viewer.browserPath, or viewer.launchMode to "default-browser"',
127
+ });
128
+ return openInDefaultBrowser(url, logger, 'isolated-app', deps, 'no Chromium-family browser found');
129
+ }
130
+ const profileDir = config.profileDir ?? path.join(home, 'viewer-profile');
131
+ try {
132
+ fs.mkdirSync(profileDir, { recursive: true });
133
+ }
134
+ catch (error) {
135
+ logger.warn('could not create the viewer profile directory', {
136
+ profileDir,
137
+ error: String(error),
138
+ });
139
+ return openInDefaultBrowser(url, logger, 'isolated-app', deps, 'profile directory unavailable');
140
+ }
141
+ // The browser is spawned directly, so "opened" means its process started.
142
+ // Its exit is not judged: a Chromium launched beside a running instance of
143
+ // the same profile hands the URL over and exits at once, with code 0, and
144
+ // the window is in the other process.
145
+ const outcome = await spawnDetached(browser, [
146
+ `--app=${url}`,
147
+ `--user-data-dir=${profileDir}`,
148
+ '--new-window',
149
+ // First-run flows would hijack the window with a sign-in wizard; the
150
+ // default-browser prompt would ask to change a setting the user never
151
+ // asked to change from a window they did not open.
152
+ '--no-first-run',
153
+ '--no-default-browser-check',
154
+ ]);
155
+ if (outcome.spawned) {
156
+ logger.info('viewer window opened', { browser, profileDir });
157
+ return { launched: true, mode, browser };
158
+ }
159
+ const error = outcome.error ?? 'the browser did not start';
160
+ logger.warn('the viewer browser failed to launch', { browser, error });
161
+ return openInDefaultBrowser(url, logger, 'isolated-app', deps, error);
162
+ }
163
+ return openInDefaultBrowser(url, logger, 'default-browser', deps);
164
+ }
165
+ /**
166
+ * The command that opens `url` in the default browser.
167
+ *
168
+ * On Windows that is cmd's `start` builtin, so the URL passes through cmd's
169
+ * command-line parser, where an unquoted `&` ends a command. The viewer URL
170
+ * holds one (`?s=<id>&vt=<grant>`), and Node quotes an argument only when it
171
+ * holds a space, so the URL goes over verbatim inside double quotes. Within
172
+ * quotes cmd still expands `%NAME%`, and `!NAME!` where delayed expansion is
173
+ * switched on in the registry; a `"` ends the quoting and a line break ends
174
+ * the command. A URL holding any of those is refused rather than handed over.
175
+ * The empty `""` is `start`'s window title, without which it would take the
176
+ * quoted URL as the title. `/d` skips cmd's AutoRun commands.
177
+ */
178
+ export function defaultBrowserCommand(url, platform = process.platform, comspec = process.env['COMSPEC']) {
179
+ if (platform === 'win32') {
180
+ if (/["%!\r\n]/.test(url)) {
181
+ throw new Error('the URL holds a quote, a percent sign, an exclamation mark or a line break, which cmd would act on');
182
+ }
183
+ return {
184
+ command: comspec ?? 'cmd.exe',
185
+ args: ['/d', '/c', 'start', '""', `"${url}"`],
186
+ windowsVerbatimArguments: true,
187
+ };
188
+ }
189
+ const command = platform === 'darwin' ? '/usr/bin/open' : '/usr/bin/xdg-open';
190
+ return { command, args: [url], windowsVerbatimArguments: false };
191
+ }
192
+ /**
193
+ * How long to wait for the system's opener to say whether it managed. `start`,
194
+ * `open` and `xdg-open` return within a fraction of a second, with a non-zero
195
+ * code when they could hand the URL to nothing (no display, no registered
196
+ * browser). An opener still running after this is taken to have become the
197
+ * browser itself, which `xdg-open` does on some desktops.
198
+ */
199
+ export const OPENER_SETTLE_MS = 1500;
200
+ async function openInDefaultBrowser(url, logger, mode, deps, fallbackReason) {
201
+ const withFallback = (reason) => fallbackReason === undefined ? reason : `${reason}; fell back: ${fallbackReason}`;
202
+ let command;
203
+ try {
204
+ command = (deps.opener ?? defaultBrowserCommand)(url);
205
+ }
206
+ catch (error) {
207
+ logger.warn('could not open the viewer in any browser', { error: String(error) });
208
+ return { launched: false, mode, reason: withFallback(String(error)) };
209
+ }
210
+ const outcome = await spawnDetached(command.command, command.args, command.windowsVerbatimArguments, deps.openerSettleMs ?? OPENER_SETTLE_MS);
211
+ if (!outcome.spawned) {
212
+ const error = outcome.error ?? 'the opener did not start';
213
+ logger.warn('could not open the viewer in any browser', { error });
214
+ return { launched: false, mode, reason: withFallback(error) };
215
+ }
216
+ if (outcome.exitCode !== undefined && outcome.exitCode !== 0) {
217
+ const reason = `${path.basename(command.command)} exited with code ${String(outcome.exitCode ?? 'signal')}`;
218
+ logger.warn('the default browser did not open the viewer', { reason, fallbackReason });
219
+ return { launched: false, mode, reason: withFallback(reason) };
220
+ }
221
+ logger.info('viewer opened in the default browser', { fallbackReason });
222
+ return {
223
+ launched: true,
224
+ mode,
225
+ ...(fallbackReason !== undefined ? { reason: `fell back: ${fallbackReason}` } : {}),
226
+ };
227
+ }
228
+ /**
229
+ * Spawn fully detached with `detached`, `stdio: 'ignore'` and `unref()`, the
230
+ * same discipline the daemon's own auto-start requires (§2.2): a browser that
231
+ * inherited this daemon's stdio, or that the daemon waited on, would tie a
232
+ * long-lived GUI process to the daemon's lifetime and hang its shutdown.
233
+ *
234
+ * The promise settles when Node says whether the process started. `spawn`
235
+ * reports a failure to execute, such as ENOENT, EACCES or a path that is a
236
+ * directory, by emitting 'error' ASYNCHRONOUSLY, so a call that returned
237
+ * without throwing has proved nothing, and a ChildProcess 'error' with no
238
+ * listener is re-thrown by Node as an uncaught exception. With `settleMs`, it
239
+ * also waits that long for the process to exit and reports the code, for an
240
+ * opener whose exit code is its answer. Nothing here throws: the caller's
241
+ * contract is that launching a viewer can never fail a session start.
242
+ */
243
+ function spawnDetached(command, args, windowsVerbatimArguments = false, settleMs = 0) {
244
+ return new Promise((resolve) => {
245
+ let settled = false;
246
+ const settle = (outcome) => {
247
+ if (settled)
248
+ return;
249
+ settled = true;
250
+ resolve(outcome);
251
+ };
252
+ let child;
253
+ try {
254
+ child = spawn(command, args, {
255
+ detached: true,
256
+ stdio: 'ignore',
257
+ windowsHide: false,
258
+ windowsVerbatimArguments,
259
+ });
260
+ }
261
+ catch (error) {
262
+ settle({ spawned: false, error: String(error) });
263
+ return;
264
+ }
265
+ child.on('error', (error) => settle({ spawned: false, error: String(error) }));
266
+ child.on('spawn', () => {
267
+ if (settleMs <= 0) {
268
+ settle({ spawned: true });
269
+ return;
270
+ }
271
+ const timer = setTimeout(() => settle({ spawned: true }), settleMs);
272
+ child.once('exit', (code) => {
273
+ clearTimeout(timer);
274
+ settle({ spawned: true, exitCode: code });
275
+ });
276
+ });
277
+ child.unref();
278
+ });
279
+ }
280
+ //# sourceMappingURL=viewerLauncher.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"viewerLauncher.js","sourceRoot":"","sources":["../../src/daemon/viewerLauncher.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAgCG;AAEH,OAAO,EAAE,KAAK,EAAE,MAAM,oBAAoB,CAAC;AAE3C,OAAO,KAAK,EAAE,MAAM,SAAS,CAAC;AAC9B,OAAO,KAAK,IAAI,MAAM,WAAW,CAAC;AAyBlC;;;;;;GAMG;AACH,MAAM,UAAU,sBAAsB;IACpC,MAAM,GAAG,GAAG,OAAO,CAAC,GAAG,CAAC;IACxB,IAAI,OAAO,CAAC,QAAQ,KAAK,OAAO,EAAE,CAAC;QACjC,MAAM,KAAK,GAAG,CAAC,GAAG,CAAC,mBAAmB,CAAC,EAAE,GAAG,CAAC,cAAc,CAAC,EAAE,GAAG,CAAC,cAAc,CAAC,CAAC,CAAC,MAAM,CACvF,CAAC,KAAK,EAAmB,EAAE,CAAC,OAAO,KAAK,KAAK,QAAQ,IAAI,KAAK,KAAK,EAAE,CACtE,CAAC;QACF,MAAM,QAAQ,GAAG;YACf,IAAI,CAAC,IAAI,CAAC,WAAW,EAAE,MAAM,EAAE,aAAa,EAAE,YAAY,CAAC;YAC3D,IAAI,CAAC,IAAI,CAAC,eAAe,EAAE,eAAe,EAAE,aAAa,EAAE,WAAW,CAAC;YACvE,IAAI,CAA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AC,MAAM,CAAC,EAAE,OAAO,EAAE,IAAI,EAAE,CAAC,EAAE,QAAQ,CAAC,CAAC;YACpE,KAAK,CAAC,IAAI,CAAC,MAAM,EAAE,CAAC,IAAI,EAAE,EAAE;gBAC1B,YAAY,CAAC,KAAK,CAAC,CAAC;gBACpB,MAAM,CAAC,EAAE,OAAO,EAAE,IAAI,EAAE,QAAQ,EAAE,IAAI,EAAE,CAAC,CAAC;YAC5C,CAAC,CAAC,CAAC;QACL,CAAC,CAAC,CAAC;QACH,KAAK,CAAC,KAAK,EAAE,CAAC;IAChB,CAAC,CAAC,CAAC;AACL,CAAC"}
@@ -0,0 +1,38 @@
1
+ /**
2
+ * The gate that keeps one viewer socket's byte stream in order across
3
+ * snapshots (design §5).
4
+ *
5
+ * A snapshot of the daemon's renderer is taken asynchronously: it resolves
6
+ * once every byte queued before the request has been parsed, and includes
7
+ * nothing queued after it (`ScreenRenderer.serialize`). Bytes that arrive
8
+ * while it is pending are NOT in it and must reach the viewer
9
+ * AFTER it; bytes that arrived before the request ARE in it and were already
10
+ * forwarded live, so they must not go out again. This class is that
11
+ * bookkeeping, with the socket and the snapshot injected so it can be tested
12
+ * without either.
13
+ *
14
+ * No I/O of its own and no logging.
15
+ */
16
+ export declare class ViewerSync {
17
+ private readonly send;
18
+ private readonly snapshot;
19
+ /** Arrival counter: every delivered chunk takes the next value. */
20
+ private seq;
21
+ /** Chunks held back while a snapshot is pending, with their arrival order. */
22
+ private held;
23
+ /** The arrival counter at each pending snapshot request, oldest first. */
24
+ private readonly pending;
25
+ private closed;
26
+ constructor(send: (bytes: string) => void, snapshot: () => Promise<string>);
27
+ /** Live bytes from the session, in arrival order. */
28
+ deliver(bytes: string): void;
29
+ /**
30
+ * Send a fresh snapshot, then everything that arrived after it was taken.
31
+ * Requests may overlap (a window being dragged): each snapshot goes out
32
+ * once, and no chunk goes out twice or not at all.
33
+ */
34
+ resync(): void;
35
+ private complete;
36
+ /** Nothing goes out after this, including a snapshot that resolves late. */
37
+ close(): void;
38
+ }
@@ -0,0 +1,83 @@
1
+ /**
2
+ * The gate that keeps one viewer socket's byte stream in order across
3
+ * snapshots (design §5).
4
+ *
5
+ * A snapshot of the daemon's renderer is taken asynchronously: it resolves
6
+ * once every byte queued before the request has been parsed, and includes
7
+ * nothing queued after it (`ScreenRenderer.serialize`). Bytes that arrive
8
+ * while it is pending are NOT in it and must reach the viewer
9
+ * AFTER it; bytes that arrived before the request ARE in it and were already
10
+ * forwarded live, so they must not go out again. This class is that
11
+ * bookkeeping, with the socket and the snapshot injected so it can be tested
12
+ * without either.
13
+ *
14
+ * No I/O of its own and no logging.
15
+ */
16
+ export class ViewerSync {
17
+ send;
18
+ snapshot;
19
+ /** Arrival counter: every delivered chunk takes the next value. */
20
+ seq = 0;
21
+ /** Chunks held back while a snapshot is pending, with their arrival order. */
22
+ held = [];
23
+ /** The arrival counter at each pending snapshot request, oldest first. */
24
+ pending = [];
25
+ closed = false;
26
+ constructor(send, snapshot) {
27
+ this.send = send;
28
+ this.snapshot = snapshot;
29
+ }
30
+ /** Live bytes from the session, in arrival order. */
31
+ deliver(bytes) {
32
+ if (this.closed)
33
+ return;
34
+ const seq = this.seq++;
35
+ if (this.pending.length === 0) {
36
+ this.send(bytes);
37
+ return;
38
+ }
39
+ this.held.push({ seq, bytes });
40
+ }
41
+ /**
42
+ * Send a fresh snapshot, then everything that arrived after it was taken.
43
+ * Requests may overlap (a window being dragged): each snapshot goes out
44
+ * once, and no chunk goes out twice or not at all.
45
+ */
46
+ resync() {
47
+ if (this.closed)
48
+ return;
49
+ // Everything delivered before this point is in the snapshot about to be
50
+ // taken: the session writes a chunk to its renderer before it notifies
51
+ // listeners, and the snapshot's marker joins the renderer's queue now.
52
+ const mark = this.seq;
53
+ this.pending.push(mark);
54
+ this.snapshot().then((state) => this.complete(mark, state), () => this.complete(mark, null));
55
+ }
56
+ complete(mark, state) {
57
+ if (this.closed)
58
+ return;
59
+ // Snapshots resolve in request order: the renderer's write queue is FIFO.
60
+ this.pending.shift();
61
+ if (state !== null) {
62
+ this.send(state);
63
+ // Chunks that arrived before this snapshot was requested are inside it.
64
+ // Only a snapshot that WENT OUT accounts for them: one that failed
65
+ // covers nothing, and pruning on its mark would lose every chunk between
66
+ // the previous request and this one. Those are released live instead,
67
+ // in order.
68
+ this.held = this.held.filter((entry) => entry.seq >= mark);
69
+ }
70
+ if (this.pending.length === 0) {
71
+ const release = this.held;
72
+ this.held = [];
73
+ for (const entry of release)
74
+ this.send(entry.bytes);
75
+ }
76
+ }
77
+ /** Nothing goes out after this, including a snapshot that resolves late. */
78
+ close() {
79
+ this.closed = true;
80
+ this.held = [];
81
+ }
82
+ }
83
+ //# sourceMappingURL=viewerSync.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"viewerSync.js","sourceRoot":"","sources":["../../src/daemon/viewerSync.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG;AACH,MAAM,OAAO,UAAU;IAUF;IACA;IAVnB,mEAAmE;IAC3D,GAAG,GAAG,CAAC,CAAC;IAChB,8EAA8E;IACtE,IAAI,GAAqC,EAAE,CAAC;IACpD,0EAA0E;IACzD,OAAO,GAAa,EAAE,CAAC;IAChC,MAAM,GAAG,KAAK,CAAC;IAEvB,YACmB,IAA6B,EAC7B,QAA+B;QAD/B,SAAI,GAAJ,IAAI,CAAyB;QAC7B,aAAQ,GAAR,QAAQ,CAAuB;IAC/C,CAAC;IAEJ,qDAAqD;IACrD,OAAO,CAAC,KAAa;QACnB,IAAI,IAAI,CAAC,MAAM;YAAE,OAAO;QACxB,MAAM,GAAG,GAAG,IAAI,CAAC,GAAG,EAAE,CAAC;QACvB,IAAI,IAAI,CAAC,OAAO,CAAC,MAAM,KAAK,CAAC,EAAE,CAAC;YAC9B,IAAI,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC;YACjB,OAAO;QACT,CAAC;QACD,IAAI,CAAC,IAAI,CAAC,IAAI,CAAC,EAAE,GAAG,EAAE,KAAK,EAAE,CA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AAI,CAAC,MAAM,GAAG,IAAI,CAAC;QACnB,IAAI,CAAC,IAAI,GAAG,EAAE,CAAC;IACjB,CAAC;CACF"}
@@ -0,0 +1,57 @@
1
+ /**
2
+ * The MCP adapter's own section of `config.json` (the daemon reads the
3
+ * rest): the framing toggle at launch, the variable list at every
4
+ * `terminal_start`. Problems are reported through the logger, which
5
+ * the adapter points at stderr: stdout belongs to the MCP protocol.
6
+ */
7
+ import type { Logger } from '../core/types.js';
8
+ export interface McpConfig {
9
+ /** §4.4 framing toggle: `{ "mcp": { "untrustedFraming": false } }` disables. */
10
+ untrustedFraming: boolean;
11
+ /**
12
+ * The variables a client may pass into a session from its own environment:
13
+ * this server for `terminal_start`'s `envNames`, and the CLI for
14
+ * `start --env-name` (§4.6). Set by the human, so the agent driving either
15
+ * can ask only for these; empty when unset, so nothing passes until a
16
+ * person lists something.
17
+ */
18
+ passEnv: string[];
19
+ }
20
+ /** The `mcp` section of a parsed config, with defaults for what is absent. */
21
+ export declare function parseMcpConfig(parsed: unknown, logger: Logger): McpConfig;
22
+ /**
23
+ * Resolve requested variable names against the human's list (§4.6), for the
24
+ * MCP server's `envNames` and the CLI's `--env-name` alike. Names off the
25
+ * list refuse the start; listed names not set in `environment` are reported,
26
+ * by name, and not passed. On Windows names compare in any case, as Windows
27
+ * reads them.
28
+ */
29
+ export declare function resolvePassedEnv(requested: readonly string[], allowed: readonly string[], environment: NodeJS.ProcessEnv): {
30
+ env: Record<string, string>;
31
+ absent: string[];
32
+ refused: string[];
33
+ };
34
+ /**
35
+ * The variables a start passes for the agent its session runs as
36
+ * (`agents.passEnv`, §4.6), with what a caller may add by name. For an agent
37
+ * session the agent's list is the whole answer: its names pass without being
38
+ * asked for, and a requested name off that list refuses the start. A session
39
+ * that runs as no agent passes only requested names on `adHoc`
40
+ * (`mcp.passEnv`). Names, never values, go into the notes and the refusal.
41
+ */
42
+ export declare function planPassedEnv(input: {
43
+ agent: string | null;
44
+ requested: readonly string[];
45
+ agentLists: Readonly<Record<string, readonly string[]>>;
46
+ adHoc: readonly string[];
47
+ environment: NodeJS.ProcessEnv;
48
+ /** Where the values come from, for the notes: "this MCP server's environment". */
49
+ source: string;
50
+ }): {
51
+ env: Record<string, string>;
52
+ notes: string[];
53
+ refusedForAgent: string[];
54
+ refused: string[];
55
+ };
56
+ /** Read the `mcp` section of `<home>/config.json`; no file or no section means the defaults. */
57
+ export declare function readMcpConfig(home: string, logger: Logger): McpConfig;
@@ -0,0 +1,106 @@
1
+ /**
2
+ * The MCP adapter's own section of `config.json` (the daemon reads the
3
+ * rest): the framing toggle at launch, the variable list at every
4
+ * `terminal_start`. Problems are reported through the logger, which
5
+ * the adapter points at stderr: stdout belongs to the MCP protocol.
6
+ */
7
+ import * as fs from 'node:fs';
8
+ import { configPath } from '../daemon/paths.js';
9
+ import { ENV_NAME_PATTERN } from '../core/types.js';
10
+ const DEFAULTS = { untrustedFraming: true, passEnv: [] };
11
+ /** The `mcp` section of a parsed config, with defaults for what is absent. */
12
+ export function parseMcpConfig(parsed, logger) {
13
+ const mcp = typeof parsed === 'object' && parsed !== null
14
+ ? parsed.mcp
15
+ : undefined;
16
+ if (mcp === undefined || mcp === null)
17
+ return { ...DEFAULTS };
18
+ const listed = mcp.passEnv;
19
+ let passEnv = [];
20
+ if (Array.isArray(listed)) {
21
+ passEnv = listed.filter((name) => typeof name === 'string' && ENV_NAME_PATTERN.test(name));
22
+ if (passEnv.length !== listed.length) {
23
+ logger.warn('mcp.passEnv: ignoring entries that are not variable names');
24
+ }
25
+ }
26
+ else if (listed !== undefined) {
27
+ logger.warn('mcp.passEnv must be an array of variable names: passing none');
28
+ }
29
+ return { untrustedFraming: mcp.untrustedFraming !== false, passEnv };
30
+ }
31
+ /**
32
+ * Resolve requested variable names against the human's list (§4.6), for the
33
+ * MCP server's `envNames` and the CLI's `--env-name` alike. Names off the
34
+ * list refuse the start; listed names not set in `environment` are reported,
35
+ * by name, and not passed. On Windows names compare in any case, as Windows
36
+ * reads them.
37
+ */
38
+ export function resolvePassedEnv(requested, allowed, environment) {
39
+ const fold = (name) => (process.platform === 'win32' ? name.toUpperCase() : name);
40
+ const allowedSet = new Set(allowed.map(fold));
41
+ const lookup = new Map();
42
+ for (const [name, value] of Object.entries(environment)) {
43
+ if (value !== undefined)
44
+ lookup.set(fold(name), value);
45
+ }
46
+ const env = {};
47
+ const absent = [];
48
+ const refused = [];
49
+ for (const name of requested) {
50
+ if (!allowedSet.has(fold(name)))
51
+ refused.push(name);
52
+ else if (lookup.has(fold(name)))
53
+ env[name] = lookup.get(fold(name));
54
+ else
55
+ absent.push(name);
56
+ }
57
+ return { env, absent, refused };
58
+ }
59
+ /**
60
+ * The variables a start passes for the agent its session runs as
61
+ * (`agents.passEnv`, §4.6), with what a caller may add by name. For an agent
62
+ * session the agent's list is the whole answer: its names pass without being
63
+ * asked for, and a requested name off that list refuses the start. A session
64
+ * that runs as no agent passes only requested names on `adHoc`
65
+ * (`mcp.passEnv`). Names, never values, go into the notes and the refusal.
66
+ */
67
+ export function planPassedEnv(input) {
68
+ const { agent, requested, environment, source } = input;
69
+ if (agent === null) {
70
+ const { env, absent, refused } = resolvePassedEnv(requested, input.adHoc, environment);
71
+ const notes = [];
72
+ if (Object.keys(env).length > 0)
73
+ notes.push(`Passed from ${source}: ${Object.keys(env).join(', ')}.`);
74
+ if (absent.length > 0)
75
+ notes.push(`Not set in ${source}, so not passed: ${absent.join(', ')}.`);
76
+ return { env, notes, refusedForAgent: [], refused };
77
+ }
78
+ // An own entry only: an agent named `constructor` or `__proto__` has no list.
79
+ const list = Object.prototype.hasOwnProperty.call(input.agentLists, agent) ? (input.agentLists[agent] ?? []) : [];
80
+ const refusedForAgent = resolvePassedEnv(requested, list, environment).refused;
81
+ const { env, absent } = resolvePassedEnv(list, list, environment);
82
+ const notes = [];
83
+ if (Object.keys(env).length > 0)
84
+ notes.push(`Passed for ${agent} from ${source}: ${Object.keys(env).join(', ')}.`);
85
+ if (absent.length > 0)
86
+ notes.push(`Listed for ${agent} but not set in ${source}, so not passed: ${absent.join(', ')}.`);
87
+ return { env, notes, refusedForAgent, refused: [] };
88
+ }
89
+ /** Read the `mcp` section of `<home>/config.json`; no file or no section means the defaults. */
90
+ export function readMcpConfig(home, logger) {
91
+ let raw;
92
+ try {
93
+ raw = fs.readFileSync(configPath(home), 'utf8');
94
+ }
95
+ catch {
96
+ return { ...DEFAULTS };
97
+ }
98
+ try {
99
+ return parseMcpConfig(JSON.parse(raw), logger);
100
+ }
101
+ catch {
102
+ logger.warn('config.json could not be parsed: using the MCP defaults');
103
+ return { ...DEFAULTS };
104
+ }
105
+ }
106
+ //# sourceMappingURL=config.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"config.js","sourceRoot":"","sources":["../../src/mcp/config.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAEH,OAAO,KAAK,EAAE,MAAM,SAAS,CAAC;AAC9B,OAAO,EAAE,UAAU,EAAE,MAAM,oBAAoB,CAAC;AAChD,OAAO,EAAE,gBAAgB,EAAE,MAAM,kBAAkB,CAAC;AAgBpD,MAAM,QAAQ,GAAc,EAAE,gBAAgB,EAAE,IAAI,EAAE,OAAO,EAAE,EAAE,EAAE,CAAC;AAEpE,8EAA8E;AAC9E,MAAM,UAAU,cAAc,CAAC,MAAe,EAAE,MAAc;IAC5D,MAAM,GAAG,GACP,OAAO,MAAM,KAAK,QAAQ,IAAI,MAAM,KAAK,IAAI;QAC3C,CAAC,CAAE,MAAsE,CAAC,GAAG;QAC7E,CAAC,CAAC,SAAS,CAAC;IAChB,IAAI,GAAG,KAAK,SAAS,IAAI,GAAG,KAAK,IAAI;QAAE,OAAO,EAAE,GAAG,QAAQ,EAAE,CAAC;IAE9D,MAAM,MAAM,GAAG,GAAG,CAAC,OAAO,CAAC;IAC3B,IAAI,OAAO,GAAa,EAAE,CAAC;IAC3B,IAAI,KAAK,CAAC,OAAO,CAAC,MAAM,CAAC,EAAE,CAAC;QAC1B,OAAO,GAAG,MAAM,CAAC,MA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,OAAO,cAAc,CAAC,IAAI,CAAC,KAAK,CAAC,GAAG,CAAC,EAAE,MAAM,CAAC,CAAC;IACjD,CAAC;IAAC,MAAM,CAAC;QACP,MAAM,CAAC,IAAI,CAAC,yDAAyD,CAAC,CAAC;QACvE,OAAO,EAAE,GAAG,QAAQ,EAAE,CAAC;IACzB,CAAC;AACH,CAAC"}
@@ -0,0 +1,10 @@
1
+ /**
2
+ * MCP adapter entry: a stdio MCP server that is a thin client to the shared
3
+ * daemon (design §2.1: it must never own PTYs itself).
4
+ *
5
+ * stdout belongs ENTIRELY to the MCP protocol. Nothing on this code path may
6
+ * print to it: diagnostics go to stderr, which MCP clients capture as logs.
7
+ * Importing this module starts the server; the CLI's `mcp` verb does exactly
8
+ * that.
9
+ */
10
+ export {};