shellpuppet 0.5.0 → 0.5.1

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.
@@ -5,7 +5,7 @@
5
5
  * Host-header validation on every request, Origin validation on WebSocket
6
6
  * upgrades, bearer-token auth on the API, no CORS headers at all.
7
7
  */
8
- import { moduleFor } from '../agents/index.js';
8
+ import { hasAgentShellNoColor, moduleFor } from '../agents/index.js';
9
9
  import * as fs from 'node:fs';
10
10
  import { randomUUID } from 'node:crypto';
11
11
  import { AsyncLocalStorage } from 'node:async_hooks';
@@ -41,7 +41,7 @@ import { acquireHomeOwner, AlreadyRunningError } from './homeOwner.js';
41
41
  import { daemonRunning } from './liveness.js';
42
42
  import { restoreRestartSource, retryRestartSource, snapshotSourceId } from './restartSource.js';
43
43
  import { packageVersion } from './meta.js';
44
- import { terminalReportKind } from './terminalReports.js';
44
+ import { terminalReportBatchKind } from './terminalReports.js';
45
45
  import { ViewerSync } from './viewerSync.js';
46
46
  import { SessionFeed } from './sessionFeed.js';
47
47
  import { compileProfilePolicy, copyDaemonEnv, describeProfileText, expandProfileText, resolveLaunchCommand, resolveAnyFolder, } from './launchProfiles.js';
@@ -454,6 +454,7 @@ function startShapeError(body) {
454
454
  }
455
455
  return null;
456
456
  }
