shellpuppet 0.2.1 → 0.3.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 (232) hide show
  1. package/README.md +63 -16
  2. package/dist/agents/agy/index.d.ts +2 -0
  3. package/dist/agents/agy/index.js +11 -0
  4. package/dist/agents/agy/index.js.map +1 -0
  5. package/dist/agents/agy/nudge.d.ts +2 -0
  6. package/dist/agents/agy/nudge.js +29 -0
  7. package/dist/agents/agy/nudge.js.map +1 -0
  8. package/dist/agents/agy/reading.d.ts +2 -0
  9. package/dist/agents/agy/reading.js +28 -0
  10. package/dist/agents/agy/reading.js.map +1 -0
  11. package/dist/agents/barNudge.d.ts +9 -0
  12. package/dist/agents/barNudge.js +21 -0
  13. package/dist/agents/barNudge.js.map +1 -0
  14. package/dist/agents/claude/index.d.ts +2 -0
  15. package/dist/agents/claude/index.js +31 -0
  16. package/dist/agents/claude/index.js.map +1 -0
  17. package/dist/agents/claude/nudge.d.ts +2 -0
  18. package/dist/agents/claude/nudge.js +38 -0
  19. package/dist/agents/claude/nudge.js.map +1 -0
  20. package/dist/agents/claude/prompts.d.ts +9 -0
  21. package/dist/agents/claude/prompts.js +16 -0
  22. package/dist/agents/claude/prompts.js.map +1 -0
  23. package/dist/agents/claude/reading.d.ts +2 -0
  24. package/dist/agents/claude/reading.js +25 -0
  25. package/dist/agents/claude/reading.js.map +1 -0
  26. package/dist/agents/codex/index.d.ts +2 -0
  27. package/dist/agents/codex/index.js +28 -0
  28. package/dist/agents/codex/index.js.map +1 -0
  29. package/dist/agents/codex/nudge.d.ts +2 -0
  30. package/dist/agents/codex/nudge.js +35 -0
  31. package/dist/agents/codex/nudge.js.map +1 -0
  32. package/dist/agents/codex/prompts.d.ts +9 -0
  33. package/dist/agents/codex/prompts.js +14 -0
  34. package/dist/agents/codex/prompts.js.map +1 -0
  35. package/dist/agents/codex/reading.d.ts +2 -0
  36. package/dist/agents/codex/reading.js +22 -0
  37. package/dist/agents/codex/reading.js.map +1 -0
  38. package/dist/agents/generic/index.d.ts +3 -0
  39. package/dist/agents/generic/index.js +9 -0
  40. package/dist/agents/generic/index.js.map +1 -0
  41. package/dist/agents/generic/prompts.d.ts +2 -0
  42. package/dist/agents/generic/prompts.js +10 -0
  43. package/dist/agents/generic/prompts.js.map +1 -0
  44. package/dist/agents/grok/actionBox.d.ts +13 -0
  45. package/dist/agents/grok/actionBox.js +127 -0
  46. package/dist/agents/grok/actionBox.js.map +1 -0
  47. package/dist/agents/grok/index.d.ts +2 -0
  48. package/dist/agents/grok/index.js +20 -0
  49. package/dist/agents/grok/index.js.map +1 -0
  50. package/dist/agents/grok/nudge.d.ts +2 -0
  51. package/dist/agents/grok/nudge.js +76 -0
  52. package/dist/agents/grok/nudge.js.map +1 -0
  53. package/dist/agents/grok/prompts.d.ts +4 -0
  54. package/dist/agents/grok/prompts.js +89 -0
  55. package/dist/agents/grok/prompts.js.map +1 -0
  56. package/dist/agents/grok/reading.d.ts +2 -0
  57. package/dist/agents/grok/reading.js +49 -0
  58. package/dist/agents/grok/reading.js.map +1 -0
  59. package/dist/agents/grok/readingRules.d.ts +2 -0
  60. package/dist/agents/grok/readingRules.js +44 -0
  61. package/dist/agents/grok/readingRules.js.map +1 -0
  62. package/dist/agents/index.d.ts +28 -0
  63. package/dist/agents/index.js +46 -0
  64. package/dist/agents/index.js.map +1 -0
  65. package/dist/agents/input.d.ts +2 -0
  66. package/dist/agents/input.js +9 -0
  67. package/dist/agents/input.js.map +1 -0
  68. package/dist/agents/mimo/index.d.ts +2 -0
  69. package/dist/agents/mimo/index.js +13 -0
  70. package/dist/agents/mimo/index.js.map +1 -0
  71. package/dist/agents/mimo/nudge.d.ts +3 -0
  72. package/dist/agents/mimo/nudge.js +59 -0
  73. package/dist/agents/mimo/nudge.js.map +1 -0
  74. package/dist/agents/mimo/prompts.d.ts +2 -0
  75. package/dist/agents/mimo/prompts.js +40 -0
  76. package/dist/agents/mimo/prompts.js.map +1 -0
  77. package/dist/agents/mimo/reading.d.ts +2 -0
  78. package/dist/agents/mimo/reading.js +31 -0
  79. package/dist/agents/mimo/reading.js.map +1 -0
  80. package/dist/agents/mimo/readingRules.d.ts +2 -0
  81. package/dist/agents/mimo/readingRules.js +79 -0
  82. package/dist/agents/mimo/readingRules.js.map +1 -0
  83. package/dist/agents/mimo/stalls.d.ts +2 -0
  84. package/dist/agents/mimo/stalls.js +81 -0
  85. package/dist/agents/mimo/stalls.js.map +1 -0
  86. package/dist/agents/muse/index.d.ts +2 -0
  87. package/dist/agents/muse/index.js +20 -0
  88. package/dist/agents/muse/index.js.map +1 -0
  89. package/dist/agents/muse/input.d.ts +3 -0
  90. package/dist/agents/muse/input.js +7 -0
  91. package/dist/agents/muse/input.js.map +1 -0
  92. package/dist/agents/muse/nudge.d.ts +2 -0
  93. package/dist/agents/muse/nudge.js +33 -0
  94. package/dist/agents/muse/nudge.js.map +1 -0
  95. package/dist/agents/muse/prompts.d.ts +14 -0
  96. package/dist/agents/muse/prompts.js +132 -0
  97. package/dist/agents/muse/prompts.js.map +1 -0
  98. package/dist/agents/muse/reading.d.ts +2 -0
  99. package/dist/agents/muse/reading.js +33 -0
  100. package/dist/agents/muse/reading.js.map +1 -0
  101. package/dist/agents/muse/readingRules.d.ts +2 -0
  102. package/dist/agents/muse/readingRules.js +49 -0
  103. package/dist/agents/muse/readingRules.js.map +1 -0
  104. package/dist/agents/nudgeReading.d.ts +74 -0
  105. package/dist/agents/nudgeReading.js +262 -0
  106. package/dist/agents/nudgeReading.js.map +1 -0
  107. package/dist/agents/opencode/index.d.ts +2 -0
  108. package/dist/agents/opencode/index.js +21 -0
  109. package/dist/agents/opencode/index.js.map +1 -0
  110. package/dist/agents/opencode/nudge.d.ts +6 -0
  111. package/dist/agents/opencode/nudge.js +187 -0
  112. package/dist/agents/opencode/nudge.js.map +1 -0
  113. package/dist/agents/opencode/prompts.d.ts +6 -0
  114. package/dist/agents/opencode/prompts.js +198 -0
  115. package/dist/agents/opencode/prompts.js.map +1 -0
  116. package/dist/agents/opencode/reading.d.ts +2 -0
  117. package/dist/agents/opencode/reading.js +29 -0
  118. package/dist/agents/opencode/reading.js.map +1 -0
  119. package/dist/agents/opencode/stalls.d.ts +3 -0
  120. package/dist/agents/opencode/stalls.js +14 -0
  121. package/dist/agents/opencode/stalls.js.map +1 -0
  122. package/dist/agents/qoder/index.d.ts +2 -0
  123. package/dist/agents/qoder/index.js +12 -0
  124. package/dist/agents/qoder/index.js.map +1 -0
  125. package/dist/agents/qoder/nudge.d.ts +2 -0
  126. package/dist/agents/qoder/nudge.js +16 -0
  127. package/dist/agents/qoder/nudge.js.map +1 -0
  128. package/dist/agents/qoder/prompts.d.ts +2 -0
  129. package/dist/agents/qoder/prompts.js +6 -0
  130. package/dist/agents/qoder/prompts.js.map +1 -0
  131. package/dist/agents/qoder/reading.d.ts +2 -0
  132. package/dist/agents/qoder/reading.js +41 -0
  133. package/dist/agents/qoder/reading.js.map +1 -0
  134. package/dist/agents/types.d.ts +187 -0
  135. package/dist/agents/types.js +2 -0
  136. package/dist/agents/types.js.map +1 -0
  137. package/dist/cli/index.js +185 -19
  138. package/dist/cli/index.js.map +1 -1
  139. package/dist/client/http.d.ts +5 -1
  140. package/dist/client/http.js +39 -9
  141. package/dist/client/http.js.map +1 -1
  142. package/dist/core/dialogs.d.ts +2 -4
  143. package/dist/core/dialogs.js +6 -12
  144. package/dist/core/dialogs.js.map +1 -1
  145. package/dist/core/mailbox.d.ts +222 -0
  146. package/dist/core/mailbox.js +545 -0
  147. package/dist/core/mailbox.js.map +1 -0
  148. package/dist/core/manager.d.ts +3 -0
  149. package/dist/core/manager.js +37 -2
  150. package/dist/core/manager.js.map +1 -1
  151. package/dist/core/messageText.d.ts +2 -0
  152. package/dist/core/messageText.js +6 -0
  153. package/dist/core/messageText.js.map +1 -0
  154. package/dist/core/nudge.d.ts +37 -0
  155. package/dist/core/nudge.js +57 -0
  156. package/dist/core/nudge.js.map +1 -0
  157. package/dist/core/promptDetector.d.ts +14 -12
  158. package/dist/core/promptDetector.js +113 -363
  159. package/dist/core/promptDetector.js.map +1 -1
  160. package/dist/core/promptText.d.ts +1 -0
  161. package/dist/core/promptText.js +4 -0
  162. package/dist/core/promptText.js.map +1 -0
  163. package/dist/core/readiness.d.ts +14 -0
  164. package/dist/core/readiness.js +95 -0
  165. package/dist/core/readiness.js.map +1 -0
  166. package/dist/core/reasoning.d.ts +68 -7
  167. package/dist/core/reasoning.js +572 -325
  168. package/dist/core/reasoning.js.map +1 -1
  169. package/dist/core/renderer.d.ts +63 -3
  170. package/dist/core/renderer.js +368 -42
  171. package/dist/core/renderer.js.map +1 -1
  172. package/dist/core/selection.d.ts +1 -1
  173. package/dist/core/selection.js +3 -3
  174. package/dist/core/selection.js.map +1 -1
  175. package/dist/core/session.d.ts +165 -13
  176. package/dist/core/session.js +998 -84
  177. package/dist/core/session.js.map +1 -1
  178. package/dist/core/types.d.ts +60 -4
  179. package/dist/core/types.js +41 -0
  180. package/dist/core/types.js.map +1 -1
  181. package/dist/core/waiter.d.ts +9 -2
  182. package/dist/core/waiter.js +35 -10
  183. package/dist/core/waiter.js.map +1 -1
  184. package/dist/daemon/audit.d.ts +1 -1
  185. package/dist/daemon/audit.js +2 -1
  186. package/dist/daemon/audit.js.map +1 -1
  187. package/dist/daemon/config.d.ts +42 -0
  188. package/dist/daemon/config.js +159 -4
  189. package/dist/daemon/config.js.map +1 -1
  190. package/dist/daemon/folderPicker.js +21 -2
  191. package/dist/daemon/folderPicker.js.map +1 -1
  192. package/dist/daemon/homeOwner.d.ts +15 -0
  193. package/dist/daemon/homeOwner.js +106 -0
  194. package/dist/daemon/homeOwner.js.map +1 -0
  195. package/dist/daemon/index.js +10 -6
  196. package/dist/daemon/index.js.map +1 -1
  197. package/dist/daemon/launchProfiles.d.ts +5 -0
  198. package/dist/daemon/launchProfiles.js +42 -40
  199. package/dist/daemon/launchProfiles.js.map +1 -1
  200. package/dist/daemon/nudgeScheduler.d.ts +21 -0
  201. package/dist/daemon/nudgeScheduler.js +61 -0
  202. package/dist/daemon/nudgeScheduler.js.map +1 -0
  203. package/dist/daemon/paths.d.ts +20 -16
  204. package/dist/daemon/paths.js +137 -49
  205. package/dist/daemon/paths.js.map +1 -1
  206. package/dist/daemon/restartSource.d.ts +7 -0
  207. package/dist/daemon/restartSource.js +89 -0
  208. package/dist/daemon/restartSource.js.map +1 -0
  209. package/dist/daemon/screenshot.d.ts +4 -1
  210. package/dist/daemon/screenshot.js +45 -7
  211. package/dist/daemon/screenshot.js.map +1 -1
  212. package/dist/daemon/server.d.ts +70 -13
  213. package/dist/daemon/server.js +1596 -294
  214. package/dist/daemon/server.js.map +1 -1
  215. package/dist/daemon/sessionFeed.js +4 -1
  216. package/dist/daemon/sessionFeed.js.map +1 -1
  217. package/dist/mcp/config.js +2 -1
  218. package/dist/mcp/config.js.map +1 -1
  219. package/dist/mcp/index.js +12 -2
  220. package/dist/mcp/index.js.map +1 -1
  221. package/dist/mcp/tools.d.ts +21 -1
  222. package/dist/mcp/tools.js +213 -28
  223. package/dist/mcp/tools.js.map +1 -1
  224. package/dist/viewer/dashboard-folders.js +7 -1
  225. package/dist/viewer/dashboard-layout.js +6 -52
  226. package/dist/viewer/dashboard.css +20 -4
  227. package/dist/viewer/dashboard.html +12 -3
  228. package/dist/viewer/dashboard.js +549 -382
  229. package/dist/viewer/pane.js +744 -136
  230. package/dist/viewer/viewer.css +1 -1
  231. package/dist/viewer/viewer.js +3 -1
  232. package/package.json +1 -1
@@ -5,8 +5,10 @@
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
9
  import * as fs from 'node:fs';
9
10
  import { randomUUID } from 'node:crypto';
11
+ import { AsyncLocalStorage } from 'node:async_hooks';
10
12
  import * as http from 'node:http';
11
13
  import { createRequire } from 'node:module';
12
14
  import * as os from 'node:os';
@@ -14,6 +16,9 @@ import * as path from 'node:path';
14
16
  import { fileURLToPath } from 'node:url';
15
17
  import { WebSocketServer } from 'ws';
16
18
  import { SessionManager, PolicyViolationError, SessionStartError } from '../core/manager.js';
19
+ import { Mailbox, MailboxError, NAME_PATTERN, buildNudge } from '../core/mailbox.js';
20
+ import { buildMessagingPolicy, DEFAULT_NUDGE_INTERVAL_MS, DEFAULT_NUDGES_PER_MINUTE } from './config.js';
21
+ import { NudgeScheduler } from './nudgeScheduler.js';
17
22
  import { CommandNotFoundError, DEFAULT_SESSION_ENV, SessionInputFailedError, SessionProgramEndedError, WindowsWithoutConPTYError, credentialShapedNames, } from '../core/session.js';
18
23
  import { NativePtyUnavailableError } from '../core/nativePty.js';
19
24
  import { checkSessionCapacity, commandLine, compilePolicy, evaluateCommand } from '../core/policy.js';
@@ -24,14 +29,16 @@ import { RegexBudgetError } from '../core/regexBudget.js';
24
29
  import { detectPrompt } from '../core/promptDetector.js';
25
30
  import { markFilteredSelectedOption } from '../core/selection.js';
26
31
  import { WaitConditionError } from '../core/waiter.js';
27
- import { agentNames, hideReasoning, latestResult, programName, signatureFor } from '../core/reasoning.js';
28
- import { DEFAULT_WAIT_TIMEOUT_MS, ENV_NAME_PATTERN, MAX_WAIT_TIMEOUT_MS, WAIT_POLL_INTERVAL_MS, howSessionEnded } from '../core/types.js';
32
+ import { agentNames, hideReasoning, latestResult, programName, signatureForSession } from '../core/reasoning.js';
33
+ import { validResumeId, DEFAULT_WAIT_TIMEOUT_MS, ENV_NAME_PATTERN, MAX_WAIT_TIMEOUT_MS, WAIT_POLL_INTERVAL_MS, howSessionEnded } from '../core/types.js';
29
34
  import { DASHBOARD_COOKIE, TokenStore, VIEWER_COOKIE, VIEWER_GRANT_TTL_MS, bearerToken, cookieValues, dashboardCookie, dashboardProofFromProtocol, tokensEqual, viewerCookie, } from './auth.js';
30
35
  import { NULL_AUDITOR } from './audit.js';
31
36
  import { findBrowser, launchDashboard, launchViewer } from './viewerLauncher.js';
32
37
  import { DEFAULT_CAPTURE_TIMEOUT_MS, MAX_CAPTURE_TIMEOUT_MS, MIN_CAPTURE_TIMEOUT_MS, captureProfileRoot, captureViewer, sweepCaptureProfiles, } from './screenshot.js';
33
- import { claimDaemonState, daemonStatePath, ensureHome, inspectDaemonState, readDaemonState, removeDaemonState, removeDaemonStateIf, removeDaemonStateIfNotARecord, } from './paths.js';
38
+ import { claimDaemonState, daemonStatePath, ensureHome, writePrivateRecord, inspectDaemonState, readDaemonState, removeDaemonStateIf, removeDaemonStateIfNotARecord, } from './paths.js';
39
+ import { acquireHomeOwner, AlreadyRunningError } from './homeOwner.js';
34
40
  import { daemonRunning } from './liveness.js';
41
+ import { restoreRestartSource, retryRestartSource, snapshotSourceId } from './restartSource.js';
35
42
  import { packageVersion } from './meta.js';
36
43
  import { terminalReportKind } from './terminalReports.js';
37
44
  import { ViewerSync } from './viewerSync.js';
@@ -193,16 +200,8 @@ const DASHBOARD_HEARTBEAT_TIMEOUT_MS = 10_000;
193
200
  const DASHBOARD_PROOF_META = '<meta name="sp-csrf" content="">';
194
201
  const DASHBOARD_FONT_META = '<meta name="sp-dashboard-font-size" content="">';
195
202
  /** Thrown by `start()` when a healthy daemon already owns this home. */
