shellpuppet 0.0.1 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (137) hide show
  1. package/LICENSE +202 -0
  2. package/NOTICE +31 -0
  3. package/README.md +499 -8
  4. package/dist/cli/desktopShortcut.d.ts +22 -0
  5. package/dist/cli/desktopShortcut.js +157 -0
  6. package/dist/cli/desktopShortcut.js.map +1 -0
  7. package/dist/cli/index.d.ts +13 -0
  8. package/dist/cli/index.js +846 -0
  9. package/dist/cli/index.js.map +1 -0
  10. package/dist/client/http.d.ts +143 -0
  11. package/dist/client/http.js +581 -0
  12. package/dist/client/http.js.map +1 -0
  13. package/dist/core/dialogs.d.ts +96 -0
  14. package/dist/core/dialogs.js +226 -0
  15. package/dist/core/dialogs.js.map +1 -0
  16. package/dist/core/echo.d.ts +71 -0
  17. package/dist/core/echo.js +249 -0
  18. package/dist/core/echo.js.map +1 -0
  19. package/dist/core/find.d.ts +34 -0
  20. package/dist/core/find.js +41 -0
  21. package/dist/core/find.js.map +1 -0
  22. package/dist/core/keys.d.ts +22 -0
  23. package/dist/core/keys.js +80 -0
  24. package/dist/core/keys.js.map +1 -0
  25. package/dist/core/manager.d.ts +96 -0
  26. package/dist/core/manager.js +271 -0
  27. package/dist/core/manager.js.map +1 -0
  28. package/dist/core/nativePty.d.ts +73 -0
  29. package/dist/core/nativePty.js +161 -0
  30. package/dist/core/nativePty.js.map +1 -0
  31. package/dist/core/policy.d.ts +61 -0
  32. package/dist/core/policy.js +143 -0
  33. package/dist/core/policy.js.map +1 -0
  34. package/dist/core/promptDetector.d.ts +109 -0
  35. package/dist/core/promptDetector.js +897 -0
  36. package/dist/core/promptDetector.js.map +1 -0
  37. package/dist/core/reasoning.d.ts +265 -0
  38. package/dist/core/reasoning.js +933 -0
  39. package/dist/core/reasoning.js.map +1 -0
  40. package/dist/core/regexBudget.d.ts +64 -0
  41. package/dist/core/regexBudget.js +103 -0
  42. package/dist/core/regexBudget.js.map +1 -0
  43. package/dist/core/renderer.d.ts +127 -0
  44. package/dist/core/renderer.js +316 -0
  45. package/dist/core/renderer.js.map +1 -0
  46. package/dist/core/selection.d.ts +6 -0
  47. package/dist/core/selection.js +48 -0
  48. package/dist/core/selection.js.map +1 -0
  49. package/dist/core/session.d.ts +565 -0
  50. package/dist/core/session.js +1450 -0
  51. package/dist/core/session.js.map +1 -0
  52. package/dist/core/types.d.ts +316 -0
  53. package/dist/core/types.js +71 -0
  54. package/dist/core/types.js.map +1 -0
  55. package/dist/core/waiter.d.ts +94 -0
  56. package/dist/core/waiter.js +310 -0
  57. package/dist/core/waiter.js.map +1 -0
  58. package/dist/core/windowsConsoleHost.d.ts +147 -0
  59. package/dist/core/windowsConsoleHost.js +588 -0
  60. package/dist/core/windowsConsoleHost.js.map +1 -0
  61. package/dist/core/windowsPtyStart.d.ts +161 -0
  62. package/dist/core/windowsPtyStart.js +236 -0
  63. package/dist/core/windowsPtyStart.js.map +1 -0
  64. package/dist/daemon/audit.d.ts +23 -0
  65. package/dist/daemon/audit.js +51 -0
  66. package/dist/daemon/audit.js.map +1 -0
  67. package/dist/daemon/auth.d.ts +197 -0
  68. package/dist/daemon/auth.js +366 -0
  69. package/dist/daemon/auth.js.map +1 -0
  70. package/dist/daemon/config.d.ts +119 -0
  71. package/dist/daemon/config.js +568 -0
  72. package/dist/daemon/config.js.map +1 -0
  73. package/dist/daemon/folderPicker.d.ts +27 -0
  74. package/dist/daemon/folderPicker.js +115 -0
  75. package/dist/daemon/folderPicker.js.map +1 -0
  76. package/dist/daemon/index.d.ts +7 -0
  77. package/dist/daemon/index.js +88 -0
  78. package/dist/daemon/index.js.map +1 -0
  79. package/dist/daemon/launchProfiles.d.ts +155 -0
  80. package/dist/daemon/launchProfiles.js +554 -0
  81. package/dist/daemon/launchProfiles.js.map +1 -0
  82. package/dist/daemon/liveness.d.ts +36 -0
  83. package/dist/daemon/liveness.js +71 -0
  84. package/dist/daemon/liveness.js.map +1 -0
  85. package/dist/daemon/logger.d.ts +7 -0
  86. package/dist/daemon/logger.js +29 -0
  87. package/dist/daemon/logger.js.map +1 -0
  88. package/dist/daemon/meta.d.ts +9 -0
  89. package/dist/daemon/meta.js +24 -0
  90. package/dist/daemon/meta.js.map +1 -0
  91. package/dist/daemon/paths.d.ts +85 -0
  92. package/dist/daemon/paths.js +154 -0
  93. package/dist/daemon/paths.js.map +1 -0
  94. package/dist/daemon/screenshot.d.ts +144 -0
  95. package/dist/daemon/screenshot.js +402 -0
  96. package/dist/daemon/screenshot.js.map +1 -0
  97. package/dist/daemon/server.d.ts +453 -0
  98. package/dist/daemon/server.js +3954 -0
  99. package/dist/daemon/server.js.map +1 -0
  100. package/dist/daemon/sessionFeed.d.ts +48 -0
  101. package/dist/daemon/sessionFeed.js +101 -0
  102. package/dist/daemon/sessionFeed.js.map +1 -0
  103. package/dist/daemon/terminalReports.d.ts +38 -0
  104. package/dist/daemon/terminalReports.js +84 -0
  105. package/dist/daemon/terminalReports.js.map +1 -0
  106. package/dist/daemon/viewerLauncher.d.ts +226 -0
  107. package/dist/daemon/viewerLauncher.js +562 -0
  108. package/dist/daemon/viewerLauncher.js.map +1 -0
  109. package/dist/daemon/viewerSync.d.ts +38 -0
  110. package/dist/daemon/viewerSync.js +83 -0
  111. package/dist/daemon/viewerSync.js.map +1 -0
  112. package/dist/mcp/config.d.ts +50 -0
  113. package/dist/mcp/config.js +95 -0
  114. package/dist/mcp/config.js.map +1 -0
  115. package/dist/mcp/index.d.ts +10 -0
  116. package/dist/mcp/index.js +78 -0
  117. package/dist/mcp/index.js.map +1 -0
  118. package/dist/mcp/tools.d.ts +66 -0
  119. package/dist/mcp/tools.js +638 -0
  120. package/dist/mcp/tools.js.map +1 -0
  121. package/dist/viewer/dashboard-folders.js +20 -0
  122. package/dist/viewer/dashboard-layout.js +52 -0
  123. package/dist/viewer/dashboard.css +67 -0
  124. package/dist/viewer/dashboard.html +44 -0
  125. package/dist/viewer/dashboard.js +1518 -0
  126. package/dist/viewer/icon-16.png +0 -0
  127. package/dist/viewer/icon-180.png +0 -0
  128. package/dist/viewer/icon-32.png +0 -0
  129. package/dist/viewer/icon-512.png +0 -0
  130. package/dist/viewer/icon.ico +0 -0
  131. package/dist/viewer/icon.svg +66 -0
  132. package/dist/viewer/index.html +61 -0
  133. package/dist/viewer/pane.js +736 -0
  134. package/dist/viewer/viewer.css +95 -0
  135. package/dist/viewer/viewer.js +84 -0
  136. package/package.json +66 -7
  137. package/index.js +0 -4
