shellpuppet 0.4.2 → 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.
Files changed (83) hide show
  1. package/README.md +16 -5
  2. package/dist/agents/agy/index.js +1 -1
  3. package/dist/agents/agy/index.js.map +1 -1
  4. package/dist/agents/claude/index.js +1 -1
  5. package/dist/agents/claude/index.js.map +1 -1
  6. package/dist/agents/claude/nudge.js +1 -1
  7. package/dist/agents/claude/nudge.js.map +1 -1
  8. package/dist/agents/codex/draft.js +13 -6
  9. package/dist/agents/codex/draft.js.map +1 -1
  10. package/dist/agents/codex/index.js +1 -1
  11. package/dist/agents/codex/index.js.map +1 -1
  12. package/dist/agents/codex/nudge.js +7 -1
  13. package/dist/agents/codex/nudge.js.map +1 -1
  14. package/dist/agents/grok/index.js +1 -1
  15. package/dist/agents/grok/index.js.map +1 -1
  16. package/dist/agents/grok/nudge.js +13 -5
  17. package/dist/agents/grok/nudge.js.map +1 -1
  18. package/dist/agents/hermes/frame.js +4 -4
  19. package/dist/agents/hermes/frame.js.map +1 -1
  20. package/dist/agents/hermes/index.js +1 -1
  21. package/dist/agents/hermes/index.js.map +1 -1
  22. package/dist/agents/index.d.ts +2 -0
  23. package/dist/agents/index.js +7 -0
  24. package/dist/agents/index.js.map +1 -1
  25. package/dist/agents/mimo/index.js +1 -1
  26. package/dist/agents/mimo/index.js.map +1 -1
  27. package/dist/agents/muse/index.js +1 -1
  28. package/dist/agents/muse/index.js.map +1 -1
  29. package/dist/agents/muse/nudge.js +8 -3
  30. package/dist/agents/muse/nudge.js.map +1 -1
  31. package/dist/agents/nudgeReading.d.ts +2 -0
  32. package/dist/agents/nudgeReading.js +3 -3
  33. package/dist/agents/nudgeReading.js.map +1 -1
  34. package/dist/agents/opencode/index.js +1 -1
  35. package/dist/agents/opencode/index.js.map +1 -1
  36. package/dist/agents/qoder/index.js +1 -1
  37. package/dist/agents/qoder/index.js.map +1 -1
  38. package/dist/agents/types.d.ts +4 -0
  39. package/dist/cli/index.js +244 -5
  40. package/dist/cli/index.js.map +1 -1
  41. package/dist/client/http.d.ts +3 -0
  42. package/dist/client/http.js +7 -0
  43. package/dist/client/http.js.map +1 -1
  44. package/dist/client/input.d.ts +18 -0
  45. package/dist/client/input.js +15 -0
  46. package/dist/client/input.js.map +1 -1
  47. package/dist/core/session.d.ts +43 -4
  48. package/dist/core/session.js +169 -29
  49. package/dist/core/session.js.map +1 -1
  50. package/dist/core/windowsPtyStart.d.ts +2 -0
  51. package/dist/core/windowsPtyStart.js +6 -0
  52. package/dist/core/windowsPtyStart.js.map +1 -1
  53. package/dist/daemon/audit.d.ts +1 -1
  54. package/dist/daemon/audit.js +1 -1
  55. package/dist/daemon/index.js +1 -0
  56. package/dist/daemon/index.js.map +1 -1
  57. package/dist/daemon/launchProfiles.d.ts +9 -2
  58. package/dist/daemon/launchProfiles.js +27 -8
  59. package/dist/daemon/launchProfiles.js.map +1 -1
  60. package/dist/daemon/liveness.d.ts +11 -0
  61. package/dist/daemon/liveness.js +39 -0
  62. package/dist/daemon/liveness.js.map +1 -1
  63. package/dist/daemon/schedules.d.ts +1 -1
  64. package/dist/daemon/schedules.js +8 -3
  65. package/dist/daemon/schedules.js.map +1 -1
  66. package/dist/daemon/screenshot.d.ts +2 -0
  67. package/dist/daemon/screenshot.js +21 -3
  68. package/dist/daemon/screenshot.js.map +1 -1
  69. package/dist/daemon/server.d.ts +17 -1
  70. package/dist/daemon/server.js +498 -187
  71. package/dist/daemon/server.js.map +1 -1
  72. package/dist/daemon/sessionFeed.d.ts +1 -1
  73. package/dist/daemon/sessionFeed.js +3 -1
  74. package/dist/daemon/sessionFeed.js.map +1 -1
  75. package/dist/daemon/terminalReports.d.ts +9 -1
  76. package/dist/daemon/terminalReports.js +54 -0
  77. package/dist/daemon/terminalReports.js.map +1 -1
  78. package/dist/mcp/tools.js +12 -9
  79. package/dist/mcp/tools.js.map +1 -1
  80. package/dist/viewer/dashboard.css +20 -7
  81. package/dist/viewer/dashboard.js +120 -31
  82. package/dist/viewer/pane.js +159 -26
  83. package/package.json +1 -1
@@ -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';
@@ -20,7 +20,7 @@ import { Mailbox, MailboxError, NAME_PATTERN, buildNudge } from '../core/mailbox
20
20
  import { buildMessagingPolicy, DEFAULT_NUDGE_INTERVAL_MS, DEFAULT_NUDGES_PER_MINUTE } from './config.js';
21
21
  import { NudgeScheduler } from './nudgeScheduler.js';
22
22
  import { ScheduleStore, PromptScheduler, watchSchedules } from './schedules.js';
23
- import { CommandNotFoundError, DEFAULT_SESSION_ENV, SessionInputFailedError, SessionProgramEndedError, WindowsWithoutConPTYError, credentialShapedNames, submitOutcome, } from '../core/session.js';
23
+ import { CommandNotFoundError, DEFAULT_SESSION_ENV, SessionInputFailedError, SessionProgramEndedError, TemporaryResizeNotReadyError, WindowsWithoutConPTYError, credentialShapedNames, submitOutcome, } from '../core/session.js';
24
24
  import { NativePtyUnavailableError } from '../core/nativePty.js';
25
25
  import { checkSessionCapacity, commandLine, compilePolicy, evaluateCommand } from '../core/policy.js';
26
26
  import { keyToBytes, knownKeys } from '../core/keys.js';
