shellpuppet 0.4.1 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (87) hide show
  1. package/README.md +26 -4
  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/codex/draft.js +13 -6
  7. package/dist/agents/codex/draft.js.map +1 -1
  8. package/dist/agents/codex/index.js +1 -1
  9. package/dist/agents/codex/index.js.map +1 -1
  10. package/dist/agents/codex/nudge.js +7 -1
  11. package/dist/agents/codex/nudge.js.map +1 -1
  12. package/dist/agents/grok/index.js +1 -1
  13. package/dist/agents/grok/index.js.map +1 -1
  14. package/dist/agents/grok/nudge.js +13 -5
  15. package/dist/agents/grok/nudge.js.map +1 -1
  16. package/dist/agents/hermes/frame.js +4 -4
  17. package/dist/agents/hermes/frame.js.map +1 -1
  18. package/dist/agents/hermes/index.js +1 -1
  19. package/dist/agents/hermes/index.js.map +1 -1
  20. package/dist/agents/mimo/index.js +1 -1
  21. package/dist/agents/mimo/index.js.map +1 -1
  22. package/dist/agents/muse/index.js +1 -1
  23. package/dist/agents/muse/index.js.map +1 -1
  24. package/dist/agents/muse/nudge.js +8 -3
  25. package/dist/agents/muse/nudge.js.map +1 -1
  26. package/dist/agents/nudgeReading.d.ts +2 -0
  27. package/dist/agents/nudgeReading.js +3 -3
  28. package/dist/agents/nudgeReading.js.map +1 -1
  29. package/dist/agents/opencode/index.js +1 -1
  30. package/dist/agents/opencode/index.js.map +1 -1
  31. package/dist/agents/qoder/index.js +1 -1
  32. package/dist/agents/qoder/index.js.map +1 -1
  33. package/dist/agents/types.d.ts +4 -0
  34. package/dist/cli/index.js +275 -16
  35. package/dist/cli/index.js.map +1 -1
  36. package/dist/client/http.d.ts +8 -0
  37. package/dist/client/http.js +15 -1
  38. package/dist/client/http.js.map +1 -1
  39. package/dist/client/input.d.ts +24 -0
  40. package/dist/client/input.js +29 -0
  41. package/dist/client/input.js.map +1 -0
  42. package/dist/core/mailbox.d.ts +18 -6
  43. package/dist/core/mailbox.js +35 -10
  44. package/dist/core/mailbox.js.map +1 -1
  45. package/dist/core/manager.d.ts +1 -2
  46. package/dist/core/manager.js +35 -16
  47. package/dist/core/manager.js.map +1 -1
  48. package/dist/core/session.d.ts +29 -0
  49. package/dist/core/session.js +65 -11
  50. package/dist/core/session.js.map +1 -1
  51. package/dist/core/types.d.ts +2 -0
  52. package/dist/core/types.js +2 -0
  53. package/dist/core/types.js.map +1 -1
  54. package/dist/core/windowsPtyStart.d.ts +2 -0
  55. package/dist/core/windowsPtyStart.js +6 -0
  56. package/dist/core/windowsPtyStart.js.map +1 -1
  57. package/dist/daemon/audit.d.ts +7 -7
  58. package/dist/daemon/audit.js +19 -17
  59. package/dist/daemon/audit.js.map +1 -1
  60. package/dist/daemon/config.d.ts +1 -1
  61. package/dist/daemon/config.js +1 -1
  62. package/dist/daemon/index.js +1 -0
  63. package/dist/daemon/index.js.map +1 -1
  64. package/dist/daemon/launchProfiles.d.ts +6 -0
  65. package/dist/daemon/launchProfiles.js +21 -4
  66. package/dist/daemon/launchProfiles.js.map +1 -1
  67. package/dist/daemon/liveness.d.ts +11 -0
  68. package/dist/daemon/liveness.js +39 -0
  69. package/dist/daemon/liveness.js.map +1 -1
  70. package/dist/daemon/schedules.d.ts +1 -1
  71. package/dist/daemon/schedules.js +8 -3
  72. package/dist/daemon/schedules.js.map +1 -1
  73. package/dist/daemon/server.d.ts +17 -0
  74. package/dist/daemon/server.js +411 -143
  75. package/dist/daemon/server.js.map +1 -1
  76. package/dist/daemon/sessionFeed.d.ts +1 -1
  77. package/dist/daemon/sessionFeed.js +3 -1
  78. package/dist/daemon/sessionFeed.js.map +1 -1
  79. package/dist/mcp/tools.js +55 -35
  80. package/dist/mcp/tools.js.map +1 -1
  81. package/dist/viewer/dashboard.css +21 -8
  82. package/dist/viewer/dashboard.js +129 -34
  83. package/dist/viewer/index.html +1 -0
  84. package/dist/viewer/pane.js +267 -20
  85. package/dist/viewer/viewer.css +1 -1
  86. package/dist/viewer/viewer.js +1 -0
  87. package/package.json +1 -1
@@ -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, } 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';
@@ -31,7 +31,7 @@ import { detectPrompt } from '../core/promptDetector.js';
31
31
  import { markFilteredSelectedOption } from '../core/selection.js';
32
32
  import { WaitConditionError } from '../core/waiter.js';
33
33
  import { agentNames, hideReasoning, latestResult, programName, signatureForSession } from '../core/reasoning.js';
34
- import { validResumeId, DEFAULT_WAIT_TIMEOUT_MS, ENV_NAME_PATTERN, MAX_WAIT_TIMEOUT_MS, WAIT_POLL_INTERVAL_MS, howSessionEnded } from '../core/types.js';
34
+ import { validResumeId, DEFAULT_WAIT_TIMEOUT_MS, ENV_NAME_PATTERN, MAX_BODY_BYTES, MAX_WAIT_TIMEOUT_MS, WAIT_POLL_INTERVAL_MS, howSessionEnded } from '../core/types.js';
35
35
  import { DASHBOARD_COOKIE, TokenStore, VIEWER_COOKIE, VIEWER_GRANT_TTL_MS, bearerToken, cookieValues, dashboardCookie, dashboardProofFromProtocol, tokensEqual, viewerCookie, } from './auth.js';
36
36
  import { NULL_AUDITOR } from './audit.js';
37
37
  import { findBrowser, launchDashboard, launchViewer } from './viewerLauncher.js';
@@ -45,7 +45,7 @@ import { terminalReportKind } 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. */
@@ -64,7 +64,6 @@ const STATE_PUBLISH_CHECK_MS = 10_000;
64
64
  * enough that a busy day of short-lived sessions does not ratchet memory.
65
65
  */
66
66
  const EXITED_SESSION_GRACE_MS = 15 * 60_000;
67
- const MAX_BODY_BYTES = 1_000_000;
68
67
  /**
69
68
  * Prompt-stall detection: how often live screens are scanned for a
70
69
  * permission prompt, and how long the SAME prompt must persist before an
@@ -204,6 +203,10 @@ const DASHBOARD_FONT_META = '<meta name="sp-dashboard-font-size" content="">';
204
203
  export { AlreadyRunningError };
205
204
  class HomeOwnershipError extends Error {
206
205
  }
206
+ class ClaimAuditError extends Error {
207
+ }
208
+ const CLAIM_RECOVERY_HINT = 'Claim the name again, using --replace if it is still held.';
209
+ const invalidClaim = { code: 'invalid-claim', hint: CLAIM_RECOVERY_HINT };
207
210
  /** The scheme and authority that open an absolute-form request target (`http://user@host:port`). */