@@ -0,0 +1,736 @@
1
+ /**
2
+ * ShellPuppet pane: the terminal client for one session in one container.
3
+ *
4
+ * It owns frame handling, typing (with term.onData registered once), sizing,
5
+ * reconnect and badges for one session. The page provides the container and
6
+ * badge elements, and wires up its controls.
7
+ *
8
+ * Wire protocol: BINARY WebSocket frames carry terminal bytes (snapshots, the
9
+ * live stream and the exit notice); TEXT frames are JSON control messages:
10
+ * `identity`, `geometry`, `input-source`, `input-refused`, `exited`,
11
+ * `prompt-stall` and `prompt-clear`. What this pane sends is text: a JSON
12
+ * resize message, or bytes for the program, which are either keystrokes or
13
+ * the terminal's own answers to the program's queries. The daemon tells those
14
+ * two apart.
15
+ *
16
+ * Three rules shape the pane:
17
+ * - `term.onData` is registered exactly ONCE, never inside the connect path.
18
+ * Registering per-connect would stack a listener per reconnect and send
19
+ * every keystroke N times.
20
+ * - The fit addon measures what grid this window would like, and the pane asks
21
+ * the daemon for it rather than assuming it (§5). The daemon decides who is
22
+ * driving the grid and answers with a geometry frame; only that frame
23
+ * resizes anything here.
24
+ * - The pane never rebuilds terminal state itself. On connect and after every
25
+ * grid change the daemon sends a snapshot of its own renderer, a wipe followed
26
+ * by the bytes that rebuild the screen, so what this pane shows is what the
27
+ * daemon renders, which is what the agent reads. A tail of the raw stream
28
+ * replayed here would start mid-frame.
29
+ */
30
+
31
+ /* global Terminal, FitAddon */
32
+
33
+ window.ShellPuppetPane = (() => {
34
+ 'use strict';
35
+
36
+ const MIN_FONT_PX = 6;
37
+ const MAX_FONT_PX = 40;
38
+ const DEFAULT_FONT_PX = 13;
39
+
40
+ function clampFont(px) {
41
+ return Math.min(MAX_FONT_PX, Math.max(MIN_FONT_PX, px));
42
+ }
43
+
44
+ /**
45
+ * Create a pane for one session in one container.
46
+ *
47
+ * @param {Object} config
48
+ * @param {HTMLElement} config.container - The element to host the terminal.
49
+ * @param {string} config.sessionId - The session to connect to.
50
+ * @param {boolean} [config.captureMode=false] - Headless screenshot mode.
51
+ * @param {boolean} [config.redactedCapture=false] - Redact sensitive rows.
52
+ * @param {Object} config.elements - References to badge elements.
53
+ * @param {number|null} [config.initialFontOverride=null] - Initial font size.
54
+ * @param {function} [config.onTitleChange] - Called when the window title should change.
55
+ * @param {function} [config.onFontOverrideChange] - Called when the font override changes.
56
+ * @param {function} [config.onGeometryReady] - Called after the first geometry frame.
57
+ * @param {function} [config.onOutsideGeometry] - Called when another client changes an unheld grid.
58
+ * @param {string} [config.dashboardProof] - Document proof for a dashboard stream.
59
+ * @param {function} [config.onAttentionChange] - Reports prompt attention.
60
+ * @returns {Object} A pane instance for the page to control.
61
+ */
62
+ function create(config) {
63
+ const {
64
+ container,
65
+ sessionId,
66
+ captureMode = false,
67
+ redactedCapture = false,
68
+ elements = {},
69
+ initialFontOverride = null,
70
+ onTitleChange = () => {},
71
+ onFontOverrideChange = () => {},
72
+ onGeometryReady = () => {},
73
+ onOutsideGeometry = () => {},
74
+ onGridTaken = () => {},
75
+ dashboardProof = null,
76
+ onAttentionChange = () => {},
77
+ } = config;
78
+
79
+ let fontOverride = initialFontOverride;
80
+ let ws = null;
81
+ let readOnly = false;
82
+ let readOnlyEnforced = false;
83
+ let retriesLeft = 8;
84
+ let everConnected = false;
85
+ let sessionEnded = false;
86
+ let inputFailed = false;
87
+ let promptWaiting = false;
88
+ let gridCols = 0;
89
+ let gridRows = 0;
90
+ let gridMax = { cols: Infinity, rows: Infinity };
91
+ let controlMode = 'adopt';
92
+ let geometryDecided = false;
93
+ let firstFrameSeen = false;
94
+ let identityTitle = `${sessionId} · ShellPuppet`;
95
+ let destroyed = false;
96
+ let reconnectTimer = null;
97
+ let pendingTakeGrid = false;
98
+ let outsideResizePending = false;
99
+ let lastOutsideFitAt = 0;
100
+ let followingExternal = false;
101
+
102
+ const showBanner = (message) => {
103
+ if (!elements.banner) return;
104
+ const text = elements.banner.querySelector('.pane-banner-message') || elements.banner;
105
+ text.textContent = message;
106
+ elements.banner.hidden = false;
107
+ positionNotices();
108
+ };
109
+
110
+ const refreshTitle = () => {
111
+ const prefix = sessionEnded ? '[ENDED] ' : promptWaiting ? '[ANSWER ME] ' : '';
112
+ onTitleChange(prefix + identityTitle);
113
+ };
114
+ refreshTitle();
115
+
116
+ const showEnded = (exitCode) => {
117
+ if (sessionEnded) return;
118
+ sessionEnded = true;
119
+ if (elements.readonly) elements.readonly.disabled = true;
120
+ const withCode = typeof exitCode === 'number';
121
+ if (elements.readonly) {
122
+ elements.readonly.title = withCode ? 'The program has exited' : 'The session has ended';
123
+ }
124
+ if (elements.modeHint) {
125
+ elements.modeHint.textContent = withCode
126
+ ? `the program has exited (code ${String(exitCode)}); this session no longer accepts input`
127
+ : 'the session has ended: its output failed; it no longer accepts input';
128
+ }
129
+ refreshTitle();
130
+ };
131
+
132
+ const showInputFailed = () => {
133
+ if (sessionEnded || inputFailed) return;
134
+ inputFailed = true;
135
+ if (elements.modeHint) {
136
+ elements.modeHint.textContent = "this session's input has failed; kill it and start it again";
137
+ }
138
+ };
139
+
140
+ const showIdentity = (identity) => {
141
+ const purpose = identity.purpose || identity.label || sessionId;
142
+ if (elements.identityPurpose) elements.identityPurpose.textContent = purpose;
143
+
144
+ const meta = [identity.session, identity.command].filter(Boolean).join(' · ');
145
+ if (elements.identityMeta) elements.identityMeta.textContent = meta;
146
+ if (elements.identity) elements.identity.hidden = false;
147
+
148
+ if (identity.startedBy && elements.sessionAgent) {
149
+ elements.sessionAgent.textContent = `started by ${identity.startedBy}`;
150
+ }
151
+
152
+ if (identity.readOnly === true) {
153
+ readOnlyEnforced = true;
154
+ readOnly = true;
155
+ showReadOnly();
156
+ }
157
+
158
+ if (identity.exited === true) showEnded(identity.exitCode);
159
+ if (identity.inputFailed === true) showInputFailed();
160
+
161
+ identityTitle = `${identity.session} ${purpose} · ShellPuppet`;
162
+ refreshTitle();
163
+ };
164
+
165
+ const showPromptAlert = (question, waitingMs, options) => {
166
+ const seconds = Math.round((waitingMs || 0) / 1000);
167
+ if (!elements.promptAlert) return;
168
+ elements.promptAlert.textContent = '';
169
+ const heading = document.createElement('div');
170
+ heading.textContent = `Waiting for you: ${String(seconds)}s unanswered`;
171
+ const question_ = document.createElement('div');
172
+ question_.className = 'question';
173
+ question_.textContent = question || '(the session is holding a prompt)';
174
+ elements.promptAlert.append(heading, question_);
175
+
176
+ if (Array.isArray(options) && options.length > 0) {
177
+ const list = document.createElement('ul');
178
+ list.className = 'options';
179
+ for (const option of options) {
180
+ const item = document.createElement('li');
181
+ item.textContent = option;
182
+ list.append(item);
183
+ }
184
+ elements.promptAlert.append(list);
185
+ }
186
+ elements.promptAlert.hidden = false;
187
+ positionNotices();
188
+ promptWaiting = true;
189
+ onAttentionChange(true);
190
+ refreshTitle();
191
+ };
192
+
193
+ const clearPromptAlert = () => {
194
+ if (!elements.promptAlert) return;
195
+ elements.promptAlert.hidden = true;
196
+ elements.promptAlert.textContent = '';
197
+ promptWaiting = false;
198
+ onAttentionChange(false);
199
+ refreshTitle();
200
+ };
201
+
202
+ const term = new Terminal({
203
+ cursorBlink: true,
204
+ fontSize: fontOverride ?? DEFAULT_FONT_PX,
205
+ scrollback: 5000,
206
+ allowProposedApi: true,
207
+ fontFamily: 'ui-monospace, "Cascadia Code", Consolas, monospace',
208
+ theme: { background: '#0b0e14', foreground: '#c5cdd9', cursor: '#6cb6ff' },
209
+ });
210
+ const fit = new FitAddon.FitAddon();
211
+ term.loadAddon(fit);
212
+ term.open(container);
213
+ const outerScroll = container.parentElement;
214
+ const helper = term.element?.querySelector('.xterm-helper-textarea');
215
+ if (dashboardProof !== null && outerScroll && helper) {
216
+ let view = { left: 0, top: 0 };
217
+ let composing = false;
218
+ const rememberView = () => {
219
+ view = { left: outerScroll.scrollLeft, top: outerScroll.scrollTop };
220
+ };
221
+ const restoreView = () => {
222
+ if (!outerScroll.classList.contains('grid-overflow')) return;
223
+ outerScroll.scrollLeft = view.left;
224
+ outerScroll.scrollTop = view.top;
225
+ };
226
+ const restoreAfterInput = () => {
227
+ restoreView();
228
+ window.requestAnimationFrame(restoreView);
229
+ };
230
+ const nativeFocus = helper.focus.bind(helper);
231
+ helper.focus = (options) => {
232
+ rememberView();
233
+ nativeFocus({ ...options, preventScroll: true });
234
+ restoreAfterInput();
235
+ };
236
+ outerScroll.addEventListener('pointerdown', rememberView, true);
237
+ helper.addEventListener('focus', restoreAfterInput);
238
+ helper.addEventListener('beforeinput', () => { if (!composing) rememberView(); });
239
+ helper.addEventListener('input', restoreAfterInput);
240
+ helper.addEventListener('compositionstart', () => { rememberView(); composing = true; restoreAfterInput(); });
241
+ helper.addEventListener('compositionupdate', restoreAfterInput);
242
+ helper.addEventListener('compositionend', () => { restoreAfterInput(); composing = false; });
243
+ }
244
+ const scrollOversizedPane = (event) => {
245
+ if (!outerScroll?.classList.contains('grid-overflow') ||
246
+ (!event.shiftKey && event.deltaX === 0)) return;
247
+ event.preventDefault();
248
+ event.stopPropagation();
249
+ outerScroll.scrollLeft += event.deltaX;
250
+ if (event.shiftKey) outerScroll.scrollTop += event.deltaY;
251
+ };
252
+ outerScroll?.addEventListener('wheel', scrollOversizedPane, { capture: true, passive: false });
253
+ const platform = navigator.userAgentData?.platform || navigator.userAgent;
254
+ const isMac = /Mac|iPhone|iPad/i.test(platform);
255
+ // Let the browser deliver paste to xterm's textarea on Windows and Linux.
256
+ term.attachCustomKeyEventHandler((event) => {
257
+ if (isMac || event.type !== 'keydown' || !event.ctrlKey || event.shiftKey || event.altKey || event.metaKey) return true;
258
+ if (event.key.toLowerCase() === 'v') return false;
259
+ if (event.key.toLowerCase() === 'c' && term.hasSelection()) {
260
+ event.preventDefault();
261
+ if (typeof navigator.clipboard?.writeText !== 'function') {
262
+ showBanner('Could not copy selected text to the clipboard.');
263
+ return false;
264
+ }
265
+ const selection = term.getSelection();
266
+ void navigator.clipboard.writeText(selection).then(() => {
267
+ if (term.getSelection() === selection) term.clearSelection();
268
+ }).catch(() => showBanner('Could not copy selected text to the clipboard.'));
269
+ return false;
270
+ }
271
+ return true;
272
+ });
273
+
274
+ // The terminal can be centred within #wrap when its grid is held. Anchor
275
+ // notices to the rendered screen, not to the outer fit box, and keep the
276
+ // cursor's half free even as a TUI moves its cursor without a grid change.
277
+ function positionNotices() {
278
+ const notices = elements.promptAlert?.parentElement || elements.banner?.parentElement;
279
+ const wrap = container.parentElement;
280
+ const screen = term.element?.querySelector('.xterm-screen');
281
+ if (!notices || !wrap || !screen || term.rows < 1) return;
282
+ const screenRect = screen.getBoundingClientRect();
283
+ const wrapRect = wrap.getBoundingClientRect();
284
+ notices.style.maxHeight = `${String(screenRect.height / 3)}px`;
285
+ if (term.buffer.active.cursorY < term.rows / 2) {
286
+ notices.style.top = 'auto';
287
+ notices.style.bottom = `${String(wrapRect.bottom - screenRect.bottom)}px`;
288
+ } else {
289
+ notices.style.bottom = 'auto';
290
+ notices.style.top = `${String(screenRect.top - wrapRect.top)}px`;
291
+ }
292
+ }
293
+ term.onCursorMove(positionNotices);
294
+ positionNotices();
295
+
296
+ if (redactedCapture) {
297
+ window.__shellpuppetCoverRows = (hiddenRows) => {
298
+ const rows = container.querySelectorAll('.xterm-rows > div');
299
+ for (const index of hiddenRows) {
300
+ const row = rows[index];
301
+ if (!row) continue;
302
+ const rect = row.getBoundingClientRect();
303
+ row.style.filter = 'blur(20px)';
304
+ const cover = document.createElement('div');
305
+ cover.style.cssText =
306
+ `position:fixed;left:0;top:${rect.top}px;width:100vw;height:${rect.height}px;` +
307
+ 'z-index:2147483647;pointer-events:none;background:rgba(20,20,20,.97);' +
308
+ 'backdrop-filter:blur(20px);color:#d0d0d0;font:11px sans-serif;';
309
+ cover.textContent = hiddenRows.includes(index - 1) ? '' : 'reasoning hidden';
310
+ document.body.append(cover);
311
+ }
312
+ };
313
+ }
314
+
315
+ term.onData((data) => {
316
+ if (destroyed || sessionEnded || readOnly) return;
317
+ if (ws && ws.readyState === 1) ws.send(data);
318
+ });
319
+
320
+ function showReadOnly() {
321
+ if (!elements.readonly) return;
322
+ elements.readonly.textContent = `read-only: ${readOnly ? 'on' : 'off'}`;
323
+ elements.readonly.classList.toggle('active', readOnly);
324
+ if (sessionEnded || inputFailed) return;
325
+ if (readOnlyEnforced) {
326
+ elements.readonly.disabled = true;
327
+ elements.readonly.title = 'This viewer link grants watching only';
328
+ if (elements.modeHint) {
329
+ elements.modeHint.textContent = 'read-only link: the session will not accept your keystrokes';
330
+ }
331
+ return;
332
+ }
333
+ if (elements.modeHint) {
334
+ elements.modeHint.textContent = readOnly
335
+ ? 'read-only: your keystrokes stay local'
336
+ : 'you and the agent share this session: type freely';
337
+ }
338
+ }
339
+
340
+ function relayout(deliberate) {
341
+ if (!geometryDecided) return;
342
+ if (dashboardProof !== null) {
343
+ applyFontPreference(gridCols, gridRows);
344
+ positionNotices();
345
+ return;
346
+ }
347
+ if (controlMode === 'held' || captureMode || (controlMode === 'adopt' && !deliberate)) {
348
+ applyFontPreference(gridCols, gridRows);
349
+ } else {
350
+ requestFit();
351
+ }
352
+ positionNotices();
353
+ }
354
+
355
+ function requestFit() {
356
+ const font = drivingFontPx();
357
+ if (term.options.fontSize !== font) {
358
+ term.options.fontSize = font;
359
+ term.resize(term.cols, term.rows);
360
+ }
361
+ updateZoomButtons();
362
+ const proposed = propose();
363
+ if (proposed === null) return;
364
+ const cols = Math.min(proposed.cols, gridMax.cols);
365
+ const rows = Math.min(proposed.rows, gridMax.rows);
366
+ if (cols === gridCols && rows === gridRows && controlMode !== 'adopt') return;
367
+ if (ws && ws.readyState === 1) {
368
+ ws.send(JSON.stringify({ type: 'resize', cols, rows }));
369
+ }
370
+ }
371
+
372
+ function propose() {
373
+ let proposed;
374
+ try {
375
+ proposed = fit.proposeDimensions();
376
+ } catch {
377
+ return null;
378
+ }
379
+ if (!proposed || !proposed.cols || !proposed.rows) return null;
380
+ return { cols: proposed.cols, rows: proposed.rows };
381
+ }
382
+
383
+ function fixedFontPx() {
384
+ return fontOverride === null ? DEFAULT_FONT_PX : fontOverride;
385
+ }
386
+
387
+ function proposeDashboardGrid() {
388
+ const drawn = term.options.fontSize;
389
+ let proposed;
390
+ try {
391
+ term.options.fontSize = fixedFontPx();
392
+ proposed = propose();
393
+ if (proposed === null) return null;
394
+ if (proposed.cols > gridMax.cols || proposed.rows > gridMax.rows) {
395
+ for (let font = fixedFontPx() + 1; font <= MAX_FONT_PX; font++) {
396
+ term.options.fontSize = font;
397
+ const larger = propose();
398
+ if (larger === null ||
399
+ (larger.cols < gridMax.cols && larger.rows < gridMax.rows)) break;
400
+ proposed = larger;
401
+ }
402
+ }
403
+ } finally {
404
+ term.options.fontSize = drawn;
405
+ }
406
+ return proposed;
407
+ }
408
+
409
+ function drivingFontPx() {
410
+ const fixed = fixedFontPx();
411
+ const drawn = term.options.fontSize;
412
+ let font = fixed;
413
+ try {
414
+ for (; font < MAX_FONT_PX; font++) {
415
+ term.options.fontSize = font;
416
+ const proposed = propose();
417
+ if (proposed === null) break;
418
+ if (proposed.cols <= gridMax.cols && proposed.rows <= gridMax.rows) break;
419
+ }
420
+ } finally {
421
+ term.options.fontSize = drawn;
422
+ }
423
+ return font;
424
+ }
425
+
426
+ function fitGridByFont(cols, rows, grow = true) {
427
+ const wrap = container.parentElement;
428
+ if (!wrap) return;
429
+
430
+ const styles = window.getComputedStyle(wrap);
431
+ const availableWidth = wrap.clientWidth
432
+ - parseFloat(styles.paddingLeft) - parseFloat(styles.paddingRight);
433
+ const availableHeight = wrap.clientHeight
434
+ - parseFloat(styles.paddingTop) - parseFloat(styles.paddingBottom);
435
+ if (availableWidth <= 0 || availableHeight <= 0) return;
436
+
437
+ for (let pass = 0; pass < 4; pass++) {
438
+ const screen = term.element && term.element.querySelector('.xterm-screen');
439
+ if (!screen) return;
440
+ const renderedWidth = screen.offsetWidth;
441
+ const renderedHeight = screen.offsetHeight;
442
+ if (renderedWidth <= 0 || renderedHeight <= 0) return;
443
+
444
+ const scale = Math.min(
445
+ availableWidth / renderedWidth,
446
+ availableHeight / renderedHeight,
447
+ );
448
+ if (Math.abs(scale - 1) < 0.01 || (scale > 1 && !grow)) return;
449
+
450
+ const current = term.options.fontSize || DEFAULT_FONT_PX;
451
+ const next = Math.min(MAX_FONT_PX, Math.max(MIN_FONT_PX, Math.floor(current * scale)));
452
+ if (next === current) return;
453
+
454
+ term.options.fontSize = next;
455
+ term.resize(cols, rows);
456
+ }
457
+ }
458
+
459
+ function updateOverflowState() {
460
+ if (dashboardProof === null) return;
461
+ const wrap = container.parentElement;
462
+ const screen = term.element?.querySelector('.xterm-screen');
463
+ if (!wrap || !screen) return;
464
+ const styles = window.getComputedStyle(wrap);
465
+ const availableWidth = wrap.clientWidth - parseFloat(styles.paddingLeft) - parseFloat(styles.paddingRight);
466
+ const availableHeight = wrap.clientHeight - parseFloat(styles.paddingTop) - parseFloat(styles.paddingBottom);
467
+ const overflowing = controlMode !== 'yours' && term.options.fontSize === MIN_FONT_PX &&
468
+ (screen.offsetWidth > availableWidth + 1 || screen.offsetHeight > availableHeight + 1);
469
+ wrap.classList.toggle('grid-overflow', overflowing);
470
+ if (elements.overflowNote) elements.overflowNote.hidden = !overflowing;
471
+ }
472
+
473
+ function applyFontPreference(cols, rows) {
474
+ if (fontOverride === null) {
475
+ fitGridByFont(cols, rows);
476
+ } else {
477
+ if (term.options.fontSize !== fontOverride) {
478
+ term.options.fontSize = fontOverride;
479
+ term.resize(cols, rows);
480
+ }
481
+ if (dashboardProof !== null) {
482
+ const capped = cols >= gridMax.cols || rows >= gridMax.rows;
483
+ if (controlMode !== 'yours' || capped) fitGridByFont(cols, rows, capped && controlMode === 'yours');
484
+ }
485
+ }
486
+ updateZoomButtons();
487
+ container.dataset.fontSize = String(term.options.fontSize);
488
+ updateOverflowState();
489
+ }
490
+
491
+ function applyGeometry(cols, rows, max) {
492
+ if (!Number.isInteger(cols) || !Number.isInteger(rows)) return;
493
+ gridCols = cols;
494
+ gridRows = rows;
495
+ if (max && Number.isInteger(max.cols) && Number.isInteger(max.rows)) {
496
+ gridMax = { cols: max.cols, rows: max.rows };
497
+ }
498
+ if (term.cols !== cols || term.rows !== rows) term.resize(cols, rows);
499
+ if (controlMode === 'yours' && !captureMode && dashboardProof === null) {
500
+ updateZoomButtons();
501
+ } else {
502
+ applyFontPreference(cols, rows);
503
+ }
504
+ if (elements.size) {
505
+ elements.size.textContent =
506
+ `${cols}×${rows}` +
507
+ (controlMode === 'held' ? ' (fixed)' : controlMode === 'adopt' ? ' (following)' : '');
508
+ }
509
+ positionNotices();
510
+ }
511
+
512
+ function updateZoomButtons() {
513
+ if (!elements.zoomAuto) return;
514
+ elements.zoomAuto.classList.toggle('active', fontOverride === null);
515
+ elements.zoomAuto.title = fontOverride === null
516
+ ? 'Text size chosen automatically (click - or + to set it yourself)'
517
+ : 'Choose the text size automatically again';
518
+ }
519
+
520
+ function setFontOverride(value) {
521
+ fontOverride = value;
522
+ onFontOverrideChange(value);
523
+ if (dashboardProof !== null) {
524
+ applyFontPreference(gridCols, gridRows);
525
+ positionNotices();
526
+ return;
527
+ }
528
+ if (controlMode === 'held' || captureMode) {
529
+ applyFontPreference(gridCols, gridRows);
530
+ positionNotices();
531
+ return;
532
+ }
533
+ requestFit();
534
+ positionNotices();
535
+ }
536
+
537
+ function nudgeFont(delta) {
538
+ const base = term.options.fontSize || DEFAULT_FONT_PX;
539
+ setFontOverride(clampFont(base + delta));
540
+ }
541
+
542
+ function showInputSource(source) {
543
+ if (!elements.inputSource) return;
544
+ const who = source === 'human' ? 'human' : 'agent';
545
+ const at = new Date().toLocaleTimeString();
546
+ elements.inputSource.textContent = `last input: ${who} ${at}`;
547
+ elements.inputSource.className = `hint ${who}`;
548
+ }
549
+
550
+ function connect() {
551
+ if (destroyed) return;
552
+ ws = new WebSocket(`ws://${location.host}/sessions/${encodeURIComponent(sessionId)}/stream`,
553
+ dashboardProof === null ? undefined : [`sp-csrf.${dashboardProof}`]);
554
+ ws.binaryType = 'arraybuffer';
555
+
556
+ ws.onopen = () => {
557
+ everConnected = true;
558
+ if (elements.dot) elements.dot.classList.remove('off');
559
+ if (elements.banner) elements.banner.hidden = true;
560
+ retriesLeft = 8;
561
+ geometryDecided = false;
562
+ };
563
+
564
+ ws.onmessage = (event) => {
565
+ if (destroyed) return;
566
+ if (event.data instanceof ArrayBuffer) {
567
+ if (redactedCapture && window.__shellpuppetPainted === true) return;
568
+ if (captureMode && !firstFrameSeen) {
569
+ firstFrameSeen = true;
570
+ term.write(new Uint8Array(event.data), () => {
571
+ window.requestAnimationFrame(() => {
572
+ window.requestAnimationFrame(() => {
573
+ window.__shellpuppetPainted = true;
574
+ });
575
+ });
576
+ });
577
+ return;
578
+ }
579
+ term.write(new Uint8Array(event.data));
580
+ return;
581
+ }
582
+ try {
583
+ const control = JSON.parse(event.data);
584
+ if (control && control.type === 'input-source') {
585
+ showInputSource(control.source);
586
+ } else if (control && control.type === 'geometry') {
587
+ const firstGeometry = !geometryDecided;
588
+ geometryDecided = true;
589
+ controlMode = captureMode ? 'adopt' : control.control || 'adopt';
590
+ if (dashboardProof !== null && firstGeometry && controlMode === 'yours') {
591
+ pendingTakeGrid = false;
592
+ onGridTaken();
593
+ }
594
+ if (dashboardProof !== null && !firstGeometry) {
595
+ if (controlMode === 'yours' && pendingTakeGrid) {
596
+ pendingTakeGrid = false;
597
+ onGridTaken();
598
+ } else if (controlMode === 'adopt' && !followingExternal) {
599
+ pendingTakeGrid = false;
600
+ if (Date.now() - lastOutsideFitAt < 10_000) {
601
+ followingExternal = true;
602
+ outsideResizePending = false;
603
+ } else {
604
+ outsideResizePending = true;
605
+ onOutsideGeometry();
606
+ }
607
+ }
608
+ }
609
+ applyGeometry(control.cols, control.rows, control.max);
610
+ if (firstGeometry) onGeometryReady();
611
+ if (controlMode === 'yours' && !captureMode && dashboardProof === null) requestFit();
612
+ } else if (control && control.type === 'identity') {
613
+ showIdentity(control);
614
+ } else if (control && control.type === 'exited') {
615
+ showEnded(control.exitCode);
616
+ } else if (control && control.type === 'input-refused') {
617
+ if (control.reason === 'exited') showEnded(control.exitCode);
618
+ else if (control.reason === 'input-failed') showInputFailed();
619
+ } else if (control && control.type === 'prompt-stall') {
620
+ showPromptAlert(control.question, control.waitingMs, control.options);
621
+ } else if (control && control.type === 'prompt-clear') {
622
+ clearPromptAlert();
623
+ }
624
+ } catch {
625
+ // Unknown text frame: ignore rather than corrupt the terminal.
626
+ }
627
+ };
628
+
629
+ ws.onclose = () => {
630
+ if (destroyed) return;
631
+ if (elements.dot) elements.dot.classList.add('off');
632
+ if (retriesLeft-- > 0) {
633
+ reconnectTimer = setTimeout(connect, 2000);
634
+ } else {
635
+ showBanner(
636
+ everConnected
637
+ ? 'Disconnected. The session has probably ended or this viewer link has been revoked. ' +
638
+ 'Ask the agent for a fresh viewer URL if the session is still running.'
639
+ : 'Could not connect. A viewer link works once, and only for a few minutes. ' +
640
+ 'Ask the agent for a fresh viewer URL.',
641
+ );
642
+ }
643
+ };
644
+ }
645
+
646
+ updateZoomButtons();
647
+ showReadOnly();
648
+ connect();
649
+
650
+ return {
651
+ destroy() {
652
+ destroyed = true;
653
+ outerScroll?.removeEventListener('wheel', scrollOversizedPane, true);
654
+ clearTimeout(reconnectTimer);
655
+ if (ws) ws.close();
656
+ if (redactedCapture) delete window.__shellpuppetCoverRows;
657
+ term.dispose();
658
+ },
659
+ setFontOverride(value) {
660
+ setFontOverride(value);
661
+ },
662
+ nudgeFont(delta) {
663
+ nudgeFont(delta);
664
+ },
665
+ getFontOverride() {
666
+ return fontOverride;
667
+ },
668
+ relayout(deliberate) {
669
+ relayout(deliberate);
670
+ },
671
+ setReadOnly(value) {
672
+ if (readOnlyEnforced) return;
673
+ readOnly = value;
674
+ showReadOnly();
675
+ },
676
+ isReadOnly() {
677
+ return readOnly;
678
+ },
679
+ isReadOnlyEnforced() {
680
+ return readOnlyEnforced;
681
+ },
682
+ getTerminal() {
683
+ return term;
684
+ },
685
+ getGrid() {
686
+ return { cols: gridCols, rows: gridRows };
687
+ },
688
+ autoFitGrid(floorCols = 80, floorRows = 24, force = false) {
689
+ if (dashboardProof === null || controlMode === 'held' || (followingExternal && !force) || !geometryDecided ||
690
+ !ws || ws.readyState !== 1 || sessionEnded) return false;
691
+ if (force) {
692
+ followingExternal = false;
693
+ outsideResizePending = false;
694
+ lastOutsideFitAt = 0;
695
+ }
696
+ let proposed = proposeDashboardGrid();
697
+ if (proposed === null) {
698
+ if (container.clientWidth <= 0 || container.clientHeight <= 0) return false;
699
+ proposed = { cols: floorCols, rows: floorRows };
700
+ }
701
+ const cols = Math.min(gridMax.cols, Math.max(floorCols, proposed.cols));
702
+ const rows = Math.min(gridMax.rows, Math.max(floorRows, proposed.rows));
703
+ if (cols === gridCols && rows === gridRows && !force) return false;
704
+ if (outsideResizePending) lastOutsideFitAt = Date.now();
705
+ outsideResizePending = false;
706
+ return this.takeGrid(cols, rows);
707
+ },
708
+ takeGrid(cols, rows) {
709
+ if (dashboardProof === null || !ws || ws.readyState !== 1 || !geometryDecided) return false;
710
+ const wanted = { cols: Math.max(2, Math.min(400, cols)), rows: Math.max(2, Math.min(150, rows)) };
711
+ pendingTakeGrid = true;
712
+ ws.send(JSON.stringify({ type: 'resize', ...wanted, take: true }));
713
+ return true;
714
+ },
715
+ fitGrid(floorCols = 0, floorRows = 0) {
716
+ if (dashboardProof === null) return false;
717
+ followingExternal = false;
718
+ outsideResizePending = false;
719
+ lastOutsideFitAt = 0;
720
+ if (term.options.fontSize !== fixedFontPx()) {
721
+ term.options.fontSize = fixedFontPx();
722
+ term.resize(term.cols, term.rows);
723
+ }
724
+ const proposed = proposeDashboardGrid();
725
+ return proposed !== null && this.takeGrid(
726
+ Math.max(floorCols, proposed.cols), Math.max(floorRows, proposed.rows));
727
+ },
728
+ fitAfterDrag(useAutoFit) {
729
+ if (controlMode === 'held' || captureMode || !geometryDecided) return false;
730
+ return useAutoFit ? this.autoFitGrid(80, 24) : this.fitGrid(80, 24);
731
+ },
732
+ };
733
+ }
734
+
735
+ return { create };
736
+ })();