@@ -41,11 +41,11 @@ 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';
48
- import { listRootFolders, resolveRootFolder } from './launchProfiles.js';
48
+ import { DEFAULT_LAUNCHES_PER_MINUTE, listRootFolders, parseLaunchesPerMinute, resolveRootFolder } from './launchProfiles.js';
49
49
  import { chooseFolder, FOLDER_PICKER_TIMEOUT_MS, FolderPickerFailureError, FolderPickerUnavailableError, FolderPickerTimeoutError } from './folderPicker.js';
50
50
  const DEFAULT_IDLE_MS = 30 * 60_000;
51
51
  /** Stop waits this long for an automatic dashboard launch before continuing. */
@@ -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;
@@ -500,6 +503,12 @@ export class Daemon {
500
503
  dashboardSocketCredential = new WeakMap();
501
504
  /** External geometry acts invalidate a temporary wider read's restoration. */
502
505
  geometryEpoch = new Map();
506
+ /** One daemon order for layout notices and deliberate grid choices. */
507
+ geometryOrder = new Map();
508
+ choiceRevision = new Map();
509
+ controllerChoiceRevision = new Map();
510
+ explicitResizeRevision = new Map();
511
+ dashboardLayouts = new WeakMap();
503
512
  widerReads = new Map();
504
513
  /** Subscribers to the daemon-wide event stream (`/events`). */
505
514
  eventSockets = new Map();
@@ -556,7 +565,9 @@ export class Daemon {
556
565
  sessionEnv;
557
566
  /** The profiles the dashboard may name, and the entries that did not load. */
558
567
  launchProfiles;
568
+ launchesPerMinute;
559
569
  daemonEnv;
570
+ omitInheritedNoColor;
560
571
  cliPath;
561
572
  /** The global policy, kept here so a launch can report it before creating. */
562
573
  compiledPolicy;
@@ -593,11 +604,14 @@ export class Daemon {
593
604
  };
594
605
  this.sessionEnv = options.sessionEnv ?? DEFAULT_SESSION_ENV;
595
606
  this.launchProfiles = options.launchProfiles ?? { profiles: [], problems: [] };
596
- this.daemonEnv = options.daemonEnv ?? process.env;
607
+ this.launchesPerMinute = this.launchProfiles.launchesPerMinute ?? DEFAULT_LAUNCHES_PER_MINUTE;
608
+ this.daemonEnv = { ...(options.daemonEnv ?? process.env) };
609
+ this.omitInheritedNoColor = hasAgentShellNoColor(this.daemonEnv);
597
610
  this.cliPath = fileURLToPath(new URL('../../dist/cli/index.js', import.meta.url));
598
611
  this.compiledPolicy = compilePolicy(options.policy);
599
612
  this.manager = new SessionManager(compilePolicy(options.policy), this.logger, {
600
613
  sessionEnv: this.sessionEnv,
614
+ omitInheritedNoColor: this.omitInheritedNoColor,
601
615
  identity: {
602
616
  token: '',
603
617
  instanceId: this.instanceId,
@@ -637,6 +651,11 @@ export class Daemon {
637
651
  });
638
652
  this.mailbox.on('state', (event) => {
639
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
+ }
640
659
  this.emitMessageEvent({ type: 'message-state', ...event }, entry);
641
660
  this.emitDashboardMessageEvent({ type: 'message-state', ...event });
642
661
  });
@@ -819,6 +838,8 @@ export class Daemon {
819
838
  // Said once, at start, because passthrough leaks silently otherwise
820
839
  // (ADR-008): the names only, never the values.
821
840
  const { exposed } = this.environmentReport();
841
+ if (this.omitInheritedNoColor)
842
+ this.logger.info('omitting inherited output setting from agent tool shell', { names: ['NO_COLOR'] });
822
843
  if (exposed.length > 0) {
823
844
  this.logger.warn('sessionEnv "passthrough" hands every session the daemon environment, including ' +
824
845
  'these variables whose names look like credentials; use "clean" or a list to keep them out', { names: exposed });
@@ -863,7 +884,14 @@ export class Daemon {
863
884
  });
864
885
  }, this.options.promptScanIntervalMs ?? PROMPT_SCAN_INTERVAL_MS);
865
886
  this.promptScanTimer.unref();
866
- this.stopScheduleWatch = watchSchedules(home, this.schedules, this.logger);
887
+ this.stopScheduleWatch = watchSchedules(home, this.schedules, this.logger, (raw, initial) => {
888
+ if (initial && raw['launcher'] === undefined)
889
+ return;
890
+ const allowance = parseLaunchesPerMinute(raw['launcher']);
891
+ this.launchesPerMinute = allowance.value;
892
+ if (!initial && allowance.problem !== undefined)
893
+ this.logger.warn('CONFIG PROBLEM', { problem: allowance.problem });
894
+ });
867
895
  this.promptScheduler.start();
868
896
  this.logger.info('daemon started', {
869
897
  port: this.portValue,
@@ -1074,11 +1102,22 @@ export class Daemon {
1074
1102
  for (const read of this.widerReads.values())
1075
1103
  read.abort.abort();
1076
1104
  const readsDone = Promise.allSettled([...this.widerReads.values()].map((read) => read.done));
1105
+ const widerDeadline = Date.now() + 250;
1077
1106
  await this.shutdownRecords;
1078
1107
  // A free port lets a successor retire the ownership marker. Keep it
1079
1108
  // bound through publication, then close without waiting for PTY teardown.
1080
1109
  const listenerClosed = this.closeServerOnly();
1081
- await readsDone;
1110
+ let widerTimer;
1111
+ const widerOutcome = await Promise.race([
1112
+ readsDone.then(() => 'settled'),
1113
+ new Promise((resolve) => {
1114
+ widerTimer = setTimeout(() => resolve('timeout'), Math.max(0, widerDeadline - Date.now()));
1115
+ }),
1116
+ ]);
1117
+ if (widerTimer !== undefined)
1118
+ clearTimeout(widerTimer);
1119
+ if (widerOutcome === 'timeout')
1120
+ this.logger.warn('wider reads exceeded shutdown restoration budget');
1082
1121
  for (const socket of this.sockets) {
1083
1122
  try {
1084
1123
  socket.close();
@@ -1921,7 +1960,7 @@ export class Daemon {
1921
1960
  });
1922
1961
  return;
1923
1962
  }
1924
- const { env, copied } = copyDaemonEnv(profile.envFromDaemon, this.daemonEnv);
1963
+ const { env, copied } = copyDaemonEnv(profile.envFromDaemon, this.daemonEnv, undefined, this.omitInheritedNoColor);
1925
1964
  const envNames = Object.keys(env);
1926
1965
  const folderLabel = freeCwd !== undefined ? freeCwd : folder?.name ?? (rootCwd !== undefined ? folderName : undefined);
1927
1966
  const options = {
@@ -1984,10 +2023,10 @@ export class Daemon {
1984
2023
  }
1985
2024
  const now = this.now();
1986
2025
  this.pruneLaunchTimes(now);
1987
- if (this.launchTimes.length + this.pendingProfileStarts.size >= 8) {
2026
+ if (this.launchTimes.length + this.pendingProfileStarts.size >= this.launchesPerMinute) {
1988
2027
  this.auditDashboardRefusal(req, 'rate', launcher?.name);
1989
2028
  json(res, 429, {
1990
- error: 'Dashboard launch rate reached (8 in 60 seconds). Wait before starting another profile.',
2029
+ error: `Dashboard launch rate reached (${String(this.launchesPerMinute)} in 60 seconds). Wait before starting another profile.`,
1991
2030
  });
1992
2031
  return;
1993
2032
  }
@@ -2312,7 +2351,7 @@ export class Daemon {
2312
2351
  // Unauthenticated by design (§4.1): clients must be able to poll before
2313
2352
  // the token file settles. The instance id is an identity, not a secret.
2314
2353
  if (req.method === 'GET' && url.pathname === '/health') {
2315
- json(res, 200, { ok: true, version: this.version, pid: process.pid, instanceId: this.instanceId });
2354
+ json(res, 200, { ok: true, version: this.version, pid: process.pid, instanceId: this.instanceId, inputSubmitMode: 1 });
2316
2355
  return;
2317
2356
  }
2318
2357
  // The viewer page itself is served without auth, and must stay that way:
@@ -2604,6 +2643,8 @@ export class Daemon {
2604
2643
  if (pendingId === id)
2605
2644
  this.pendingSchedules.delete(name);
2606
2645
  this.nudges.remove(id);
2646
+ this.queuedMessageNudges.delete(id);
2647
+ this.inboxReadVersions.delete(id);
2607
2648
  // Audit before end can trim old tombstones from retained history.
2608
2649
  for (const entry of this.mailbox.log({ participantId: id })) {
2609
2650
  if (entry.to.id === id && (entry.state === 'waiting' || entry.state === 'nudged')) {
@@ -2628,38 +2669,68 @@ export class Daemon {
2628
2669
  }
2629
2670
  async deliverNudge(id) {
2630
2671
  const session = this.manager.get(id);
2631
- 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);
2632
2674
  return 'done';
2675
+ }
2633
2676
  const pendingIds = session.nudgePendingLine() !== null ? [...session.nudgePendingIds()] : [];
2634
2677
  // A scheduled body has no mailbox ids. It can clear on proof of consumption,
2635
2678
  // but a later inbox message can never authorise its submit key.
2636
2679
  if (session.nudgePendingLine() !== null && pendingIds.length === 0 &&
2637
2680
  !await this.clearScheduledBody(session))
2638
2681
  return 'wait';
2639
- const clearedIds = pendingIds.length > 0 && await session.clearConsumedNudge() ? pendingIds : [];
2640
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 : [];
2641
2694
  if (clearedIds.length > 0) {
2642
2695
  this.audit.record('daemon', 'nudge-cleared', id, { messageIds: clearedIds,
2643
2696
  waitingMessageIds: unread.map((entry) => entry.id) });
2644
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.
2645
2700
  const pending = session.nudgePendingLine();
2646
2701
  if (pending !== null) {
2647
2702
  if (session.nudgePendingIds().length === 0)
2648
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
+ };
2649
2711
  const ids = unread.filter((entry) => entry.state === 'waiting').map((entry) => entry.id);
2650
- if (ids.length === 0)
2712
+ if (ids.length === 0) {
2713
+ auditPending('messages-changed');
2651
2714
  return 'done';
2652
- const covered = session.nudgePendingIds();
2653
- 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()) {
2654
2721
  if (session.nudgeReadyWithLine(pending) && session.nudgePendingTouchRefusal()) {
2655
2722
  this.audit.record('daemon', 'nudge-aborted', id, {
2656
2723
  messageIds: [...covered], count: covered.length, reason: 'person-input-since',
2724
+ ...session.nudgePendingBodyMeta(),
2657
2725
  });
2658
2726
  }
2727
+ auditPending('person-input-since');
2659
2728
  return 'wait';
2660
2729
  }
2661
- if (!session.nudgeReadyWithLine(pending))
2730
+ if (!session.nudgeReadyWithLine(pending)) {
2731
+ auditPending('line-not-seen');
2662
2732
  return 'wait';
2733
+ }
2663
2734
  const inputVersion = session.nudgeInputVersion();
2664
2735
  const queuedInputVersion = session.nudgeQueuedInputVersion();
2665
2736
  const screenRevision = session.nudgeScreenRevision();
@@ -2667,10 +2738,13 @@ export class Daemon {
2667
2738
  const waitingIds = this.mailbox.inbox(id, { markRead: false })
2668
2739
  .filter((entry) => entry.state === 'waiting').map((entry) => entry.id);
2669
2740
  return !session.exited && !session.getStalled() &&
2741
+ session.nudgePendingSafeToSubmit() &&
2670
2742
  session.nudgeInputVersion() === inputVersion &&
2671
2743
  session.nudgeQueuedInputVersion() === queuedInputVersion &&
2672
2744
  session.nudgeScreenRevision() === screenRevision &&
2673
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)) &&
2674
2748
  waitingIds.length === ids.length &&
2675
2749
  ids.every((messageId) => waitingIds.includes(messageId));
2676
2750
  });
@@ -2678,8 +2752,10 @@ export class Daemon {
2678
2752
  if (session.nudgePendingTouchRefusal()) {
2679
2753
  this.audit.record('daemon', 'nudge-aborted', id, {
2680
2754
  messageIds: [...covered], count: covered.length, reason: 'person-input-since',
2755
+ ...session.nudgePendingBodyMeta(),
2681
2756
  });
2682
2757
  }
2758
+ auditPending('person-input-since');
2683
2759
  return 'wait';
2684
2760
  }
2685
2761
  this.mailbox.markNudged(ids);
@@ -2688,25 +2764,48 @@ export class Daemon {
2688
2764
  staleMessageIds: covered.filter((messageId) => !unread.some((entry) => entry.id === messageId)) });
2689
2765
  return 'sent';
2690
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
+ }
2691
2785
  // Only a message that has not been nudged yet starts a nudge. One that was
2692
2786
  // nudged but is still unread (the agent did not read its inbox) is listed
2693
- // 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.
2694
2788
  const ids = unread.filter((entry) => entry.state === 'waiting').map((entry) => entry.id);
2695
2789
  if (ids.length === 0)
2696
2790
  return 'done';
2697
2791
  if (!session.hasPainted() || !session.nudgeReady(this.now()))
2698
2792
  return 'wait';
2699
2793
  const line = buildNudge(unread);
2794
+ const readVersion = this.inboxReadVersions?.get(id) ?? 0;
2700
2795
  const result = await this.deliverLine(session, line, undefined, ids, () => {
2701
2796
  const current = this.mailbox.inbox(id, { markRead: false });
2702
2797
  return ids.every(messageId => current.some(entry => entry.id === messageId && entry.state === 'waiting'));
2703
2798
  });
2704
2799
  if (result.outcome === 'aborted') {
2705
- 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() });
2706
2802
  }
2707
2803
  if (result.outcome !== 'sent' && result.outcome !== 'queued')
2708
2804
  return 'wait';
2709
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
+ }
2710
2809
  this.audit.record('daemon', 'nudge', id, { messageIds: ids, count: ids.length,
2711
2810
  ...(result.outcome === 'queued' ? { queued: true } : {}) });
2712
2811
  return 'sent';
@@ -2814,6 +2913,14 @@ export class Daemon {
2814
2913
  }
2815
2914
  }
2816
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
+ }
2817
2924
  if (error instanceof SessionInputFailedError)
2818
2925
  return { outcome: 'skipped', reason: 'input-failed' };
2819
2926
  if (error instanceof SessionProgramEndedError)
@@ -3035,11 +3142,20 @@ export class Daemon {
3035
3142
  json(res, 200, { schedules: this.promptScheduler.list() });
3036
3143
  return;
3037
3144
  }
3145
+ if (url.pathname === '/daemon/stop-info' && req.method === 'GET') {
3146
+ res.setHeader('Cache-Control', 'no-store');
3147
+ json(res, 200, { completion: { version: 1,
3148
+ role: this.options.exitProcessOnStop === true ? 'standalone' : 'embedded',
3149
+ pid: process.pid, instanceId: this.instanceId } });
3150
+ return;
3151
+ }
3038
3152
  if (segments[0] === 'daemon' && segments[1] === 'shutdown' && req.method === 'POST') {
3039
3153
  const body = await readBody(req);
3154
+ const completion = { version: 1, role: this.options.exitProcessOnStop === true ? 'standalone' : 'embedded',
3155
+ pid: process.pid, instanceId: this.instanceId };
3040
3156
  if (this.stopping) {
3041
3157
  await this.shutdownRecords;
3042
- json(res, 200, { ok: true, stopping: true, warnings: this.shutdownWarnings });
3158
+ json(res, 200, { ok: true, stopping: true, warnings: this.shutdownWarnings, completion });
3043
3159
  return;
3044
3160
  }
3045
3161
  const force = asBoolean(body['force']) ?? false;
@@ -3054,7 +3170,7 @@ export class Daemon {
3054
3170
  const stopping = this.stop({ restart: body['restart'] === true });
3055
3171
  this.audit.record(actor, 'shutdown', undefined, { force, liveSessions: live });
3056
3172
  await this.shutdownRecords;
3057
- json(res, 200, { ok: true, stopping: true, warnings: this.shutdownWarnings });
3173
+ json(res, 200, { ok: true, stopping: true, warnings: this.shutdownWarnings, completion });
3058
3174
  void stopping.then(() => {
3059
3175
  this.options.onSelfStop?.('shutdown-request');
3060
3176
  });
@@ -3402,7 +3518,7 @@ export class Daemon {
3402
3518
  this.audit.record(actor, 'wider-read', id, { requested, original });
3403
3519
  try {
3404
3520
  if (target.cols !== original.cols || target.rows !== original.rows) {
3405
- await session.resize(target.cols, target.rows);
3521
+ await session.resize(target.cols, target.rows, { temporarySignal: abort.signal });
3406
3522
  announce();
3407
3523
  }
3408
3524
  const settled = await session.waitFor({ quiet: 250 }, {
@@ -3425,6 +3541,7 @@ export class Daemon {
3425
3541
  // Only a deliberate geometry act wins. A departing controller does
3426
3542
  // not choose a new size; keep the control state its departure left.
3427
3543
  const mayRestore = () => (this.geometryEpoch.get(id) ?? 0) === epoch &&
3544
+ this.manager.get(id) === session && !session.isKilled &&
3428
3545
  !session.geometryHeld && !session.exited &&
3429
3546
  session.cols === target.cols && session.rows === target.rows;
3430
3547
  restored = target.cols === original.cols && target.rows === original.rows
@@ -3449,6 +3566,9 @@ export class Daemon {
3449
3566
  const code = readError instanceof SessionProgramEndedError ? readError.exitCode : session.exitCode;
3450
3567
  json(res, 409, { error: endedRefusal(id, code, session.fault) });
3451
3568
  }
3569
+ else if (readError instanceof TemporaryResizeNotReadyError) {
3570
+ json(res, 409, { error: readError.message });
3571
+ }
3452
3572
  else if (readError !== undefined) {
3453
3573
  throw readError instanceof Error ? readError : new Error('Wider read failed with a non-Error value.');
3454
3574
  }
@@ -3481,12 +3601,25 @@ export class Daemon {
3481
3601
  return;
3482
3602
  }
3483
3603
  if (req.method === 'POST' && action === 'input') {
3604
+ const header = req.headers['x-shellpuppet-submit'];
3605
+ const submitMode = header === undefined ? undefined : header === 'auto' || header === 'on' || header === 'off' ? header : null;
3606
+ if (submitMode === null) {
3607
+ json(res, 400, { error: 'Invalid submit mode.' });
3608
+ return;
3609
+ }
3610
+ if (req.headers['x-shellpuppet-expected-instance'] !== undefined &&
3611
+ req.headers['x-shellpuppet-expected-instance'] !== this.instanceId) {
3612
+ json(res, 409, { error: 'The daemon changed after submit preflight.' });
3613
+ return;
3614
+ }
3484
3615
  const body = await readBody(req);
3485
3616
  const data = asString(body['data']);
3486
3617
  if (data === undefined) {
3487
3618
  json(res, 400, { error: 'data (string) is required.' });
3488
3619
  return;
3489
3620
  }
3621
+ const report = (submitMode === undefined || submitMode === 'off') && body['submit'] !== true
3622
+ ? terminalReportBatchKind(data) : null;
3490
3623
  // Awaited: long input is chunked (Session.write), so verify below must
3491
3624
  // not read the screen until every chunk has actually been written.
3492
3625
  // The write resolves with the screen as it was just before this input
@@ -3503,7 +3636,9 @@ export class Daemon {
3503
3636
  const submit = body['submit'] === true;
3504
3637
  let written;
3505
3638
  try {
3506
- written = await session.writeWithResult(data);
3639
+ written = await session.writeWithResult(data, {
3640
+ ...(submitMode !== undefined ? { submitMode } : {}), terminalReport: report !== null,
3641
+ });
3507
3642
  }
3508
3643
  catch (error) {
3509
3644
  json(res, 409, {
@@ -3513,10 +3648,20 @@ export class Daemon {
3513
3648
  });
3514
3649
  return;
3515
3650
  }
3516
- const reporting = submit ? submitOutcome(written) : undefined;
3517
- this.audit.record(actor, 'input', id, { chars: data.length,
3518
- ...(reporting ? { submit: true, ...reporting } : {}) });
3519
- this.broadcastControl(id, { type: 'input-source', source: 'agent' });
3651
+ const reporting = submitMode === undefined ? submit ? submitOutcome(written) : undefined
3652
+ : submitMode === 'off' || (submitMode === 'auto' && !written.submitApplied)
3653
+ ? { outcome: 'not-requested' }
3654
+ : submitOutcome(written, true);
3655
+ const bytes = submitMode === undefined ? data.length : written.inputBytes ?? 0;
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
+ }
3520
3665
  // §3.1: TUIs silently swallow input while loading or when a panel has
3521
3666
  // stolen focus. verify re-reads the screen and reports whether the
3522
3667
  // text landed (best effort: hidden-input prompts and heavy
@@ -3524,7 +3669,7 @@ export class Daemon {
3524
3669
  if (asBoolean(body['verify']) === true) {
3525
3670
  json(res, 200, {
3526
3671
  ok: true,
3527
- bytes: data.length,
3672
+ bytes,
3528
3673
  ...reporting,
3529
3674
  verified: await this.verifyTyped(session, data, written.before),
3530
3675
  ...(written.submitted !== undefined ? { submitted: written.submitted } : {}),
@@ -3533,7 +3678,7 @@ export class Daemon {
3533
3678
  });
3534
3679
  return;
3535
3680
  }
3536
- json(res, 200, { ok: true, bytes: data.length,
3681
+ json(res, 200, { ok: true, bytes,
3537
3682
  ...reporting,
3538
3683
  ...(written.submitted !== undefined ? { submitted: written.submitted } : {}),
3539
3684
  ...(written.submitRetried ? { submitRetried: true } : {}),
@@ -3777,12 +3922,13 @@ export class Daemon {
3777
3922
  await session.resize(cols, rows, { hold, onApplied: () => {
3778
3923
  this.audit.record(actor, 'resize', id, { cols, rows, hold });
3779
3924
  this.geometryEpoch.set(id, (this.geometryEpoch.get(id) ?? 0) + 1);
3925
+ this.explicitResizeRevision.set(id, this.recordGeometryChoice(id));
3780
3926
  // An API resize takes the grid away from whichever viewport had it.
3781
3927
  this.geometryController.delete(id);
3782
3928
  this.dashboardGeometryOwner.delete(id);
3783
3929
  this.dashboardCredentialOwner.delete(id);
3784
3930
  this.dashboardTransferable.delete(id);
3785
- this.announceGeometry(id, session);
3931
+ this.announceGeometry(id, session, { clientResize: true });
3786
3932
  } });
3787
3933
  }
3788
3934
  catch (error) {
@@ -4177,6 +4323,10 @@ export class Daemon {
4177
4323
  this.dashboardCredentialOwner.delete(id);
4178
4324
  this.dashboardTransferable.delete(id);
4179
4325
  this.geometryEpoch.delete(id);
4326
+ this.geometryOrder.delete(id);
4327
+ this.choiceRevision.delete(id);
4328
+ this.controllerChoiceRevision.delete(id);
4329
+ this.explicitResizeRevision.delete(id);
4180
4330
  }
4181
4331
  /** Whether a live viewport is currently driving this session's grid. */
4182
4332
  hasGeometryController(sessionId) {
@@ -4188,6 +4338,32 @@ export class Daemon {
4188
4338
  this.geometryController.delete(sessionId);
4189
4339
  return false;
4190
4340
  }
4341
+ nextGeometryOrder(id) {
4342
+ const order = (this.geometryOrder.get(id) ?? 0) + 1;
4343
+ this.geometryOrder.set(id, order);
4344
+ return order;
4345
+ }
4346
+ recordGeometryChoice(id, controller = false) {
4347
+ const revision = this.nextGeometryOrder(id);
4348
+ this.choiceRevision.set(id, revision);
4349
+ if (controller)
4350
+ this.controllerChoiceRevision.set(id, revision);
4351
+ return revision;
4352
+ }
4353
+ /** A document can reserve its grid only while its credential and proof are valid. */
4354
+ hasDashboardGeometryOwner(id) {
4355
+ const owner = this.dashboardGeometryOwner.get(id);
4356
+ if (owner === undefined)
4357
+ return false;
4358
+ if (this.tokens.verifyDashboardToken(this.dashboardCredentialOwner.get(id)) &&
4359
+ (this.dashboardTransferable.has(id) || this.tokens.acceptsDashboardProof(dashboardProofFromProtocol(owner))))
4360
+ return true;
4361
+ this.dashboardGeometryOwner.delete(id);
4362
+ this.dashboardCredentialOwner.delete(id);
4363
+ this.dashboardTransferable.delete(id);
4364
+ this.recordGeometryChoice(id);
4365
+ return false;
4366
+ }
4191
4367
  // ---------------------------------------------------- prompt-stall alerts
4192
4368
  /**
4193
4369
  * Wait, for a session just created, until its program exists (the start
@@ -4267,10 +4443,10 @@ export class Daemon {
4267
4443
  },
4268
4444
  };
4269
4445
  }
4270
- updateFeedSession(id) {
4446
+ updateFeedSession(id, promptRestarted = false) {
4271
4447
  const session = this.manager.get(id);
4272
4448
  if (session !== undefined)
4273
- this.sessionFeed.update(this.summaryWithPrompt(session.summary()));
4449
+ this.sessionFeed.update(this.summaryWithPrompt(session.summary()), promptRestarted);
4274
4450
  }
4275
4451
  /** One transition drives the feed, audit, log and both notification channels. */
4276
4452
  watchStalls(session) {
@@ -4400,6 +4576,13 @@ export class Daemon {
4400
4576
  previous.prompt.selectedOption !== detected.selectedOption ||
4401
4577
  previous.prompt.options.length !== detected.options.length ||
4402
4578
  previous.prompt.options.some((option, index) => option !== detected.options[index]);
4579
+ const inputVersion = session.promptInputVersion();
4580
+ // Input alone does not mean this prompt was answered: a key may start
4581
+ // a repaint while the same decision remains on screen. A missed prompt
4582
+ // after input is evidence of a transition only when a prompt appears
4583
+ // again; the normal grace check still handles a lasting disappearance.
4584
+ const answered = previous !== undefined && previous.inputVersion !== inputVersion &&
4585
+ previous.missingSince !== null;
4403
4586
  if (previous !== undefined) {
4404
4587
  this.clearPromptGraceCheck(session.id);
4405
4588
  previous.missingSince = null;
@@ -4410,7 +4593,7 @@ export class Daemon {
4410
4593
  // then changes although the person still faces the same decision.
4411
4594
  // A stable signature also covers focus markers moving among options.
4412
4595
  const sameContent = previous !== undefined && !promptChanged;
4413
- if (previous === undefined || (previous.signature !== detected.signature && !sameContent)) {
4596
+ if (previous === undefined || answered || (previous.signature !== detected.signature && !sameContent)) {
4414
4597
  // A new (or changed) prompt starts its stall clock; it has not
4415
4598
  // alerted yet, so a prompt answered promptly stays silent.
4416
4599
  if (previous?.alerted === true) {
@@ -4433,13 +4616,13 @@ export class Daemon {
4433
4616
  }
4434
4617
  this.promptStates.set(session.id, {
4435
4618
  signature: detected.signature,
4619
+ inputVersion,
4436
4620
  since: this.now(),
4437
4621
  alerted: false,
4438
4622
  prompt: detected,
4439
4623
  missingSince: null,
4440
4624
  });
4441
- if (promptChanged || previous?.alerted === true)
4442
- this.updateFeedSession(session.id);
4625
+ this.updateFeedSession(session.id, previous !== undefined);
4443
4626
  continue;
4444
4627
  }
4445
4628
  previous.signature = detected.signature;
@@ -4918,7 +5101,11 @@ export class Daemon {
4918
5101
  announceGeometry(sessionId, session, options = {}) {
4919
5102
  for (const [ws, sync] of this.sessionSockets.get(sessionId) ?? []) {
4920
5103
  if (ws.readyState === ws.OPEN) {
4921
- ws.send(JSON.stringify(this.geometryFrame(session, ws)));
5104
+ ws.send(JSON.stringify({ ...this.geometryFrame(session, ws),
5105
+ ...(options.clientResize ? { clientResize: true,
5106
+ layoutFence: this.dashboardLayouts.get(ws)?.realId ?? 0 } : {}),
5107
+ ...(ws === this.geometryController.get(sessionId) && options.acceptedTakeId !== undefined
5108
+ ? { acceptedTakeId: options.acceptedTakeId } : {}) }));
4922
5109
  }
4923
5110
  if (options.resync !== false)
4924
5111
  sync.resync();
@@ -4933,8 +5120,13 @@ export class Daemon {
4933
5120
  }
4934
5121
  /** What one watcher is told about the grid, from its own point of view. */
4935
5122
  geometryFrame(session, ws) {
5123
+ const reserved = this.dashboardSocketCredential.has(ws) && this.hasDashboardGeometryOwner(session.id);
5124
+ const controlled = this.hasGeometryController(session.id);
4936
5125
  return {
4937
5126
  type: 'geometry',
5127
+ choiceRevision: this.choiceRevision.get(session.id) ?? 0,
5128
+ controllerChoiceRevision: this.controllerChoiceRevision.get(session.id) ?? 0,
5129
+ explicitResizeRevision: this.explicitResizeRevision.get(session.id) ?? 0,
4938
5130
  ...(this.widerReads.get(session.id)?.isTemporary() ? { temporary: true } : {}),
4939
5131
  cols: session.cols,
4940
5132
  rows: session.rows,
@@ -4944,8 +5136,7 @@ export class Daemon {
4944
5136
  max: { cols: MAX_VIEWPORT_COLS, rows: MAX_VIEWPORT_ROWS },
4945
5137
  // An adopting dashboard must distinguish a fresh session from one
4946
5138
  // already taken in another window before scheduling its initial fit.
4947
- owned: this.hasGeometryController(session.id) ||
4948
- (this.dashboardSocketCredential.has(ws) && this.dashboardGeometryOwner.has(session.id)),
5139
+ owned: controlled || reserved,
4949
5140
  // Only a controller's explicit assignment handover offers its grid to
4950
5141
  // another dashboard pane while the old socket is closing.
4951
5142
  dashboardTransferable: this.gridOfferedTo(session.id, ws),
@@ -4980,7 +5171,7 @@ export class Daemon {
4980
5171
  * exit notice); TEXT frames are JSON control messages. Incoming text frames
4981
5172
  * are either JSON controls (resize) or bytes for the program: a person's
4982
5173
  * keystrokes, or the viewer's terminal answering the program
4983
- * (terminalReports.ts).
5174
+ * (terminalReports.ts). Incoming binary frames carry raw onBinary input.
4984
5175
  */
4985
5176
  attachSocket(ws, session, credential, options = {}) {
4986
5177
  const { readOnly } = credential;
@@ -5057,12 +5248,13 @@ export class Daemon {
5057
5248
  if (credential.kind === 'dashboard' &&
5058
5249
  // The returning document can restore its grid while a release to a
5059
5250
  // different assignment belongs to that recipient alone.
5060
- this.dashboardGeometryOwner.has(session.id) &&
5251
+ this.hasDashboardGeometryOwner(session.id) &&
5061
5252
  (!this.dashboardTransferable.has(session.id) || this.gridOfferedTo(session.id, ws)) &&
5062
5253
  tokensEqual(this.dashboardGeometryOwner.get(session.id), ws.protocol) &&
5063
5254
  !session.exited &&
5064
5255
  !this.hasGeometryController(session.id)) {
5065
5256
  this.geometryController.set(session.id, ws);
5257
+ this.recordGeometryChoice(session.id, true);
5066
5258
  this.dashboardTransferable.delete(session.id);
5067
5259
  this.announceGeometry(session.id, session, { resync: false });
5068
5260
  }
@@ -5070,8 +5262,9 @@ export class Daemon {
5070
5262
  !readOnly &&
5071
5263
  !passive &&
5072
5264
  !this.hasGeometryController(session.id) &&
5073
- !this.dashboardGeometryOwner.has(session.id)) {
5265
+ !this.hasDashboardGeometryOwner(session.id)) {
5074
5266
  this.geometryController.set(session.id, ws);
5267
+ this.recordGeometryChoice(session.id, true);
5075
5268
  this.dashboardGeometryOwner.delete(session.id);
5076
5269
  this.dashboardCredentialOwner.delete(session.id);
5077
5270
  this.dashboardTransferable.delete(session.id);
@@ -5146,160 +5339,273 @@ export class Daemon {
5146
5339
  });
5147
5340
  /** Whether this socket has been told that the session's input has failed. */
5148
5341
  let toldInputFailed = false;
5149
- const onViewerMessage = async (message) => {
5342
+ const onViewerMessage = async (message, isBinary) => {
5150
5343
  this.lastActivity = Date.now();
5151
- const text = typeof message === 'string' ? message : message.toString('utf8');
5152
- try {
5153
- const parsed = JSON.parse(text);
5154
- if (typeof parsed === 'object' && parsed !== null &&
5155
- parsed.type === 'release-grid') {
5156
- // Only the current controller can give up a dashboard grid. Another
5157
- // document with the same cookie cannot make a live controller yield.
5158
- if (credential.kind === 'dashboard' && !session.exited && !session.geometryHeld &&
5159
- this.geometryController.get(session.id) === ws) {
5160
- const windows = this.dashboardWindows();
5161
- const target = windows.find(({ pair }) => this.dashboardAssignments.get(pair)?.includes(session.id));
5162
- if (target)
5163
- this.dashboardTransferable.set(session.id, target.socket.protocol);
5164
- else if (windows.length === 0)
5165
- this.dashboardTransferable.set(session.id, null);
5166
- this.announceGeometry(session.id, session, { resync: false });
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 });
5362
+ }
5363
+ return;
5167
5364
  }
5168
- return;
5169
- }
5170
- if (typeof parsed === 'object' &&
5171
- parsed !== null &&
5172
- parsed.type === 'resize') {
5173
- const { cols, rows, take, acceptOffer } = parsed;
5174
- // Fit, Enlarge, Focus and Restore are a resize that says `take`.
5175
- // A passive socket's other resizes, including one a dashboard pane
5176
- // sends because the window moved, are not that act: the grid stays,
5177
- // nobody is handed it, and nothing is audited. Passivity is the
5178
- // dashboard credential, or `drive=0` on a viewer or client socket.
5179
- 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
+ }
5180
5380
  return;
5181
- if (!readOnly &&
5182
- typeof cols === 'number' &&
5183
- typeof rows === 'number' &&
5184
- Number.isInteger(cols) &&
5185
- Number.isInteger(rows) &&
5186
- cols >= 2 &&
5187
- cols <= 1_000 &&
5188
- rows >= 2 &&
5189
- rows <= 500 &&
5190
- !session.exited) {
5191
- if (session.geometryHeld) {
5192
- // Held against viewports. Answer with the real grid so the page
5193
- // stops proposing one it will never be given.
5194
- 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();
5195
5397
  return;
5196
5398
  }
5197
- const wanted = {
5198
- cols: Math.min(cols, MAX_VIEWPORT_COLS),
5199
- rows: Math.min(rows, MAX_VIEWPORT_ROWS),
5200
- };
5201
- if (!this.widerReads.has(session.id) && acceptOffer !== true) {
5202
- // Wider restores and conditional offer takes check ownership
5203
- // in the session's resize queue below.
5204
- const handedOver = this.geometryController.get(session.id) !== ws;
5205
- const changed = wanted.cols !== session.cols || wanted.rows !== session.rows;
5206
- let applied = false;
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) {
5494
+ let applied = false;
5495
+ let changedAtApply = false;
5496
+ const shouldApply = () => {
5497
+ if (session.geometryHeld || session.exited || ws.readyState !== ws.OPEN ||
5498
+ !this.sessionSockets.get(session.id)?.has(ws))
5499
+ return false;
5500
+ changedAtApply = wanted.cols !== session.cols || wanted.rows !== session.rows;
5501
+ return true;
5502
+ };
5503
+ const onApplied = () => {
5504
+ applied = true;
5505
+ const handedOver = this.geometryController.get(session.id) !== ws;
5506
+ this.geometryController.set(session.id, ws);
5507
+ this.recordGeometryChoice(session.id, true);
5508
+ this.dashboardTransferable.delete(session.id);
5509
+ this.geometryEpoch.set(session.id, (this.geometryEpoch.get(session.id) ?? 0) + 1);
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) {
5519
+ this.audit.record(actor, 'resize', session.id, {
5520
+ cols: wanted.cols, rows: wanted.rows, hold: false,
5521
+ });
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)));
5528
+ };
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)));
5538
+ }
5539
+ catch (error) {
5540
+ if (error instanceof SessionProgramEndedError)
5541
+ return;
5542
+ this.logger.warn('viewer resize failed', { id: session.id, error: String(error) });
5543
+ }
5544
+ return;
5545
+ }
5207
5546
  try {
5208
- if (changed)
5209
- await session.resize(wanted.cols, wanted.rows);
5210
- applied = true;
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);
5579
+ if (!applied && ws.readyState === ws.OPEN)
5580
+ ws.send(JSON.stringify(this.geometryFrame(session, ws)));
5211
5581
  }
5212
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.
5213
5590
  if (error instanceof SessionProgramEndedError)
5214
5591
  return;
5215
- this.logger.warn('viewer resize failed', { id: session.id, error: String(error) });
5216
- }
5217
- this.geometryController.set(session.id, ws);
5218
- this.dashboardTransferable.delete(session.id);
5219
- this.geometryEpoch.set(session.id, (this.geometryEpoch.get(session.id) ?? 0) + 1);
5220
- if (credential.kind === 'dashboard') {
5221
- this.dashboardGeometryOwner.set(session.id, ws.protocol);
5222
- this.dashboardCredentialOwner.set(session.id, credential.dashboardToken);
5223
- }
5224
- else {
5225
- this.dashboardGeometryOwner.delete(session.id);
5226
- this.dashboardCredentialOwner.delete(session.id);
5227
- }
5228
- if (changed && applied) {
5229
- this.audit.record(actor, 'resize', session.id, {
5230
- cols: wanted.cols, rows: wanted.rows, hold: false,
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),
5231
5598
  });
5232
5599
  }
5233
- if (changed)
5234
- this.announceGeometry(session.id, session);
5235
- else if (handedOver)
5236
- this.announceGeometry(session.id, session, { resync: false });
5237
- else if (take === true)
5238
- ws.send(JSON.stringify(this.geometryFrame(session, ws)));
5239
- return;
5240
- }
5241
- try {
5242
- const applied = await session.resizeIfCurrent(wanted.cols, wanted.rows,
5243
- // A viewport that left while its take waited in the queue made
5244
- // no lasting choice: skip it so the pending wider restore runs.
5245
- () => !session.geometryHeld && !session.exited && ws.readyState === ws.OPEN &&
5246
- (acceptOffer !== true || this.gridOfferedTo(session.id, ws)) &&
5247
- (this.sessionSockets.get(session.id)?.has(ws) ?? false), (changed) => {
5248
- const handedOver = this.geometryController.get(session.id) !== ws;
5249
- // The controller change and epoch belong to the same queued
5250
- // act as the resize, before a queued wider restore can run.
5251
- this.geometryController.set(session.id, ws);
5252
- this.dashboardTransferable.delete(session.id);
5253
- this.geometryEpoch.set(session.id, (this.geometryEpoch.get(session.id) ?? 0) + 1);
5254
- if (credential.kind === 'dashboard') {
5255
- this.dashboardGeometryOwner.set(session.id, ws.protocol);
5256
- this.dashboardCredentialOwner.set(session.id, credential.dashboardToken);
5257
- }
5258
- else {
5259
- this.dashboardGeometryOwner.delete(session.id);
5260
- this.dashboardCredentialOwner.delete(session.id);
5261
- }
5262
- if (changed) {
5263
- this.audit.record(actor, 'resize', session.id, {
5264
- cols: wanted.cols, rows: wanted.rows, hold: false,
5265
- });
5266
- this.announceGeometry(session.id, session);
5267
- }
5268
- else if (handedOver)
5269
- this.announceGeometry(session.id, session, { resync: false });
5270
- else if (take === true)
5271
- ws.send(JSON.stringify(this.geometryFrame(session, ws)));
5272
- }, true);
5273
- if (!applied && ws.readyState === ws.OPEN)
5274
- ws.send(JSON.stringify(this.geometryFrame(session, ws)));
5275
- }
5276
- catch (error) {
5277
- // The program has ended (a viewer fitting its window while
5278
- // looking at a dying session), and the session's exit follows
5279
- // within about a second, with an `exited` frame to every
5280
- // watcher. Nothing moved and nobody takes the grid, so nothing
5281
- // is said: an answer would have a driving page whose window
5282
- // does not fit the grid propose again at once, over and over
5283
- // until the exit arrives.
5284
- if (error instanceof SessionProgramEndedError)
5285
- return;
5286
- // Any other failure is logged rather than left to escape: an
5287
- // exception from a WS handler would take the whole daemon down
5288
- // via the uncaughtException path.
5289
- this.logger.warn('viewer resize failed', {
5290
- id: session.id,
5291
- error: String(error),
5292
- });
5293
5600
  }
5601
+ return;
5294
5602
  }
5295
- return;
5296
5603
  }
5297
- }
5298
- catch {
5299
- // Not JSON: bytes for the program, a person's keystrokes or the
5300
- // viewer's terminal answering the program. Straight into the PTY
5301
- // either way: shared typing is the point of the tool.
5302
- }
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
+ }
5303
5609
  if (readOnly) {
5304
5610
  // A watch-only credential. Dropped silently and on the daemon's side:
5305
5611
  // the page has already been told it is read-only and disables its own
@@ -5339,8 +5645,12 @@ export class Daemon {
5339
5645
  // sequences, so this is not always one keystroke.) .catch keeps the exit
5340
5646
  // race, the session dying mid-write, from escaping as an unhandled
5341
5647
  // rejection.
5342
- const report = terminalReportKind(text);
5343
- 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) => {
5344
5654
  this.logger.warn('viewer input failed', {
5345
5655
  id: session.id,
5346
5656
  error: String(error),
@@ -5354,21 +5664,21 @@ export class Daemon {
5354
5664
  if (report !== null) {
5355
5665
  this.audit.record(actor, 'report', session.id, {
5356
5666
  kind: report,
5357
- chars: text.length,
5358
- ...(this.audit.captureContent ? { data: text } : {}),
5667
+ chars: bytes?.length ?? text.length,
5668
+ ...(this.audit.captureContent ? { data: bytes === null ? text : bytes.toString('latin1') } : {}),
5359
5669
  });
5360
5670
  return;
5361
5671
  }
5362
5672
  this.audit.record(actor, 'input', session.id, {
5363
- chars: text.length,
5673
+ chars: bytes?.length ?? text.length,
5364
5674
  });
5365
5675
  this.broadcastControl(session.id, { type: 'input-source', source: 'human' });
5366
5676
  };
5367
- ws.on('message', (message) => {
5677
+ ws.on('message', (message, isBinary) => {
5368
5678
  if (actor === 'dashboard' && ws.readyState !== ws.OPEN)
5369
5679
  return;
5370
5680
  this.callerContext.run(options.callerSession, () => {
5371
- void onViewerMessage(message).catch((error) => {
5681
+ void onViewerMessage(message, isBinary).catch((error) => {
5372
5682
  this.logger.warn('viewer message failed', { id: session.id, error: String(error) });
5373
5683
  });
5374
5684
  });
@@ -5389,6 +5699,7 @@ export class Daemon {
5389
5699
  // does not inherit it.
5390
5700
  if (this.geometryController.get(session.id) === ws) {
5391
5701
  this.geometryController.delete(session.id);
5702
+ this.recordGeometryChoice(session.id);
5392
5703
  this.announceGeometry(session.id, session, { resync: false });
5393
5704
  }
5394
5705
  this.lastActivity = Date.now();