208
211
  const SCHEME_AND_AUTHORITY = /^[a-z][a-z0-9+.-]*:\/\/[^/]*/i;
209
212
  /**
@@ -497,6 +500,12 @@ export class Daemon {
497
500
  dashboardSocketCredential = new WeakMap();
498
501
  /** External geometry acts invalidate a temporary wider read's restoration. */
499
502
  geometryEpoch = new Map();
503
+ /** One daemon order for layout notices and deliberate grid choices. */
504
+ geometryOrder = new Map();
505
+ choiceRevision = new Map();
506
+ controllerChoiceRevision = new Map();
507
+ explicitResizeRevision = new Map();
508
+ dashboardLayouts = new WeakMap();
500
509
  widerReads = new Map();
501
510
  /** Subscribers to the daemon-wide event stream (`/events`). */
502
511
  eventSockets = new Map();
@@ -553,12 +562,14 @@ export class Daemon {
553
562
  sessionEnv;
554
563
  /** The profiles the dashboard may name, and the entries that did not load. */
555
564
  launchProfiles;
565
+ launchesPerMinute;
556
566
  daemonEnv;
557
567
  cliPath;
558
568
  /** The global policy, kept here so a launch can report it before creating. */
559
569
  compiledPolicy;
560
570
  /** Accepted launch times, for the sliding sixty-second cap. */
561
571
  launchTimes = [];
572
+ pendingProfileStarts = new Set();
562
573
  claimTimes = [];
563
574
  claimCount = 0;
564
575
  folderPickerBusy = false;
@@ -581,6 +592,7 @@ export class Daemon {
581
592
  const auditor = options.audit ?? NULL_AUDITOR;
582
593
  this.audit = {
583
594
  captureContent: auditor.captureContent,
595
+ recordRequired: auditor.recordRequired?.bind(auditor),
584
596
  record: (actor, action, session, meta) => auditor.record(actor, action, session, meta,
585
597
  // A session's timers and listeners can inherit the request that created
586
598
  // them. Daemon observations must not inherit that caller's identity.
@@ -588,6 +600,7 @@ export class Daemon {
588
600
  };
589
601
  this.sessionEnv = options.sessionEnv ?? DEFAULT_SESSION_ENV;
590
602
  this.launchProfiles = options.launchProfiles ?? { profiles: [], problems: [] };
603
+ this.launchesPerMinute = this.launchProfiles.launchesPerMinute ?? DEFAULT_LAUNCHES_PER_MINUTE;
591
604
  this.daemonEnv = options.daemonEnv ?? process.env;
592
605
  this.cliPath = fileURLToPath(new URL('../../dist/cli/index.js', import.meta.url));
593
606
  this.compiledPolicy = compilePolicy(options.policy);
@@ -858,7 +871,14 @@ export class Daemon {
858
871
  });
859
872
  }, this.options.promptScanIntervalMs ?? PROMPT_SCAN_INTERVAL_MS);
860
873
  this.promptScanTimer.unref();
861
- this.stopScheduleWatch = watchSchedules(home, this.schedules, this.logger);
874
+ this.stopScheduleWatch = watchSchedules(home, this.schedules, this.logger, (raw, initial) => {
875
+ if (initial && raw['launcher'] === undefined)
876
+ return;
877
+ const allowance = parseLaunchesPerMinute(raw['launcher']);
878
+ this.launchesPerMinute = allowance.value;
879
+ if (!initial && allowance.problem !== undefined)
880
+ this.logger.warn('CONFIG PROBLEM', { problem: allowance.problem });
881
+ });
862
882
  this.promptScheduler.start();
863
883
  this.logger.info('daemon started', {
864
884
  port: this.portValue,
@@ -1069,11 +1089,22 @@ export class Daemon {
1069
1089
  for (const read of this.widerReads.values())
1070
1090
  read.abort.abort();
1071
1091
  const readsDone = Promise.allSettled([...this.widerReads.values()].map((read) => read.done));
1092
+ const widerDeadline = Date.now() + 250;
1072
1093
  await this.shutdownRecords;
1073
1094
  // A free port lets a successor retire the ownership marker. Keep it
1074
1095
  // bound through publication, then close without waiting for PTY teardown.
1075
1096
  const listenerClosed = this.closeServerOnly();
1076
- await readsDone;
1097
+ let widerTimer;
1098
+ const widerOutcome = await Promise.race([
1099
+ readsDone.then(() => 'settled'),
1100
+ new Promise((resolve) => {
1101
+ widerTimer = setTimeout(() => resolve('timeout'), Math.max(0, widerDeadline - Date.now()));
1102
+ }),
1103
+ ]);
1104
+ if (widerTimer !== undefined)
1105
+ clearTimeout(widerTimer);
1106
+ if (widerOutcome === 'timeout')
1107
+ this.logger.warn('wider reads exceeded shutdown restoration budget');
1077
1108
  for (const socket of this.sockets) {
1078
1109
  try {
1079
1110
  socket.close();
@@ -1968,16 +1999,21 @@ export class Daemon {
1968
1999
  json(res, 503, { error: 'The daemon is stopping.' });
1969
2000
  return;
1970
2001
  }
1971
- if (launcher && this.grantedLauncher(req)?.id !== launcher.id) {
1972
- json(res, 403, { error: 'Session launch permission required.' });
1973
- return;
2002
+ if (launcher) {
2003
+ const current = this.grantedLauncher(req, res);
2004
+ if (!current)
2005
+ return;
2006
+ if (current.id !== launcher.id) {
2007
+ json(res, 403, { error: 'Session launch permission required.' });
2008
+ return;
2009
+ }
1974
2010
  }
1975
2011
  const now = this.now();
1976
2012
  this.pruneLaunchTimes(now);
1977
- if (this.launchTimes.length >= 8) {
2013
+ if (this.launchTimes.length + this.pendingProfileStarts.size >= this.launchesPerMinute) {
1978
2014
  this.auditDashboardRefusal(req, 'rate', launcher?.name);
1979
2015
  json(res, 429, {
1980
- error: 'Dashboard launch rate reached (8 in 60 seconds). Wait before starting another profile.',
2016
+ error: `Dashboard launch rate reached (${String(this.launchesPerMinute)} in 60 seconds). Wait before starting another profile.`,
1981
2017
  });
1982
2018
  return;
1983
2019
  }
@@ -2027,18 +2063,20 @@ export class Daemon {
2027
2063
  json(res, 500, { error: `Failed to start session: ${String(error)}` });
2028
2064
  return;
2029
2065
  }
2030
- // Counted the moment the launch is accepted, before the start contract's
2031
- // wait: the rate check above and this record must sit in the same
2032
- // synchronous stretch, or twelve launches fired together would all pass
2033
- // the check before any of them was counted.
2034
- this.launchTimes.push(now);
2035
- // The same start contract as `POST /sessions`: the dashboard's pane is a
2036
- // session only once its program exists, and a start that ends before any
2037
- // program did fails as 1.1.0's spawn did, leaving nothing in the grid.
2038
- const startedSession = await this.programStarted(session, options, res, 'dashboard session start failed');
2039
- if (startedSession === null)
2040
- return;
2041
- session = startedSession;
2066
+ // Reserve before yielding. Only a confirmed program starts its rolling minute.
2067
+ const reserved = session;
2068
+ this.pendingProfileStarts.add(reserved);
2069
+ const releaseReservation = () => { this.pendingProfileStarts.delete(reserved); };
2070
+ try {
2071
+ const started = await this.programStarted(session, options, res, 'dashboard session start failed', releaseReservation);
2072
+ if (started === null)
2073
+ return;
2074
+ session = started;
2075
+ this.launchTimes.push(this.now());
2076
+ }
2077
+ finally {
2078
+ releaseReservation();
2079
+ }
2042
2080
  // A launch is an API call: the idle timer counts from it, so a session
2043
2081
  // that has just started is not reaped sooner than `idleMinutes` allows.
2044
2082
  this.lastActivity = Date.now();
@@ -2300,7 +2338,7 @@ export class Daemon {
2300
2338
  // Unauthenticated by design (§4.1): clients must be able to poll before
2301
2339
  // the token file settles. The instance id is an identity, not a secret.
2302
2340
  if (req.method === 'GET' && url.pathname === '/health') {
2303
- json(res, 200, { ok: true, version: this.version, pid: process.pid, instanceId: this.instanceId });
2341
+ json(res, 200, { ok: true, version: this.version, pid: process.pid, instanceId: this.instanceId, inputSubmitMode: 1 });
2304
2342
  return;
2305
2343
  }
2306
2344
  // The viewer page itself is served without auth, and must stay that way:
@@ -2520,7 +2558,7 @@ export class Daemon {
2520
2558
  });
2521
2559
  writePrivateRecord(path.join(this.options.home, 'previous-sessions.json'), { version: 1, outgoingInstanceId: this.instanceId, sessions });
2522
2560
  }
2523
- saveLauncherClaims(excludeId) {
2561
+ saveLauncherClaims(excludeId, next, beforePublish) {
2524
2562
  const grants = this.launchProfiles.sessionLaunch ?? [];
2525
2563
  const file = path.join(this.options.home, 'launcher-claims.json');
2526
2564
  if (!this.claimsRestored)
@@ -2528,25 +2566,57 @@ export class Daemon {
2528
2566
  if (grants.length || fs.existsSync(file)) {
2529
2567
  let discovery = this.requireHomeOwner();
2530
2568
  const claims = this.mailbox.savedClaims(grants).filter(claim => claim.id !== excludeId);
2531
- writePrivateRecord(file, claims, () => { discovery = this.requireHomeOwner(); });
2569
+ if (next)
2570
+ claims.push(next);
2571
+ writePrivateRecord(file, claims, () => {
2572
+ beforePublish?.();
2573
+ discovery = this.requireHomeOwner();
2574
+ });
2532
2575
  if (!this.stopping && (discovery.kind === 'missing' || discovery.kind === 'not-a-record')) {
2533
2576
  void this.keepStatePublished();
2534
2577
  }
2535
2578
  }
2536
2579
  }
2537
- grantedLauncher(req) {
2580
+ auditReplacement(actor, oldClaimId, next) {
2581
+ const failure = 'Could not write the audit record for the claim replacement.';
2582
+ if (!this.audit.recordRequired)
2583
+ throw new ClaimAuditError(failure);
2584
+ try {
2585
+ this.audit.recordRequired(actor, 'msg-replace', next.id, {
2586
+ name: next.name, oldClaimId, newClaimId: next.id, member: this.isReservedClaimName(next.name),
2587
+ });
2588
+ }
2589
+ catch {
2590
+ throw new ClaimAuditError(failure);
2591
+ }
2592
+ }
2593
+ presentedClaim(req, allowMarked = true) {
2594
+ const id = req.headers['x-shellpuppet-claim'];
2595
+ const secret = req.headers['x-shellpuppet-claim-secret'];
2596
+ if (id === undefined && secret === undefined)
2597
+ return {};
2598
+ const marked = req.headers['x-shellpuppet-inside-session'] === '1';
2599
+ if ((!marked || allowMarked) && typeof id === 'string' && typeof secret === 'string' &&
2600
+ this.mailbox.verifyClaim(id, secret, !marked))
2601
+ return { id };
2602
+ return { refused: true };
2603
+ }
2604
+ grantedLauncher(req, res) {
2538
2605
  this.lapseIdleClaims();
2539
2606
  let id = this.callerContext.getStore();
2540
2607
  if (id === undefined) {
2541
- const claim = headerOne(req, 'x-shellpuppet-claim');
2542
- const secret = headerOne(req, 'x-shellpuppet-claim-secret');
2543
- if (req.headers['x-shellpuppet-inside-session'] === '1' || !claim || !secret ||
2544
- !this.mailbox.verifyClaim(claim, secret))
2608
+ const claim = this.presentedClaim(req, false);
2609
+ if (claim.refused) {
2610
+ json(res, 403, { error: 'Session launch permission required.', ...invalidClaim });
2545
2611
  return undefined;
2546
- id = claim;
2612
+ }
2613
+ id = claim.id;
2547
2614
  }
2548
- const caller = this.mailbox.participant(id);
2549
- return caller && this.launchProfiles.sessionLaunch?.includes(caller.name) ? caller : undefined;
2615
+ const caller = id === undefined ? undefined : this.mailbox.participant(id);
2616
+ if (caller && this.launchProfiles.sessionLaunch?.includes(caller.name))
2617
+ return caller;
2618
+ json(res, 403, { error: 'Session launch permission required.' });
2619
+ return undefined;
2550
2620
  }
2551
2621
  messageAudit(action, entry, actor = 'daemon') {
2552
2622
  this.audit.record(actor, action, entry.from.id, {
@@ -2567,6 +2637,9 @@ export class Daemon {
2567
2637
  }
2568
2638
  }
2569
2639
  this.mailbox.end(id);
2640
+ this.closeParticipantSockets(id);
2641
+ }
2642
+ closeParticipantSockets(id) {
2570
2643
  for (const [ws, participant] of this.eventSockets) {
2571
2644
  if (participant === id)
2572
2645
  ws.close();
@@ -2807,18 +2880,14 @@ export class Daemon {
2807
2880
  return;
2808
2881
  }
2809
2882
  this.lapseIdleClaims();
2810
- const claimId = req.headers['x-shellpuppet-claim'];
2811
- const claimSecret = req.headers['x-shellpuppet-claim-secret'];
2812
- const claimPresented = claimId !== undefined || claimSecret !== undefined;
2813
- const claimValid = typeof claimId === 'string' && typeof claimSecret === 'string' &&
2814
- this.mailbox.verifyClaim(claimId, claimSecret);
2815
2883
  const route = segments[1];
2816
2884
  const creatingClaim = req.method === 'POST' && route === 'claims' && segments.length === 2;
2817
- if (claimPresented && !claimValid && !creatingClaim) {
2818
- json(res, 403, { error: 'Messaging claim was not recognised.' });
2885
+ const { id: claimId, refused } = this.presentedClaim(req);
2886
+ if (refused && !creatingClaim) {
2887
+ json(res, 403, { error: 'Messaging claim was not recognised.', ...invalidClaim });
2819
2888
  return;
2820
2889
  }
2821
- const caller = this.callerContext.getStore() ?? (claimValid ? claimId : undefined);
2890
+ const caller = this.callerContext.getStore() ?? claimId;
2822
2891
  if (creatingClaim) {
2823
2892
  // Each refusal says only what the daemon knows: a verified session, a valid claim, a mark on the request.
2824
2893
  if (this.callerContext.getStore() !== undefined) {
@@ -2826,9 +2895,9 @@ export class Daemon {
2826
2895
  return;
2827
2896
  }
2828
2897
  const marked = req.headers['x-shellpuppet-inside-session'] === '1';
2829
- if (claimValid || marked) {
2898
+ if (claimId !== undefined || marked) {
2830
2899
  const reasons = [];
2831
- if (claimValid) {
2900
+ if (claimId !== undefined) {
2832
2901
  reasons.push('This client already holds a messaging claim: release it first (msg release), or stop ' +
2833
2902
  'presenting it (SHELLPUPPET_CLAIM), to make another.');
2834
2903
  }
@@ -2842,10 +2911,18 @@ export class Daemon {
2842
2911
  return;
2843
2912
  }
2844
2913
  const body = await readBody(req);
2845
- if (typeof body['name'] !== 'string') {
2914
+ const name = body['name'];
2915
+ const replace = body['replace'] === true;
2916
+ if (typeof name !== 'string') {
2846
2917
  json(res, 400, { error: 'A valid name is required.' });
2847
2918
  return;
2848
2919
  }
2920
+ if (body['replace'] !== undefined && typeof body['replace'] !== 'boolean') {
2921
+ json(res, 400, { error: 'replace must be a boolean.' });
2922
+ return;
2923
+ }
2924
+ if (replace)
2925
+ this.lapseIdleClaims();
2849
2926
  const now = this.now();
2850
2927
  while (this.claimTimes.length > 0 && (this.claimTimes[0] ?? now) <= now - 60_000)
2851
2928
  this.claimTimes.shift();
@@ -2857,35 +2934,38 @@ export class Daemon {
2857
2934
  json(res, 429, { error: 'Messaging claim rate reached (8 in 60 seconds).' });
2858
2935
  return;
2859
2936
  }
2860
- const claim = this.mailbox.claim(body['name']);
2861
- this.claimTimes.push(now);
2862
- this.claimCount++;
2863
- if (this.launchProfiles.sessionLaunch?.includes(body['name'])) {
2864
- try {
2865
- this.saveLauncherClaims();
2866
- }
2867
- catch (error) {
2868
- this.mailbox.release(claim.claimId);
2869
- this.claimCount--;
2870
- throw error;
2871
- }
2872
- }
2873
- this.audit.record(actor, 'msg-claim', claim.claimId, {
2874
- fromId: claim.claimId, fromName: body['name'], toId: null, toName: null,
2875
- messageId: null, length: 0, member: this.isReservedClaimName(body['name']),
2937
+ const { claimId: newId, secret, previousId } = this.mailbox.claim(name, {
2938
+ replace,
2939
+ beforeCommit: (next, oldId) => {
2940
+ this.claimTimes.push(now);
2941
+ const audit = oldId === undefined ? undefined : () => this.auditReplacement(actor, oldId, next);
2942
+ if (this.launchProfiles.sessionLaunch?.includes(name))
2943
+ this.saveLauncherClaims(oldId, next, audit);
2944
+ else
2945
+ audit?.();
2946
+ },
2876
2947
  });
2877
- json(res, 201, claim);
2948
+ if (previousId !== undefined) {
2949
+ this.closeParticipantSockets(previousId);
2950
+ }
2951
+ else {
2952
+ this.claimCount++;
2953
+ this.audit.record(actor, 'msg-claim', newId, {
2954
+ fromId: newId, fromName: name, toId: null, toName: null,
2955
+ messageId: null, length: 0, member: this.isReservedClaimName(name),
2956
+ });
2957
+ }
2958
+ json(res, 201, { claimId: newId, secret });
2878
2959
  return;
2879
2960
  }
2880
2961
  if (caller === undefined) {
2881
2962
  json(res, 403, { error: 'Not a messaging participant.' });
2882
2963
  return;
2883
2964
  }
2884
- if (claimValid)
2885
- this.mailbox.touchClaim(claimId);
2886
2965
  if (req.method === 'DELETE' && route === 'claims' && segments.length === 3) {
2887
- if (!claimValid || claimId !== segments[2]) {
2888
- json(res, 403, { error: 'The matching claim is required.' });
2966
+ if (claimId === undefined || claimId !== segments[2]) {
2967
+ json(res, 403, { error: 'The matching claim is required.',
2968
+ ...(claimId === undefined ? {} : { hint: CLAIM_RECOVERY_HINT }) });
2889
2969
  return;
2890
2970
  }
2891
2971
  const name = this.mailbox.participant(claimId)?.name;
@@ -2959,7 +3039,7 @@ export class Daemon {
2959
3039
  finally {
2960
3040
  res.off('close', onClose);
2961
3041
  }
2962
- if (claimValid)
3042
+ if (claimId !== undefined && req.headers['x-shellpuppet-inside-session'] !== '1')
2963
3043
  this.mailbox.touchClaim(claimId);
2964
3044
  return;
2965
3045
  }
@@ -2981,11 +3061,20 @@ export class Daemon {
2981
3061
  json(res, 200, { schedules: this.promptScheduler.list() });
2982
3062
  return;
2983
3063
  }
3064
+ if (url.pathname === '/daemon/stop-info' && req.method === 'GET') {
3065
+ res.setHeader('Cache-Control', 'no-store');
3066
+ json(res, 200, { completion: { version: 1,
3067
+ role: this.options.exitProcessOnStop === true ? 'standalone' : 'embedded',
3068
+ pid: process.pid, instanceId: this.instanceId } });
3069
+ return;
3070
+ }
2984
3071
  if (segments[0] === 'daemon' && segments[1] === 'shutdown' && req.method === 'POST') {
2985
3072
  const body = await readBody(req);
3073
+ const completion = { version: 1, role: this.options.exitProcessOnStop === true ? 'standalone' : 'embedded',
3074
+ pid: process.pid, instanceId: this.instanceId };
2986
3075
  if (this.stopping) {
2987
3076
  await this.shutdownRecords;
2988
- json(res, 200, { ok: true, stopping: true, warnings: this.shutdownWarnings });
3077
+ json(res, 200, { ok: true, stopping: true, warnings: this.shutdownWarnings, completion });
2989
3078
  return;
2990
3079
  }
2991
3080
  const force = asBoolean(body['force']) ?? false;
@@ -3000,7 +3089,7 @@ export class Daemon {
3000
3089
  const stopping = this.stop({ restart: body['restart'] === true });
3001
3090
  this.audit.record(actor, 'shutdown', undefined, { force, liveSessions: live });
3002
3091
  await this.shutdownRecords;
3003
- json(res, 200, { ok: true, stopping: true, warnings: this.shutdownWarnings });
3092
+ json(res, 200, { ok: true, stopping: true, warnings: this.shutdownWarnings, completion });
3004
3093
  void stopping.then(() => {
3005
3094
  this.options.onSelfStop?.('shutdown-request');
3006
3095
  });
@@ -3021,10 +3110,8 @@ export class Daemon {
3021
3110
  return;
3022
3111
  }
3023
3112
  if (url.pathname === '/launcher/previous' && req.method === 'GET') {
3024
- if (!this.grantedLauncher(req)) {
3025
- json(res, 403, { error: 'Session launch permission required.' });
3113
+ if (!this.grantedLauncher(req, res))
3026
3114
  return;
3027
- }
3028
3115
  const file = path.join(this.options.home, 'previous-sessions.json');
3029
3116
  try {
3030
3117
  // Older version 1 records used the generated session id as an explicit name.
@@ -3045,11 +3132,9 @@ export class Daemon {
3045
3132
  return;
3046
3133
  }
3047
3134
  if (url.pathname === '/launcher/launch' && req.method === 'POST') {
3048
- const caller = this.grantedLauncher(req);
3049
- if (!caller) {
3050
- json(res, 403, { error: 'Session launch permission required.' });
3135
+ const caller = this.grantedLauncher(req, res);
3136
+ if (!caller)
3051
3137
  return;
3052
- }
3053
3138
  if ((headerOne(req, 'content-type') ?? '').split(';')[0]?.trim().toLowerCase() !== 'application/json') {
3054
3139
  json(res, 415, { error: 'The launch body must be JSON.' });
3055
3140
  return;
@@ -3352,7 +3437,7 @@ export class Daemon {
3352
3437
  this.audit.record(actor, 'wider-read', id, { requested, original });
3353
3438
  try {
3354
3439
  if (target.cols !== original.cols || target.rows !== original.rows) {
3355
- await session.resize(target.cols, target.rows);
3440
+ await session.resize(target.cols, target.rows, { temporarySignal: abort.signal });
3356
3441
  announce();
3357
3442
  }
3358
3443
  const settled = await session.waitFor({ quiet: 250 }, {
@@ -3375,6 +3460,7 @@ export class Daemon {
3375
3460
  // Only a deliberate geometry act wins. A departing controller does
3376
3461
  // not choose a new size; keep the control state its departure left.
3377
3462
  const mayRestore = () => (this.geometryEpoch.get(id) ?? 0) === epoch &&
3463
+ this.manager.get(id) === session && !session.isKilled &&
3378
3464
  !session.geometryHeld && !session.exited &&
3379
3465
  session.cols === target.cols && session.rows === target.rows;
3380
3466
  restored = target.cols === original.cols && target.rows === original.rows
@@ -3399,6 +3485,9 @@ export class Daemon {
3399
3485
  const code = readError instanceof SessionProgramEndedError ? readError.exitCode : session.exitCode;
3400
3486
  json(res, 409, { error: endedRefusal(id, code, session.fault) });
3401
3487
  }
3488
+ else if (readError instanceof TemporaryResizeNotReadyError) {
3489
+ json(res, 409, { error: readError.message });
3490
+ }
3402
3491
  else if (readError !== undefined) {
3403
3492
  throw readError instanceof Error ? readError : new Error('Wider read failed with a non-Error value.');
3404
3493
  }
@@ -3431,6 +3520,17 @@ export class Daemon {
3431
3520
  return;
3432
3521
  }
3433
3522
  if (req.method === 'POST' && action === 'input') {
3523
+ const header = req.headers['x-shellpuppet-submit'];
3524
+ const submitMode = header === undefined ? undefined : header === 'auto' || header === 'on' || header === 'off' ? header : null;
3525
+ if (submitMode === null) {
3526
+ json(res, 400, { error: 'Invalid submit mode.' });
3527
+ return;
3528
+ }
3529
+ if (req.headers['x-shellpuppet-expected-instance'] !== undefined &&
3530
+ req.headers['x-shellpuppet-expected-instance'] !== this.instanceId) {
3531
+ json(res, 409, { error: 'The daemon changed after submit preflight.' });
3532
+ return;
3533
+ }
3434
3534
  const body = await readBody(req);
3435
3535
  const data = asString(body['data']);
3436
3536
  if (data === undefined) {
@@ -3450,9 +3550,12 @@ export class Daemon {
3450
3550
  // caller's request for a race in the session's lifetime. A session
3451
3551
  // whose input pipe has failed refuses the write too, and its error
3452
3552
  // says what to do.
3553
+ const submit = body['submit'] === true;
3453
3554
  let written;
3454
3555
  try {
3455
- written = await session.writeWithResult(data);
3556
+ written = submitMode === undefined
3557
+ ? await session.writeWithResult(data)
3558
+ : await session.writeWithResult(data, { submitMode });
3456
3559
  }
3457
3560
  catch (error) {
3458
3561
  json(res, 409, {
@@ -3462,12 +3565,13 @@ export class Daemon {
3462
3565
  });
3463
3566
  return;
3464
3567
  }
3465
- // §4.5: content NEVER logged by default, only the length. Keystrokes
3466
- // are where the secrets are.
3467
- this.audit.record(actor, 'input', id, {
3468
- chars: data.length,
3469
- ...(this.audit.captureContent ? { data } : {}),
3470
- });
3568
+ const reporting = submitMode === undefined ? submit ? submitOutcome(written) : undefined
3569
+ : submitMode === 'off' || (submitMode === 'auto' && !written.submitApplied)
3570
+ ? { outcome: 'not-requested' }
3571
+ : submitOutcome(written, true);
3572
+ 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 } : {}) });
3471
3575
  this.broadcastControl(id, { type: 'input-source', source: 'agent' });
3472
3576
  // §3.1: TUIs silently swallow input while loading or when a panel has
3473
3577
  // stolen focus. verify re-reads the screen and reports whether the
@@ -3476,7 +3580,8 @@ export class Daemon {
3476
3580
  if (asBoolean(body['verify']) === true) {
3477
3581
  json(res, 200, {
3478
3582
  ok: true,
3479
- bytes: data.length,
3583
+ bytes,
3584
+ ...reporting,
3480
3585
  verified: await this.verifyTyped(session, data, written.before),
3481
3586
  ...(written.submitted !== undefined ? { submitted: written.submitted } : {}),
3482
3587
  ...(written.submitRetried ? { submitRetried: true } : {}),
@@ -3484,7 +3589,8 @@ export class Daemon {
3484
3589
  });
3485
3590
  return;
3486
3591
  }
3487
- json(res, 200, { ok: true, bytes: data.length,
3592
+ json(res, 200, { ok: true, bytes,
3593
+ ...reporting,
3488
3594
  ...(written.submitted !== undefined ? { submitted: written.submitted } : {}),
3489
3595
  ...(written.submitRetried ? { submitRetried: true } : {}),
3490
3596
  ...(written.message !== undefined ? { message: written.message } : {}),
@@ -3727,12 +3833,13 @@ export class Daemon {
3727
3833
  await session.resize(cols, rows, { hold, onApplied: () => {
3728
3834
  this.audit.record(actor, 'resize', id, { cols, rows, hold });
3729
3835
  this.geometryEpoch.set(id, (this.geometryEpoch.get(id) ?? 0) + 1);
3836
+ this.explicitResizeRevision.set(id, this.recordGeometryChoice(id));
3730
3837
  // An API resize takes the grid away from whichever viewport had it.
3731
3838
  this.geometryController.delete(id);
3732
3839
  this.dashboardGeometryOwner.delete(id);
3733
3840
  this.dashboardCredentialOwner.delete(id);
3734
3841
  this.dashboardTransferable.delete(id);
3735
- this.announceGeometry(id, session);
3842
+ this.announceGeometry(id, session, { clientResize: true });
3736
3843
  } });
3737
3844
  }
3738
3845
  catch (error) {
@@ -3751,6 +3858,10 @@ export class Daemon {
3751
3858
  json(res, 409, { error: error.message });
3752
3859
  return;
3753
3860
  }
3861
+ if (error instanceof ClaimAuditError) {
3862
+ json(res, 503, { error: error.message });
3863
+ return;
3864
+ }
3754
3865
  if (error instanceof MailboxError) {
3755
3866
  const status = error.code === 'unknown-name' ? 404 :
3756
3867
  error.code === 'not-allowed' || error.code === 'unknown-sender' ? 403 :
@@ -3767,7 +3878,7 @@ export class Daemon {
3767
3878
  'text-too-large': 'A message exceeds the 16 KiB limit.',
3768
3879
  'mailbox-full': 'The mailbox is full.',
3769
3880
  };
3770
- json(res, status, { error: messages[error.code] });
3881
+ json(res, status, { error: messages[error.code], hint: error.hint });
3771
3882
  return;
3772
3883
  }
3773
3884
  if (error instanceof WaitConditionError) {
@@ -4123,6 +4234,10 @@ export class Daemon {
4123
4234
  this.dashboardCredentialOwner.delete(id);
4124
4235
  this.dashboardTransferable.delete(id);
4125
4236
  this.geometryEpoch.delete(id);
4237
+ this.geometryOrder.delete(id);
4238
+ this.choiceRevision.delete(id);
4239
+ this.controllerChoiceRevision.delete(id);
4240
+ this.explicitResizeRevision.delete(id);
4126
4241
  }
4127
4242
  /** Whether a live viewport is currently driving this session's grid. */
4128
4243
  hasGeometryController(sessionId) {
@@ -4134,6 +4249,32 @@ export class Daemon {
4134
4249
  this.geometryController.delete(sessionId);
4135
4250
  return false;
4136
4251
  }
4252
+ nextGeometryOrder(id) {
4253
+ const order = (this.geometryOrder.get(id) ?? 0) + 1;
4254
+ this.geometryOrder.set(id, order);
4255
+ return order;
4256
+ }
4257
+ recordGeometryChoice(id, controller = false) {
4258
+ const revision = this.nextGeometryOrder(id);
4259
+ this.choiceRevision.set(id, revision);
4260
+ if (controller)
4261
+ this.controllerChoiceRevision.set(id, revision);
4262
+ return revision;
4263
+ }
4264
+ /** A document can reserve its grid only while its credential and proof are valid. */
4265
+ hasDashboardGeometryOwner(id) {
4266
+ const owner = this.dashboardGeometryOwner.get(id);
4267
+ if (owner === undefined)
4268
+ return false;
4269
+ if (this.tokens.verifyDashboardToken(this.dashboardCredentialOwner.get(id)) &&
4270
+ (this.dashboardTransferable.has(id) || this.tokens.acceptsDashboardProof(dashboardProofFromProtocol(owner))))
4271
+ return true;
4272
+ this.dashboardGeometryOwner.delete(id);
4273
+ this.dashboardCredentialOwner.delete(id);
4274
+ this.dashboardTransferable.delete(id);
4275
+ this.recordGeometryChoice(id);
4276
+ return false;
4277
+ }
4137
4278
  // ---------------------------------------------------- prompt-stall alerts
4138
4279
  /**
4139
4280
  * Wait, for a session just created, until its program exists (the start
@@ -4146,11 +4287,11 @@ export class Daemon {
4146
4287
  * is returned with the response already sent. Only the proven ConPTY worker
4147
4288
  * timeout gets one replacement attempt under the same id.
4148
4289
  */
4149
- async programStarted(session, options, res, logMessage) {
4290
+ async programStarted(session, options, res, logMessage, onTerminalFailure) {
4150
4291
  this.startingIds.add(session.id);
4151
4292
  try {
4152
4293
  if (this.manager.get(session.id) === session)
4153
- return await this.manager.finishStart(session, options);
4294
+ return await this.manager.finishStart(session, options, onTerminalFailure);
4154
4295
  // Test-only dashboard factories may supply a session outside the manager.
4155
4296
  if (await session.startedProgramPid() !== null)
4156
4297
  return session;
@@ -4213,10 +4354,10 @@ export class Daemon {
4213
4354
  },
4214
4355
  };
4215
4356
  }
4216
- updateFeedSession(id) {
4357
+ updateFeedSession(id, promptRestarted = false) {
4217
4358
  const session = this.manager.get(id);
4218
4359
  if (session !== undefined)
4219
- this.sessionFeed.update(this.summaryWithPrompt(session.summary()));
4360
+ this.sessionFeed.update(this.summaryWithPrompt(session.summary()), promptRestarted);
4220
4361
  }
4221
4362
  /** One transition drives the feed, audit, log and both notification channels. */
4222
4363
  watchStalls(session) {
@@ -4346,6 +4487,13 @@ export class Daemon {
4346
4487
  previous.prompt.selectedOption !== detected.selectedOption ||
4347
4488
  previous.prompt.options.length !== detected.options.length ||
4348
4489
  previous.prompt.options.some((option, index) => option !== detected.options[index]);
4490
+ const inputVersion = session.promptInputVersion();
4491
+ // Input alone does not mean this prompt was answered: a key may start
4492
+ // a repaint while the same decision remains on screen. A missed prompt
4493
+ // after input is evidence of a transition only when a prompt appears
4494
+ // again; the normal grace check still handles a lasting disappearance.
4495
+ const answered = previous !== undefined && previous.inputVersion !== inputVersion &&
4496
+ previous.missingSince !== null;
4349
4497
  if (previous !== undefined) {
4350
4498
  this.clearPromptGraceCheck(session.id);
4351
4499
  previous.missingSince = null;
@@ -4356,7 +4504,7 @@ export class Daemon {
4356
4504
  // then changes although the person still faces the same decision.
4357
4505
  // A stable signature also covers focus markers moving among options.
4358
4506
  const sameContent = previous !== undefined && !promptChanged;
4359
- if (previous === undefined || (previous.signature !== detected.signature && !sameContent)) {
4507
+ if (previous === undefined || answered || (previous.signature !== detected.signature && !sameContent)) {
4360
4508
  // A new (or changed) prompt starts its stall clock; it has not
4361
4509
  // alerted yet, so a prompt answered promptly stays silent.
4362
4510
  if (previous?.alerted === true) {
@@ -4379,13 +4527,13 @@ export class Daemon {
4379
4527
  }
4380
4528
  this.promptStates.set(session.id, {
4381
4529
  signature: detected.signature,
4530
+ inputVersion,
4382
4531
  since: this.now(),
4383
4532
  alerted: false,
4384
4533
  prompt: detected,
4385
4534
  missingSince: null,
4386
4535
  });
4387
- if (promptChanged || previous?.alerted === true)
4388
- this.updateFeedSession(session.id);
4536
+ this.updateFeedSession(session.id, previous !== undefined);
4389
4537
  continue;
4390
4538
  }
4391
4539
  previous.signature = detected.signature;
@@ -4467,8 +4615,9 @@ export class Daemon {
4467
4615
  // refusal never reaches. An error with no listener would be an uncaught
4468
4616
  // exception, on which the daemon shuts down with every session.
4469
4617
  socket.on('error', () => socket.destroy());
4470
- const reject = (code, reason) => {
4471
- socket.write(`HTTP/1.1 ${String(code)} ${reason}\r\nReferrer-Policy: no-referrer\r\nConnection: close\r\n\r\n`);
4618
+ const reject = (code, reason, hint) => {
4619
+ const headers = hint ? `X-ShellPuppet-Hint: ${hint}\r\n` : '';
4620
+ socket.write(`HTTP/1.1 ${String(code)} ${reason}\r\n${headers}Referrer-Policy: no-referrer\r\nConnection: close\r\n\r\n`);
4472
4621
  socket.destroy();
4473
4622
  };
4474
4623
  if (!this.hostAllowed(req.headers.host)) {
@@ -4532,18 +4681,16 @@ export class Daemon {
4532
4681
  reject(403, 'Forbidden');
4533
4682
  return;
4534
4683
  }
4535
- const claimId = req.headers['x-shellpuppet-claim'];
4536
- const claimSecret = req.headers['x-shellpuppet-claim-secret'];
4537
- const claimPresented = claimId !== undefined || claimSecret !== undefined;
4538
- if (claimPresented)
4684
+ if (req.headers['x-shellpuppet-claim'] !== undefined || req.headers['x-shellpuppet-claim-secret'] !== undefined) {
4539
4685
  this.lapseIdleClaims();
4540
- if (claimPresented && (typeof claimId !== 'string' || typeof claimSecret !== 'string' ||
4541
- !this.mailbox.verifyClaim(claimId, claimSecret))) {
4542
- reject(403, 'Forbidden');
4686
+ }
4687
+ const claim = this.presentedClaim(req);
4688
+ if (claim.refused) {
4689
+ reject(403, 'Forbidden', CLAIM_RECOVERY_HINT);
4543
4690
  return;
4544
4691
  }
4545
4692
  this.wss.handleUpgrade(req, socket, head, (ws) => {
4546
- this.callerContext.run(caller.session, () => this.attachEventSocket(ws, caller.session ?? (typeof claimId === 'string' ? claimId : undefined)));
4693
+ this.callerContext.run(caller.session, () => this.attachEventSocket(ws, caller.session ?? claim.id));
4547
4694
  });
4548
4695
  return;
4549
4696
  }
@@ -4865,7 +5012,11 @@ export class Daemon {
4865
5012
  announceGeometry(sessionId, session, options = {}) {
4866
5013
  for (const [ws, sync] of this.sessionSockets.get(sessionId) ?? []) {
4867
5014
  if (ws.readyState === ws.OPEN) {
4868
- ws.send(JSON.stringify(this.geometryFrame(session, ws)));
5015
+ ws.send(JSON.stringify({ ...this.geometryFrame(session, ws),
5016
+ ...(options.clientResize ? { clientResize: true,
5017
+ layoutFence: this.dashboardLayouts.get(ws)?.realId ?? 0 } : {}),
5018
+ ...(ws === this.geometryController.get(sessionId) && options.acceptedTakeId !== undefined
5019
+ ? { acceptedTakeId: options.acceptedTakeId } : {}) }));
4869
5020
  }
4870
5021
  if (options.resync !== false)
4871
5022
  sync.resync();
@@ -4880,8 +5031,13 @@ export class Daemon {
4880
5031
  }
4881
5032
  /** What one watcher is told about the grid, from its own point of view. */
4882
5033
  geometryFrame(session, ws) {
5034
+ const reserved = this.dashboardSocketCredential.has(ws) && this.hasDashboardGeometryOwner(session.id);
5035
+ const controlled = this.hasGeometryController(session.id);
4883
5036
  return {
4884
5037
  type: 'geometry',
5038
+ choiceRevision: this.choiceRevision.get(session.id) ?? 0,
5039
+ controllerChoiceRevision: this.controllerChoiceRevision.get(session.id) ?? 0,
5040
+ explicitResizeRevision: this.explicitResizeRevision.get(session.id) ?? 0,
4885
5041
  ...(this.widerReads.get(session.id)?.isTemporary() ? { temporary: true } : {}),
4886
5042
  cols: session.cols,
4887
5043
  rows: session.rows,
@@ -4891,8 +5047,7 @@ export class Daemon {
4891
5047
  max: { cols: MAX_VIEWPORT_COLS, rows: MAX_VIEWPORT_ROWS },
4892
5048
  // An adopting dashboard must distinguish a fresh session from one
4893
5049
  // already taken in another window before scheduling its initial fit.
4894
- owned: this.hasGeometryController(session.id) ||
4895
- (this.dashboardSocketCredential.has(ws) && this.dashboardGeometryOwner.has(session.id)),
5050
+ owned: controlled || reserved,
4896
5051
  // Only a controller's explicit assignment handover offers its grid to
4897
5052
  // another dashboard pane while the old socket is closing.
4898
5053
  dashboardTransferable: this.gridOfferedTo(session.id, ws),
@@ -5004,12 +5159,13 @@ export class Daemon {
5004
5159
  if (credential.kind === 'dashboard' &&
5005
5160
  // The returning document can restore its grid while a release to a
5006
5161
  // different assignment belongs to that recipient alone.
5007
- this.dashboardGeometryOwner.has(session.id) &&
5162
+ this.hasDashboardGeometryOwner(session.id) &&
5008
5163
  (!this.dashboardTransferable.has(session.id) || this.gridOfferedTo(session.id, ws)) &&
5009
5164
  tokensEqual(this.dashboardGeometryOwner.get(session.id), ws.protocol) &&
5010
5165
  !session.exited &&
5011
5166
  !this.hasGeometryController(session.id)) {
5012
5167
  this.geometryController.set(session.id, ws);
5168
+ this.recordGeometryChoice(session.id, true);
5013
5169
  this.dashboardTransferable.delete(session.id);
5014
5170
  this.announceGeometry(session.id, session, { resync: false });
5015
5171
  }
@@ -5017,8 +5173,9 @@ export class Daemon {
5017
5173
  !readOnly &&
5018
5174
  !passive &&
5019
5175
  !this.hasGeometryController(session.id) &&
5020
- !this.dashboardGeometryOwner.has(session.id)) {
5176
+ !this.hasDashboardGeometryOwner(session.id)) {
5021
5177
  this.geometryController.set(session.id, ws);
5178
+ this.recordGeometryChoice(session.id, true);
5022
5179
  this.dashboardGeometryOwner.delete(session.id);
5023
5180
  this.dashboardCredentialOwner.delete(session.id);
5024
5181
  this.dashboardTransferable.delete(session.id);
@@ -5114,10 +5271,40 @@ export class Daemon {
5114
5271
  }
5115
5272
  return;
5116
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 });
5287
+ }
5288
+ }
5289
+ return;
5290
+ }
5117
5291
  if (typeof parsed === 'object' &&
5118
5292
  parsed !== null &&
5119
5293
  parsed.type === 'resize') {
5120
- const { cols, rows, take, acceptOffer } = parsed;
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
+ return;
5307
+ }
5121
5308
  // Fit, Enlarge, Focus and Restore are a resize that says `take`.
5122
5309
  // A passive socket's other resizes, including one a dashboard pane
5123
5310
  // sends because the window moved, are not that act: the grid stays,
@@ -5138,51 +5325,131 @@ export class Daemon {
5138
5325
  if (session.geometryHeld) {
5139
5326
  // Held against viewports. Answer with the real grid so the page
5140
5327
  // stops proposing one it will never be given.
5141
- ws.send(JSON.stringify(this.geometryFrame(session, ws)));
5328
+ if (autoTake)
5329
+ refuseAuto();
5330
+ else
5331
+ ws.send(JSON.stringify(this.geometryFrame(session, ws)));
5142
5332
  return;
5143
5333
  }
5144
5334
  const wanted = {
5145
5335
  cols: Math.min(cols, MAX_VIEWPORT_COLS),
5146
5336
  rows: Math.min(rows, MAX_VIEWPORT_ROWS),
5147
5337
  };
5338
+ if (autoTake) {
5339
+ try {
5340
+ let applied = false;
5341
+ let changedAtApply = false;
5342
+ let staleLayoutId = false;
5343
+ const shouldApply = () => {
5344
+ 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))
5367
+ return false;
5368
+ changedAtApply = wanted.cols !== session.cols || wanted.rows !== session.rows;
5369
+ return true;
5370
+ };
5371
+ const onApplied = () => {
5372
+ applied = true;
5373
+ const handedOver = this.geometryController.get(session.id) !== ws;
5374
+ 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
+ this.recordGeometryChoice(session.id, true);
5379
+ this.geometryEpoch.set(session.id, (this.geometryEpoch.get(session.id) ?? 0) + 1);
5380
+ if (changedAtApply)
5381
+ this.audit.record(actor, 'resize', session.id, {
5382
+ cols: wanted.cols, rows: wanted.rows, hold: false,
5383
+ });
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 }));
5388
+ };
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
+ }
5148
5402
  if (!this.widerReads.has(session.id) && acceptOffer !== true) {
5149
- // Wider restores and conditional offer takes check ownership
5150
- // in the session's resize queue below.
5151
- const handedOver = this.geometryController.get(session.id) !== ws;
5152
- const changed = wanted.cols !== session.cols || wanted.rows !== session.rows;
5153
5403
  let applied = false;
5154
- try {
5155
- if (changed)
5156
- await session.resize(wanted.cols, wanted.rows);
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 = () => {
5157
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);
5426
+ }
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);
5432
+ }
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
+ };
5438
+ 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
+ }
5445
+ if (!applied && ws.readyState === ws.OPEN)
5446
+ ws.send(JSON.stringify(this.geometryFrame(session, ws)));
5158
5447
  }
5159
5448
  catch (error) {
5160
5449
  if (error instanceof SessionProgramEndedError)
5161
5450
  return;
5162
5451
  this.logger.warn('viewer resize failed', { id: session.id, error: String(error) });
5163
5452
  }
5164
- this.geometryController.set(session.id, ws);
5165
- this.dashboardTransferable.delete(session.id);
5166
- this.geometryEpoch.set(session.id, (this.geometryEpoch.get(session.id) ?? 0) + 1);
5167
- if (credential.kind === 'dashboard') {
5168
- this.dashboardGeometryOwner.set(session.id, ws.protocol);
5169
- this.dashboardCredentialOwner.set(session.id, credential.dashboardToken);
5170
- }
5171
- else {
5172
- this.dashboardGeometryOwner.delete(session.id);
5173
- this.dashboardCredentialOwner.delete(session.id);
5174
- }
5175
- if (changed && applied) {
5176
- this.audit.record(actor, 'resize', session.id, {
5177
- cols: wanted.cols, rows: wanted.rows, hold: false,
5178
- });
5179
- }
5180
- if (changed)
5181
- this.announceGeometry(session.id, session);
5182
- else if (handedOver)
5183
- this.announceGeometry(session.id, session, { resync: false });
5184
- else if (take === true)
5185
- ws.send(JSON.stringify(this.geometryFrame(session, ws)));
5186
5453
  return;
5187
5454
  }
5188
5455
  try {
@@ -5196,6 +5463,7 @@ export class Daemon {
5196
5463
  // The controller change and epoch belong to the same queued
5197
5464
  // act as the resize, before a queued wider restore can run.
5198
5465
  this.geometryController.set(session.id, ws);
5466
+ this.recordGeometryChoice(session.id, true);
5199
5467
  this.dashboardTransferable.delete(session.id);
5200
5468
  this.geometryEpoch.set(session.id, (this.geometryEpoch.get(session.id) ?? 0) + 1);
5201
5469
  if (credential.kind === 'dashboard') {
@@ -5297,7 +5565,7 @@ export class Daemon {
5297
5565
  // is or that the window gained focus, is written above like a keystroke
5298
5566
  // because the program asked for it. Nobody typed it, so it is audited
5299
5567
  // as a report and leaves the "last input" indicator alone (§4.5, §5).
5300
- // Content only under captureContent, as for input.
5568
+ // Only reports allow opt-in content capture.
5301
5569
  if (report !== null) {
5302
5570
  this.audit.record(actor, 'report', session.id, {
5303
5571
  kind: report,
@@ -5308,7 +5576,6 @@ export class Daemon {
5308
5576
  }
5309
5577
  this.audit.record(actor, 'input', session.id, {
5310
5578
  chars: text.length,
5311
- ...(this.audit.captureContent ? { data: text } : {}),
5312
5579
  });
5313
5580
  this.broadcastControl(session.id, { type: 'input-source', source: 'human' });
5314
5581
  };
@@ -5337,6 +5604,7 @@ export class Daemon {
5337
5604
  // does not inherit it.
5338
5605
  if (this.geometryController.get(session.id) === ws) {
5339
5606
  this.geometryController.delete(session.id);
5607
+ this.recordGeometryChoice(session.id);
5340
5608
  this.announceGeometry(session.id, session, { resync: false });
5341
5609
  }
5342
5610
  this.lastActivity = Date.now();