457
+ const QUEUED_NUDGE_MAX_MS = 5 * 60_000;
457
458
  export class Daemon {
458
459
  options;
459
460
  logger;
@@ -461,6 +462,8 @@ export class Daemon {
461
462
  manager;
462
463
  mailbox;
463
464
  nudges;
465
+ queuedMessageNudges = new Map();
466
+ inboxReadVersions = new Map();
464
467
  schedules = new ScheduleStore();
465
468
  pendingSchedules = new Map();
466
469
  promptScheduler;
@@ -564,6 +567,7 @@ export class Daemon {
564
567
  launchProfiles;
565
568
  launchesPerMinute;
566
569
  daemonEnv;
570
+ omitInheritedNoColor;
567
571
  cliPath;
568
572
  /** The global policy, kept here so a launch can report it before creating. */
569
573
  compiledPolicy;
@@ -601,11 +605,13 @@ export class Daemon {
601
605
  this.sessionEnv = options.sessionEnv ?? DEFAULT_SESSION_ENV;
602
606
  this.launchProfiles = options.launchProfiles ?? { profiles: [], problems: [] };
603
607
  this.launchesPerMinute = this.launchProfiles.launchesPerMinute ?? DEFAULT_LAUNCHES_PER_MINUTE;
604
- this.daemonEnv = options.daemonEnv ?? process.env;
608
+ this.daemonEnv = { ...(options.daemonEnv ?? process.env) };
609
+ this.omitInheritedNoColor = hasAgentShellNoColor(this.daemonEnv);
605
610
  this.cliPath = fileURLToPath(new URL('../../dist/cli/index.js', import.meta.url));
606
611
  this.compiledPolicy = compilePolicy(options.policy);
607
612
  this.manager = new SessionManager(compilePolicy(options.policy), this.logger, {
608
613
  sessionEnv: this.sessionEnv,
614
+ omitInheritedNoColor: this.omitInheritedNoColor,
609
615
  identity: {
610
616
  token: '',
611
617
  instanceId: this.instanceId,
@@ -645,6 +651,11 @@ export class Daemon {
645
651
  });
646
652
  this.mailbox.on('state', (event) => {
647
653
  const entry = this.mailbox.log().find((item) => item.id === event.id);
654
+ if (event.state === 'read' && entry !== undefined) {
655
+ const id = entry.to.id;
656
+ this.inboxReadVersions.set(id, (this.inboxReadVersions.get(id) ?? 0) + 1);
657
+ this.queuedMessageNudges.delete(id);
658
+ }
648
659
  this.emitMessageEvent({ type: 'message-state', ...event }, entry);
649
660
  this.emitDashboardMessageEvent({ type: 'message-state', ...event });
650
661
  });
@@ -827,6 +838,8 @@ export class Daemon {
827
838
  // Said once, at start, because passthrough leaks silently otherwise
828
839
  // (ADR-008): the names only, never the values.
829
840
  const { exposed } = this.environmentReport();
841
+ if (this.omitInheritedNoColor)
842
+ this.logger.info('omitting inherited output setting from agent tool shell', { names: ['NO_COLOR'] });
830
843
  if (exposed.length > 0) {
831
844
  this.logger.warn('sessionEnv "passthrough" hands every session the daemon environment, including ' +
832
845
  'these variables whose names look like credentials; use "clean" or a list to keep them out', { names: exposed });
@@ -1947,7 +1960,7 @@ export class Daemon {
1947
1960
  });
1948
1961
  return;
1949
1962
  }
1950
- const { env, copied } = copyDaemonEnv(profile.envFromDaemon, this.daemonEnv);
1963
+ const { env, copied } = copyDaemonEnv(profile.envFromDaemon, this.daemonEnv, undefined, this.omitInheritedNoColor);
1951
1964
  const envNames = Object.keys(env);
1952
1965
  const folderLabel = freeCwd !== undefined ? freeCwd : folder?.name ?? (rootCwd !== undefined ? folderName : undefined);
1953
1966
  const options = {
@@ -2630,6 +2643,8 @@ export class Daemon {
2630
2643
  if (pendingId === id)
2631
2644
  this.pendingSchedules.delete(name);
2632
2645
  this.nudges.remove(id);
2646
+ this.queuedMessageNudges.delete(id);
2647
+ this.inboxReadVersions.delete(id);
2633
2648
  // Audit before end can trim old tombstones from retained history.
2634
2649
  for (const entry of this.mailbox.log({ participantId: id })) {
2635
2650
  if (entry.to.id === id && (entry.state === 'waiting' || entry.state === 'nudged')) {
@@ -2654,38 +2669,68 @@ export class Daemon {
2654
2669
  }
2655
2670
  async deliverNudge(id) {
2656
2671
  const session = this.manager.get(id);
2657
- if (session === undefined || session.exited || this.mailbox.participant(id)?.kind !== 'session')
2672
+ if (session === undefined || session.exited || this.mailbox.participant(id)?.kind !== 'session') {
2673
+ this.queuedMessageNudges.delete(id);
2658
2674
  return 'done';
2675
+ }
2659
2676
  const pendingIds = session.nudgePendingLine() !== null ? [...session.nudgePendingIds()] : [];
2660
2677
  // A scheduled body has no mailbox ids. It can clear on proof of consumption,
2661
2678
  // but a later inbox message can never authorise its submit key.
2662
2679
  if (session.nudgePendingLine() !== null && pendingIds.length === 0 &&
2663
2680
  !await this.clearScheduledBody(session))
2664
2681
  return 'wait';
2665
- const clearedIds = pendingIds.length > 0 && await session.clearConsumedNudge() ? pendingIds : [];
2666
2682
  const unread = this.mailbox.inbox(id, { markRead: false });
2683
+ const stale = pendingIds.length > 0 &&
2684
+ pendingIds.every((messageId) => !unread.some((entry) => entry.id === messageId));
2685
+ if (stale) {
2686
+ const line = session.nudgePendingLine();
2687
+ if (line === null || !session.discardStalePendingNudge(line, pendingIds))
2688
+ return 'wait';
2689
+ this.audit.record('daemon', 'nudge-pending-stale', id, {
2690
+ messageIds: pendingIds, count: pendingIds.length,
2691
+ });
2692
+ }
2693
+ const clearedIds = !stale && pendingIds.length > 0 && await session.clearConsumedNudge() ? pendingIds : [];
2667
2694
  if (clearedIds.length > 0) {
2668
2695
  this.audit.record('daemon', 'nudge-cleared', id, { messageIds: clearedIds,
2669
2696
  waitingMessageIds: unread.map((entry) => entry.id) });
2670
2697
  }
2698
+ // Resolve a retained line before the queued-message hold below. It may
2699
+ // receive its own submit key, but another body must never be typed over it.
2671
2700
  const pending = session.nudgePendingLine();
2672
2701
  if (pending !== null) {
2673
2702
  if (session.nudgePendingIds().length === 0)
2674
2703
  return 'wait';
2704
+ const covered = session.nudgePendingIds();
2705
+ const auditPending = (reason) => {
2706
+ if (session.nudgePendingAuditOnce())
2707
+ this.audit.record('daemon', 'nudge-pending', id, {
2708
+ messageIds: [...covered], count: covered.length, reason,
2709
+ });
2710
+ };
2675
2711
  const ids = unread.filter((entry) => entry.state === 'waiting').map((entry) => entry.id);
2676
- if (ids.length === 0)
2712
+ if (ids.length === 0) {
2713
+ auditPending('messages-changed');
2677
2714
  return 'done';
2678
- const covered = session.nudgePendingIds();
2679
- if (!session.nudgePendingUntouched()) {
2715
+ }
2716
+ if (!covered.every((messageId) => unread.some((entry) => entry.id === messageId))) {
2717
+ auditPending('messages-changed');
2718
+ return 'wait';
2719
+ }
2720
+ if (!session.nudgePendingSafeToSubmit()) {
2680
2721
  if (session.nudgeReadyWithLine(pending) && session.nudgePendingTouchRefusal()) {
2681
2722
  this.audit.record('daemon', 'nudge-aborted', id, {
2682
2723
  messageIds: [...covered], count: covered.length, reason: 'person-input-since',
2724
+ ...session.nudgePendingBodyMeta(),
2683
2725
  });
2684
2726
  }
2727
+ auditPending('person-input-since');
2685
2728
  return 'wait';
2686
2729
  }
2687
- if (!session.nudgeReadyWithLine(pending))
2730
+ if (!session.nudgeReadyWithLine(pending)) {
2731
+ auditPending('line-not-seen');
2688
2732
  return 'wait';
2733
+ }
2689
2734
  const inputVersion = session.nudgeInputVersion();
2690
2735
  const queuedInputVersion = session.nudgeQueuedInputVersion();
2691
2736
  const screenRevision = session.nudgeScreenRevision();
@@ -2693,10 +2738,13 @@ export class Daemon {
2693
2738
  const waitingIds = this.mailbox.inbox(id, { markRead: false })
2694
2739
  .filter((entry) => entry.state === 'waiting').map((entry) => entry.id);
2695
2740
  return !session.exited && !session.getStalled() &&
2741
+ session.nudgePendingSafeToSubmit() &&
2696
2742
  session.nudgeInputVersion() === inputVersion &&
2697
2743
  session.nudgeQueuedInputVersion() === queuedInputVersion &&
2698
2744
  session.nudgeScreenRevision() === screenRevision &&
2699
2745
  session.answerablePrompt(screen) === null && session.nudgePendingIds().length > 0 &&
2746
+ covered.every((messageId) => this.mailbox.inbox(id, { markRead: false })
2747
+ .some((entry) => entry.id === messageId)) &&
2700
2748
  waitingIds.length === ids.length &&
2701
2749
  ids.every((messageId) => waitingIds.includes(messageId));
2702
2750
  });
@@ -2704,8 +2752,10 @@ export class Daemon {
2704
2752
  if (session.nudgePendingTouchRefusal()) {
2705
2753
  this.audit.record('daemon', 'nudge-aborted', id, {
2706
2754
  messageIds: [...covered], count: covered.length, reason: 'person-input-since',
2755
+ ...session.nudgePendingBodyMeta(),
2707
2756
  });
2708
2757
  }
2758
+ auditPending('person-input-since');
2709
2759
  return 'wait';
2710
2760
  }
2711
2761
  this.mailbox.markNudged(ids);
@@ -2714,25 +2764,48 @@ export class Daemon {
2714
2764
  staleMessageIds: covered.filter((messageId) => !unread.some((entry) => entry.id === messageId)) });
2715
2765
  return 'sent';
2716
2766
  }
2767
+ const queued = this.queuedMessageNudges?.get(id);
2768
+ if (queued !== undefined) {
2769
+ const state = session.nudgeState(this.now());
2770
+ if (this.now() - queued.at >= QUEUED_NUDGE_MAX_MS || (state.ready && !state.queued)) {
2771
+ this.queuedMessageNudges.delete(id);
2772
+ }
2773
+ else {
2774
+ const waitingIds = unread.filter((entry) => entry.state === 'waiting').map((entry) => entry.id);
2775
+ const newlyHeld = waitingIds.filter((messageId) => !queued.heldIds.has(messageId));
2776
+ if (newlyHeld.length > 0) {
2777
+ for (const messageId of newlyHeld)
2778
+ queued.heldIds.add(messageId);
2779
+ this.audit.record('daemon', 'nudge-held', id, { reason: 'queued-nudge-pending',
2780
+ messageIds: newlyHeld, count: newlyHeld.length, queuedMessageIds: queued.messageIds });
2781
+ }
2782
+ return waitingIds.length > 0 ? 'wait' : 'done';
2783
+ }
2784
+ }
2717
2785
  // Only a message that has not been nudged yet starts a nudge. One that was
2718
2786
  // nudged but is still unread (the agent did not read its inbox) is listed
2719
- // in the line again when a later message arrives, so delivery never stops.
2787
+ // in the line again when a later message arrives after any queued hold ends.
2720
2788
  const ids = unread.filter((entry) => entry.state === 'waiting').map((entry) => entry.id);
2721
2789
  if (ids.length === 0)
2722
2790
  return 'done';
2723
2791
  if (!session.hasPainted() || !session.nudgeReady(this.now()))
2724
2792
  return 'wait';
2725
2793
  const line = buildNudge(unread);
2794
+ const readVersion = this.inboxReadVersions?.get(id) ?? 0;
2726
2795
  const result = await this.deliverLine(session, line, undefined, ids, () => {
2727
2796
  const current = this.mailbox.inbox(id, { markRead: false });
2728
2797
  return ids.every(messageId => current.some(entry => entry.id === messageId && entry.state === 'waiting'));
2729
2798
  });
2730
2799
  if (result.outcome === 'aborted') {
2731
- this.audit.record('daemon', 'nudge-aborted', id, { messageIds: ids, count: ids.length, reason: result.reason });
2800
+ this.audit.record('daemon', 'nudge-aborted', id, { messageIds: ids, count: ids.length, reason: result.reason,
2801
+ ...session.nudgePendingBodyMeta() });
2732
2802
  }
2733
2803
  if (result.outcome !== 'sent' && result.outcome !== 'queued')
2734
2804
  return 'wait';
2735
2805
  this.mailbox.markNudged(ids);
2806
+ if (result.outcome === 'queued' && (this.inboxReadVersions?.get(id) ?? 0) === readVersion) {
2807
+ this.queuedMessageNudges.set(id, { at: this.now(), messageIds: ids, heldIds: new Set() });
2808
+ }
2736
2809
  this.audit.record('daemon', 'nudge', id, { messageIds: ids, count: ids.length,
2737
2810
  ...(result.outcome === 'queued' ? { queued: true } : {}) });
2738
2811
  return 'sent';
@@ -2840,6 +2913,14 @@ export class Daemon {
2840
2913
  }
2841
2914
  }
2842
2915
  catch (error) {
2916
+ const pendingBody = session.nudgePendingBodyMeta();
2917
+ if (ids.length > 0 && pendingBody.pendingBody) {
2918
+ const reason = error instanceof SessionInputFailedError ? 'input-failed'
2919
+ : error instanceof SessionProgramEndedError ? 'session-ended' : 'write-failed';
2920
+ this.audit.record('daemon', 'nudge-aborted', session.id, {
2921
+ messageIds: ids, count: ids.length, reason, ...pendingBody,
2922
+ });
2923
+ }
2843
2924
  if (error instanceof SessionInputFailedError)
2844
2925
  return { outcome: 'skipped', reason: 'input-failed' };
2845
2926
  if (error instanceof SessionProgramEndedError)
@@ -3537,6 +3618,8 @@ export class Daemon {
3537
3618
  json(res, 400, { error: 'data (string) is required.' });
3538
3619
  return;
3539
3620
  }
3621
+ const report = (submitMode === undefined || submitMode === 'off') && body['submit'] !== true
3622
+ ? terminalReportBatchKind(data) : null;
3540
3623
  // Awaited: long input is chunked (Session.write), so verify below must
3541
3624
  // not read the screen until every chunk has actually been written.
3542
3625
  // The write resolves with the screen as it was just before this input
@@ -3553,9 +3636,9 @@ export class Daemon {
3553
3636
  const submit = body['submit'] === true;
3554
3637
  let written;
3555
3638
  try {
3556
- written = submitMode === undefined
3557
- ? await session.writeWithResult(data)
3558
- : await session.writeWithResult(data, { submitMode });
3639
+ written = await session.writeWithResult(data, {
3640
+ ...(submitMode !== undefined ? { submitMode } : {}), terminalReport: report !== null,
3641
+ });
3559
3642
  }
3560
3643
  catch (error) {
3561
3644
  json(res, 409, {
@@ -3570,9 +3653,15 @@ export class Daemon {
3570
3653
  ? { outcome: 'not-requested' }
3571
3654
  : submitOutcome(written, true);
3572
3655
  const bytes = submitMode === undefined ? data.length : written.inputBytes ?? 0;
3573
- this.audit.record(actor, 'input', id, { chars: bytes,
3574
- ...(submitMode !== undefined ? { submitMode, ...reporting } : reporting ? { submit: true, ...reporting } : {}) });
3575
- this.broadcastControl(id, { type: 'input-source', source: 'agent' });
3656
+ if (report !== null) {
3657
+ this.audit.record(actor, 'report', id, { kind: report, chars: bytes,
3658
+ ...(this.audit.captureContent ? { data } : {}) });
3659
+ }
3660
+ else {
3661
+ this.audit.record(actor, 'input', id, { chars: bytes,
3662
+ ...(submitMode !== undefined ? { submitMode, ...reporting } : reporting ? { submit: true, ...reporting } : {}) });
3663
+ this.broadcastControl(id, { type: 'input-source', source: 'agent' });
3664
+ }
3576
3665
  // §3.1: TUIs silently swallow input while loading or when a panel has
3577
3666
  // stolen focus. verify re-reads the screen and reports whether the
3578
3667
  // text landed (best effort: hidden-input prompts and heavy
@@ -5082,7 +5171,7 @@ export class Daemon {
5082
5171
  * exit notice); TEXT frames are JSON control messages. Incoming text frames
5083
5172
  * are either JSON controls (resize) or bytes for the program: a person's
5084
5173
  * keystrokes, or the viewer's terminal answering the program
5085
- * (terminalReports.ts).
5174
+ * (terminalReports.ts). Incoming binary frames carry raw onBinary input.
5086
5175
  */
5087
5176
  attachSocket(ws, session, credential, options = {}) {
5088
5177
  const { readOnly } = credential;
@@ -5250,120 +5339,163 @@ export class Daemon {
5250
5339
  });
5251
5340
  /** Whether this socket has been told that the session's input has failed. */
5252
5341
  let toldInputFailed = false;
5253
- const onViewerMessage = async (message) => {
5342
+ const onViewerMessage = async (message, isBinary) => {
5254
5343
  this.lastActivity = Date.now();
5255
- const text = typeof message === 'string' ? message : message.toString('utf8');
5256
- try {
5257
- const parsed = JSON.parse(text);
5258
- if (typeof parsed === 'object' && parsed !== null &&
5259
- parsed.type === 'release-grid') {
5260
- // Only the current controller can give up a dashboard grid. Another
5261
- // document with the same cookie cannot make a live controller yield.
5262
- if (credential.kind === 'dashboard' && !session.exited && !session.geometryHeld &&
5263
- this.geometryController.get(session.id) === ws) {
5264
- const windows = this.dashboardWindows();
5265
- const target = windows.find(({ pair }) => this.dashboardAssignments.get(pair)?.includes(session.id));
5266
- if (target)
5267
- this.dashboardTransferable.set(session.id, target.socket.protocol);
5268
- else if (windows.length === 0)
5269
- this.dashboardTransferable.set(session.id, null);
5270
- this.announceGeometry(session.id, session, { resync: false });
5271
- }
5272
- return;
5273
- }
5274
- if (typeof parsed === 'object' && parsed !== null &&
5275
- parsed.type === 'layout') {
5276
- const notice = parsed;
5277
- if (credential.kind === 'dashboard' && this.dashboardFeedCurrent(ws) &&
5278
- Number.isSafeInteger(notice.layoutId) && Number(notice.layoutId) > 0 &&
5279
- typeof notice.eligible === 'boolean') {
5280
- const id = Number(notice.layoutId);
5281
- if (id > (this.dashboardLayouts.get(ws)?.id ?? 0)) {
5282
- const prior = this.dashboardLayouts.get(ws);
5283
- const real = notice.real === true;
5284
- this.dashboardLayouts.set(ws, { id, realId: real ? id : (prior?.realId ?? 0),
5285
- order: real ? this.nextGeometryOrder(session.id) : (prior?.order ?? 0),
5286
- eligible: notice.eligible });
5344
+ const bytes = isBinary ? Buffer.from(message) : null;
5345
+ const text = bytes === null ? (typeof message === 'string' ? message : message.toString('utf8')) : '';
5346
+ if (!isBinary)
5347
+ try {
5348
+ const parsed = JSON.parse(text);
5349
+ if (typeof parsed === 'object' && parsed !== null &&
5350
+ parsed.type === 'release-grid') {
5351
+ // Only the current controller can give up a dashboard grid. Another
5352
+ // document with the same cookie cannot make a live controller yield.
5353
+ if (credential.kind === 'dashboard' && !session.exited && !session.geometryHeld &&
5354
+ this.geometryController.get(session.id) === ws) {
5355
+ const windows = this.dashboardWindows();
5356
+ const target = windows.find(({ pair }) => this.dashboardAssignments.get(pair)?.includes(session.id));
5357
+ if (target)
5358
+ this.dashboardTransferable.set(session.id, target.socket.protocol);
5359
+ else if (windows.length === 0)
5360
+ this.dashboardTransferable.set(session.id, null);
5361
+ this.announceGeometry(session.id, session, { resync: false });
5287
5362
  }
5288
- }
5289
- return;
5290
- }
5291
- if (typeof parsed === 'object' &&
5292
- parsed !== null &&
5293
- parsed.type === 'resize') {
5294
- const { cols, rows, take, acceptOffer, automatic, takeId, choiceRevision, layoutId } = parsed;
5295
- const autoTake = automatic === true && take === true && acceptOffer !== true &&
5296
- credential.kind === 'dashboard';
5297
- const requestId = Number.isSafeInteger(takeId) && Number(takeId) > 0 ? Number(takeId) : undefined;
5298
- const refuseAuto = (staleLayoutId = false) => {
5299
- if (ws.readyState === ws.OPEN)
5300
- ws.send(JSON.stringify({ ...this.geometryFrame(session, ws),
5301
- refusedTakeId: requestId, ...(staleLayoutId ? { staleLayoutId: true } : {}) }));
5302
- };
5303
- if (automatic === true && (!autoTake || requestId === undefined ||
5304
- !Number.isSafeInteger(choiceRevision) || !Number.isSafeInteger(layoutId))) {
5305
- refuseAuto();
5306
5363
  return;
5307
5364
  }
5308
- // Fit, Enlarge, Focus and Restore are a resize that says `take`.
5309
- // A passive socket's other resizes, including one a dashboard pane
5310
- // sends because the window moved, are not that act: the grid stays,
5311
- // nobody is handed it, and nothing is audited. Passivity is the
5312
- // dashboard credential, or `drive=0` on a viewer or client socket.
5313
- if (passive && take !== true)
5365
+ if (typeof parsed === 'object' && parsed !== null &&
5366
+ parsed.type === 'layout') {
5367
+ const notice = parsed;
5368
+ if (credential.kind === 'dashboard' && this.dashboardFeedCurrent(ws) &&
5369
+ Number.isSafeInteger(notice.layoutId) && Number(notice.layoutId) > 0 &&
5370
+ typeof notice.eligible === 'boolean') {
5371
+ const id = Number(notice.layoutId);
5372
+ if (id > (this.dashboardLayouts.get(ws)?.id ?? 0)) {
5373
+ const prior = this.dashboardLayouts.get(ws);
5374
+ const real = notice.real === true;
5375
+ this.dashboardLayouts.set(ws, { id, realId: real ? id : (prior?.realId ?? 0),
5376
+ order: real ? this.nextGeometryOrder(session.id) : (prior?.order ?? 0),
5377
+ eligible: notice.eligible });
5378
+ }
5379
+ }
5314
5380
  return;
5315
- if (!readOnly &&
5316
- typeof cols === 'number' &&
5317
- typeof rows === 'number' &&
5318
- Number.isInteger(cols) &&
5319
- Number.isInteger(rows) &&
5320
- cols >= 2 &&
5321
- cols <= 1_000 &&
5322
- rows >= 2 &&
5323
- rows <= 500 &&
5324
- !session.exited) {
5325
- if (session.geometryHeld) {
5326
- // Held against viewports. Answer with the real grid so the page
5327
- // stops proposing one it will never be given.
5328
- if (autoTake)
5329
- refuseAuto();
5330
- else
5331
- ws.send(JSON.stringify(this.geometryFrame(session, ws)));
5381
+ }
5382
+ if (typeof parsed === 'object' &&
5383
+ parsed !== null &&
5384
+ parsed.type === 'resize') {
5385
+ const { cols, rows, take, acceptOffer, automatic, takeId, choiceRevision, layoutId } = parsed;
5386
+ const autoTake = automatic === true && take === true && acceptOffer !== true &&
5387
+ credential.kind === 'dashboard';
5388
+ const requestId = Number.isSafeInteger(takeId) && Number(takeId) > 0 ? Number(takeId) : undefined;
5389
+ const refuseAuto = (staleLayoutId = false) => {
5390
+ if (ws.readyState === ws.OPEN)
5391
+ ws.send(JSON.stringify({ ...this.geometryFrame(session, ws),
5392
+ refusedTakeId: requestId, ...(staleLayoutId ? { staleLayoutId: true } : {}) }));
5393
+ };
5394
+ if (automatic === true && (!autoTake || requestId === undefined ||
5395
+ !Number.isSafeInteger(choiceRevision) || !Number.isSafeInteger(layoutId))) {
5396
+ refuseAuto();
5332
5397
  return;
5333
5398
  }
5334
- const wanted = {
5335
- cols: Math.min(cols, MAX_VIEWPORT_COLS),
5336
- rows: Math.min(rows, MAX_VIEWPORT_ROWS),
5337
- };
5338
- if (autoTake) {
5339
- try {
5399
+ // Fit, Enlarge, Focus and Restore are a resize that says `take`.
5400
+ // A passive socket's other resizes, including one a dashboard pane
5401
+ // sends because the window moved, are not that act: the grid stays,
5402
+ // nobody is handed it, and nothing is audited. Passivity is the
5403
+ // dashboard credential, or `drive=0` on a viewer or client socket.
5404
+ if (passive && take !== true)
5405
+ return;
5406
+ if (!readOnly &&
5407
+ typeof cols === 'number' &&
5408
+ typeof rows === 'number' &&
5409
+ Number.isInteger(cols) &&
5410
+ Number.isInteger(rows) &&
5411
+ cols >= 2 &&
5412
+ cols <= 1_000 &&
5413
+ rows >= 2 &&
5414
+ rows <= 500 &&
5415
+ !session.exited) {
5416
+ if (session.geometryHeld) {
5417
+ // Held against viewports. Answer with the real grid so the page
5418
+ // stops proposing one it will never be given.
5419
+ if (autoTake)
5420
+ refuseAuto();
5421
+ else
5422
+ ws.send(JSON.stringify(this.geometryFrame(session, ws)));
5423
+ return;
5424
+ }
5425
+ const wanted = {
5426
+ cols: Math.min(cols, MAX_VIEWPORT_COLS),
5427
+ rows: Math.min(rows, MAX_VIEWPORT_ROWS),
5428
+ };
5429
+ if (autoTake) {
5430
+ try {
5431
+ let applied = false;
5432
+ let changedAtApply = false;
5433
+ let staleLayoutId = false;
5434
+ const shouldApply = () => {
5435
+ if (session.geometryHeld || session.exited || ws.readyState !== ws.OPEN ||
5436
+ !this.sessionSockets.get(session.id)?.has(ws) || !this.dashboardFeedCurrent(ws))
5437
+ return false;
5438
+ const layout = this.dashboardLayouts.get(ws);
5439
+ if (Number(layoutId) !== (layout?.id ?? 0)) {
5440
+ staleLayoutId = true;
5441
+ return false;
5442
+ }
5443
+ if (layout?.eligible === false)
5444
+ return false;
5445
+ const ownerPresent = this.hasGeometryController(session.id);
5446
+ if (ownerPresent && this.geometryController.get(session.id) !== ws)
5447
+ return false;
5448
+ const reserved = this.hasDashboardGeometryOwner(session.id);
5449
+ if (reserved && this.geometryController.get(session.id) !== ws)
5450
+ return false;
5451
+ const explicit = this.explicitResizeRevision.get(session.id) ?? 0;
5452
+ if (explicit > (this.controllerChoiceRevision.get(session.id) ?? 0) &&
5453
+ (layout?.order ?? 0) <= explicit)
5454
+ return false;
5455
+ const current = this.choiceRevision.get(session.id) ?? 0;
5456
+ if (Number(choiceRevision) !== current &&
5457
+ !(layout !== undefined && layout.id === Number(layoutId) && layout.order > current))
5458
+ return false;
5459
+ changedAtApply = wanted.cols !== session.cols || wanted.rows !== session.rows;
5460
+ return true;
5461
+ };
5462
+ const onApplied = () => {
5463
+ applied = true;
5464
+ const handedOver = this.geometryController.get(session.id) !== ws;
5465
+ this.geometryController.set(session.id, ws);
5466
+ this.dashboardGeometryOwner.set(session.id, ws.protocol);
5467
+ this.dashboardCredentialOwner.set(session.id, credential.dashboardToken);
5468
+ this.dashboardTransferable.delete(session.id);
5469
+ this.recordGeometryChoice(session.id, true);
5470
+ this.geometryEpoch.set(session.id, (this.geometryEpoch.get(session.id) ?? 0) + 1);
5471
+ if (changedAtApply)
5472
+ this.audit.record(actor, 'resize', session.id, {
5473
+ cols: wanted.cols, rows: wanted.rows, hold: false,
5474
+ });
5475
+ if (changedAtApply || handedOver)
5476
+ this.announceGeometry(session.id, session, { resync: changedAtApply, acceptedTakeId: requestId });
5477
+ else
5478
+ ws.send(JSON.stringify({ ...this.geometryFrame(session, ws), acceptedTakeId: requestId }));
5479
+ };
5480
+ await session.resize(wanted.cols, wanted.rows, { shouldApply, skipIfSame: true, onApplied });
5481
+ if (!applied)
5482
+ refuseAuto(staleLayoutId);
5483
+ }
5484
+ catch (error) {
5485
+ refuseAuto();
5486
+ if (!(error instanceof SessionProgramEndedError))
5487
+ this.logger.warn('viewer resize failed', {
5488
+ id: session.id, error: String(error),
5489
+ });
5490
+ }
5491
+ return;
5492
+ }
5493
+ if (!this.widerReads.has(session.id) && acceptOffer !== true) {
5340
5494
  let applied = false;
5341
5495
  let changedAtApply = false;
5342
- let staleLayoutId = false;
5343
5496
  const shouldApply = () => {
5344
5497
  if (session.geometryHeld || session.exited || ws.readyState !== ws.OPEN ||
5345
- !this.sessionSockets.get(session.id)?.has(ws) || !this.dashboardFeedCurrent(ws))
5346
- return false;
5347
- const layout = this.dashboardLayouts.get(ws);
5348
- if (Number(layoutId) !== (layout?.id ?? 0)) {
5349
- staleLayoutId = true;
5350
- return false;
5351
- }
5352
- if (layout?.eligible === false)
5353
- return false;
5354
- const ownerPresent = this.hasGeometryController(session.id);
5355
- if (ownerPresent && this.geometryController.get(session.id) !== ws)
5356
- return false;
5357
- const reserved = this.hasDashboardGeometryOwner(session.id);
5358
- if (reserved && this.geometryController.get(session.id) !== ws)
5359
- return false;
5360
- const explicit = this.explicitResizeRevision.get(session.id) ?? 0;
5361
- if (explicit > (this.controllerChoiceRevision.get(session.id) ?? 0) &&
5362
- (layout?.order ?? 0) <= explicit)
5363
- return false;
5364
- const current = this.choiceRevision.get(session.id) ?? 0;
5365
- if (Number(choiceRevision) !== current &&
5366
- !(layout !== undefined && layout.id === Number(layoutId) && layout.order > current))
5498
+ !this.sessionSockets.get(session.id)?.has(ws))
5367
5499
  return false;
5368
5500
  changedAtApply = wanted.cols !== session.cols || wanted.rows !== session.rows;
5369
5501
  return true;
@@ -5372,149 +5504,108 @@ export class Daemon {
5372
5504
  applied = true;
5373
5505
  const handedOver = this.geometryController.get(session.id) !== ws;
5374
5506
  this.geometryController.set(session.id, ws);
5375
- this.dashboardGeometryOwner.set(session.id, ws.protocol);
5376
- this.dashboardCredentialOwner.set(session.id, credential.dashboardToken);
5377
- this.dashboardTransferable.delete(session.id);
5378
5507
  this.recordGeometryChoice(session.id, true);
5508
+ this.dashboardTransferable.delete(session.id);
5379
5509
  this.geometryEpoch.set(session.id, (this.geometryEpoch.get(session.id) ?? 0) + 1);
5380
- if (changedAtApply)
5510
+ if (credential.kind === 'dashboard') {
5511
+ this.dashboardGeometryOwner.set(session.id, ws.protocol);
5512
+ this.dashboardCredentialOwner.set(session.id, credential.dashboardToken);
5513
+ }
5514
+ else {
5515
+ this.dashboardGeometryOwner.delete(session.id);
5516
+ this.dashboardCredentialOwner.delete(session.id);
5517
+ }
5518
+ if (changedAtApply) {
5381
5519
  this.audit.record(actor, 'resize', session.id, {
5382
5520
  cols: wanted.cols, rows: wanted.rows, hold: false,
5383
5521
  });
5384
- if (changedAtApply || handedOver)
5385
- this.announceGeometry(session.id, session, { resync: changedAtApply, acceptedTakeId: requestId });
5386
- else
5387
- ws.send(JSON.stringify({ ...this.geometryFrame(session, ws), acceptedTakeId: requestId }));
5522
+ this.announceGeometry(session.id, session);
5523
+ }
5524
+ else if (handedOver)
5525
+ this.announceGeometry(session.id, session, { resync: false });
5526
+ else if (take === true)
5527
+ ws.send(JSON.stringify(this.geometryFrame(session, ws)));
5388
5528
  };
5389
- await session.resize(wanted.cols, wanted.rows, { shouldApply, skipIfSame: true, onApplied });
5390
- if (!applied)
5391
- refuseAuto(staleLayoutId);
5392
- }
5393
- catch (error) {
5394
- refuseAuto();
5395
- if (!(error instanceof SessionProgramEndedError))
5396
- this.logger.warn('viewer resize failed', {
5397
- id: session.id, error: String(error),
5398
- });
5399
- }
5400
- return;
5401
- }
5402
- if (!this.widerReads.has(session.id) && acceptOffer !== true) {
5403
- let applied = false;
5404
- let changedAtApply = false;
5405
- const shouldApply = () => {
5406
- if (session.geometryHeld || session.exited || ws.readyState !== ws.OPEN ||
5407
- !this.sessionSockets.get(session.id)?.has(ws))
5408
- return false;
5409
- changedAtApply = wanted.cols !== session.cols || wanted.rows !== session.rows;
5410
- return true;
5411
- };
5412
- const onApplied = () => {
5413
- applied = true;
5414
- const handedOver = this.geometryController.get(session.id) !== ws;
5415
- this.geometryController.set(session.id, ws);
5416
- this.recordGeometryChoice(session.id, true);
5417
- this.dashboardTransferable.delete(session.id);
5418
- this.geometryEpoch.set(session.id, (this.geometryEpoch.get(session.id) ?? 0) + 1);
5419
- if (credential.kind === 'dashboard') {
5420
- this.dashboardGeometryOwner.set(session.id, ws.protocol);
5421
- this.dashboardCredentialOwner.set(session.id, credential.dashboardToken);
5422
- }
5423
- else {
5424
- this.dashboardGeometryOwner.delete(session.id);
5425
- this.dashboardCredentialOwner.delete(session.id);
5529
+ try {
5530
+ if (wanted.cols !== session.cols || wanted.rows !== session.rows) {
5531
+ await session.resize(wanted.cols, wanted.rows, { shouldApply, skipIfSame: true, onApplied });
5532
+ }
5533
+ else {
5534
+ await session.resizeIfCurrent(wanted.cols, wanted.rows, shouldApply, () => onApplied(), true);
5535
+ }
5536
+ if (!applied && ws.readyState === ws.OPEN)
5537
+ ws.send(JSON.stringify(this.geometryFrame(session, ws)));
5426
5538
  }
5427
- if (changedAtApply) {
5428
- this.audit.record(actor, 'resize', session.id, {
5429
- cols: wanted.cols, rows: wanted.rows, hold: false,
5430
- });
5431
- this.announceGeometry(session.id, session);
5539
+ catch (error) {
5540
+ if (error instanceof SessionProgramEndedError)
5541
+ return;
5542
+ this.logger.warn('viewer resize failed', { id: session.id, error: String(error) });
5432
5543
  }
5433
- else if (handedOver)
5434
- this.announceGeometry(session.id, session, { resync: false });
5435
- else if (take === true)
5436
- ws.send(JSON.stringify(this.geometryFrame(session, ws)));
5437
- };
5544
+ return;
5545
+ }
5438
5546
  try {
5439
- if (wanted.cols !== session.cols || wanted.rows !== session.rows) {
5440
- await session.resize(wanted.cols, wanted.rows, { shouldApply, skipIfSame: true, onApplied });
5441
- }
5442
- else {
5443
- await session.resizeIfCurrent(wanted.cols, wanted.rows, shouldApply, () => onApplied(), true);
5444
- }
5547
+ const applied = await session.resizeIfCurrent(wanted.cols, wanted.rows,
5548
+ // A viewport that left while its take waited in the queue made
5549
+ // no lasting choice: skip it so the pending wider restore runs.
5550
+ () => !session.geometryHeld && !session.exited && ws.readyState === ws.OPEN &&
5551
+ (acceptOffer !== true || this.gridOfferedTo(session.id, ws)) &&
5552
+ (this.sessionSockets.get(session.id)?.has(ws) ?? false), (changed) => {
5553
+ const handedOver = this.geometryController.get(session.id) !== ws;
5554
+ // The controller change and epoch belong to the same queued
5555
+ // act as the resize, before a queued wider restore can run.
5556
+ this.geometryController.set(session.id, ws);
5557
+ this.recordGeometryChoice(session.id, true);
5558
+ this.dashboardTransferable.delete(session.id);
5559
+ this.geometryEpoch.set(session.id, (this.geometryEpoch.get(session.id) ?? 0) + 1);
5560
+ if (credential.kind === 'dashboard') {
5561
+ this.dashboardGeometryOwner.set(session.id, ws.protocol);
5562
+ this.dashboardCredentialOwner.set(session.id, credential.dashboardToken);
5563
+ }
5564
+ else {
5565
+ this.dashboardGeometryOwner.delete(session.id);
5566
+ this.dashboardCredentialOwner.delete(session.id);
5567
+ }
5568
+ if (changed) {
5569
+ this.audit.record(actor, 'resize', session.id, {
5570
+ cols: wanted.cols, rows: wanted.rows, hold: false,
5571
+ });
5572
+ this.announceGeometry(session.id, session);
5573
+ }
5574
+ else if (handedOver)
5575
+ this.announceGeometry(session.id, session, { resync: false });
5576
+ else if (take === true)
5577
+ ws.send(JSON.stringify(this.geometryFrame(session, ws)));
5578
+ }, true);
5445
5579
  if (!applied && ws.readyState === ws.OPEN)
5446
5580
  ws.send(JSON.stringify(this.geometryFrame(session, ws)));
5447
5581
  }
5448
5582
  catch (error) {
5583
+ // The program has ended (a viewer fitting its window while
5584
+ // looking at a dying session), and the session's exit follows
5585
+ // within about a second, with an `exited` frame to every
5586
+ // watcher. Nothing moved and nobody takes the grid, so nothing
5587
+ // is said: an answer would have a driving page whose window
5588
+ // does not fit the grid propose again at once, over and over
5589
+ // until the exit arrives.
5449
5590
  if (error instanceof SessionProgramEndedError)
5450
5591
  return;
5451
- this.logger.warn('viewer resize failed', { id: session.id, error: String(error) });
5592
+ // Any other failure is logged rather than left to escape: an
5593
+ // exception from a WS handler would take the whole daemon down
5594
+ // via the uncaughtException path.
5595
+ this.logger.warn('viewer resize failed', {
5596
+ id: session.id,
5597
+ error: String(error),
5598
+ });
5452
5599
  }
5453
- return;
5454
- }
5455
- try {
5456
- const applied = await session.resizeIfCurrent(wanted.cols, wanted.rows,
5457
- // A viewport that left while its take waited in the queue made
5458
- // no lasting choice: skip it so the pending wider restore runs.
5459
- () => !session.geometryHeld && !session.exited && ws.readyState === ws.OPEN &&
5460
- (acceptOffer !== true || this.gridOfferedTo(session.id, ws)) &&
5461
- (this.sessionSockets.get(session.id)?.has(ws) ?? false), (changed) => {
5462
- const handedOver = this.geometryController.get(session.id) !== ws;
5463
- // The controller change and epoch belong to the same queued
5464
- // act as the resize, before a queued wider restore can run.
5465
- this.geometryController.set(session.id, ws);
5466
- this.recordGeometryChoice(session.id, true);
5467
- this.dashboardTransferable.delete(session.id);
5468
- this.geometryEpoch.set(session.id, (this.geometryEpoch.get(session.id) ?? 0) + 1);
5469
- if (credential.kind === 'dashboard') {
5470
- this.dashboardGeometryOwner.set(session.id, ws.protocol);
5471
- this.dashboardCredentialOwner.set(session.id, credential.dashboardToken);
5472
- }
5473
- else {
5474
- this.dashboardGeometryOwner.delete(session.id);
5475
- this.dashboardCredentialOwner.delete(session.id);
5476
- }
5477
- if (changed) {
5478
- this.audit.record(actor, 'resize', session.id, {
5479
- cols: wanted.cols, rows: wanted.rows, hold: false,
5480
- });
5481
- this.announceGeometry(session.id, session);
5482
- }
5483
- else if (handedOver)
5484
- this.announceGeometry(session.id, session, { resync: false });
5485
- else if (take === true)
5486
- ws.send(JSON.stringify(this.geometryFrame(session, ws)));
5487
- }, true);
5488
- if (!applied && ws.readyState === ws.OPEN)
5489
- ws.send(JSON.stringify(this.geometryFrame(session, ws)));
5490
- }
5491
- catch (error) {
5492
- // The program has ended (a viewer fitting its window while
5493
- // looking at a dying session), and the session's exit follows
5494
- // within about a second, with an `exited` frame to every
5495
- // watcher. Nothing moved and nobody takes the grid, so nothing
5496
- // is said: an answer would have a driving page whose window
5497
- // does not fit the grid propose again at once, over and over
5498
- // until the exit arrives.
5499
- if (error instanceof SessionProgramEndedError)
5500
- return;
5501
- // Any other failure is logged rather than left to escape: an
5502
- // exception from a WS handler would take the whole daemon down
5503
- // via the uncaughtException path.
5504
- this.logger.warn('viewer resize failed', {
5505
- id: session.id,
5506
- error: String(error),
5507
- });
5508
5600
  }
5601
+ return;
5509
5602
  }
5510
- return;
5511
5603
  }
5512
- }
5513
- catch {
5514
- // Not JSON: bytes for the program, a person's keystrokes or the
5515
- // viewer's terminal answering the program. Straight into the PTY
5516
- // either way: shared typing is the point of the tool.
5517
- }
5604
+ catch {
5605
+ // Not JSON: bytes for the program, a person's keystrokes or the
5606
+ // viewer's terminal answering the program. Straight into the PTY
5607
+ // either way: shared typing is the point of the tool.
5608
+ }
5518
5609
  if (readOnly) {
5519
5610
  // A watch-only credential. Dropped silently and on the daemon's side:
5520
5611
  // the page has already been told it is read-only and disables its own
@@ -5554,8 +5645,12 @@ export class Daemon {
5554
5645
  // sequences, so this is not always one keystroke.) .catch keeps the exit
5555
5646
  // race, the session dying mid-write, from escaping as an unhandled
5556
5647
  // rejection.
5557
- const report = terminalReportKind(text);
5558
- void session.write(text, { terminalReport: report !== null, humanInput: report === null }).catch((error) => {
5648
+ const mouseReport = bytes !== null && bytes.length === 6 && bytes[0] === 0x1b &&
5649
+ bytes[1] === 0x5b && bytes[2] === 0x4d;
5650
+ const report = bytes === null ? terminalReportBatchKind(text) : mouseReport ? 'mouse' : null;
5651
+ void (bytes === null
5652
+ ? session.write(text, { terminalReport: report !== null, humanInput: report === null })
5653
+ : session.writeBinary(bytes, { terminalReport: mouseReport })).catch((error) => {
5559
5654
  this.logger.warn('viewer input failed', {
5560
5655
  id: session.id,
5561
5656
  error: String(error),
@@ -5569,21 +5664,21 @@ export class Daemon {
5569
5664
  if (report !== null) {
5570
5665
  this.audit.record(actor, 'report', session.id, {
5571
5666
  kind: report,
5572
- chars: text.length,
5573
- ...(this.audit.captureContent ? { data: text } : {}),
5667
+ chars: bytes?.length ?? text.length,
5668
+ ...(this.audit.captureContent ? { data: bytes === null ? text : bytes.toString('latin1') } : {}),
5574
5669
  });
5575
5670
  return;
5576
5671
  }
5577
5672
  this.audit.record(actor, 'input', session.id, {
5578
- chars: text.length,
5673
+ chars: bytes?.length ?? text.length,
5579
5674
  });
5580
5675
  this.broadcastControl(session.id, { type: 'input-source', source: 'human' });
5581
5676
  };
5582
- ws.on('message', (message) => {
5677
+ ws.on('message', (message, isBinary) => {
5583
5678
  if (actor === 'dashboard' && ws.readyState !== ws.OPEN)
5584
5679
  return;
5585
5680
  this.callerContext.run(options.callerSession, () => {
5586
- void onViewerMessage(message).catch((error) => {
5681
+ void onViewerMessage(message, isBinary).catch((error) => {
5587
5682
  this.logger.warn('viewer message failed', { id: session.id, error: String(error) });
5588
5683
  });
5589
5684
  });