196
- /** The largest dashboard window registration frame the daemon will parse. */
197
- const MAX_WINDOW_REGISTRATION_BYTES = 256;
198
- export class AlreadyRunningError extends Error {
199
- state;
200
- constructor(state) {
201
- super(`A healthy daemon is already running (pid ${String(state.pid)}, ` +
202
- `port ${String(state.port)}).`);
203
- this.state = state;
204
- this.name = 'AlreadyRunningError';
205
- }
203
+ export { AlreadyRunningError };
204
+ class HomeOwnershipError extends Error {
206
205
  }
207
206
  /** The scheme and authority that open an absolute-form request target (`http://user@host:port`). */
208
207
  const SCHEME_AND_AUTHORITY = /^[a-z][a-z0-9+.-]*:\/\/[^/]*/i;
@@ -234,9 +233,9 @@ function offeredProtocols(req) {
234
233
  .filter((part) => part !== '');
235
234
  }
236
235
  /** The 409 for input, a key or a resize sent to a session that has ended. */
237
- function endedRefusal(id, exitCode) {
236
+ function endedRefusal(id, exitCode, fault = null) {
238
237
  return (`Session ${id} has ${exitCode === null ? 'ended' : 'exited'} ` +
239
- `(${howSessionEnded(exitCode)}) and no longer accepts input or geometry changes.`);
238
+ `(${fault ?? howSessionEnded(exitCode)}) and no longer accepts input or geometry changes.`);
240
239
  }
241
240
  function isRecord(value) {
242
241
  return typeof value === 'object' && value !== null && !Array.isArray(value);
@@ -350,12 +349,18 @@ function overBudgetMessage(signature) {
350
349
  'aside for a minute, so the screen is not returned filtered. Try again shortly.');
351
350
  }
352
351
  /** Read one rendered frame for both a filtered wait predicate and its reply. */
353
- function filteredWaitScreen(session, signature) {
352
+ function filteredWaitScreen(session, signature, prompt) {
354
353
  const view = session.styledScreenNow(REASONING_CONTEXT_LINES);
355
354
  const filtered = hideReasoning(view.lines, signature, view.firstVisible);
356
355
  if (filtered === null)
357
356
  throw new WaitConditionError(overBudgetMessage(signature));
358
- return { screen: markFilteredSelectedOption(filtered.lines, view.lines).join('\n'), filtered };
357
+ const styled = prompt ? filteredPromptStyles(filtered, view) : undefined;
358
+ return { screen: markFilteredSelectedOption(filtered.lines, view.lines, session.agent).join('\n'), filtered, styled };
359
+ }
360
+ /** Wrap flags and padding must describe exactly the rows the wait can read. */
361
+ function filteredPromptStyles(filtered, view) {
362
+ return filtered.rows.map((row, i) => filtered.markers[i]
363
+ ? { text: filtered.lines[i], spans: [] } : view.lines[view.firstVisible + row]);
359
364
  }
360
365
  /**
361
366
  * A query flag: absent, `0` or `false` is off, `1` or `true` is on, and
@@ -413,6 +418,8 @@ function startShapeError(body) {
413
418
  ['label', (value) => typeof value === 'string', 'a string'],
414
419
  ['purpose', (value) => typeof value === 'string', 'a string'],
415
420
  ['readyText', (value) => typeof value === 'string', 'a string'],
421
+ ['waitReady', (value) => typeof value === 'boolean', 'a boolean'],
422
+ ['readyTimeout', (value) => typeof value === 'number' && Number.isFinite(value) && value >= 0, 'a non-negative number of milliseconds'],
416
423
  [
417
424
  'readyQuiet',
418
425
  (value) => typeof value === 'number' && Number.isFinite(value) && value >= 0,
@@ -448,6 +455,8 @@ export class Daemon {
448
455
  logger;
449
456
  tokens = new TokenStore();
450
457
  manager;
458
+ mailbox;
459
+ nudges;
451
460
  server;
452
461
  wss = new WebSocketServer({
453
462
  noServer: true,
@@ -477,15 +486,28 @@ export class Daemon {
477
486
  geometryController = new Map();
478
487
  /** A dashboard document keeps its grid while a covered pane reconnects. */
479
488
  dashboardGeometryOwner = new Map();
489
+ /** The credential shared by that dashboard's windows, for transfers between documents. */
490
+ dashboardCredentialOwner = new Map();
491
+ /** Destination document for a released grid. A rosterless release allows a
492
+ * same-credential stream (null). A release awaiting a new assignment has no recipient. */
493
+ dashboardTransferable = new Map();
494
+ dashboardSocketCredential = new WeakMap();
495
+ /** External geometry acts invalidate a temporary wider read's restoration. */
496
+ geometryEpoch = new Map();
497
+ widerReads = new Map();
480
498
  /** Subscribers to the daemon-wide event stream (`/events`). */
481
- eventSockets = new Set();
499
+ eventSockets = new Map();
482
500
  /**
483
501
  * Open `/dashboard/events` sockets. While one is open, a session start does
484
502
  * not launch a per-session viewer window and does not hand back a viewer URL.
485
503
  */
486
504
  dashboardEventSockets = new Set();
487
- /** Opaque roster ids carried by dashboard feed sockets, never used for authorisation. */
505
+ /** Dashboard windows and assignments are owned by the authenticated feed. */
488
506
  dashboardWindowIds = new Map();
507
+ dashboardAssignments = new Map();
508
+ dashboardDesignated = null;
509
+ /** The document proof survives a feed reconnect and expires with the proof ring. */
510
+ dashboardDocumentFocus = new Map();
489
511
  liveDashboardEventSockets = new Set();
490
512
  /** A launched dashboard has 30 seconds to connect before a start may retry. */
491
513
  dashboardWindowStartedAt = 0;
@@ -502,10 +524,13 @@ export class Daemon {
502
524
  portValue = null;
503
525
  waitsInFlight = 0;
504
526
  lastActivity = Date.now();
527
+ shutdownWarnings = [];
505
528
  idleTimer = null;
506
529
  raceCheckTimer = null;
507
530
  statePublishTimer = null;
508
531
  statePublishRunning = false;
532
+ homeOwner;
533
+ claimsRestored = false;
509
534
  /** What this daemon published in daemon.json, once it has claimed it. */
510
535
  publishedState = null;
511
536
  instanceId = randomUUID();
@@ -516,6 +541,7 @@ export class Daemon {
516
541
  promptScanRunning = false;
517
542
  stopPromise = null;
518
543
  audit;
544
+ callerContext = new AsyncLocalStorage();
519
545
  /**
520
546
  * What sessions get from the daemon's environment (ADR-008), resolved once so
521
547
  * that what the daemon reports is what its sessions get.
@@ -524,10 +550,13 @@ export class Daemon {
524
550
  /** The profiles the dashboard may name, and the entries that did not load. */
525
551
  launchProfiles;
526
552
  daemonEnv;
553
+ cliPath;
527
554
  /** The global policy, kept here so a launch can report it before creating. */
528
555
  compiledPolicy;
529
556
  /** Accepted launch times, for the sliding sixty-second cap. */
530
557
  launchTimes = [];
558
+ claimTimes = [];
559
+ claimCount = 0;
531
560
  folderPickerBusy = false;
532
561
  folderPickerAbort = null;
533
562
  folderPickerDone = null;
@@ -541,16 +570,64 @@ export class Daemon {
541
570
  constructor(options) {
542
571
  const startedWrapped = process.env['SHELLPUPPET_DAEMON_STARTED_WRAPPED'] === '1';
543
572
  delete process.env['SHELLPUPPET_DAEMON_STARTED_WRAPPED'];
544
- this.options = { ...options, startedWrapped: options.startedWrapped ?? startedWrapped };
573
+ this.options = { ...options,
574
+ home: path.resolve(options.home),
575
+ startedWrapped: options.startedWrapped ?? startedWrapped };
545
576
  this.logger = options.logger;
546
- this.audit = options.audit ?? NULL_AUDITOR;
577
+ const auditor = options.audit ?? NULL_AUDITOR;
578
+ this.audit = {
579
+ captureContent: auditor.captureContent,
580
+ record: (actor, action, session, meta) => auditor.record(actor, action, session, meta,
581
+ // A session's timers and listeners can inherit the request that created
582
+ // them. Daemon observations must not inherit that caller's identity.
583
+ actor === 'daemon' ? undefined : this.callerContext.getStore()),
584
+ };
547
585
  this.sessionEnv = options.sessionEnv ?? DEFAULT_SESSION_ENV;
548
586
  this.launchProfiles = options.launchProfiles ?? { profiles: [], problems: [] };
549
587
  this.daemonEnv = options.daemonEnv ?? process.env;
588
+ this.cliPath = fileURLToPath(new URL('../../dist/cli/index.js', import.meta.url));
550
589
  this.compiledPolicy = compilePolicy(options.policy);
551
590
  this.manager = new SessionManager(compilePolicy(options.policy), this.logger, {
552
591
  sessionEnv: this.sessionEnv,
553
- }, (id) => this.sessionFeed.remove(id));
592
+ identity: {
593
+ token: '',
594
+ instanceId: this.instanceId,
595
+ cliPath: this.cliPath,
596
+ home: this.options.home,
597
+ },
598
+ }, (id) => {
599
+ this.endMailboxParticipant(id);
600
+ this.sessionFeed.remove(id);
601
+ });
602
+ this.mailbox = new Mailbox({
603
+ enabled: options.messaging?.enabled === true,
604
+ reservedNames: new Set((options.messaging?.allow ?? []).flatMap((rule) => rule === 'parent-child' ? [] : rule.members)),
605
+ claimIdleMinutes: options.messaging?.claimIdleMinutes,
606
+ now: () => this.now(),
607
+ policy: buildMessagingPolicy(options.messaging, {
608
+ parentOf: (id) => this.manager.get(id)?.parent,
609
+ }),
610
+ });
611
+ this.nudges = new NudgeScheduler({
612
+ now: () => this.now(),
613
+ intervalMs: options.messaging?.nudgeIntervalMs ?? DEFAULT_NUDGE_INTERVAL_MS,
614
+ perMinute: options.messaging?.nudgesPerMinute ?? DEFAULT_NUDGES_PER_MINUTE,
615
+ deliver: (id) => this.deliverNudge(id),
616
+ });
617
+ this.mailbox.on('message', (event) => {
618
+ const entry = this.mailbox.log().find((item) => item.id === event.id);
619
+ if (entry !== undefined)
620
+ this.messageAudit('msg-send', entry);
621
+ this.emitMessageEvent({ type: 'message', ...event }, entry);
622
+ this.emitDashboardMessageEvent({ type: 'message', ...event });
623
+ if (this.mailbox.participant(event.to.id)?.kind === 'session')
624
+ this.nudges.queue(event.to.id);
625
+ });
626
+ this.mailbox.on('state', (event) => {
627
+ const entry = this.mailbox.log().find((item) => item.id === event.id);
628
+ this.emitMessageEvent({ type: 'message-state', ...event }, entry);
629
+ this.emitDashboardMessageEvent({ type: 'message-state', ...event });
630
+ });
554
631
  this.sessionFeed = new SessionFeed(this.version, () => this.listedSummaries().map((summary) => this.summaryWithPrompt(summary)), this.logger);
555
632
  this.server = http.createServer((req, res) => {
556
633
  this.handleRequest(req, res).catch((error) => {
@@ -603,18 +680,15 @@ export class Daemon {
603
680
  // ------------------------------------------------------------------ start
604
681
  async start() {
605
682
  const { home } = this.options;
606
- const homeResult = await ensureHome(home);
607
- if (homeResult.warning !== undefined) {
608
- this.logger.warn('home hardening warning', { warning: homeResult.warning });
609
- }
683
+ ensureHome(home);
610
684
  // Defer to an incumbent that is running, even one too busy to answer its
611
685
  // health check; clear a record whose daemon has gone (design §2.3).
612
686
  const existing = readDaemonState(home);
613
687
  if (existing !== null) {
614
688
  if (await this.incumbentRunning(existing))
615
689
  throw new AlreadyRunningError(existing);
616
- this.logger.info('clearing stale daemon state', { stalePid: existing.pid });
617
- removeDaemonStateIf(home, existing);
690
+ if (this.stopping)
691
+ throw new Error('Daemon stopped during startup.');
618
692
  }
619
693
  await new Promise((resolve, reject) => {
620
694
  this.server.once('error', reject);
@@ -630,6 +704,10 @@ export class Daemon {
630
704
  resolve();
631
705
  });
632
706
  });
707
+ if (this.stopping) {
708
+ await this.closeServerOnly();
709
+ throw new Error('Daemon stopped during startup.');
710
+ }
633
711
  const address = this.server.address();
634
712
  if (address === null || typeof address === 'string') {
635
713
  throw new Error('Failed to determine bound port.');
@@ -651,28 +729,50 @@ export class Daemon {
651
729
  instanceId: this.instanceId,
652
730
  startedWrapped: this.options.startedWrapped ?? false,
653
731
  };
654
- // Atomic claim; on losing the race, defer to the winner (design §2.2:
655
- // the race is normal, not exceptional). A file that holds no record at all,
656
- // such as an emptied one, is cleared like a stale record.
657
- if (!claimDaemonState(home, state)) {
658
- const winner = inspectDaemonState(home);
659
- if (winner.kind === 'record' && (await this.incumbentRunning(winner.state))) {
660
- await this.closeServerOnly();
661
- throw new AlreadyRunningError(winner.state);
662
- }
663
- if (winner.kind === 'record')
664
- removeDaemonStateIf(home, winner.state);
665
- if (winner.kind === 'not-a-record') {
666
- this.logger.warn('clearing a daemon.json that holds no daemon record', {
667
- length: winner.raw.length,
668
- });
669
- removeDaemonStateIfNotARecord(home, winner.raw);
732
+ // Hold the home independently of discovery, including while restoring
733
+ // claims and publishing shutdown records. This also serialises takeovers.
734
+ try {
735
+ this.homeOwner = await acquireHomeOwner(home, state.port, this.instanceId);
736
+ if (this.stopping)
737
+ throw new Error('Daemon stopped during startup.');
738
+ const file = inspectDaemonState(home);
739
+ if (file.kind === 'record' && await this.incumbentRunning(file.state)) {
740
+ throw new AlreadyRunningError(file.state);
670
741
  }
671
- if (!claimDaemonState(home, state)) {
672
- await this.closeServerOnly();
673
- throw new Error(`Could not claim ${daemonStatePath(home)}: it could not be read, or another ` +
674
- `daemon claimed it first.`);
742
+ if (this.stopping)
743
+ throw new Error('Daemon stopped during startup.');
744
+ if (file.kind === 'unreadable')
745
+ throw new Error('Could not read daemon.json to claim the home.');
746
+ Object.assign(state, restoreRestartSource(home, file, this.logger));
747
+ if (file.kind === 'missing') {
748
+ if (!claimDaemonState(home, state))
749
+ throw new Error('Another daemon claimed daemon.json first.');
675
750
  }
751
+ else {
752
+ // A failed rename leaves the entire predecessor record in place.
753
+ writePrivateRecord(daemonStatePath(home), state);
754
+ }
755
+ }
756
+ catch (error) {
757
+ this.releaseOwnership();
758
+ await this.closeServerOnly();
759
+ throw error;
760
+ }
761
+ this.publishedState = state;
762
+ const claimsFile = path.join(home, 'launcher-claims.json');
763
+ try {
764
+ const rows = JSON.parse(fs.readFileSync(claimsFile, 'utf8'));
765
+ if (!Array.isArray(rows))
766
+ throw new Error('Expected saved launcher claims to be an array.');
767
+ this.claimCount = this.mailbox.restoreClaims(rows, this.options.messaging?.enabled ? this.launchProfiles.sessionLaunch ?? [] : []);
768
+ this.claimsRestored = true;
769
+ this.saveLauncherClaims();
770
+ }
771
+ catch (error) {
772
+ if (error.code === 'ENOENT')
773
+ this.claimsRestored = true;
774
+ else
775
+ this.logger.warn(this.claimsRestored ? 'Could not update saved launcher claims.' : 'Could not restore saved launcher claims.');
676
776
  }
677
777
  // Belt and braces for the unlink/claim TOCTOU sliver: shortly after
678
778
  // start-up, if the published record names someone else and nobody is
@@ -681,7 +781,7 @@ export class Daemon {
681
781
  this.raceCheckTimer = setTimeout(() => {
682
782
  const current = readDaemonState(home);
683
783
  if (current !== null &&
684
- current.pid !== process.pid &&
784
+ current.instanceId !== this.instanceId &&
685
785
  this.manager.size() === 0 &&
686
786
  this.sockets.size === 0) {
687
787
  this.logger.info('lost start-up race after claim, stopping', {
@@ -704,13 +804,13 @@ export class Daemon {
704
804
  this.logger.warn('sessionEnv "passthrough" hands every session the daemon environment, including ' +
705
805
  'these variables whose names look like credentials; use "clean" or a list to keep them out', { names: exposed });
706
806
  }
707
- this.publishedState = state;
708
807
  this.statePublishTimer = setInterval(() => {
709
808
  void this.keepStatePublished();
710
809
  }, this.options.statePublishCheckMs ?? STATE_PUBLISH_CHECK_MS);
711
810
  this.statePublishTimer.unref();
712
811
  const idleMs = this.options.idleMs ?? DEFAULT_IDLE_MS;
713
812
  this.idleTimer = setInterval(() => {
813
+ this.lapseIdleClaims();
714
814
  // Reap sessions whose grace has lapsed before judging idleness. A
715
815
  // rejected sweep must be caught here, or it becomes an
716
816
  // unhandledRejection and the handler in index.ts stops the daemon.
@@ -760,7 +860,7 @@ export class Daemon {
760
860
  * process that had the same pid.
761
861
  */
762
862
  async incumbentRunning(record) {
763
- if (record.pid === process.pid && record.port === this.portValue)
863
+ if (record.port === this.portValue)
764
864
  return false;
765
865
  if (await this.isHealthy(record.port))
766
866
  return true;
@@ -786,7 +886,7 @@ export class Daemon {
786
886
  */
787
887
  async keepStatePublished() {
788
888
  const published = this.publishedState;
789
- if (published === null || this.stopPromise !== null || this.statePublishRunning)
889
+ if (published === null || this.stopping || this.statePublishRunning || !this.homeOwner?.held())
790
890
  return;
791
891
  this.statePublishRunning = true;
792
892
  try {
@@ -796,7 +896,7 @@ export class Daemon {
796
896
  return;
797
897
  if (file.kind === 'record') {
798
898
  const current = file.state;
799
- if (current.pid === published.pid && current.port === published.port) {
899
+ if (current.instanceId === this.instanceId && current.pid === published.pid && current.port === published.port) {
800
900
  this.foreignOwnerReported = null;
801
901
  return;
802
902
  }
@@ -811,6 +911,8 @@ export class Daemon {
811
911
  }
812
912
  return;
813
913
  }
914
+ if (this.stopping || !this.homeOwner?.held())
915
+ return;
814
916
  removeDaemonStateIf(home, current);
815
917
  }
816
918
  else if (file.kind === 'not-a-record') {
@@ -850,8 +952,8 @@ export class Daemon {
850
952
  }
851
953
  // ------------------------------------------------------------------- stop
852
954
  /**
853
- * Kill every session's process tree, close everything, remove the state
854
- * file (unless we lost the race and it now belongs to the winner).
955
+ * Kill every session's process tree and release our discovery record. A
956
+ * restart leaves a credential-free handoff for the next owner.
855
957
  * The daemon must never exit and strand running agent CLIs (design §2.3).
856
958
  */
857
959
  stop(opts = {}) {
@@ -859,11 +961,76 @@ export class Daemon {
859
961
  // awaits the one real shutdown.
860
962
  if (this.stopPromise === null) {
861
963
  this.stopping = true;
862
- this.stopPromise = this.doStop(opts);
964
+ if (opts.removeState !== false && this.publishedState && this.homeOwner) {
965
+ const state = this.publishedState;
966
+ this.writeShutdownRecord('launcher-claims.json', () => this.saveLauncherClaims());
967
+ if (opts.restart) {
968
+ this.writeShutdownRecord('restart-source.json', () => {
969
+ this.requireHomeOwner();
970
+ writePrivateRecord(path.join(this.options.home, 'restart-source.json'), { restartFrom: this.instanceId });
971
+ });
972
+ this.writeShutdownRecord('previous-sessions.json', () => {
973
+ this.requireHomeOwner();
974
+ this.savePreviousSessions();
975
+ });
976
+ }
977
+ this.writeShutdownRecord('daemon.json', () => this.finishDiscovery(state, opts.restart === true));
978
+ }
979
+ this.releaseOwnership();
980
+ this.stopPromise = this.doStop();
863
981
  }
864
982
  return this.stopPromise;
865
983
  }
866
- async doStop(opts) {
984
+ finishDiscovery(state, restart) {
985
+ const discovery = this.requireHomeOwner();
986
+ if (discovery.kind === 'unreadable')
987
+ throw new Error('Could not read daemon.json before shutdown.');
988
+ const handoff = restart ? { restartFrom: this.instanceId } : {
989
+ restartFrom: state.restartFrom, restartSourcePending: state.restartSourcePending, restartCandidates: state.restartCandidates,
990
+ };
991
+ if (handoff.restartFrom || handoff.restartCandidates) {
992
+ // If replacement fails, the live record can still confirm a snapshot
993
+ // stamped by this instance after the storage fault clears.
994
+ writePrivateRecord(daemonStatePath(this.options.home), handoff);
995
+ }
996
+ else if (discovery.kind === 'not-a-record') {
997
+ removeDaemonStateIfNotARecord(this.options.home, discovery.raw);
998
+ }
999
+ else {
1000
+ removeDaemonStateIf(this.options.home, state);
1001
+ }
1002
+ }
1003
+ writeShutdownRecord(file, write, verb = 'save') {
1004
+ try {
1005
+ write();
1006
+ }
1007
+ catch (error) {
1008
+ const message = `Could not ${verb} ${file} during shutdown.`;
1009
+ this.shutdownWarnings.push(message);
1010
+ this.logger.warn(message, { code: error.code });
1011
+ }
1012
+ }
1013
+ releaseOwnership() {
1014
+ const owner = this.homeOwner;
1015
+ this.homeOwner = undefined;
1016
+ if (owner)
1017
+ this.writeShutdownRecord('daemon-owner', owner.release, 'release');
1018
+ }
1019
+ requireHomeOwner() {
1020
+ const state = this.publishedState;
1021
+ if (this.homeOwner?.held() && state) {
1022
+ const file = inspectDaemonState(this.options.home);
1023
+ // The exclusive home marker still protects the durable files when
1024
+ // discovery is missing, damaged or temporarily inaccessible.
1025
+ if (file.kind !== 'record' && file.kind !== 'restart-handoff')
1026
+ return file;
1027
+ if (file.kind === 'record' && file.state.instanceId === this.instanceId &&
1028
+ file.state.pid === state.pid && file.state.port === state.port)
1029
+ return file;
1030
+ }
1031
+ throw new HomeOwnershipError('This daemon no longer owns the discovery record.');
1032
+ }
1033
+ async doStop() {
867
1034
  if (this.idleTimer !== null)
868
1035
  clearInterval(this.idleTimer);
869
1036
  if (this.raceCheckTimer !== null)
@@ -876,6 +1043,9 @@ export class Daemon {
876
1043
  clearTimeout(timer);
877
1044
  this.promptGraceTimers.clear();
878
1045
  this.folderPickerAbort?.abort(new FolderPickerFailureError('The folder picker was stopped.'));
1046
+ for (const read of this.widerReads.values())
1047
+ read.abort.abort();
1048
+ await Promise.allSettled([...this.widerReads.values()].map((read) => read.done));
879
1049
  // Stop LISTENING first, before tearing down session trees. Killing process
880
1050
  // trees is not fast (`taskkill /T` on a loaded machine can take seconds
881
1051
  // per session), and a daemon that still answers on its port while shutting
@@ -925,17 +1095,6 @@ export class Daemon {
925
1095
  if (timer !== undefined)
926
1096
  clearTimeout(timer);
927
1097
  }
928
- if (opts.removeState !== false) {
929
- // Remove this daemon's record, or a file that holds none. A file that
930
- // cannot be read says nothing about what it holds, so it stays.
931
- const file = inspectDaemonState(this.options.home);
932
- if (file.kind === 'record' && file.state.pid === process.pid) {
933
- removeDaemonState(this.options.home);
934
- }
935
- else if (file.kind === 'not-a-record') {
936
- removeDaemonStateIfNotARecord(this.options.home, file.raw);
937
- }
938
- }
939
1098
  // Only now terminate lingering keep-alive connections, so close() cannot hang.
940
1099
  this.server.closeAllConnections();
941
1100
  await listenerClosed;
@@ -1045,8 +1204,8 @@ export class Daemon {
1045
1204
  }
1046
1205
  return null;
1047
1206
  }
1048
- auditDashboardRefusal(req, reason) {
1049
- this.audit.record('dashboard', 'refuse', undefined, {
1207
+ auditDashboardRefusal(req, reason, actor = 'dashboard') {
1208
+ this.audit.record(actor, 'refuse', undefined, {
1050
1209
  method: req.method ?? '',
1051
1210
  path: pathOnly(req.url),
1052
1211
  reason,
@@ -1103,6 +1262,7 @@ export class Daemon {
1103
1262
  if (grantPresented) {
1104
1263
  const redeemed = this.tokens.redeemDashboardGrant(grant, this.now());
1105
1264
  if (redeemed !== null) {
1265
+ this.retireDashboardFeeds();
1106
1266
  this.audit.record('dashboard', 'grant-redeem');
1107
1267
  res.writeHead(303, {
1108
1268
  location: '/dashboard',
@@ -1116,6 +1276,8 @@ export class Daemon {
1116
1276
  return;
1117
1277
  }
1118
1278
  const proof = cookie === null ? null : this.tokens.issueDashboardProof();
1279
+ if (proof !== null)
1280
+ this.retireDashboardFeeds();
1119
1281
  this.sendDashboardPage(res, proof, req.method === 'HEAD');
1120
1282
  return;
1121
1283
  }
@@ -1151,6 +1313,7 @@ export class Daemon {
1151
1313
  this.pendingDashboardGrants.delete(grant);
1152
1314
  if (this.stopping || !opened.launched || opened.mode === 'default-browser') {
1153
1315
  this.tokens.revokeDashboardGrant(grant);
1316
+ this.retireDashboardFeeds();
1154
1317
  this.auditDashboardRefusal(req, 'launch-failed');
1155
1318
  return false;
1156
1319
  }
@@ -1240,12 +1403,14 @@ export class Daemon {
1240
1403
  async waitAcrossSessions(res, url) {
1241
1404
  const hide = queryFlag(url, 'hideReasoning');
1242
1405
  const now = queryFlag(url, 'now');
1406
+ const stalled = queryFlag(url, 'stalled');
1407
+ const prompt = queryFlag(url, 'prompt');
1243
1408
  const timeoutText = url.searchParams.get('timeout');
1244
1409
  const timeout = timeoutText === null ? DEFAULT_WAIT_TIMEOUT_MS : Number(timeoutText);
1245
- if (hide === null || now === null || url.searchParams.get('prompt') !== 'true' ||
1410
+ if (hide === null || now === null || stalled === null || prompt === null || (!prompt && !stalled) ||
1246
1411
  !Number.isFinite(timeout) || timeout < 0 || timeout > MAX_WAIT_TIMEOUT_MS ||
1247
1412
  ['text', 'regex', 'quiet', 'debounce', 'matchAfterInput'].some((key) => url.searchParams.has(key))) {
1248
- json(res, 400, { error: 'A multi-session wait needs prompt=true, optional now, hideReasoning and a timeout from 0 to 300000 ms.' });
1413
+ json(res, 400, { error: 'A multi-session wait needs prompt=true and/or stalled=true, optional now, hideReasoning and a timeout from 0 to 300000 ms.' });
1249
1414
  return;
1250
1415
  }
1251
1416
  const requested = url.searchParams.getAll('session');
@@ -1258,10 +1423,13 @@ export class Daemon {
1258
1423
  this.waitsInFlight += 1;
1259
1424
  try {
1260
1425
  while (!res.destroyed) {
1261
- const sessions = this.waitingSessions(hide, ids);
1426
+ const waiting = prompt ? this.waitingSessions(hide, ids) : [];
1427
+ const stalledSessions = stalled ? this.listWithPrompts(hide).flatMap(session => session.exited || session.stalled === undefined || (ids !== undefined && !ids.has(session.id)) ? [] :
1428
+ [{ id: session.id, label: session.label, reason: 'stalled', stalled: session.stalled }]) : [];
1429
+ const sessions = [...(stalled ? waiting.map(session => ({ ...session, reason: 'prompt' })) : waiting), ...stalledSessions];
1262
1430
  const waitedMs = Date.now() - started;
1263
1431
  if (sessions.length > 0 || now || waitedMs >= timeout) {
1264
- json(res, 200, { matched: sessions.length > 0, reason: sessions.length > 0 ? 'prompt' : 'timeout', waitedMs, sessions });
1432
+ json(res, 200, { matched: sessions.length > 0, reason: waiting.length > 0 ? 'prompt' : stalledSessions.length > 0 ? 'stalled' : 'timeout', waitedMs, sessions });
1265
1433
  return;
1266
1434
  }
1267
1435
  await new Promise((resolve) => setTimeout(resolve, Math.min(WAIT_POLL_INTERVAL_MS, timeout - waitedMs)));
@@ -1295,6 +1463,39 @@ export class Daemon {
1295
1463
  this.lastActivity = Date.now();
1296
1464
  this.writeSessionList(res, url);
1297
1465
  }
1466
+ /** Owner-wide history is available only with the dashboard cookie and document proof. */
1467
+ serveDashboardMessages(req, res, url) {
1468
+ const presented = this.dashboardCookiePresented(req.headers.cookie);
1469
+ if (this.dashboardCookieToken(req.headers.cookie) === null) {
1470
+ if (presented)
1471
+ this.auditDashboardRefusal(req, 'unauthenticated');
1472
+ json(res, 401, { error: 'Unauthorised.' });
1473
+ return;
1474
+ }
1475
+ if (!this.isSameOriginRead(req)) {
1476
+ this.auditDashboardRefusal(req, this.cookieRefusalReason(req));
1477
+ json(res, 403, { error: 'Forbidden.' });
1478
+ return;
1479
+ }
1480
+ if (!this.tokens.acceptsDashboardProof(headerOne(req, 'x-shellpuppet-csrf'))) {
1481
+ this.auditDashboardRefusal(req, 'proof');
1482
+ json(res, 403, { error: 'Forbidden.' });
1483
+ return;
1484
+ }
1485
+ const messages = this.mailbox.log();
1486
+ const counts = {};
1487
+ for (const entry of messages) {
1488
+ if (entry.state === 'waiting' || entry.state === 'nudged')
1489
+ counts[entry.to.id] = (counts[entry.to.id] ?? 0) + 1;
1490
+ }
1491
+ const summary = url.searchParams.get('summary') === '1';
1492
+ const groups = (this.options.messaging?.allow ?? []).filter((rule) => typeof rule !== 'string')
1493
+ .map((rule) => ({ group: rule.group, members: rule.members, roles: rule.roles ?? [] }));
1494
+ this.audit.record('dashboard', 'msg-log', undefined, { count: messages.length });
1495
+ this.lastActivity = Date.now();
1496
+ json(res, 200, { enabled: this.options.messaging?.enabled === true,
1497
+ counts, ...(summary ? {} : { messages, groups }) });
1498
+ }
1298
1499
  /** A cookie mutation: same-origin Fetch Metadata and a matching Origin. */
1299
1500
  isSameOriginMutation(req) {
1300
1501
  if (headerOne(req, 'sec-fetch-site') !== 'same-origin')
@@ -1323,10 +1524,12 @@ export class Daemon {
1323
1524
  async profileDescription(profile) {
1324
1525
  return {
1325
1526
  name: profile.name,
1527
+ role: profile.role ?? 'delegate',
1326
1528
  label: describeProfileText(profile.label ?? '', profile.name),
1327
1529
  purpose: describeProfileText(profile.purpose ?? '', profile.name),
1328
1530
  command: profile.command,
1329
1531
  args: [...profile.args],
1532
+ ...(profile.resume ? { canResume: true } : {}),
1330
1533
  folderRequired: profile.askCwd,
1331
1534
  anyFolder: profile.anyFolder,
1332
1535
  folders: profile.folders.map((folder) => ({ name: folder.name, path: folder.path })),
@@ -1522,23 +1725,27 @@ export class Daemon {
1522
1725
  json(res, 415, { error: 'The launch body must be JSON (application/json).' });
1523
1726
  return;
1524
1727
  }
1525
- if (!this.tokens.acceptsDashboardProof(headerOne(req, 'x-shellpuppet-csrf'))) {
1728
+ const documentProof = headerOne(req, 'x-shellpuppet-csrf');
1729
+ if (!this.tokens.acceptsDashboardProof(documentProof)) {
1526
1730
  this.auditDashboardRefusal(req, 'proof');
1527
1731
  json(res, 403, { error: 'Forbidden.' });
1528
1732
  return;
1529
1733
  }
1734
+ await this.launchProfile(req, res, { documentProof });
1735
+ }
1736
+ async launchProfile(req, res, { launcher, documentProof }) {
1530
1737
  let body;
1531
1738
  try {
1532
1739
  body = await readBody(req);
1533
1740
  }
1534
1741
  catch (error) {
1535
1742
  if (error instanceof RequestBodyTooLargeError) {
1536
- this.auditDashboardRefusal(req, 'body-size');
1743
+ this.auditDashboardRefusal(req, 'body-size', launcher?.name);
1537
1744
  json(res, 413, { error: error.message });
1538
1745
  return;
1539
1746
  }
1540
1747
  if (error instanceof Error && error.message.startsWith('Request body')) {
1541
- this.auditDashboardRefusal(req, 'body');
1748
+ this.auditDashboardRefusal(req, 'body', launcher?.name);
1542
1749
  json(res, 400, { error: error.message });
1543
1750
  return;
1544
1751
  }
@@ -1549,21 +1756,49 @@ export class Daemon {
1549
1756
  json(res, 400, { error: 'profile (string) is required.' });
1550
1757
  return;
1551
1758
  }
1759
+ const allowedKeys = ['profile', 'name', 'folder', 'rootIndex', 'folderPath', 'resumeId'];
1760
+ if (documentProof !== undefined)
1761
+ allowedKeys.push('window');
1552
1762
  for (const key of Object.keys(body)) {
1553
- if (key !== 'profile' && key !== 'folder' && key !== 'rootIndex' && key !== 'folderPath') {
1554
- this.auditDashboardRefusal(req, 'body');
1763
+ if (!allowedKeys.includes(key)) {
1764
+ this.auditDashboardRefusal(req, 'body', launcher?.name);
1555
1765
  json(res, 400, {
1556
- error: `The launch body may name only profile, folder, rootIndex and folderPath: "${key}" is not accepted. ` +
1766
+ error: `The launch body may name only ${allowedKeys.join(', ')}: "${key}" is not accepted. ` +
1557
1767
  'A command, arguments and environment value come from the profile.',
1558
1768
  });
1559
1769
  return;
1560
1770
  }
1561
1771
  }
1772
+ const requestedWindow = body['window'];
1773
+ const launchingWindow = requestedWindow === undefined ? undefined : this.dashboardWindows().find((window) => window.pair === requestedWindow && dashboardProofFromProtocol(window.socket.protocol) === documentProof);
1774
+ if (requestedWindow !== undefined && launchingWindow === undefined) {
1775
+ json(res, 409, { error: 'The launching dashboard window has closed.' });
1776
+ return;
1777
+ }
1562
1778
  const profile = this.launchProfiles.profiles.find((entry) => entry.name === profileName);
1563
1779
  if (profile === undefined) {
1564
1780
  json(res, 400, { error: `No such launch profile: ${profileName}` });
1565
1781
  return;
1566
1782
  }
1783
+ const resumeId = body['resumeId'];
1784
+ if (resumeId !== undefined && (!profile.resume || !validResumeId(resumeId))) {
1785
+ json(res, 400, { error: 'Resume requires a profile with resume arguments and a valid resume id.' });
1786
+ return;
1787
+ }
1788
+ const args = [...profile.args];
1789
+ if (typeof resumeId === 'string')
1790
+ args.push(...profile.resume.map(arg => arg === '{id}' ? resumeId : arg));
1791
+ const caller = this.resolveCallerIdentity(req);
1792
+ if (caller.presented && caller.session === undefined) {
1793
+ json(res, 403, { error: 'Session identity was not recognised.' });
1794
+ return;
1795
+ }
1796
+ const requestedName = body['name'] === undefined ? profile.name : body['name'];
1797
+ if (typeof requestedName !== 'string' || !NAME_PATTERN.test(requestedName) ||
1798
+ (body['name'] !== undefined && (/^s[0-9]+$/.test(requestedName) || this.isReservedClaimName(requestedName)))) {
1799
+ json(res, 400, { error: 'Name must be 1 to 40 letters, digits, dots, underscores or hyphens, and must not be reserved.' });
1800
+ return;
1801
+ }
1567
1802
  const folderName = body['folder'];
1568
1803
  const rootIndex = body['rootIndex'];
1569
1804
  const freePath = body['folderPath'];
@@ -1573,13 +1808,13 @@ export class Daemon {
1573
1808
  if (profile.askCwd) {
1574
1809
  if (freePath !== undefined) {
1575
1810
  if (!profile.anyFolder || folderName !== undefined || rootIndex !== undefined) {
1576
- this.auditDashboardRefusal(req, 'body');
1811
+ this.auditDashboardRefusal(req, 'body', launcher?.name);
1577
1812
  json(res, 400, { error: 'This profile does not accept that folder path.' });
1578
1813
  return;
1579
1814
  }
1580
1815
  const choice = resolveAnyFolder(freePath);
1581
1816
  if ('error' in choice) {
1582
- this.auditDashboardRefusal(req, 'body');
1817
+ this.auditDashboardRefusal(req, 'body', launcher?.name);
1583
1818
  json(res, 400, { error: choice.error });
1584
1819
  return;
1585
1820
  }
@@ -1597,7 +1832,7 @@ export class Daemon {
1597
1832
  if (rootIndex !== undefined) {
1598
1833
  const choice = await resolveRootFolder(profile.folderRoots.map((root) => path.resolve(os.homedir(), root)), rootIndex, folderName);
1599
1834
  if ('error' in choice) {
1600
- this.auditDashboardRefusal(req, 'body');
1835
+ this.auditDashboardRefusal(req, 'body', launcher?.name);
1601
1836
  json(res, 400, { error: choice.error });
1602
1837
  return;
1603
1838
  }
@@ -1606,7 +1841,7 @@ export class Daemon {
1606
1841
  else {
1607
1842
  folder = profile.folders.find((entry) => entry.name === folderName);
1608
1843
  if (folder === undefined) {
1609
- this.auditDashboardRefusal(req, 'body');
1844
+ this.auditDashboardRefusal(req, 'body', launcher?.name);
1610
1845
  json(res, 400, { error: `No such folder for profile "${profileName}": ${folderName}` });
1611
1846
  return;
1612
1847
  }
@@ -1614,7 +1849,7 @@ export class Daemon {
1614
1849
  }
1615
1850
  }
1616
1851
  else if (folderName !== undefined || rootIndex !== undefined || freePath !== undefined) {
1617
- this.auditDashboardRefusal(req, 'body');
1852
+ this.auditDashboardRefusal(req, 'body', launcher?.name);
1618
1853
  json(res, 400, {
1619
1854
  error: `Profile "${profileName}" uses a fixed working directory and does not accept a folder.`,
1620
1855
  });
@@ -1622,22 +1857,22 @@ export class Daemon {
1622
1857
  }
1623
1858
  const resolved = freeCwd !== undefined ? { cwd: freeCwd } : rootCwd === undefined ? this.resolveLaunchCwd(profile, folder) : { cwd: rootCwd };
1624
1859
  if ('error' in resolved) {
1625
- this.auditDashboardRefusal(req, 'body');
1860
+ this.auditDashboardRefusal(req, 'body', launcher?.name);
1626
1861
  json(res, 400, { error: resolved.error });
1627
1862
  return;
1628
1863
  }
1629
1864
  // Global policy runs first, then the profile's own deny and allow lists.
1630
1865
  // Both see the real command line, before any Windows shell wrap.
1631
- const globalDecision = evaluateCommand(this.compiledPolicy, profile.command, profile.args);
1866
+ const globalDecision = evaluateCommand(this.compiledPolicy, profile.command, args);
1632
1867
  if (!globalDecision.allowed) {
1633
- this.auditDashboardRefusal(req, 'policy');
1868
+ this.auditDashboardRefusal(req, 'policy', launcher?.name);
1634
1869
  json(res, 403, { error: globalDecision.reason ?? 'Command refused by policy.' });
1635
1870
  return;
1636
1871
  }
1637
1872
  if (profile.policy !== undefined) {
1638
- const ownDecision = evaluateCommand(compileProfilePolicy(profile.policy), profile.command, profile.args);
1873
+ const ownDecision = evaluateCommand(compileProfilePolicy(profile.policy), profile.command, args);
1639
1874
  if (!ownDecision.allowed) {
1640
- this.auditDashboardRefusal(req, 'policy');
1875
+ this.auditDashboardRefusal(req, 'policy', launcher?.name);
1641
1876
  json(res, 403, { error: ownDecision.reason ?? 'Command refused by policy.' });
1642
1877
  return;
1643
1878
  }
@@ -1647,69 +1882,48 @@ export class Daemon {
1647
1882
  // absolute path, so the folder's contents cannot choose the program.
1648
1883
  const resolvedCommand = resolveLaunchCommand(profile.command, resolved.cwd);
1649
1884
  if ('error' in resolvedCommand) {
1650
- this.auditDashboardRefusal(req, 'command');
1885
+ this.auditDashboardRefusal(req, 'command', launcher?.name);
1651
1886
  json(res, 400, {
1652
1887
  error: `Profile "${profile.name}" cannot be started: ${resolvedCommand.error}`,
1653
1888
  });
1654
1889
  return;
1655
1890
  }
1656
- const now = this.now();
1657
- this.pruneLaunchTimes(now);
1658
- if (this.launchTimes.length >= 8) {
1659
- this.auditDashboardRefusal(req, 'rate');
1660
- json(res, 429, {
1661
- error: 'Dashboard launch rate reached (8 in 60 seconds). Wait before starting another profile.',
1662
- });
1663
- return;
1664
- }
1665
- const live = this.manager.liveCount();
1666
- if (this.compiledPolicy.maxSessions === undefined) {
1667
- if (live >= 32) {
1668
- this.auditDashboardRefusal(req, 'limit');
1669
- json(res, 403, {
1670
- error: 'Session limit reached (32 live sessions). Kill a session or set policy.maxSessions.',
1671
- });
1672
- return;
1673
- }
1674
- }
1675
- else {
1676
- const capacity = checkSessionCapacity(this.compiledPolicy, live);
1677
- if (!capacity.allowed) {
1678
- this.auditDashboardRefusal(req, 'limit');
1679
- json(res, 403, { error: capacity.reason ?? 'Session limit reached.' });
1680
- return;
1681
- }
1682
- }
1683
1891
  const { env, copied } = copyDaemonEnv(profile.envFromDaemon, this.daemonEnv);
1684
1892
  const envNames = Object.keys(env);
1685
1893
  const folderLabel = freeCwd !== undefined ? freeCwd : folder?.name ?? (rootCwd !== undefined ? folderName : undefined);
1686
1894
  const options = {
1687
1895
  command: resolvedCommand.file,
1688
- args: [...profile.args],
1896
+ args,
1689
1897
  cwd: resolved.cwd,
1690
1898
  ...(profile.shell !== undefined ? { shell: profile.shell } : {}),
1691
1899
  ...(profile.agent !== undefined ? { agent: profile.agent } : {}),
1692
1900
  ...(profile.readyText !== undefined ? { readyText: profile.readyText } : {}),
1693
1901
  ...(profile.readyQuiet !== undefined ? { readyQuiet: profile.readyQuiet } : {}),
1694
- // The written command stays the session's label, as it was before the
1695
- // path was resolved: the page shows the profile, not a machine path.
1696
- ...(profile.label !== undefined
1697
- ? { label: expandProfileText(profile.label, profile.name, folderLabel) }
1698
- : { label: profile.command }),
1902
+ // An explicit launcher name becomes the label. A configured profile
1903
+ // label remains the default when the launch request omits a name.
1904
+ label: body['name'] === undefined
1905
+ ? (profile.label !== undefined ? expandProfileText(profile.label, profile.name, folderLabel) : profile.name)
1906
+ : requestedName,
1907
+ launchProfile: { profile: profile.name, folder: resolved.cwd,
1908
+ folderChoice: freeCwd !== undefined ? { folderPath: freeCwd } : typeof folderName === 'string'
1909
+ ? { folder: folderName, ...(typeof rootIndex === 'number' ? { rootIndex } : {}) } : {},
1910
+ ...(typeof resumeId === 'string' ? { resumeId } : {}) },
1911
+ role: launcher !== undefined || caller.session === undefined ? (profile.role ?? 'delegate') : 'delegate',
1912
+ ...((launcher?.id ?? caller.session) === undefined ? {} : { parent: launcher?.id ?? caller.session }),
1699
1913
  ...(profile.purpose !== undefined
1700
1914
  ? { purpose: expandProfileText(profile.purpose, profile.name, folderLabel) }
1701
1915
  : {}),
1702
1916
  ...(envNames.length > 0 ? { env } : {}),
1703
1917
  // The audit actor, not a caller-declared identity: the dashboard page
1704
1918
  // has no client environment and no other way to name itself.
1705
- startedBy: 'dashboard',
1919
+ startedBy: launcher?.name ?? 'dashboard',
1706
1920
  };
1707
1921
  // Keep the path check adjacent to spawn. A local writer can still replace
1708
1922
  // a directory after this check, as the security model records.
1709
1923
  if (rootCwd !== undefined) {
1710
1924
  const latest = await resolveRootFolder(profile.folderRoots.map((root) => path.resolve(os.homedir(), root)), rootIndex, folderName);
1711
1925
  if ('error' in latest || latest.cwd !== rootCwd) {
1712
- this.auditDashboardRefusal(req, 'body');
1926
+ this.auditDashboardRefusal(req, 'body', launcher?.name);
1713
1927
  json(res, 400, { error: 'Folder is no longer available from this root.' });
1714
1928
  return;
1715
1929
  }
@@ -1717,18 +1931,53 @@ export class Daemon {
1717
1931
  if (freeCwd !== undefined) {
1718
1932
  const latest = resolveAnyFolder(freePath);
1719
1933
  if ('error' in latest || latest.cwd !== freeCwd) {
1720
- this.auditDashboardRefusal(req, 'body');
1934
+ this.auditDashboardRefusal(req, 'body', launcher?.name);
1721
1935
  json(res, 400, { error: 'The chosen folder is no longer available.' });
1722
1936
  return;
1723
1937
  }
1724
1938
  }
1939
+ if (this.stopping) {
1940
+ json(res, 503, { error: 'The daemon is stopping.' });
1941
+ return;
1942
+ }
1943
+ if (launcher && this.grantedLauncher(req)?.id !== launcher.id) {
1944
+ json(res, 403, { error: 'Session launch permission required.' });
1945
+ return;
1946
+ }
1947
+ const now = this.now();
1948
+ this.pruneLaunchTimes(now);
1949
+ if (this.launchTimes.length >= 8) {
1950
+ this.auditDashboardRefusal(req, 'rate', launcher?.name);
1951
+ json(res, 429, {
1952
+ error: 'Dashboard launch rate reached (8 in 60 seconds). Wait before starting another profile.',
1953
+ });
1954
+ return;
1955
+ }
1956
+ const live = this.manager.liveCount();
1957
+ if (this.compiledPolicy.maxSessions === undefined) {
1958
+ if (live >= 32) {
1959
+ this.auditDashboardRefusal(req, 'limit', launcher?.name);
1960
+ json(res, 403, {
1961
+ error: 'Session limit reached (32 live sessions). Kill a session or set policy.maxSessions.',
1962
+ });
1963
+ return;
1964
+ }
1965
+ }
1966
+ else {
1967
+ const capacity = checkSessionCapacity(this.compiledPolicy, live);
1968
+ if (!capacity.allowed) {
1969
+ this.auditDashboardRefusal(req, 'limit', launcher?.name);
1970
+ json(res, 403, { error: capacity.reason ?? 'Session limit reached.' });
1971
+ return;
1972
+ }
1973
+ }
1725
1974
  let session;
1726
1975
  try {
1727
1976
  session = (this.options.dashboardSessionFactory ?? ((value) => this.manager.create(value)))(options);
1728
1977
  }
1729
1978
  catch (error) {
1730
1979
  if (error instanceof PolicyViolationError) {
1731
- this.auditDashboardRefusal(req, 'policy');
1980
+ this.auditDashboardRefusal(req, 'policy', launcher?.name);
1732
1981
  json(res, 403, { error: error.message });
1733
1982
  return;
1734
1983
  }
@@ -1765,21 +2014,32 @@ export class Daemon {
1765
2014
  // A launch is an API call: the idle timer counts from it, so a session
1766
2015
  // that has just started is not reaped sooner than `idleMinutes` allows.
1767
2016
  this.lastActivity = Date.now();
2017
+ this.registerMailboxSession(session, requestedName);
2018
+ if (launchingWindow && launchingWindow.socket.readyState === launchingWindow.socket.OPEN &&
2019
+ this.dashboardWindowIds.has(launchingWindow.socket)) {
2020
+ const { pair } = launchingWindow;
2021
+ this.dashboardAssignments.set(pair, [...(this.dashboardAssignments.get(pair) ?? []), session.id]);
2022
+ }
1768
2023
  this.sessionFeed.add(this.summaryWithPrompt(session.summary()));
1769
2024
  session.onExit(() => {
1770
2025
  this.geometryController.delete(session.id);
1771
2026
  this.dashboardGeometryOwner.delete(session.id);
2027
+ this.dashboardCredentialOwner.delete(session.id);
2028
+ this.dashboardTransferable.delete(session.id);
1772
2029
  this.updateFeedSession(session.id);
1773
2030
  });
1774
2031
  session.onReady(() => this.updateFeedSession(session.id));
2032
+ this.watchStalls(session);
1775
2033
  // The profile name and the written command line, the file that was
1776
2034
  // actually resolved and started, and copied variable names or "all".
1777
2035
  // Never a value.
1778
- this.audit.record('dashboard', 'start', session.id, {
2036
+ this.audit.record(options.startedBy, 'start', session.id, {
2037
+ startedBy: options.startedBy, ...(launcher ? { launcherId: launcher.id } : {}),
1779
2038
  profile: profile.name,
1780
2039
  command: profile.command,
1781
- args: profile.args,
2040
+ args,
1782
2041
  resolvedCommand: resolvedCommand.file,
2042
+ agent: session.agent,
1783
2043
  ...(profile.envFromDaemon === 'all'
1784
2044
  ? { envFromDaemon: 'all' }
1785
2045
  : copied.length > 0 ? { envFromDaemon: copied } : {}),
@@ -1851,13 +2111,86 @@ export class Daemon {
1851
2111
  this.dropSessionArtifacts(id);
1852
2112
  json(res, 200, { ok: true, killed: id });
1853
2113
  }
2114
+ async handleDashboardRename(req, res, id) {
2115
+ const presented = this.dashboardCookiePresented(req.headers.cookie);
2116
+ if (this.dashboardCookieToken(req.headers.cookie) === null) {
2117
+ if (presented)
2118
+ this.auditDashboardRefusal(req, 'unauthenticated');
2119
+ json(res, 401, { error: 'A dashboard credential is required.' });
2120
+ return;
2121
+ }
2122
+ if (!this.isSameOriginMutation(req)) {
2123
+ this.auditDashboardRefusal(req, this.mutationRefusalReason(req));
2124
+ json(res, 403, { error: 'Forbidden.' });
2125
+ return;
2126
+ }
2127
+ if (!this.tokens.acceptsDashboardProof(headerOne(req, 'x-shellpuppet-csrf'))) {
2128
+ this.auditDashboardRefusal(req, 'proof');
2129
+ json(res, 403, { error: 'Forbidden.' });
2130
+ return;
2131
+ }
2132
+ if ((headerOne(req, 'content-type') ?? '').split(';', 1)[0]?.trim().toLowerCase() !== 'application/json') {
2133
+ json(res, 415, { error: 'The rename body must be JSON.' });
2134
+ return;
2135
+ }
2136
+ let body;
2137
+ try {
2138
+ body = await readBody(req);
2139
+ }
2140
+ catch (error) {
2141
+ if (error instanceof RequestBodyTooLargeError) {
2142
+ json(res, 413, { error: error.message });
2143
+ return;
2144
+ }
2145
+ if (error instanceof Error && error.message.startsWith('Request body')) {
2146
+ json(res, 400, { error: error.message });
2147
+ return;
2148
+ }
2149
+ throw error;
2150
+ }
2151
+ if (Object.keys(body).some((key) => key !== 'name') || typeof body['name'] !== 'string' ||
2152
+ !NAME_PATTERN.test(body['name']) || /^s[0-9]+$/.test(body['name'])) {
2153
+ json(res, 400, { error: 'Name must be 1 to 40 letters, digits, dots, underscores or hyphens, and must not be reserved.' });
2154
+ return;
2155
+ }
2156
+ const session = this.manager.get(id);
2157
+ if (session === undefined) {
2158
+ json(res, 404, { error: `No such session: ${id}` });
2159
+ return;
2160
+ }
2161
+ if (session.exited) {
2162
+ json(res, 409, { error: `Session ${id} has ended and cannot be renamed.` });
2163
+ return;
2164
+ }
2165
+ const previous = this.mailbox.participant(id)?.name;
2166
+ if (previous === undefined) {
2167
+ json(res, 409, { error: 'The session has ended.' });
2168
+ return;
2169
+ }
2170
+ try {
2171
+ this.mailbox.rename(id, body['name']);
2172
+ }
2173
+ catch (error) {
2174
+ if (error instanceof MailboxError) {
2175
+ json(res, error.code === 'duplicate-name' ? 409 : 400, { error: error.message });
2176
+ return;
2177
+ }
2178
+ throw error;
2179
+ }
2180
+ const oldLabel = session.label;
2181
+ session.label = body['name'];
2182
+ this.audit.record('dashboard', 'rename', id, { oldName: previous, newName: body['name'], oldLabel });
2183
+ this.updateFeedSession(id);
2184
+ json(res, 200, { id, name: body['name'], label: session.label });
2185
+ }
1854
2186
  /**
1855
- * Why a `/dashboard/events` upgrade is refused, or null when it may attach.
2187
+ * Authenticate the dashboard event feed and retain its issuing credential.
1856
2188
  * The client token on the query is not a way in. The proof is the
1857
2189
  * subprotocol, not `X-ShellPuppet-CSRF`.
1858
2190
  */
1859
- dashboardUpgradeRefusal(req) {
1860
- if (this.dashboardCookieToken(req.headers.cookie) === null) {
2191
+ dashboardUpgradeCredential(req) {
2192
+ const token = this.dashboardCookieToken(req.headers.cookie);
2193
+ if (token === null) {
1861
2194
  return { code: 401, reason: 'Unauthorized', audit: 'unauthenticated' };
1862
2195
  }
1863
2196
  if (!this.originMatchesRequest(req)) {
@@ -1878,7 +2211,7 @@ export class Daemon {
1878
2211
  });
1879
2212
  if (!accepted)
1880
2213
  return { code: 403, reason: 'Forbidden', audit: 'proof' };
1881
- return null;
2214
+ return token;
1882
2215
  }
1883
2216
  /**
1884
2217
  * Select `sp-csrf.<proof>` when this upgrade's credential is the dashboard
@@ -1935,9 +2268,10 @@ export class Daemon {
1935
2268
  }
1936
2269
  return { ok: true, credential: { kind: 'client', readOnly: false } };
1937
2270
  }
1938
- const dashboard = this.dashboardUpgradeRefusal(req);
1939
- if (dashboard === null) {
1940
- return { ok: true, credential: { kind: 'dashboard', readOnly: false } };
2271
+ const dashboard = this.dashboardUpgradeCredential(req);
2272
+ if (typeof dashboard === 'string') {
2273
+ return { ok: true, credential: { kind: 'dashboard', readOnly: false,
2274
+ dashboardToken: dashboard } };
1941
2275
  }
1942
2276
  const viewer = cookieValues(req.headers.cookie, VIEWER_COOKIE)
1943
2277
  .map((value) => ({ value, credential: this.tokens.verifyStreamToken(value) }))
@@ -2016,7 +2350,7 @@ export class Daemon {
2016
2350
  // learns it. A link whose `s=` had been edited would otherwise spend
2017
2351
  // its grant on a page that then asks for the wrong stream.
2018
2352
  if (url.searchParams.get('s') !== redeemed.sessionId) {
2019
- headers['location'] = `/view?s=${encodeURIComponent(redeemed.sessionId)}`;
2353
+ headers['location'] = `/view?s=${encodeURIComponent(redeemed.sessionId)}${passiveDrive(url) ? '&drive=0' : ''}`;
2020
2354
  res.writeHead(302, headers);
2021
2355
  res.end();
2022
2356
  return;
@@ -2063,10 +2397,18 @@ export class Daemon {
2063
2397
  await this.serveDashboardProfiles(req, res);
2064
2398
  return;
2065
2399
  }
2400
+ if (req.method === 'GET' && url.pathname === '/dashboard/messages') {
2401
+ this.serveDashboardMessages(req, res, url);
2402
+ return;
2403
+ }
2066
2404
  if (req.method === 'POST' && url.pathname === '/dashboard/launch') {
2067
2405
  await this.handleDashboardLaunch(req, res);
2068
2406
  return;
2069
2407
  }
2408
+ if (req.method === 'POST' && segments.length === 4 && segments[0] === 'dashboard' && segments[1] === 'sessions' && segments[3] === 'rename') {
2409
+ await this.handleDashboardRename(req, res, segments[2] ?? '');
2410
+ return;
2411
+ }
2070
2412
  if (req.method === 'POST' && url.pathname === '/dashboard/folder-picker') {
2071
2413
  const handler = this.handleDashboardFolderPicker(req, res);
2072
2414
  this.folderPickerHandlers.add(handler);
@@ -2103,17 +2445,486 @@ export class Daemon {
2103
2445
  return;
2104
2446
  }
2105
2447
  this.lastActivity = Date.now();
2106
- // Audit actor (design §4.5): adapters self-identify via a header, the MCP
2107
- // adapter as `mcp:<clientInfo.name>` and the CLI as `cli`. Untrusted input,
2108
- // so sanitise; it labels log lines and nothing else.
2448
+ // The adapter label remains the audit actor even when a session proves
2449
+ // which session it is. It is still a client-supplied label.
2109
2450
  const actorHeader = req.headers['x-shellpuppet-actor'];
2110
2451
  const actor = (typeof actorHeader === 'string'
2111
2452
  ? // eslint-disable-next-line no-control-regex
2112
2453
  actorHeader.replace(/[\x00-\x1f\x7f]/g, '').slice(0, 64)
2113
2454
  : '') || 'client';
2455
+ const caller = this.resolveCallerIdentity(req);
2456
+ if (caller.presented && caller.session === undefined) {
2457
+ this.audit.record(actor, 'refuse', undefined, { reason: 'session identity not recognised' });
2458
+ json(res, 403, { error: 'Session identity was not recognised.' });
2459
+ return;
2460
+ }
2461
+ if (caller.session !== undefined) {
2462
+ const session = this.manager.get(caller.session);
2463
+ const candidates = headerOne(req, 'x-shellpuppet-resume-ids') ?? headerOne(req, 'x-shellpuppet-resume-id');
2464
+ if (candidates)
2465
+ session?.observeResumeId(...candidates.split(','));
2466
+ }
2467
+ return this.callerContext.run(caller.session, () => this.handleClientRequest(req, res, url, segments, actor));
2468
+ }
2469
+ resolveCallerIdentity(req) {
2470
+ const id = req.headers['x-shellpuppet-session'];
2471
+ const token = req.headers['x-shellpuppet-session-token'];
2472
+ return {
2473
+ presented: id !== undefined || token !== undefined,
2474
+ ...(typeof id === 'string' && typeof token === 'string'
2475
+ && this.manager.recognisesCaller(id, token) ? { session: id } : {}),
2476
+ };
2477
+ }
2478
+ verifiedRestartSnapshot(record) {
2479
+ const state = this.publishedState;
2480
+ const snapshot = snapshotSourceId(record);
2481
+ if (!state || !snapshot)
2482
+ return false;
2483
+ let discovery;
2484
+ try {
2485
+ discovery = this.requireHomeOwner();
2486
+ }
2487
+ catch {
2488
+ return false;
2489
+ }
2490
+ if (state.restartCandidates) {
2491
+ const home = this.options.home;
2492
+ const resolved = retryRestartSource(home, state, snapshot, this.logger, () => this.requireHomeOwner());
2493
+ if (resolved.restartCandidates)
2494
+ return false;
2495
+ // Remember a verified writer even when it rules out the rows just read.
2496
+ // A later loss of the source must not revive those older rows.
2497
+ delete state.restartCandidates;
2498
+ delete state.restartSourcePending;
2499
+ Object.assign(state, resolved);
2500
+ if (discovery.kind === 'record') {
2501
+ try {
2502
+ writePrivateRecord(daemonStatePath(home), state, () => {
2503
+ if (this.requireHomeOwner().kind !== 'record')
2504
+ throw new Error('Discovery changed during recovery.');
2505
+ });
2506
+ }
2507
+ catch (error) {
2508
+ this.logger.warn('Could not update restart evidence in daemon.json.', { code: error.code });
2509
+ }
2510
+ }
2511
+ else {
2512
+ void this.keepStatePublished();
2513
+ }
2514
+ }
2515
+ return state.restartFrom === snapshot;
2516
+ }
2517
+ savePreviousSessions() {
2518
+ const endedAt = new Date(this.now()).toISOString();
2519
+ const sessions = this.manager.list().flatMap(summary => {
2520
+ const session = this.manager.get(summary.id);
2521
+ // A deferred start has no participant until the program has started and acquired its name.
2522
+ const participant = this.mailbox.participant(summary.id);
2523
+ if (!participant || !session || session.exited || session.isKilled || !session.launchProfile)
2524
+ return [];
2525
+ return [{ ...session.launchProfile, name: participant.name === session.id ? null : participant.name,
2526
+ agent: session.agent, resumeId: session.resumeId, endedAt }];
2527
+ });
2528
+ writePrivateRecord(path.join(this.options.home, 'previous-sessions.json'), { version: 1, outgoingInstanceId: this.instanceId, sessions });
2529
+ }
2530
+ saveLauncherClaims(excludeId) {
2531
+ const grants = this.launchProfiles.sessionLaunch ?? [];
2532
+ const file = path.join(this.options.home, 'launcher-claims.json');
2533
+ if (!this.claimsRestored)
2534
+ throw new Error('Saved launcher claims could not be restored.');
2535
+ if (grants.length || fs.existsSync(file)) {
2536
+ let discovery = this.requireHomeOwner();
2537
+ const claims = this.mailbox.savedClaims(grants).filter(claim => claim.id !== excludeId);
2538
+ writePrivateRecord(file, claims, () => { discovery = this.requireHomeOwner(); });
2539
+ if (!this.stopping && (discovery.kind === 'missing' || discovery.kind === 'not-a-record')) {
2540
+ void this.keepStatePublished();
2541
+ }
2542
+ }
2543
+ }
2544
+ grantedLauncher(req) {
2545
+ this.lapseIdleClaims();
2546
+ let id = this.callerContext.getStore();
2547
+ if (id === undefined) {
2548
+ const claim = headerOne(req, 'x-shellpuppet-claim');
2549
+ const secret = headerOne(req, 'x-shellpuppet-claim-secret');
2550
+ if (req.headers['x-shellpuppet-inside-session'] === '1' || !claim || !secret ||
2551
+ !this.mailbox.verifyClaim(claim, secret))
2552
+ return undefined;
2553
+ id = claim;
2554
+ }
2555
+ const caller = this.mailbox.participant(id);
2556
+ return caller && this.launchProfiles.sessionLaunch?.includes(caller.name) ? caller : undefined;
2557
+ }
2558
+ messageAudit(action, entry, actor = 'daemon') {
2559
+ this.audit.record(actor, action, entry.from.id, {
2560
+ fromId: entry.from.id, fromName: entry.from.name,
2561
+ toId: entry.to.id, toName: entry.to.name,
2562
+ messageId: entry.id, length: Buffer.byteLength(entry.text, 'utf8'),
2563
+ });
2564
+ }
2565
+ endMailboxParticipant(id) {
2566
+ this.nudges.remove(id);
2567
+ // Audit before end can trim old tombstones from retained history.
2568
+ for (const entry of this.mailbox.log({ participantId: id })) {
2569
+ if (entry.to.id === id && (entry.state === 'waiting' || entry.state === 'nudged')) {
2570
+ this.messageAudit('msg-undelivered', entry);
2571
+ }
2572
+ }
2573
+ this.mailbox.end(id);
2574
+ for (const [ws, participant] of this.eventSockets) {
2575
+ if (participant === id)
2576
+ ws.close();
2577
+ }
2578
+ }
2579
+ lapseIdleClaims() {
2580
+ for (const id of this.mailbox.expiredClaims()) {
2581
+ this.claimCount--;
2582
+ this.endMailboxParticipant(id);
2583
+ this.audit.record('daemon', 'msg-lapse', id);
2584
+ }
2585
+ }
2586
+ async deliverNudge(id) {
2587
+ const session = this.manager.get(id);
2588
+ if (session === undefined || session.exited || this.mailbox.participant(id)?.kind !== 'session')
2589
+ return 'done';
2590
+ const pendingIds = session.nudgePendingLine() !== null ? [...session.nudgePendingIds()] : [];
2591
+ const clearedIds = pendingIds.length > 0 && await session.clearConsumedNudge() ? pendingIds : [];
2592
+ const unread = this.mailbox.inbox(id, { markRead: false });
2593
+ if (clearedIds.length > 0) {
2594
+ this.audit.record('daemon', 'nudge-cleared', id, { messageIds: clearedIds,
2595
+ waitingMessageIds: unread.map((entry) => entry.id) });
2596
+ }
2597
+ const pending = session.nudgePendingLine();
2598
+ if (pending !== null) {
2599
+ const ids = unread.filter((entry) => entry.state === 'waiting').map((entry) => entry.id);
2600
+ if (ids.length === 0)
2601
+ return 'done';
2602
+ const covered = session.nudgePendingIds();
2603
+ if (!session.nudgePendingUntouched()) {
2604
+ if (session.nudgeReadyWithLine(pending) && session.nudgePendingTouchRefusal()) {
2605
+ this.audit.record('daemon', 'nudge-aborted', id, {
2606
+ messageIds: [...covered], count: covered.length, reason: 'person-input-since',
2607
+ });
2608
+ }
2609
+ return 'wait';
2610
+ }
2611
+ if (!session.nudgeReadyWithLine(pending))
2612
+ return 'wait';
2613
+ const inputVersion = session.nudgeInputVersion();
2614
+ const queuedInputVersion = session.nudgeQueuedInputVersion();
2615
+ const screenRevision = session.nudgeScreenRevision();
2616
+ const submitted = await session.submitPendingNudge(pending, (screen) => {
2617
+ const waitingIds = this.mailbox.inbox(id, { markRead: false })
2618
+ .filter((entry) => entry.state === 'waiting').map((entry) => entry.id);
2619
+ return !session.exited && !session.getStalled() &&
2620
+ session.nudgeInputVersion() === inputVersion &&
2621
+ session.nudgeQueuedInputVersion() === queuedInputVersion &&
2622
+ session.nudgeScreenRevision() === screenRevision &&
2623
+ session.answerablePrompt(screen) === null &&
2624
+ waitingIds.length === ids.length &&
2625
+ ids.every((messageId) => waitingIds.includes(messageId));
2626
+ });
2627
+ if (!submitted) {
2628
+ if (session.nudgePendingTouchRefusal()) {
2629
+ this.audit.record('daemon', 'nudge-aborted', id, {
2630
+ messageIds: [...covered], count: covered.length, reason: 'person-input-since',
2631
+ });
2632
+ }
2633
+ return 'wait';
2634
+ }
2635
+ this.mailbox.markNudged(ids);
2636
+ this.audit.record('daemon', 'nudge', id, { messageIds: [...covered], count: covered.length,
2637
+ waitingMessageIds: ids.filter((messageId) => !covered.includes(messageId)),
2638
+ staleMessageIds: covered.filter((messageId) => !unread.some((entry) => entry.id === messageId)) });
2639
+ return 'sent';
2640
+ }
2641
+ // Only a message that has not been nudged yet starts a nudge. One that was
2642
+ // nudged but is still unread (the agent did not read its inbox) is listed
2643
+ // in the line again when a later message arrives, so delivery never stops.
2644
+ const ids = unread.filter((entry) => entry.state === 'waiting').map((entry) => entry.id);
2645
+ if (ids.length === 0)
2646
+ return 'done';
2647
+ const line = buildNudge(unread);
2648
+ if (!session.hasPainted() || !session.nudgeReady(this.now()))
2649
+ return 'wait';
2650
+ const snapshot = await session.snapshot();
2651
+ const state = session.nudgeState(this.now());
2652
+ if (snapshot.exited || session.answerablePrompt(snapshot.screen) !== null || !state.ready)
2653
+ return 'wait';
2654
+ // Check the same region again before typing. A running turn can repaint
2655
+ // its transcript, and a separate sidebar can repaint beside an idle pane.
2656
+ const queued = state.queued;
2657
+ const outputAt = session.lastChangeAt();
2658
+ const inputVersion = session.nudgeInputVersion();
2659
+ const queuedInputVersion = session.nudgeQueuedInputVersion();
2660
+ const screenRevision = session.nudgeScreenRevision();
2661
+ const stillWaiting = () => {
2662
+ const current = this.mailbox.inbox(id, { markRead: false });
2663
+ return ids.every((messageId) => current.some((entry) => entry.id === messageId && entry.state === 'waiting'));
2664
+ };
2665
+ let failedCheck = 'line-not-seen';
2666
+ const ready = (screen, phase) => {
2667
+ if (session.exited) {
2668
+ failedCheck = 'session-ended';
2669
+ return false;
2670
+ }
2671
+ if (session.getStalled()) {
2672
+ failedCheck = 'stalled';
2673
+ return false;
2674
+ }
2675
+ const current = phase === 'before' ? session.nudgeState(this.now()) : undefined;
2676
+ if (session.nudgeScreenRevision() !== screenRevision ||
2677
+ (phase === 'before' && (queued || state.paneQuiet ? current?.regionKey !== state.regionKey
2678
+ : session.lastChangeAt() !== outputAt || screen !== snapshot.screen))) {
2679
+ failedCheck = 'screen-changed';
2680
+ return false;
2681
+ }
2682
+ if (session.nudgeQueuedInputVersion() !== queuedInputVersion ||
2683
+ session.nudgeInputVersion() !== inputVersion + (phase === 'submit' ? 1 : 0)) {
2684
+ failedCheck = 'other-input-arrived';
2685
+ return false;
2686
+ }
2687
+ if (session.answerablePrompt(screen) !== null) {
2688
+ failedCheck = 'prompt-showing';
2689
+ return false;
2690
+ }
2691
+ if (!stillWaiting()) {
2692
+ failedCheck = 'messages-changed';
2693
+ return false;
2694
+ }
2695
+ if (phase === 'before' ? !current?.ready : !session.nudgeReadyWithLine(line)) {
2696
+ failedCheck = 'line-not-seen';
2697
+ return false;
2698
+ }
2699
+ return true;
2700
+ };
2701
+ try {
2702
+ const result = await session.writeNudgeWithReason(line + session.nudgeSubmit(), ready, ids, () => failedCheck);
2703
+ if (result === 'wait')
2704
+ return 'wait';
2705
+ if (result.startsWith('aborted-')) {
2706
+ const reason = result.slice('aborted-'.length);
2707
+ this.audit.record('daemon', 'nudge-aborted', id, { messageIds: ids, count: ids.length, reason });
2708
+ return 'wait';
2709
+ }
2710
+ }
2711
+ catch (error) {
2712
+ if (error instanceof SessionInputFailedError || error instanceof SessionProgramEndedError)
2713
+ return 'wait';
2714
+ throw error;
2715
+ }
2716
+ this.mailbox.markNudged(ids);
2717
+ this.audit.record('daemon', 'nudge', id, { messageIds: ids, count: ids.length, ...(queued ? { queued: true } : {}) });
2718
+ return 'sent';
2719
+ }
2720
+ registerMailboxSession(session, profileName) {
2721
+ const label = profileName ?? session.label;
2722
+ const freeFormGrant = profileName === undefined && this.launchProfiles.sessionLaunch?.includes(label);
2723
+ let name = !freeFormGrant && NAME_PATTERN.test(label) &&
2724
+ (!/^s[0-9]+$/.test(label) || label === session.id) &&
2725
+ !this.mailbox.nameTaken(label) ? label : session.id;
2726
+ if (profileName !== undefined && name === session.id && NAME_PATTERN.test(label) &&
2727
+ !/^s[0-9]+$/.test(label) && !this.isReservedClaimName(label)) {
2728
+ for (let index = 2; index < 10_000; index++) {
2729
+ const candidate = `${label.slice(0, 40 - String(index).length - 1)}-${index}`;
2730
+ if (!this.mailbox.nameTaken(candidate)) {
2731
+ name = candidate;
2732
+ break;
2733
+ }
2734
+ }
2735
+ }
2736
+ this.mailbox.register({ kind: 'session', id: session.id, name, role: session.role });
2737
+ if (NAME_PATTERN.test(session.label))
2738
+ session.label = name;
2739
+ session.onExit(() => this.endMailboxParticipant(session.id));
2740
+ if (session.exited)
2741
+ this.endMailboxParticipant(session.id);
2742
+ }
2743
+ isReservedClaimName(name) {
2744
+ return (this.options.messaging?.allow ?? []).some((rule) => rule !== 'parent-child' && rule.members.includes(name));
2745
+ }
2746
+ async handleMessages(req, res, url, segments, actor) {
2747
+ if (this.options.messaging?.enabled !== true) {
2748
+ json(res, 403, { error: 'Messaging is off.' });
2749
+ return;
2750
+ }
2751
+ this.lapseIdleClaims();
2752
+ const claimId = req.headers['x-shellpuppet-claim'];
2753
+ const claimSecret = req.headers['x-shellpuppet-claim-secret'];
2754
+ const claimPresented = claimId !== undefined || claimSecret !== undefined;
2755
+ const claimValid = typeof claimId === 'string' && typeof claimSecret === 'string' &&
2756
+ this.mailbox.verifyClaim(claimId, claimSecret);
2757
+ const route = segments[1];
2758
+ const creatingClaim = req.method === 'POST' && route === 'claims' && segments.length === 2;
2759
+ if (claimPresented && !claimValid && !creatingClaim) {
2760
+ json(res, 403, { error: 'Messaging claim was not recognised.' });
2761
+ return;
2762
+ }
2763
+ const caller = this.callerContext.getStore() ?? (claimValid ? claimId : undefined);
2764
+ if (creatingClaim) {
2765
+ // Each refusal says only what the daemon knows: a verified session, a valid claim, a mark on the request.
2766
+ if (this.callerContext.getStore() !== undefined) {
2767
+ json(res, 409, { error: 'This session already messages under its own name.' });
2768
+ return;
2769
+ }
2770
+ const marked = req.headers['x-shellpuppet-inside-session'] === '1';
2771
+ if (claimValid || marked) {
2772
+ const reasons = [];
2773
+ if (claimValid) {
2774
+ reasons.push('This client already holds a messaging claim: release it first (msg release), or stop ' +
2775
+ 'presenting it (SHELLPUPPET_CLAIM), to make another.');
2776
+ }
2777
+ if (marked) {
2778
+ reasons.push('This request is marked as coming from inside a ShellPuppet session, and a session ' +
2779
+ 'messages under its own name. A ShellPuppet client adds that mark when SHELLPUPPET_SESSION, ' +
2780
+ 'SHELLPUPPET_SESSION_TOKEN or SHELLPUPPET_DAEMON_INSTANCE is set in its environment; if this is not ' +
2781
+ 'a session, clear them.');
2782
+ }
2783
+ json(res, 409, { error: reasons.join(' ') });
2784
+ return;
2785
+ }
2786
+ const body = await readBody(req);
2787
+ if (typeof body['name'] !== 'string') {
2788
+ json(res, 400, { error: 'A valid name is required.' });
2789
+ return;
2790
+ }
2791
+ const now = this.now();
2792
+ while (this.claimTimes.length > 0 && (this.claimTimes[0] ?? now) <= now - 60_000)
2793
+ this.claimTimes.shift();
2794
+ if (this.claimCount >= 64) {
2795
+ json(res, 429, { error: 'Messaging claim limit reached (64 live claims).' });
2796
+ return;
2797
+ }
2798
+ if (this.claimTimes.length >= 8) {
2799
+ json(res, 429, { error: 'Messaging claim rate reached (8 in 60 seconds).' });
2800
+ return;
2801
+ }
2802
+ const claim = this.mailbox.claim(body['name']);
2803
+ this.claimTimes.push(now);
2804
+ this.claimCount++;
2805
+ if (this.launchProfiles.sessionLaunch?.includes(body['name'])) {
2806
+ try {
2807
+ this.saveLauncherClaims();
2808
+ }
2809
+ catch (error) {
2810
+ this.mailbox.release(claim.claimId);
2811
+ this.claimCount--;
2812
+ throw error;
2813
+ }
2814
+ }
2815
+ this.audit.record(actor, 'msg-claim', claim.claimId, {
2816
+ fromId: claim.claimId, fromName: body['name'], toId: null, toName: null,
2817
+ messageId: null, length: 0, member: this.isReservedClaimName(body['name']),
2818
+ });
2819
+ json(res, 201, claim);
2820
+ return;
2821
+ }
2822
+ if (caller === undefined) {
2823
+ json(res, 403, { error: 'Not a messaging participant.' });
2824
+ return;
2825
+ }
2826
+ if (claimValid)
2827
+ this.mailbox.touchClaim(claimId);
2828
+ if (req.method === 'DELETE' && route === 'claims' && segments.length === 3) {
2829
+ if (!claimValid || claimId !== segments[2]) {
2830
+ json(res, 403, { error: 'The matching claim is required.' });
2831
+ return;
2832
+ }
2833
+ const name = this.mailbox.participant(claimId)?.name;
2834
+ if (name && this.launchProfiles.sessionLaunch?.includes(name))
2835
+ this.saveLauncherClaims(claimId);
2836
+ this.endMailboxParticipant(claimId);
2837
+ this.claimCount--;
2838
+ this.audit.record(actor, 'msg-release', claimId, {
2839
+ fromId: claimId, fromName: name, toId: null, toName: null, messageId: null, length: 0,
2840
+ });
2841
+ json(res, 200, { released: true });
2842
+ return;
2843
+ }
2844
+ const limitText = url.searchParams.get('limit');
2845
+ const limit = limitText === null ? undefined : Number(limitText);
2846
+ if (limit !== undefined && (!Number.isInteger(limit) || limit < 0 || limit > 2000)) {
2847
+ json(res, 400, { error: 'limit must be an integer from 0 to 2000.' });
2848
+ return;
2849
+ }
2850
+ if (req.method === 'POST' && route === undefined) {
2851
+ const body = await readBody(req);
2852
+ const result = this.mailbox.send(caller, body['to'], body['text']);
2853
+ json(res, 201, result);
2854
+ return;
2855
+ }
2856
+ if (req.method === 'GET' && route === 'inbox') {
2857
+ const mark = url.searchParams.get('markRead');
2858
+ if (mark !== null && mark !== 'true' && mark !== 'false') {
2859
+ json(res, 400, { error: 'markRead must be true or false.' });
2860
+ return;
2861
+ }
2862
+ const entries = this.mailbox.inbox(caller, { markRead: mark !== 'false', limit });
2863
+ this.audit.record(actor, 'msg-read', caller, { count: entries.length, source: 'inbox' });
2864
+ json(res, 200, { messages: entries });
2865
+ return;
2866
+ }
2867
+ if (req.method === 'GET' && route === 'outbox') {
2868
+ const messages = this.mailbox.outbox(caller, { limit });
2869
+ this.audit.record(actor, 'msg-read', caller, { count: messages.length, source: 'outbox' });
2870
+ json(res, 200, { messages });
2871
+ return;
2872
+ }
2873
+ if (req.method === 'GET' && route === 'directory') {
2874
+ json(res, 200, { participants: this.mailbox.directory(caller) });
2875
+ return;
2876
+ }
2877
+ if (req.method === 'GET' && route === 'wait') {
2878
+ const raw = url.searchParams.get('timeoutMs');
2879
+ const requested = raw === null ? DEFAULT_WAIT_TIMEOUT_MS : Number(raw);
2880
+ if (!Number.isInteger(requested) || requested < 0) {
2881
+ json(res, 400, { error: 'timeoutMs must be a non-negative integer.' });
2882
+ return;
2883
+ }
2884
+ const controller = new AbortController();
2885
+ const onClose = () => controller.abort();
2886
+ res.on('close', onClose);
2887
+ try {
2888
+ const entry = await this.mailbox.waitForMessage(caller, {
2889
+ ...(url.searchParams.has('from') ? { from: url.searchParams.get('from') } : {}),
2890
+ timeoutMs: Math.min(requested, MAX_WAIT_TIMEOUT_MS), signal: controller.signal,
2891
+ });
2892
+ if (entry !== undefined)
2893
+ this.audit.record(actor, 'msg-read', caller, { count: 1, source: 'wait' });
2894
+ if (!res.destroyed)
2895
+ json(res, 200, { message: entry ?? null });
2896
+ }
2897
+ catch (error) {
2898
+ if (!(error instanceof Error) || error.name !== 'AbortError')
2899
+ throw error;
2900
+ }
2901
+ finally {
2902
+ res.off('close', onClose);
2903
+ }
2904
+ if (claimValid)
2905
+ this.mailbox.touchClaim(claimId);
2906
+ return;
2907
+ }
2908
+ if (req.method === 'GET' && route === 'log') {
2909
+ if (url.searchParams.has('participant') && url.searchParams.get('participant') !== caller) {
2910
+ json(res, 403, { error: 'Log participant must be the caller.' });
2911
+ return;
2912
+ }
2913
+ const messages = this.mailbox.log({ participantId: caller, limit });
2914
+ this.audit.record(actor, 'msg-log', caller, { count: messages.length });
2915
+ json(res, 200, { messages });
2916
+ return;
2917
+ }
2918
+ json(res, 404, { error: 'Messaging route not found.' });
2919
+ }
2920
+ async handleClientRequest(req, res, url, segments, actor) {
2114
2921
  try {
2115
2922
  if (segments[0] === 'daemon' && segments[1] === 'shutdown' && req.method === 'POST') {
2116
2923
  const body = await readBody(req);
2924
+ if (this.stopping) {
2925
+ json(res, 200, { ok: true, stopping: true, warnings: this.shutdownWarnings });
2926
+ return;
2927
+ }
2117
2928
  const force = asBoolean(body['force']) ?? false;
2118
2929
  const live = this.manager.liveCount();
2119
2930
  if (live > 0 && !force) {
@@ -2123,9 +2934,10 @@ export class Daemon {
2123
2934
  });
2124
2935
  return;
2125
2936
  }
2937
+ const stopping = this.stop({ restart: body['restart'] === true });
2126
2938
  this.audit.record(actor, 'shutdown', undefined, { force, liveSessions: live });
2127
- json(res, 200, { ok: true, stopping: true });
2128
- void this.stop().then(() => {
2939
+ json(res, 200, { ok: true, stopping: true, warnings: this.shutdownWarnings });
2940
+ void stopping.then(() => {
2129
2941
  this.options.onSelfStop?.('shutdown-request');
2130
2942
  });
2131
2943
  return;
@@ -2144,6 +2956,47 @@ export class Daemon {
2144
2956
  await this.handleDesktopOpen(req, res, actor);
2145
2957
  return;
2146
2958
  }
2959
+ if (url.pathname === '/launcher/previous' && req.method === 'GET') {
2960
+ if (!this.grantedLauncher(req)) {
2961
+ json(res, 403, { error: 'Session launch permission required.' });
2962
+ return;
2963
+ }
2964
+ const file = path.join(this.options.home, 'previous-sessions.json');
2965
+ try {
2966
+ // Older version 1 records used the generated session id as an explicit name.
2967
+ const record = JSON.parse(fs.readFileSync(file, 'utf8'), (key, value) => key === 'name' && typeof value === 'string' && /^s[0-9]+$/.test(value) ? null : value);
2968
+ if (!this.verifiedRestartSnapshot(record)) {
2969
+ json(res, 409, { error: 'No verified session snapshot is available for the previous restart.' });
2970
+ return;
2971
+ }
2972
+ json(res, 200, record);
2973
+ }
2974
+ catch (error) {
2975
+ if (error.code === 'ENOENT') {
2976
+ json(res, 409, { error: 'No verified session snapshot is available for the previous restart.' });
2977
+ }
2978
+ else
2979
+ json(res, 500, { error: 'The previous sessions record could not be read.' });
2980
+ }
2981
+ return;
2982
+ }
2983
+ if (url.pathname === '/launcher/launch' && req.method === 'POST') {
2984
+ const caller = this.grantedLauncher(req);
2985
+ if (!caller) {
2986
+ json(res, 403, { error: 'Session launch permission required.' });
2987
+ return;
2988
+ }
2989
+ if ((headerOne(req, 'content-type') ?? '').split(';')[0]?.trim().toLowerCase() !== 'application/json') {
2990
+ json(res, 415, { error: 'The launch body must be JSON.' });
2991
+ return;
2992
+ }
2993
+ await this.launchProfile(req, res, { launcher: caller });
2994
+ return;
2995
+ }
2996
+ if (segments[0] === 'messages') {
2997
+ await this.handleMessages(req, res, url, segments, actor);
2998
+ return;
2999
+ }
2147
3000
  if (segments[0] !== 'sessions') {
2148
3001
  json(res, 404, { error: 'Not found.', path: url.pathname });
2149
3002
  return;
@@ -2345,43 +3198,149 @@ export class Daemon {
2345
3198
  json(res, 400, { error: BAD_HIDE_REASONING });
2346
3199
  return;
2347
3200
  }
2348
- if (!hide) {
3201
+ // Fails closed: without a signature to read the screen by, nothing
3202
+ // is returned, never the screen unfiltered.
3203
+ const signature = hide ? this.readerFor(session, res) : null;
3204
+ if (hide && signature === null)
3205
+ return;
3206
+ const read = async () => {
2349
3207
  const snapshot = await session.snapshot();
2350
- json(res, 200, count === undefined ? snapshot : { ...snapshot, lastLines: await session.lastLines(count) });
3208
+ if (signature === null)
3209
+ return count === undefined ? { ...snapshot } : { ...snapshot, lastLines: await session.lastLines(count) };
3210
+ const view = await session.styledScreen(REASONING_CONTEXT_LINES);
3211
+ const screen = hideReasoning(view.lines, signature, view.firstVisible);
3212
+ let tail;
3213
+ let tailSource;
3214
+ if (count !== undefined) {
3215
+ tailSource = await session.styledTail(count, REASONING_CONTEXT_LINES);
3216
+ tail = hideReasoning(tailSource.lines, signature, tailSource.firstVisible);
3217
+ }
3218
+ if (screen === null || tail === null) {
3219
+ json(res, 400, { error: overBudgetMessage(signature) });
3220
+ return null;
3221
+ }
3222
+ return {
3223
+ ...snapshot,
3224
+ screen: markFilteredSelectedOption(screen.lines, view.lines, session.agent).join('\n'),
3225
+ cursor: filteredCursor(snapshot.cursor, screen),
3226
+ ...(tail !== undefined && tailSource !== undefined
3227
+ ? { lastLines: markFilteredSelectedOption(tail.lines, tailSource.lines, session.agent) }
3228
+ : {}),
3229
+ reasoning: {
3230
+ agent: signature.name,
3231
+ hiddenLines: screen.hiddenLines,
3232
+ hiddenBlocks: screen.hiddenBlocks,
3233
+ ...(tail !== undefined ? { lastLinesHiddenLines: tail.hiddenLines } : {}),
3234
+ },
3235
+ };
3236
+ };
3237
+ const wider = url.searchParams.get('wider');
3238
+ if (wider === null) {
3239
+ const payload = await read();
3240
+ if (payload !== null)
3241
+ json(res, 200, payload);
2351
3242
  return;
2352
3243
  }
2353
- // Fails closed: without a signature to read the screen by, nothing
2354
- // is returned, never the screen unfiltered.
2355
- const signature = this.readerFor(session, res);
2356
- if (signature === null)
3244
+ const match = /^(\d+)x(\d+)$/.exec(wider);
3245
+ const cols = match === null ? undefined : Number(match[1]);
3246
+ const rows = match === null ? undefined : Number(match[2]);
3247
+ if (cols === undefined || rows === undefined || !Number.isInteger(cols) || !Number.isInteger(rows) ||
3248
+ cols < MIN_GRID_SIDE || rows < MIN_GRID_SIDE || cols > MAX_VIEWPORT_COLS || rows > MAX_VIEWPORT_ROWS) {
3249
+ json(res, 400, { error: `wider must be COLSxROWS with 2 to ${MAX_VIEWPORT_COLS} columns and 2 to ${MAX_VIEWPORT_ROWS} rows.` });
2357
3250
  return;
2358
- const snapshot = await session.snapshot();
2359
- const view = await session.styledScreen(REASONING_CONTEXT_LINES);
2360
- const screen = hideReasoning(view.lines, signature, view.firstVisible);
2361
- let tail;
2362
- let tailSource;
2363
- if (count !== undefined) {
2364
- tailSource = await session.styledTail(count, REASONING_CONTEXT_LINES);
2365
- tail = hideReasoning(tailSource.lines, signature, tailSource.firstVisible);
2366
- }
2367
- if (screen === null || tail === null) {
2368
- json(res, 400, { error: overBudgetMessage(signature) });
3251
+ }
3252
+ const timeoutParam = url.searchParams.get('widerTimeout');
3253
+ const timeout = timeoutParam === null ? 1500 : Number(timeoutParam);
3254
+ if (!Number.isInteger(timeout) || timeout < 250 || timeout > 30_000) {
3255
+ json(res, 400, { error: 'widerTimeout must be an integer from 250 to 30000 ms.' });
2369
3256
  return;
2370
3257
  }
2371
- json(res, 200, {
2372
- ...snapshot,
2373
- screen: markFilteredSelectedOption(screen.lines, view.lines).join('\n'),
2374
- cursor: filteredCursor(snapshot.cursor, screen),
2375
- ...(tail !== undefined && tailSource !== undefined
2376
- ? { lastLines: markFilteredSelectedOption(tail.lines, tailSource.lines) }
2377
- : {}),
2378
- reasoning: {
2379
- agent: signature.name,
2380
- hiddenLines: screen.hiddenLines,
2381
- hiddenBlocks: screen.hiddenBlocks,
2382
- ...(tail !== undefined ? { lastLinesHiddenLines: tail.hiddenLines } : {}),
2383
- },
2384
- });
3258
+ if (session.exited) {
3259
+ json(res, 409, { error: endedRefusal(id, session.exitCode, session.fault) });
3260
+ return;
3261
+ }
3262
+ if (session.geometryHeld) {
3263
+ json(res, 409, { error: 'The grid is held by its owner; a wider read cannot resize it.' });
3264
+ return;
3265
+ }
3266
+ if (this.widerReads.has(id)) {
3267
+ json(res, 409, { error: 'A wider read is already in progress for this session.' });
3268
+ return;
3269
+ }
3270
+ const abort = new AbortController();
3271
+ let finish = () => undefined;
3272
+ const done = new Promise((resolve) => { finish = resolve; });
3273
+ const onClose = () => { if (!res.writableEnded)
3274
+ abort.abort(); };
3275
+ res.on('close', onClose);
3276
+ const original = { cols: session.cols, rows: session.rows };
3277
+ const requested = { cols, rows };
3278
+ const target = { cols: Math.max(cols, original.cols), rows: Math.max(rows, original.rows) };
3279
+ const epoch = this.geometryEpoch.get(id) ?? 0;
3280
+ const announce = () => { if (!session.exited)
3281
+ this.announceGeometry(id, session); };
3282
+ const isTemporary = () => (target.cols !== original.cols || target.rows !== original.rows) &&
3283
+ session.cols === target.cols && session.rows === target.rows && (this.geometryEpoch.get(id) ?? 0) === epoch;
3284
+ this.widerReads.set(id, { abort, done, isTemporary });
3285
+ let payload = null;
3286
+ let restored = true;
3287
+ let readError;
3288
+ this.audit.record(actor, 'wider-read', id, { requested, original });
3289
+ try {
3290
+ if (target.cols !== original.cols || target.rows !== original.rows) {
3291
+ await session.resize(target.cols, target.rows);
3292
+ announce();
3293
+ }
3294
+ const settled = await session.waitFor({ quiet: 250 }, {
3295
+ timeout,
3296
+ quietSince: Date.now(),
3297
+ signal: abort.signal,
3298
+ });
3299
+ if (settled.reason === 'exited' || session.exited) {
3300
+ readError = new SessionProgramEndedError(id, session.exitCode);
3301
+ }
3302
+ else if (!abort.signal.aborted) {
3303
+ payload = await read();
3304
+ }
3305
+ }
3306
+ catch (error) {
3307
+ readError = error;
3308
+ }
3309
+ finally {
3310
+ try {
3311
+ // Only a deliberate geometry act wins. A departing controller does
3312
+ // not choose a new size; keep the control state its departure left.
3313
+ const mayRestore = () => (this.geometryEpoch.get(id) ?? 0) === epoch &&
3314
+ !session.geometryHeld && !session.exited &&
3315
+ session.cols === target.cols && session.rows === target.rows;
3316
+ restored = target.cols === original.cols && target.rows === original.rows
3317
+ ? mayRestore()
3318
+ : await session.resizeIfCurrent(original.cols, original.rows, mayRestore, announce);
3319
+ }
3320
+ catch (error) {
3321
+ // node-pty can record the program's code before the exit event.
3322
+ if (error instanceof SessionProgramEndedError || readError === undefined)
3323
+ readError = error;
3324
+ restored = false;
3325
+ }
3326
+ finally {
3327
+ res.off('close', onClose);
3328
+ this.widerReads.delete(id);
3329
+ finish();
3330
+ }
3331
+ }
3332
+ if (abort.signal.aborted || res.writableEnded)
3333
+ return;
3334
+ if (session.exited || readError instanceof SessionProgramEndedError) {
3335
+ const code = readError instanceof SessionProgramEndedError ? readError.exitCode : session.exitCode;
3336
+ json(res, 409, { error: endedRefusal(id, code, session.fault) });
3337
+ }
3338
+ else if (readError !== undefined) {
3339
+ throw readError instanceof Error ? readError : new Error('Wider read failed with a non-Error value.');
3340
+ }
3341
+ else if (payload !== null) {
3342
+ json(res, 200, { ...payload, restored });
3343
+ }
2385
3344
  return;
2386
3345
  }
2387
3346
  if (req.method === 'GET' && action === 'result') {
@@ -2427,9 +3386,9 @@ export class Daemon {
2427
3386
  // caller's request for a race in the session's lifetime. A session
2428
3387
  // whose input pipe has failed refuses the write too, and its error
2429
3388
  // says what to do.
2430
- let before;
3389
+ let written;
2431
3390
  try {
2432
- before = await session.write(data);
3391
+ written = await session.writeWithResult(data);
2433
3392
  }
2434
3393
  catch (error) {
2435
3394
  json(res, 409, {
@@ -2454,11 +3413,18 @@ export class Daemon {
2454
3413
  json(res, 200, {
2455
3414
  ok: true,
2456
3415
  bytes: data.length,
2457
- verified: await this.verifyTyped(session, data, before),
3416
+ verified: await this.verifyTyped(session, data, written.before),
3417
+ ...(written.submitted !== undefined ? { submitted: written.submitted } : {}),
3418
+ ...(written.submitRetried ? { submitRetried: true } : {}),
3419
+ ...(written.message !== undefined ? { message: written.message } : {}),
2458
3420
  });
2459
3421
  return;
2460
3422
  }
2461
- json(res, 200, { ok: true, bytes: data.length });
3423
+ json(res, 200, { ok: true, bytes: data.length,
3424
+ ...(written.submitted !== undefined ? { submitted: written.submitted } : {}),
3425
+ ...(written.submitRetried ? { submitRetried: true } : {}),
3426
+ ...(written.message !== undefined ? { message: written.message } : {}),
3427
+ });
2462
3428
  return;
2463
3429
  }
2464
3430
  if (req.method === 'POST' && action === 'key') {
@@ -2497,14 +3463,20 @@ export class Daemon {
2497
3463
  json(res, 400, { error: BAD_HIDE_REASONING });
2498
3464
  return;
2499
3465
  }
2500
- const reader = hide ? this.readerFor(session, res) : null;
2501
- if (hide && reader === null)
3466
+ const stalled = queryFlag(url, 'stalled');
3467
+ if (stalled === null) {
3468
+ json(res, 400, { error: 'stalled must be true or false.' });
3469
+ return;
3470
+ }
3471
+ const prompt = url.searchParams.get('prompt');
3472
+ const metadataOnly = stalled && (prompt === null || prompt === 'false' || prompt === '0');
3473
+ const reader = hide && !metadataOnly ? this.readerFor(session, res) : null;
3474
+ if (hide && !metadataOnly && reader === null)
2502
3475
  return;
2503
3476
  const condition = {};
2504
3477
  const text = url.searchParams.get('text');
2505
3478
  const regex = url.searchParams.get('regex');
2506
3479
  const quiet = url.searchParams.get('quiet');
2507
- const prompt = url.searchParams.get('prompt');
2508
3480
  if (text !== null)
2509
3481
  condition.text = text;
2510
3482
  if (regex !== null)
@@ -2516,8 +3488,10 @@ export class Daemon {
2516
3488
  // `prompt === true` only.
2517
3489
  if (prompt !== null)
2518
3490
  condition.prompt = prompt !== 'false' && prompt !== '0';
3491
+ if (stalled)
3492
+ condition.stalled = true;
2519
3493
  const filteredMatch = reader !== null && (condition.text !== undefined || condition.regex !== undefined || condition.prompt === true);
2520
- const muse = signatureFor(session.agent, session.command);
3494
+ const pendingReader = signatureForSession(session);
2521
3495
  let matchView;
2522
3496
  const timeoutParam = url.searchParams.get('timeout');
2523
3497
  const debounceParam = url.searchParams.get('debounce');
@@ -2545,12 +3519,12 @@ export class Daemon {
2545
3519
  ? { matchAfterInput: afterInputParam !== 'false' && afterInputParam !== '0' }
2546
3520
  : {}),
2547
3521
  ...(filteredMatch ? { screenForMatch: () => {
2548
- matchView = filteredWaitScreen(session, reader);
3522
+ matchView = filteredWaitScreen(session, reader, condition.prompt === true);
2549
3523
  return matchView.screen;
2550
- } } : {}),
2551
- ...(muse?.name === 'muse' ? {
3524
+ }, stylesForMatch: () => matchView?.styled } : {}),
3525
+ ...(pendingReader !== null && moduleFor(session.agent)?.readingRules?.pendingComposer === true ? {
2552
3526
  composerPending: () => {
2553
- const result = latestResult(session.styledScreenNow(REASONING_CONTEXT_LINES).lines, muse);
3527
+ const result = latestResult(session.styledScreenNow(REASONING_CONTEXT_LINES).lines, pendingReader);
2554
3528
  return !result.found && result.reason === 'prompt-typed';
2555
3529
  },
2556
3530
  } : {}),
@@ -2564,6 +3538,10 @@ export class Daemon {
2564
3538
  // Nobody to answer, and writing to a closed response throws.
2565
3539
  if (abort.signal.aborted)
2566
3540
  return;
3541
+ if (result.reason === 'stalled') {
3542
+ json(res, 200, { ...result, id: session.id, exited: session.exited, exitCode: session.exitCode });
3543
+ return;
3544
+ }
2567
3545
  if (reader !== null) {
2568
3546
  if (filteredMatch && matchView !== undefined) {
2569
3547
  json(res, 200, {
@@ -2583,10 +3561,10 @@ export class Daemon {
2583
3561
  json(res, 400, { error: overBudgetMessage(reader) });
2584
3562
  return;
2585
3563
  }
2586
- const marked = markFilteredSelectedOption(filtered.lines, view.lines);
3564
+ const marked = markFilteredSelectedOption(filtered.lines, view.lines, session.agent);
2587
3565
  const visiblePrompt = result.prompt === undefined
2588
3566
  ? null
2589
- : detectPrompt(marked.join('\n'));
3567
+ : detectPrompt(marked.join('\n'), session.agent, undefined, filteredPromptStyles(filtered, view));
2590
3568
  const prompt = visiblePrompt !== null && visiblePrompt.signature === result.prompt?.signature
2591
3569
  ? {
2592
3570
  question: visiblePrompt.question,
@@ -2682,7 +3660,16 @@ export class Daemon {
2682
3660
  }
2683
3661
  const hold = body['hold'] === true;
2684
3662
  try {
2685
- await session.resize(cols, rows, { hold });
3663
+ await session.resize(cols, rows, { hold, onApplied: () => {
3664
+ this.audit.record(actor, 'resize', id, { cols, rows, hold });
3665
+ this.geometryEpoch.set(id, (this.geometryEpoch.get(id) ?? 0) + 1);
3666
+ // An API resize takes the grid away from whichever viewport had it.
3667
+ this.geometryController.delete(id);
3668
+ this.dashboardGeometryOwner.delete(id);
3669
+ this.dashboardCredentialOwner.delete(id);
3670
+ this.dashboardTransferable.delete(id);
3671
+ this.announceGeometry(id, session);
3672
+ } });
2686
3673
  }
2687
3674
  catch (error) {
2688
3675
  if (!(error instanceof SessionProgramEndedError))
@@ -2690,21 +3677,35 @@ export class Daemon {
2690
3677
  json(res, 409, { error: endedRefusal(id, error.exitCode) });
2691
3678
  return;
2692
3679
  }
2693
- this.audit.record(actor, 'resize', id, { cols, rows, hold });
2694
- // An API resize takes the grid away from whichever viewport had it, so
2695
- // nobody is left believing they still drive it. It does NOT hold
2696
- // unless asked: a human whose window is now the wrong shape gets it
2697
- // back by moving that window, which is the only escape they have while
2698
- // there is no takeover control to press (§5).
2699
- this.geometryController.delete(id);
2700
- this.dashboardGeometryOwner.delete(id);
2701
- this.announceGeometry(id, session);
2702
3680
  json(res, 200, { ok: true, cols, rows, geometryHeld: session.geometryHeld });
2703
3681
  return;
2704
3682
  }
2705
3683
  json(res, 404, { error: 'Not found.', path: url.pathname });
2706
3684
  }
2707
3685
  catch (error) {
3686
+ if (error instanceof HomeOwnershipError) {
3687
+ json(res, 409, { error: error.message });
3688
+ return;
3689
+ }
3690
+ if (error instanceof MailboxError) {
3691
+ const status = error.code === 'unknown-name' ? 404 :
3692
+ error.code === 'not-allowed' || error.code === 'unknown-sender' ? 403 :
3693
+ error.code === 'duplicate-name' || error.code === 'mailbox-full' ? 409 : 400;
3694
+ const messages = {
3695
+ 'invalid-name': 'A valid participant name is required.',
3696
+ 'duplicate-name': 'That participant name is already held.',
3697
+ 'duplicate-id': 'That participant id is already held.',
3698
+ 'messaging-disabled': 'Messaging is off.',
3699
+ 'unknown-sender': 'Not a messaging participant.',
3700
+ 'unknown-name': 'No live participant has that name.',
3701
+ 'not-allowed': error.message,
3702
+ 'empty-text': 'A message cannot be empty.',
3703
+ 'text-too-large': 'A message exceeds the 16 KiB limit.',
3704
+ 'mailbox-full': 'The mailbox is full.',
3705
+ };
3706
+ json(res, status, { error: messages[error.code] });
3707
+ return;
3708
+ }
2708
3709
  if (error instanceof WaitConditionError) {
2709
3710
  json(res, 400, { error: error.message });
2710
3711
  return;
@@ -2780,6 +3781,9 @@ export class Daemon {
2780
3781
  // diverge from the audit trail. Self-declared, not authenticated: see
2781
3782
  // SessionOptions.startedBy.
2782
3783
  startedBy: actor,
3784
+ ...(this.callerContext.getStore() !== undefined ? { parent: this.callerContext.getStore() } : {}),
3785
+ ...(body['waitReady'] === true ? { waitReady: true } : {}),
3786
+ ...(asNumber(body['readyTimeout']) !== undefined ? { readyTimeout: asNumber(body['readyTimeout']) } : {}),
2783
3787
  ...(asString(body['readyText']) !== undefined
2784
3788
  ? { readyText: asString(body['readyText']) }
2785
3789
  : {}),
@@ -2800,7 +3804,7 @@ export class Daemon {
2800
3804
  json(res, 403, { error: error.message });
2801
3805
  return;
2802
3806
  }
2803
- if (error instanceof CommandNotFoundError) {
3807
+ if (error instanceof CommandNotFoundError || error instanceof WaitConditionError) {
2804
3808
  json(res, 400, { error: error.message });
2805
3809
  return;
2806
3810
  }
@@ -2832,15 +3836,19 @@ export class Daemon {
2832
3836
  session = startedSession;
2833
3837
  // Registration is synchronous with creation, before any asynchronous
2834
3838
  // viewer launch or readiness work can publish a change for this id.
3839
+ this.registerMailboxSession(session);
2835
3840
  this.sessionFeed.add(this.summaryWithPrompt(session.summary()));
2836
3841
  session.onExit(() => {
2837
3842
  this.clearPromptGraceCheck(session.id);
2838
3843
  this.promptStates.delete(session.id);
2839
3844
  this.geometryController.delete(session.id);
2840
3845
  this.dashboardGeometryOwner.delete(session.id);
3846
+ this.dashboardCredentialOwner.delete(session.id);
3847
+ this.dashboardTransferable.delete(session.id);
2841
3848
  this.updateFeedSession(session.id);
2842
3849
  });
2843
3850
  session.onReady(() => this.updateFeedSession(session.id));
3851
+ this.watchStalls(session);
2844
3852
  // Commands are policy-visible by definition, so the command line IS
2845
3853
  // audited (§4.5), unlike typed content. Passed variables are audited by
2846
3854
  // name only, whatever `audit.captureContent` says: a value is a secret
@@ -2849,7 +3857,7 @@ export class Daemon {
2849
3857
  command: options.command,
2850
3858
  args: options.args ?? [],
2851
3859
  ...(envNames.length > 0 ? { envNames } : {}),
2852
- ...(agent !== undefined ? { agent } : {}),
3860
+ agent: session.agent,
2853
3861
  label: session.label,
2854
3862
  });
2855
3863
  // The human's way in (design §3.1): the dashboard, a single-session viewer
@@ -2919,6 +3927,15 @@ export class Daemon {
2919
3927
  const handOver = wantsViewer && !dashboardWatching && !opened.launched && viewerUrl !== '';
2920
3928
  if (handOver)
2921
3929
  this.audit.record(actor, 'grant-mint', session.id, { readOnly: false });
3930
+ const cancelled = new AbortController();
3931
+ const onClose = () => cancelled.abort();
3932
+ res.on('close', onClose);
3933
+ if (res.destroyed)
3934
+ cancelled.abort();
3935
+ const readyWait = options.waitReady === true
3936
+ ? await session.waitUntilReady(options.readyTimeout, cancelled.signal)
3937
+ : undefined;
3938
+ res.off('close', onClose);
2922
3939
  json(res, 200, {
2923
3940
  id: session.id,
2924
3941
  label: session.label,
@@ -2929,6 +3946,7 @@ export class Daemon {
2929
3946
  // Without the reason, `ready: true` is ambiguous: it may mean nothing
2930
3947
  // was checked. Callers need to tell those apart before they type.
2931
3948
  readyReason: session.readyReason,
3949
+ ...(readyWait === undefined ? {} : { readyWait, exited: session.exited, exitCode: session.exitCode }),
2932
3950
  geometryHeld: session.geometryHeld,
2933
3951
  viewer: {
2934
3952
  opened: opened.launched,
@@ -2944,12 +3962,12 @@ export class Daemon {
2944
3962
  * readers fail closed.
2945
3963
  */
2946
3964
  readerFor(session, res) {
2947
- const signature = signatureFor(session.agent, session.command);
3965
+ const signature = signatureForSession(session);
2948
3966
  if (signature !== null)
2949
3967
  return signature;
2950
3968
  const known = agentNames().join(', ');
2951
3969
  json(res, 400, {
2952
- error: session.agent !== undefined
3970
+ error: session.agentSource !== 'fallback'
2953
3971
  ? `Session ${session.id} was started as agent "${session.agent}", whose signature is not ` +
2954
3972
  `available now (removed from config, or set aside for running past its time budget), ` +
2955
3973
  `so its screen is not read for hideReasoning or a result.`
@@ -3034,6 +4052,9 @@ export class Daemon {
3034
4052
  this.sessionSockets.delete(id);
3035
4053
  this.geometryController.delete(id);
3036
4054
  this.dashboardGeometryOwner.delete(id);
4055
+ this.dashboardCredentialOwner.delete(id);
4056
+ this.dashboardTransferable.delete(id);
4057
+ this.geometryEpoch.delete(id);
3037
4058
  }
3038
4059
  /** Whether a live viewport is currently driving this session's grid. */
3039
4060
  hasGeometryController(sessionId) {
@@ -3079,7 +4100,8 @@ export class Daemon {
3079
4100
  }
3080
4101
  /** The sessions a client or the dashboard may see: every one but those still starting. */
3081
4102
  listedSummaries() {
3082
- return this.manager.list().filter((summary) => !this.startingIds.has(summary.id));
4103
+ return this.manager.list().filter((summary) => !this.startingIds.has(summary.id))
4104
+ .map((summary) => ({ ...summary, name: this.mailbox.participant(summary.id)?.name ?? summary.id }));
3083
4105
  }
3084
4106
  /**
3085
4107
  * Session list decorated with whatever prompt each session is holding. The
@@ -3096,7 +4118,7 @@ export class Daemon {
3096
4118
  * against prompts that sit for minutes.
3097
4119
  */
3098
4120
  listWithPrompts(hideReasoning = false) {
3099
- const now = Date.now();
4121
+ const now = this.now();
3100
4122
  return this.listedSummaries().map((summary) => {
3101
4123
  const full = this.summaryWithPrompt(summary, now);
3102
4124
  const waiting = full.waitingOnPrompt;
@@ -3105,7 +4127,10 @@ export class Daemon {
3105
4127
  return { ...full, waitingOnPrompt: { waitingMs: waiting.waitingMs, alerted: waiting.alerted } };
3106
4128
  });
3107
4129
  }
3108
- summaryWithPrompt(summary, now = Date.now()) {
4130
+ summaryWithPrompt(summary, now = this.now()) {
4131
+ summary = { ...summary, name: this.mailbox.participant(summary.id)?.name ?? summary.id };
4132
+ if (summary.stalled?.reason === 'server-lost')
4133
+ return summary;
3109
4134
  const state = this.promptStates.get(summary.id);
3110
4135
  if (state === undefined)
3111
4136
  return summary;
@@ -3125,6 +4150,30 @@ export class Daemon {
3125
4150
  if (session !== undefined)
3126
4151
  this.sessionFeed.update(this.summaryWithPrompt(session.summary()));
3127
4152
  }
4153
+ /** One transition drives the feed, audit, log and both notification channels. */
4154
+ watchStalls(session) {
4155
+ session.onStall((stalled) => {
4156
+ if (stalled?.reason === 'server-lost') {
4157
+ // The covered dialog cannot be answered. End its old alert now so the
4158
+ // next scan cannot leave a waiting badge beside the stall notice.
4159
+ const held = this.promptStates.get(session.id);
4160
+ this.clearPromptGraceCheck(session.id);
4161
+ this.promptStates.delete(session.id);
4162
+ if (held?.alerted === true) {
4163
+ this.emitEvent({ type: 'prompt-clear', session: session.id, label: session.label ?? null });
4164
+ this.broadcastControl(session.id, { type: 'prompt-clear' });
4165
+ }
4166
+ }
4167
+ this.updateFeedSession(session.id);
4168
+ const type = stalled === undefined ? 'session-stall-clear' : 'session-stalled';
4169
+ const details = stalled === undefined ? {} : { stalled };
4170
+ this.audit.record('daemon', type, session.id, details);
4171
+ if (stalled !== undefined)
4172
+ this.logger.warn('session stalled', { id: session.id, ...details });
4173
+ this.emitEvent({ type, session: session.id, ...details });
4174
+ this.broadcastControl(session.id, { type, ...details });
4175
+ });
4176
+ }
3128
4177
  clearPromptGraceCheck(id) {
3129
4178
  const timer = this.promptGraceTimers.get(id);
3130
4179
  if (timer !== undefined)
@@ -3190,8 +4239,8 @@ export class Daemon {
3190
4239
  // scan interval; a lasting disappearance still clears it.
3191
4240
  if (previous !== undefined) {
3192
4241
  if (previous.missingSince === null)
3193
- previous.missingSince = Date.now();
3194
- const remaining = previous.missingSince + PROMPT_REPAINT_GRACE_MS - Date.now();
4242
+ previous.missingSince = this.now();
4243
+ const remaining = previous.missingSince + PROMPT_REPAINT_GRACE_MS - this.now();
3195
4244
  if (remaining > 0) {
3196
4245
  this.schedulePromptGraceCheck(session.id, remaining);
3197
4246
  continue;
@@ -3259,7 +4308,7 @@ export class Daemon {
3259
4308
  }
3260
4309
  this.promptStates.set(session.id, {
3261
4310
  signature: detected.signature,
3262
- since: Date.now(),
4311
+ since: this.now(),
3263
4312
  alerted: false,
3264
4313
  prompt: detected,
3265
4314
  missingSince: null,
@@ -3271,10 +4320,10 @@ export class Daemon {
3271
4320
  previous.signature = detected.signature;
3272
4321
  if (promptChanged)
3273
4322
  this.updateFeedSession(session.id);
3274
- if (!previous.alerted && Date.now() - previous.since >= stallMs) {
4323
+ if (!previous.alerted && this.now() - previous.since >= stallMs) {
3275
4324
  previous.alerted = true;
3276
4325
  this.updateFeedSession(session.id);
3277
- const waitingMs = Date.now() - previous.since;
4326
+ const waitingMs = this.now() - previous.since;
3278
4327
  this.audit.record('daemon', 'prompt-stall', session.id);
3279
4328
  this.logger.warn('session waiting on a prompt', {
3280
4329
  id: session.id,
@@ -3312,15 +4361,34 @@ export class Daemon {
3312
4361
  this.updateFeedSession(id);
3313
4362
  }
3314
4363
  }
4364
+ await this.nudges.tick();
3315
4365
  }
3316
4366
  /** Fan an event out to every `/events` subscriber (TEXT JSON frames). */
3317
4367
  emitEvent(event) {
3318
4368
  const message = JSON.stringify({ ...event, at: new Date().toISOString() });
3319
- for (const ws of this.eventSockets) {
4369
+ for (const ws of this.eventSockets.keys()) {
3320
4370
  if (ws.readyState === ws.OPEN)
3321
4371
  ws.send(message);
3322
4372
  }
3323
4373
  }
4374
+ emitMessageEvent(event, entry) {
4375
+ if (entry === undefined)
4376
+ return;
4377
+ const message = JSON.stringify({ ...event, at: new Date().toISOString() });
4378
+ for (const [ws, participant] of this.eventSockets) {
4379
+ if (ws.readyState === ws.OPEN && participant !== undefined &&
4380
+ (participant === entry.from.id || participant === entry.to.id))
4381
+ ws.send(message);
4382
+ }
4383
+ }
4384
+ /** Dashboard notifications carry metadata only; the page fetches text separately. */
4385
+ emitDashboardMessageEvent(event) {
4386
+ const frame = JSON.stringify({ ...event, at: new Date().toISOString() });
4387
+ for (const ws of this.dashboardEventSockets) {
4388
+ if (ws.readyState === ws.OPEN)
4389
+ ws.send(frame);
4390
+ }
4391
+ }
3324
4392
  // ------------------------------------------------------------- websockets
3325
4393
  handleUpgrade(req, socket, head) {
3326
4394
  // Node takes its own 'error' listener off the socket before it emits
@@ -3365,14 +4433,14 @@ export class Daemon {
3365
4433
  // The dashboard feed is cookie-only. Its Origin rule is stricter than the
3366
4434
  // client-token sockets below, which still allow a missing Origin.
3367
4435
  if (segments[0] === 'dashboard' && segments[1] === 'events' && segments.length === 2) {
3368
- const refusal = this.dashboardUpgradeRefusal(req);
3369
- if (refusal !== null) {
3370
- this.auditDashboardRefusal(req, refusal.audit);
3371
- reject(refusal.code, refusal.reason);
4436
+ const credential = this.dashboardUpgradeCredential(req);
4437
+ if (typeof credential !== 'string') {
4438
+ this.auditDashboardRefusal(req, credential.audit);
4439
+ reject(credential.code, credential.reason);
3372
4440
  return;
3373
4441
  }
3374
4442
  this.wss.handleUpgrade(req, socket, head, (ws) => {
3375
- this.attachDashboardSocket(ws);
4443
+ this.attachDashboardSocket(ws, credential);
3376
4444
  });
3377
4445
  return;
3378
4446
  }
@@ -3386,8 +4454,24 @@ export class Daemon {
3386
4454
  reject(401, 'Unauthorized');
3387
4455
  return;
3388
4456
  }
4457
+ const caller = this.resolveCallerIdentity(req);
4458
+ if (caller.presented && caller.session === undefined) {
4459
+ this.audit.record('client', 'refuse', undefined, { reason: 'session identity not recognised' });
4460
+ reject(403, 'Forbidden');
4461
+ return;
4462
+ }
4463
+ const claimId = req.headers['x-shellpuppet-claim'];
4464
+ const claimSecret = req.headers['x-shellpuppet-claim-secret'];
4465
+ const claimPresented = claimId !== undefined || claimSecret !== undefined;
4466
+ if (claimPresented)
4467
+ this.lapseIdleClaims();
4468
+ if (claimPresented && (typeof claimId !== 'string' || typeof claimSecret !== 'string' ||
4469
+ !this.mailbox.verifyClaim(claimId, claimSecret))) {
4470
+ reject(403, 'Forbidden');
4471
+ return;
4472
+ }
3389
4473
  this.wss.handleUpgrade(req, socket, head, (ws) => {
3390
- this.attachEventSocket(ws);
4474
+ this.callerContext.run(caller.session, () => this.attachEventSocket(ws, caller.session ?? (typeof claimId === 'string' ? claimId : undefined)));
3391
4475
  });
3392
4476
  return;
3393
4477
  }
@@ -3414,6 +4498,13 @@ export class Daemon {
3414
4498
  reject(decision.code, decision.reason);
3415
4499
  return;
3416
4500
  }
4501
+ const caller = decision.credential.kind === 'client' ? this.resolveCallerIdentity(req)
4502
+ : { presented: false, session: undefined };
4503
+ if (caller.presented && caller.session === undefined) {
4504
+ this.audit.record('client', 'refuse', undefined, { reason: 'session identity not recognised' });
4505
+ reject(403, 'Forbidden');
4506
+ return;
4507
+ }
3417
4508
  const session = this.manager.get(sessionId);
3418
4509
  if (session === undefined) {
3419
4510
  reject(404, 'Not Found');
@@ -3428,13 +4519,13 @@ export class Daemon {
3428
4519
  // names that credential rather than assuming a browser: `client` for
3429
4520
  // the client token on the query, `viewer` for a viewer cookie,
3430
4521
  // `dashboard` for the dashboard cookie.
3431
- this.attachSocket(ws, session, decision.credential, { passive, frozen: decision.frozen });
4522
+ this.callerContext.run(caller.session, () => this.attachSocket(ws, session, decision.credential, { passive, frozen: decision.frozen, callerSession: caller.session }));
3432
4523
  });
3433
4524
  }
3434
4525
  /** Attach a subscriber to the daemon-wide event stream. */
3435
- attachEventSocket(ws) {
4526
+ attachEventSocket(ws, participant) {
3436
4527
  this.sockets.add(ws);
3437
- this.eventSockets.add(ws);
4528
+ this.eventSockets.set(ws, participant);
3438
4529
  this.lastActivity = Date.now();
3439
4530
  this.audit.record('client', 'events-connect', '-');
3440
4531
  ws.send(JSON.stringify({ type: 'hello', version: this.version }));
@@ -3449,13 +4540,97 @@ export class Daemon {
3449
4540
  // The stream is outbound-only; inbound frames are ignored by design.
3450
4541
  }
3451
4542
  /**
3452
- * Attach a subscriber to the dashboard session feed. Frames are the feed's
3453
- * own: hello, a snapshot, then session deltas. The only inbound frame read is
3454
- * one small window registration; every other inbound frame is ignored.
4543
+ * Attach a subscriber to the dashboard session feed. After hello and a
4544
+ * snapshot, registered windows receive roster and assignment state. A
4545
+ * registered socket may focus, designate or move a pane through the daemon.
3455
4546
  * The socket counts as connected so idle shutdown waits while the dashboard
3456
4547
  * is open.
3457
4548
  */
3458
- attachDashboardSocket(ws) {
4549
+ dashboardPair(window) {
4550
+ return JSON.stringify([window.id, window.instance]);
4551
+ }
4552
+ dashboardWindows() {
4553
+ return [...this.dashboardWindowIds.entries()]
4554
+ .filter(([socket]) => socket.readyState === socket.OPEN)
4555
+ .map(([socket, window]) => ({ socket, pair: this.dashboardPair(window), focused: window.focused }));
4556
+ }
4557
+ dashboardFocusTime(value) {
4558
+ // Documents on this host report the focus event in epoch milliseconds.
4559
+ // A late registration can report the past, but cannot reserve a future turn.
4560
+ const now = performance.timeOrigin + performance.now();
4561
+ return typeof value === 'number' && Number.isFinite(value) ? Math.max(0, Math.min(now, value)) : 0;
4562
+ }
4563
+ updateDashboardOffers(windows) {
4564
+ for (const [id, previous] of this.dashboardTransferable) {
4565
+ const owner = windows.find(w => this.dashboardAssignments.get(w.pair)?.includes(id));
4566
+ const recipient = owner?.socket.protocol;
4567
+ if (recipient === previous || (previous === null && windows.length === 0))
4568
+ continue;
4569
+ this.dashboardTransferable.set(id, recipient);
4570
+ const session = this.manager.get(id);
4571
+ if (session)
4572
+ this.announceGeometry(id, session, { resync: false });
4573
+ }
4574
+ }
4575
+ publishDashboardWindows(move) {
4576
+ const windows = this.dashboardWindows();
4577
+ const roster = [...new Set(windows.map((window) => window.pair))];
4578
+ if (windows.length === 0) {
4579
+ this.dashboardDesignated = null;
4580
+ this.dashboardAssignments.clear();
4581
+ this.updateDashboardOffers(windows);
4582
+ return;
4583
+ }
4584
+ if (!windows.some((window) => window.pair === this.dashboardDesignated)) {
4585
+ this.dashboardDesignated = [...windows].sort((a, b) => b.focused - a.focused)[0].pair;
4586
+ }
4587
+ const live = new Set(this.manager.list().filter((session) => !this.startingIds.has(session.id)).map((session) => session.id));
4588
+ for (const [pair, ids] of this.dashboardAssignments) {
4589
+ if (!roster.includes(pair)) {
4590
+ this.dashboardAssignments.delete(pair);
4591
+ this.dashboardAssignments.set(this.dashboardDesignated, [
4592
+ ...(this.dashboardAssignments.get(this.dashboardDesignated) ?? []), ...ids.filter((id) => live.has(id)),
4593
+ ]);
4594
+ }
4595
+ else
4596
+ this.dashboardAssignments.set(pair, ids.filter((id) => live.has(id)));
4597
+ }
4598
+ const placed = new Set([...this.dashboardAssignments.values()].flat());
4599
+ for (const id of live) {
4600
+ if (placed.has(id))
4601
+ continue;
4602
+ this.dashboardAssignments.set(this.dashboardDesignated, [...(this.dashboardAssignments.get(this.dashboardDesignated) ?? []), id]);
4603
+ }
4604
+ const frame = JSON.stringify({ type: 'window-state', designated: this.dashboardDesignated,
4605
+ windows: roster, assignments: Object.fromEntries(this.dashboardAssignments),
4606
+ ...(move === undefined ? {} : { move }) });
4607
+ for (const window of windows)
4608
+ window.socket.send(frame);
4609
+ this.updateDashboardOffers(windows);
4610
+ }
4611
+ dashboardFeedCurrent(ws) {
4612
+ return this.tokens.verifyDashboardToken(this.dashboardSocketCredential.get(ws)) &&
4613
+ this.tokens.acceptsDashboardProof(dashboardProofFromProtocol(ws.protocol));
4614
+ }
4615
+ retireDashboardFeeds() {
4616
+ for (const protocol of this.dashboardDocumentFocus.keys()) {
4617
+ if (!this.tokens.acceptsDashboardProof(dashboardProofFromProtocol(protocol)))
4618
+ this.dashboardDocumentFocus.delete(protocol);
4619
+ }
4620
+ let changed = false;
4621
+ for (const ws of this.dashboardEventSockets) {
4622
+ if (ws.readyState === ws.OPEN && !this.dashboardFeedCurrent(ws)) {
4623
+ if (this.dashboardWindowIds.delete(ws))
4624
+ changed = true;
4625
+ this.liveDashboardEventSockets.delete(ws);
4626
+ ws.close(1008, 'Dashboard access expired');
4627
+ }
4628
+ }
4629
+ if (changed)
4630
+ this.publishDashboardWindows();
4631
+ }
4632
+ attachDashboardSocket(ws, credential) {
4633
+ this.dashboardSocketCredential.set(ws, credential);
3459
4634
  this.sockets.add(ws);
3460
4635
  this.dashboardEventSockets.add(ws);
3461
4636
  this.liveDashboardEventSockets.add(ws);
@@ -3483,16 +4658,18 @@ export class Daemon {
3483
4658
  const unsubscribe = this.subscribeDashboardFeed((frame) => {
3484
4659
  if (ws.readyState === ws.OPEN)
3485
4660
  ws.send(JSON.stringify(frame));
4661
+ if ((frame.type === 'session-added' || frame.type === 'session-removed') &&
4662
+ this.dashboardWindows()[0]?.socket === ws)
4663
+ this.publishDashboardWindows();
3486
4664
  });
3487
4665
  ws.on('message', (raw) => {
3488
- // This id only speeds roster departure. It grants no daemon action.
3489
- if (this.dashboardWindowIds.has(ws))
4666
+ if (!this.dashboardFeedCurrent(ws))
3490
4667
  return;
3491
4668
  let frame;
3492
4669
  try {
3493
4670
  const bytes = Array.isArray(raw) ? Buffer.concat(raw) : Buffer.from(raw);
3494
- // A registration is a few dozen bytes: never parse anything larger.
3495
- if (bytes.length > MAX_WINDOW_REGISTRATION_BYTES)
4671
+ // Window control frames are small: never parse anything larger.
4672
+ if (bytes.length > 1024)
3496
4673
  return;
3497
4674
  frame = JSON.parse(bytes.toString('utf8'));
3498
4675
  }
@@ -3502,17 +4679,57 @@ export class Daemon {
3502
4679
  if (typeof frame !== 'object' || frame === null)
3503
4680
  return;
3504
4681
  const claim = frame;
4682
+ const current = this.dashboardWindowIds.get(ws);
4683
+ if (current !== undefined) {
4684
+ const pair = this.dashboardPair(current);
4685
+ if (claim.type === 'window-focus') {
4686
+ const at = claim.focusedAt === undefined ? performance.timeOrigin + performance.now() : claim.focusedAt;
4687
+ current.focused = Math.max(current.focused, this.dashboardFocusTime(at));
4688
+ this.dashboardDocumentFocus.set(ws.protocol, { id: current.id, focused: current.focused });
4689
+ this.publishDashboardWindows();
4690
+ }
4691
+ else if (claim.type === 'window-designate') {
4692
+ this.dashboardDesignated = pair;
4693
+ this.publishDashboardWindows();
4694
+ }
4695
+ else if (claim.type === 'window-move' && typeof claim.session === 'string' &&
4696
+ typeof claim.source === 'string' && typeof claim.target === 'string' &&
4697
+ (claim.source === pair || claim.target === pair) &&
4698
+ claim.session.length <= 100 &&
4699
+ this.dashboardAssignments.get(claim.source)?.includes(claim.session)) {
4700
+ const open = this.dashboardWindows().map((window) => window.pair);
4701
+ if (!open.includes(claim.source) || !open.includes(claim.target))
4702
+ return;
4703
+ if (claim.source === claim.target && claim.before === claim.session)
4704
+ return;
4705
+ this.dashboardAssignments.set(claim.source, this.dashboardAssignments.get(claim.source).filter((id) => id !== claim.session));
4706
+ const target = this.dashboardAssignments.get(claim.target) ?? [];
4707
+ const before = typeof claim.before === 'string' ? target.indexOf(claim.before) : -1;
4708
+ const anchor = target[before];
4709
+ target.splice(before < 0 ? target.length : before, 0, claim.session);
4710
+ this.dashboardAssignments.set(claim.target, target);
4711
+ this.publishDashboardWindows({ session: claim.session, target: claim.target,
4712
+ ...(anchor === undefined ? {} : { before: anchor }) });
4713
+ }
4714
+ return;
4715
+ }
3505
4716
  if (claim.type !== 'window-register' || typeof claim.id !== 'string' ||
3506
4717
  !/^[a-z0-9]+-[a-z0-9]+(?:-[1-9][0-9]*)?$/.test(claim.id) || claim.id.length > 100 ||
3507
4718
  typeof claim.instance !== 'string' ||
3508
4719
  !/^[a-z0-9]+-[a-z0-9]+(?:-[1-9][0-9]*)?$/.test(claim.instance) ||
3509
4720
  claim.instance.length > 100)
3510
4721
  return;
3511
- this.dashboardWindowIds.set(ws, { id: claim.id, instance: claim.instance });
4722
+ const previous = this.dashboardDocumentFocus.get(ws.protocol);
4723
+ const focused = Math.max(previous?.id === claim.id ? previous.focused : 0, this.dashboardFocusTime(claim.focusedAt));
4724
+ this.dashboardWindowIds.set(ws, { id: claim.id, instance: claim.instance, focused });
4725
+ this.dashboardDocumentFocus.set(ws.protocol, { id: claim.id, focused });
4726
+ this.publishDashboardWindows();
3512
4727
  });
3513
4728
  ws.on('close', () => {
3514
4729
  const windowClaim = this.dashboardWindowIds.get(ws);
3515
4730
  this.dashboardWindowIds.delete(ws);
4731
+ if (windowClaim !== undefined)
4732
+ this.publishDashboardWindows();
3516
4733
  unsubscribe();
3517
4734
  this.sockets.delete(ws);
3518
4735
  this.dashboardEventSockets.delete(ws);
@@ -3569,16 +4786,30 @@ export class Daemon {
3569
4786
  }
3570
4787
  this.updateFeedSession(sessionId);
3571
4788
  }
4789
+ gridOfferedTo(id, ws) {
4790
+ const recipient = this.dashboardTransferable.get(id);
4791
+ return (recipient === null || recipient === ws.protocol) &&
4792
+ this.dashboardCredentialOwner.has(id) && this.dashboardSocketCredential.has(ws) &&
4793
+ tokensEqual(this.dashboardCredentialOwner.get(id), this.dashboardSocketCredential.get(ws));
4794
+ }
3572
4795
  /** What one watcher is told about the grid, from its own point of view. */
3573
4796
  geometryFrame(session, ws) {
3574
4797
  return {
3575
4798
  type: 'geometry',
4799
+ ...(this.widerReads.get(session.id)?.isTemporary() ? { temporary: true } : {}),
3576
4800
  cols: session.cols,
3577
4801
  rows: session.rows,
3578
4802
  // The most a viewport may ask for (§5), with every frame: a page whose
3579
4803
  // window wants more can then size its text for the grid it will be
3580
4804
  // given, rather than proposing one it never will be.
3581
4805
  max: { cols: MAX_VIEWPORT_COLS, rows: MAX_VIEWPORT_ROWS },
4806
+ // An adopting dashboard must distinguish a fresh session from one
4807
+ // already taken in another window before scheduling its initial fit.
4808
+ owned: this.hasGeometryController(session.id) ||
4809
+ (this.dashboardSocketCredential.has(ws) && this.dashboardGeometryOwner.has(session.id)),
4810
+ // Only a controller's explicit assignment handover offers its grid to
4811
+ // another dashboard pane while the old socket is closing.
4812
+ dashboardTransferable: this.gridOfferedTo(session.id, ws),
3582
4813
  control: session.geometryHeld
3583
4814
  ? 'held'
3584
4815
  : this.geometryController.get(session.id) === ws
@@ -3628,6 +4859,8 @@ export class Daemon {
3628
4859
  // or program behind it.
3629
4860
  const actor = credential.kind;
3630
4861
  this.sockets.add(ws);
4862
+ if (credential.dashboardToken !== undefined)
4863
+ this.dashboardSocketCredential.set(ws, credential.dashboardToken);
3631
4864
  let watchers = this.sessionSockets.get(session.id);
3632
4865
  if (watchers === undefined) {
3633
4866
  watchers = new Map();
@@ -3679,22 +4912,29 @@ export class Daemon {
3679
4912
  // never picks it up by connecting, whatever the query says, and neither
3680
4913
  // does a `drive=0` socket. Neither inherits a controller that has left:
3681
4914
  // this is the only place a socket becomes the controller without sending
3682
- // `take`.
4915
+ // `take`. While a dashboard's grid is remembered for its absent socket,
4916
+ // a viewer or client socket follows it too, until a deliberate resize.
3683
4917
  if (credential.kind === 'dashboard' &&
3684
- // The remembered proof identifies the dashboard credential, not a browser window;
3685
- // any holder may already take this grid deliberately, so restoring it is enough.
4918
+ // The returning document can restore its grid while a release to a
4919
+ // different assignment belongs to that recipient alone.
3686
4920
  this.dashboardGeometryOwner.has(session.id) &&
4921
+ (!this.dashboardTransferable.has(session.id) || this.gridOfferedTo(session.id, ws)) &&
3687
4922
  tokensEqual(this.dashboardGeometryOwner.get(session.id), ws.protocol) &&
3688
4923
  !session.exited &&
3689
4924
  !this.hasGeometryController(session.id)) {
3690
4925
  this.geometryController.set(session.id, ws);
4926
+ this.dashboardTransferable.delete(session.id);
4927
+ this.announceGeometry(session.id, session, { resync: false });
3691
4928
  }
3692
4929
  else if (!session.geometryHeld &&
3693
4930
  !readOnly &&
3694
4931
  !passive &&
3695
- !this.hasGeometryController(session.id)) {
4932
+ !this.hasGeometryController(session.id) &&
4933
+ !this.dashboardGeometryOwner.has(session.id)) {
3696
4934
  this.geometryController.set(session.id, ws);
3697
4935
  this.dashboardGeometryOwner.delete(session.id);
4936
+ this.dashboardCredentialOwner.delete(session.id);
4937
+ this.dashboardTransferable.delete(session.id);
3698
4938
  }
3699
4939
  ws.send(JSON.stringify(options.frozen === undefined
3700
4940
  ? this.geometryFrame(session, ws)
@@ -3727,13 +4967,16 @@ export class Daemon {
3727
4967
  // AFTER the resync, so the gate holds it behind the snapshot instead of
3728
4968
  // letting the snapshot's wipe erase it.
3729
4969
  if (session.exited) {
3730
- sync.deliver(exitNotice(session.exitCode));
4970
+ sync.deliver(session.fault === null ? exitNotice(session.exitCode) : `session ended: ${session.fault}`);
3731
4971
  }
3732
4972
  // A stall is announced once, at the moment it trips. Someone who opens the
3733
4973
  // viewer BECAUSE they were told a session is stuck arrives after
3734
4974
  // the only announcement, and is the exact person the badge is for. Replay the
3735
4975
  // current state to them.
3736
4976
  const held = this.promptStates.get(session.id);
4977
+ const stalled = session.getStalled();
4978
+ if (stalled !== undefined)
4979
+ ws.send(JSON.stringify({ type: 'session-stalled', stalled }));
3737
4980
  if (held?.alerted === true) {
3738
4981
  ws.send(JSON.stringify({
3739
4982
  type: 'prompt-stall',
@@ -3746,11 +4989,12 @@ export class Daemon {
3746
4989
  const unsubscribeData = session.onData((data) => sync.deliver(data));
3747
4990
  this.updateFeedSession(session.id);
3748
4991
  const unsubscribeExit = session.onExit((exitCode) => {
3749
- sync.deliver(exitNotice(exitCode));
4992
+ sync.deliver(session.fault === null ? exitNotice(exitCode) : `session ended: ${session.fault}`);
3750
4993
  // The notice is bytes on the terminal; the page needs a frame to change
3751
4994
  // its own state.
3752
4995
  if (ws.readyState === ws.OPEN) {
3753
- ws.send(JSON.stringify({ type: 'exited', exitCode }));
4996
+ ws.send(JSON.stringify({ type: 'exited', exitCode,
4997
+ ...(session.fault === null ? {} : { fault: session.fault }) }));
3754
4998
  }
3755
4999
  });
3756
5000
  // A protocol error, such as a malformed frame or a reset mid-handshake,
@@ -3767,10 +5011,26 @@ export class Daemon {
3767
5011
  const text = typeof message === 'string' ? message : message.toString('utf8');
3768
5012
  try {
3769
5013
  const parsed = JSON.parse(text);
5014
+ if (typeof parsed === 'object' && parsed !== null &&
5015
+ parsed.type === 'release-grid') {
5016
+ // Only the current controller can give up a dashboard grid. Another
5017
+ // document with the same cookie cannot make a live controller yield.
5018
+ if (credential.kind === 'dashboard' && !session.exited && !session.geometryHeld &&
5019
+ this.geometryController.get(session.id) === ws) {
5020
+ const windows = this.dashboardWindows();
5021
+ const target = windows.find(({ pair }) => this.dashboardAssignments.get(pair)?.includes(session.id));
5022
+ if (target)
5023
+ this.dashboardTransferable.set(session.id, target.socket.protocol);
5024
+ else if (windows.length === 0)
5025
+ this.dashboardTransferable.set(session.id, null);
5026
+ this.announceGeometry(session.id, session, { resync: false });
5027
+ }
5028
+ return;
5029
+ }
3770
5030
  if (typeof parsed === 'object' &&
3771
5031
  parsed !== null &&
3772
5032
  parsed.type === 'resize') {
3773
- const { cols, rows, take } = parsed;
5033
+ const { cols, rows, take, acceptOffer } = parsed;
3774
5034
  // Fit, Enlarge, Focus and Restore are a resize that says `take`.
3775
5035
  // A passive socket's other resizes, including one a dashboard pane
3776
5036
  // sends because the window moved, are not that act: the grid stays,
@@ -3798,12 +5058,80 @@ export class Daemon {
3798
5058
  cols: Math.min(cols, MAX_VIEWPORT_COLS),
3799
5059
  rows: Math.min(rows, MAX_VIEWPORT_ROWS),
3800
5060
  };
3801
- const handedOver = this.geometryController.get(session.id) !== ws;
3802
- const changed = wanted.cols !== session.cols || wanted.rows !== session.rows;
3803
- let applied = false;
5061
+ if (!this.widerReads.has(session.id) && acceptOffer !== true) {
5062
+ // Wider restores and conditional offer takes check ownership
5063
+ // in the session's resize queue below.
5064
+ const handedOver = this.geometryController.get(session.id) !== ws;
5065
+ const changed = wanted.cols !== session.cols || wanted.rows !== session.rows;
5066
+ let applied = false;
5067
+ try {
5068
+ if (changed)
5069
+ await session.resize(wanted.cols, wanted.rows);
5070
+ applied = true;
5071
+ }
5072
+ catch (error) {
5073
+ if (error instanceof SessionProgramEndedError)
5074
+ return;
5075
+ this.logger.warn('viewer resize failed', { id: session.id, error: String(error) });
5076
+ }
5077
+ this.geometryController.set(session.id, ws);
5078
+ this.dashboardTransferable.delete(session.id);
5079
+ this.geometryEpoch.set(session.id, (this.geometryEpoch.get(session.id) ?? 0) + 1);
5080
+ if (credential.kind === 'dashboard') {
5081
+ this.dashboardGeometryOwner.set(session.id, ws.protocol);
5082
+ this.dashboardCredentialOwner.set(session.id, credential.dashboardToken);
5083
+ }
5084
+ else {
5085
+ this.dashboardGeometryOwner.delete(session.id);
5086
+ this.dashboardCredentialOwner.delete(session.id);
5087
+ }
5088
+ if (changed && applied) {
5089
+ this.audit.record(actor, 'resize', session.id, {
5090
+ cols: wanted.cols, rows: wanted.rows, hold: false,
5091
+ });
5092
+ }
5093
+ if (changed)
5094
+ this.announceGeometry(session.id, session);
5095
+ else if (handedOver)
5096
+ this.announceGeometry(session.id, session, { resync: false });
5097
+ else if (take === true)
5098
+ ws.send(JSON.stringify(this.geometryFrame(session, ws)));
5099
+ return;
5100
+ }
3804
5101
  try {
3805
- await session.resize(wanted.cols, wanted.rows);
3806
- applied = true;
5102
+ const applied = await session.resizeIfCurrent(wanted.cols, wanted.rows,
5103
+ // A viewport that left while its take waited in the queue made
5104
+ // no lasting choice: skip it so the pending wider restore runs.
5105
+ () => !session.geometryHeld && !session.exited && ws.readyState === ws.OPEN &&
5106
+ (acceptOffer !== true || this.gridOfferedTo(session.id, ws)) &&
5107
+ (this.sessionSockets.get(session.id)?.has(ws) ?? false), (changed) => {
5108
+ const handedOver = this.geometryController.get(session.id) !== ws;
5109
+ // The controller change and epoch belong to the same queued
5110
+ // act as the resize, before a queued wider restore can run.
5111
+ this.geometryController.set(session.id, ws);
5112
+ this.dashboardTransferable.delete(session.id);
5113
+ this.geometryEpoch.set(session.id, (this.geometryEpoch.get(session.id) ?? 0) + 1);
5114
+ if (credential.kind === 'dashboard') {
5115
+ this.dashboardGeometryOwner.set(session.id, ws.protocol);
5116
+ this.dashboardCredentialOwner.set(session.id, credential.dashboardToken);
5117
+ }
5118
+ else {
5119
+ this.dashboardGeometryOwner.delete(session.id);
5120
+ this.dashboardCredentialOwner.delete(session.id);
5121
+ }
5122
+ if (changed) {
5123
+ this.audit.record(actor, 'resize', session.id, {
5124
+ cols: wanted.cols, rows: wanted.rows, hold: false,
5125
+ });
5126
+ this.announceGeometry(session.id, session);
5127
+ }
5128
+ else if (handedOver)
5129
+ this.announceGeometry(session.id, session, { resync: false });
5130
+ else if (take === true)
5131
+ ws.send(JSON.stringify(this.geometryFrame(session, ws)));
5132
+ }, true);
5133
+ if (!applied && ws.readyState === ws.OPEN)
5134
+ ws.send(JSON.stringify(this.geometryFrame(session, ws)));
3807
5135
  }
3808
5136
  catch (error) {
3809
5137
  // The program has ended (a viewer fitting its window while
@@ -3823,39 +5151,6 @@ export class Daemon {
3823
5151
  error: String(error),
3824
5152
  });
3825
5153
  }
3826
- // Asking is the deliberate act that takes control, whether or not
3827
- // the grid actually moves: a viewport that already fits is still
3828
- // the one driving.
3829
- this.geometryController.set(session.id, ws);
3830
- if (credential.kind === 'dashboard')
3831
- this.dashboardGeometryOwner.set(session.id, ws.protocol);
3832
- else
3833
- this.dashboardGeometryOwner.delete(session.id);
3834
- // A geometry change is a geometry change whoever made it, and
3835
- // `resize` is on the list of audited actions the security page
3836
- // publishes. Only the ones that actually took: a proposal the
3837
- // grid already satisfied moved nothing, and one that failed moved
3838
- // nothing either, so neither is recorded as a success. `hold` is
3839
- // false because a viewport never holds: holding is asked for
3840
- // explicitly, over the API (§5).
3841
- if (changed && applied) {
3842
- this.audit.record(actor, 'resize', session.id, {
3843
- cols: wanted.cols,
3844
- rows: wanted.rows,
3845
- hold: false,
3846
- });
3847
- }
3848
- // Everyone sees the same grid, and each is told whether they are
3849
- // now driving it. A proposal that changed nothing needs no
3850
- // snapshot, because the page already shows this grid. But if the
3851
- // grid changed hands, everyone is told that much, or the old
3852
- // driver goes on believing it is theirs.
3853
- if (changed)
3854
- this.announceGeometry(session.id, session);
3855
- else if (handedOver)
3856
- this.announceGeometry(session.id, session, { resync: false });
3857
- else if (take === true)
3858
- ws.send(JSON.stringify(this.geometryFrame(session, ws)));
3859
5154
  }
3860
5155
  return;
3861
5156
  }
@@ -3904,7 +5199,8 @@ export class Daemon {
3904
5199
  // sequences, so this is not always one keystroke.) .catch keeps the exit
3905
5200
  // race, the session dying mid-write, from escaping as an unhandled
3906
5201
  // rejection.
3907
- void session.write(text).catch((error) => {
5202
+ const report = terminalReportKind(text);
5203
+ void session.write(text, { terminalReport: report !== null, humanInput: report === null }).catch((error) => {
3908
5204
  this.logger.warn('viewer input failed', {
3909
5205
  id: session.id,
3910
5206
  error: String(error),
@@ -3915,7 +5211,6 @@ export class Daemon {
3915
5211
  // because the program asked for it. Nobody typed it, so it is audited
3916
5212
  // as a report and leaves the "last input" indicator alone (§4.5, §5).
3917
5213
  // Content only under captureContent, as for input.
3918
- const report = terminalReportKind(text);
3919
5214
  if (report !== null) {
3920
5215
  this.audit.record(actor, 'report', session.id, {
3921
5216
  kind: report,
@@ -3931,26 +5226,33 @@ export class Daemon {
3931
5226
  this.broadcastControl(session.id, { type: 'input-source', source: 'human' });
3932
5227
  };
3933
5228
  ws.on('message', (message) => {
3934
- void onViewerMessage(message).catch((error) => {
3935
- this.logger.warn('viewer message failed', { id: session.id, error: String(error) });
5229
+ this.callerContext.run(options.callerSession, () => {
5230
+ void onViewerMessage(message).catch((error) => {
5231
+ this.logger.warn('viewer message failed', { id: session.id, error: String(error) });
5232
+ });
3936
5233
  });
3937
5234
  });
3938
5235
  ws.on('close', () => {
3939
- unsubscribeData();
3940
- unsubscribeExit();
3941
- sync.close();
3942
- this.sockets.delete(ws);
3943
- this.sessionSockets.get(session.id)?.delete(ws);
3944
- this.updateFeedSession(session.id);
3945
- // The grid stays where it is; it simply no longer belongs to anyone.
3946
- // The next single-session viewport to arrive, or a `take`, picks it
3947
- // up. A dashboard socket, and a `drive=0` socket, that is already
3948
- // connected does not inherit it.
3949
- if (this.geometryController.get(session.id) === ws) {
3950
- this.geometryController.delete(session.id);
3951
- }
3952
- this.lastActivity = Date.now();
3953
- this.audit.record(actor, 'ws-close', session.id);
5236
+ this.callerContext.run(options.callerSession, () => {
5237
+ unsubscribeData();
5238
+ unsubscribeExit();
5239
+ sync.close();
5240
+ this.sockets.delete(ws);
5241
+ this.sessionSockets.get(session.id)?.delete(ws);
5242
+ this.updateFeedSession(session.id);
5243
+ // The grid stays where it is. A dashboard's grid stays remembered for
5244
+ // that dashboard document, which takes it back when it reconnects; any
5245
+ // other socket follows it until a deliberate resize. Otherwise the next
5246
+ // single-session viewport to arrive, or a `take`, picks it up. A
5247
+ // dashboard socket, and a `drive=0` socket, that is already connected
5248
+ // does not inherit it.
5249
+ if (this.geometryController.get(session.id) === ws) {
5250
+ this.geometryController.delete(session.id);
5251
+ this.announceGeometry(session.id, session, { resync: false });
5252
+ }
5253
+ this.lastActivity = Date.now();
5254
+ this.audit.record(actor, 'ws-close', session.id);
5255
+ });
3954
5256
  });
3955
5257
  }
3956
5258
  }