shellpuppet 0.2.0 → 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 (238) hide show
  1. package/README.md +83 -18
  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 +255 -33
  138. package/dist/cli/index.js.map +1 -1
  139. package/dist/client/http.d.ts +17 -3
  140. package/dist/client/http.js +232 -35
  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 +166 -14
  176. package/dist/core/session.js +1000 -86
  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/liveness.d.ts +1 -1
  201. package/dist/daemon/liveness.js +2 -2
  202. package/dist/daemon/liveness.js.map +1 -1
  203. package/dist/daemon/nudgeScheduler.d.ts +21 -0
  204. package/dist/daemon/nudgeScheduler.js +61 -0
  205. package/dist/daemon/nudgeScheduler.js.map +1 -0
  206. package/dist/daemon/paths.d.ts +22 -16
  207. package/dist/daemon/paths.js +137 -49
  208. package/dist/daemon/paths.js.map +1 -1
  209. package/dist/daemon/restartHold.d.ts +16 -0
  210. package/dist/daemon/restartHold.js +126 -0
  211. package/dist/daemon/restartHold.js.map +1 -0
  212. package/dist/daemon/restartSource.d.ts +7 -0
  213. package/dist/daemon/restartSource.js +89 -0
  214. package/dist/daemon/restartSource.js.map +1 -0
  215. package/dist/daemon/screenshot.d.ts +4 -1
  216. package/dist/daemon/screenshot.js +45 -7
  217. package/dist/daemon/screenshot.js.map +1 -1
  218. package/dist/daemon/server.d.ts +71 -13
  219. package/dist/daemon/server.js +1601 -296
  220. package/dist/daemon/server.js.map +1 -1
  221. package/dist/daemon/sessionFeed.js +4 -1
  222. package/dist/daemon/sessionFeed.js.map +1 -1
  223. package/dist/mcp/config.js +2 -1
  224. package/dist/mcp/config.js.map +1 -1
  225. package/dist/mcp/index.js +12 -2
  226. package/dist/mcp/index.js.map +1 -1
  227. package/dist/mcp/tools.d.ts +21 -1
  228. package/dist/mcp/tools.js +213 -28
  229. package/dist/mcp/tools.js.map +1 -1
  230. package/dist/viewer/dashboard-folders.js +7 -1
  231. package/dist/viewer/dashboard-layout.js +6 -52
  232. package/dist/viewer/dashboard.css +20 -4
  233. package/dist/viewer/dashboard.html +12 -3
  234. package/dist/viewer/dashboard.js +550 -378
  235. package/dist/viewer/pane.js +744 -136
  236. package/dist/viewer/viewer.css +1 -1
  237. package/dist/viewer/viewer.js +3 -1
  238. package/package.json +1 -1
@@ -5,7 +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';
10
+ import { randomUUID } from 'node:crypto';
11
+ import { AsyncLocalStorage } from 'node:async_hooks';
9
12
  import * as http from 'node:http';
10
13
  import { createRequire } from 'node:module';
11
14
  import * as os from 'node:os';
@@ -13,6 +16,9 @@ import * as path from 'node:path';
13
16
  import { fileURLToPath } from 'node:url';
14
17
  import { WebSocketServer } from 'ws';
15
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';
16
22
  import { CommandNotFoundError, DEFAULT_SESSION_ENV, SessionInputFailedError, SessionProgramEndedError, WindowsWithoutConPTYError, credentialShapedNames, } from '../core/session.js';
17
23
  import { NativePtyUnavailableError } from '../core/nativePty.js';
18
24
  import { checkSessionCapacity, commandLine, compilePolicy, evaluateCommand } from '../core/policy.js';
@@ -23,14 +29,16 @@ import { RegexBudgetError } from '../core/regexBudget.js';
23
29
  import { detectPrompt } from '../core/promptDetector.js';
24
30
  import { markFilteredSelectedOption } from '../core/selection.js';
25
31
  import { WaitConditionError } from '../core/waiter.js';
26
- import { agentNames, hideReasoning, latestResult, programName, signatureFor } from '../core/reasoning.js';
27
- 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';
28
34
  import { DASHBOARD_COOKIE, TokenStore, VIEWER_COOKIE, VIEWER_GRANT_TTL_MS, bearerToken, cookieValues, dashboardCookie, dashboardProofFromProtocol, tokensEqual, viewerCookie, } from './auth.js';
29
35
  import { NULL_AUDITOR } from './audit.js';
30
36
  import { findBrowser, launchDashboard, launchViewer } from './viewerLauncher.js';
31
37
  import { DEFAULT_CAPTURE_TIMEOUT_MS, MAX_CAPTURE_TIMEOUT_MS, MIN_CAPTURE_TIMEOUT_MS, captureProfileRoot, captureViewer, sweepCaptureProfiles, } from './screenshot.js';
32
- 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';
33
40
  import { daemonRunning } from './liveness.js';
41
+ import { restoreRestartSource, retryRestartSource, snapshotSourceId } from './restartSource.js';
34
42
  import { packageVersion } from './meta.js';
35
43
  import { terminalReportKind } from './terminalReports.js';
36
44
  import { ViewerSync } from './viewerSync.js';
@@ -192,16 +200,8 @@ const DASHBOARD_HEARTBEAT_TIMEOUT_MS = 10_000;
192
200
  const DASHBOARD_PROOF_META = '<meta name="sp-csrf" content="">';
193
201
  const DASHBOARD_FONT_META = '<meta name="sp-dashboard-font-size" content="">';
194
202
  /** Thrown by `start()` when a healthy daemon already owns this home. */
195
- /** The largest dashboard window registration frame the daemon will parse. */
196
- const MAX_WINDOW_REGISTRATION_BYTES = 256;
197
- export class AlreadyRunningError extends Error {
198
- state;
199
- constructor(state) {
200
- super(`A healthy daemon is already running (pid ${String(state.pid)}, ` +
201
- `port ${String(state.port)}).`);
202
- this.state = state;
203
- this.name = 'AlreadyRunningError';
204
- }
203
+ export { AlreadyRunningError };
204
+ class HomeOwnershipError extends Error {
205
205
  }
206
206
  /** The scheme and authority that open an absolute-form request target (`http://user@host:port`). */
207
207
  const SCHEME_AND_AUTHORITY = /^[a-z][a-z0-9+.-]*:\/\/[^/]*/i;
@@ -233,9 +233,9 @@ function offeredProtocols(req) {
233
233
  .filter((part) => part !== '');
234
234
  }
235
235
  /** The 409 for input, a key or a resize sent to a session that has ended. */
236
- function endedRefusal(id, exitCode) {
236
+ function endedRefusal(id, exitCode, fault = null) {
237
237
  return (`Session ${id} has ${exitCode === null ? 'ended' : 'exited'} ` +
238
- `(${howSessionEnded(exitCode)}) and no longer accepts input or geometry changes.`);
238
+ `(${fault ?? howSessionEnded(exitCode)}) and no longer accepts input or geometry changes.`);
239
239
  }
240
240
  function isRecord(value) {
241
241
  return typeof value === 'object' && value !== null && !Array.isArray(value);
@@ -349,12 +349,18 @@ function overBudgetMessage(signature) {
349
349
  'aside for a minute, so the screen is not returned filtered. Try again shortly.');
350
350
  }
351
351
  /** Read one rendered frame for both a filtered wait predicate and its reply. */
352
- function filteredWaitScreen(session, signature) {
352
+ function filteredWaitScreen(session, signature, prompt) {
353
353
  const view = session.styledScreenNow(REASONING_CONTEXT_LINES);
354
354
  const filtered = hideReasoning(view.lines, signature, view.firstVisible);
355
355
  if (filtered === null)
356
356
  throw new WaitConditionError(overBudgetMessage(signature));
357
- 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]);
358
364
  }
359
365
  /**
360
366
  * A query flag: absent, `0` or `false` is off, `1` or `true` is on, and
@@ -412,6 +418,8 @@ function startShapeError(body) {
412
418
  ['label', (value) => typeof value === 'string', 'a string'],
413
419
  ['purpose', (value) => typeof value === 'string', 'a string'],
414
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'],
415
423
  [
416
424
  'readyQuiet',
417
425
  (value) => typeof value === 'number' && Number.isFinite(value) && value >= 0,
@@ -447,6 +455,8 @@ export class Daemon {
447
455
  logger;
448
456
  tokens = new TokenStore();
449
457
  manager;
458
+ mailbox;
459
+ nudges;
450
460
  server;
451
461
  wss = new WebSocketServer({
452
462
  noServer: true,
@@ -476,15 +486,28 @@ export class Daemon {
476
486
  geometryController = new Map();
477
487
  /** A dashboard document keeps its grid while a covered pane reconnects. */
478
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();
479
498
  /** Subscribers to the daemon-wide event stream (`/events`). */
480
- eventSockets = new Set();
499
+ eventSockets = new Map();
481
500
  /**
482
501
  * Open `/dashboard/events` sockets. While one is open, a session start does
483
502
  * not launch a per-session viewer window and does not hand back a viewer URL.
484
503
  */
485
504
  dashboardEventSockets = new Set();
486
- /** Opaque roster ids carried by dashboard feed sockets, never used for authorisation. */
505
+ /** Dashboard windows and assignments are owned by the authenticated feed. */
487
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();
488
511
  liveDashboardEventSockets = new Set();
489
512
  /** A launched dashboard has 30 seconds to connect before a start may retry. */
490
513
  dashboardWindowStartedAt = 0;
@@ -501,12 +524,16 @@ export class Daemon {
501
524
  portValue = null;
502
525
  waitsInFlight = 0;
503
526
  lastActivity = Date.now();
527
+ shutdownWarnings = [];
504
528
  idleTimer = null;
505
529
  raceCheckTimer = null;
506
530
  statePublishTimer = null;
507
531
  statePublishRunning = false;
532
+ homeOwner;
533
+ claimsRestored = false;
508
534
  /** What this daemon published in daemon.json, once it has claimed it. */
509
535
  publishedState = null;
536
+ instanceId = randomUUID();
510
537
  /** The pid of another running daemon already reported as owning daemon.json. */
511
538
  foreignOwnerReported = null;
512
539
  promptScanTimer = null;
@@ -514,6 +541,7 @@ export class Daemon {
514
541
  promptScanRunning = false;
515
542
  stopPromise = null;
516
543
  audit;
544
+ callerContext = new AsyncLocalStorage();
517
545
  /**
518
546
  * What sessions get from the daemon's environment (ADR-008), resolved once so
519
547
  * that what the daemon reports is what its sessions get.
@@ -522,10 +550,13 @@ export class Daemon {
522
550
  /** The profiles the dashboard may name, and the entries that did not load. */
523
551
  launchProfiles;
524
552
  daemonEnv;
553
+ cliPath;
525
554
  /** The global policy, kept here so a launch can report it before creating. */
526
555
  compiledPolicy;
527
556
  /** Accepted launch times, for the sliding sixty-second cap. */
528
557
  launchTimes = [];
558
+ claimTimes = [];
559
+ claimCount = 0;
529
560
  folderPickerBusy = false;
530
561
  folderPickerAbort = null;
531
562
  folderPickerDone = null;
@@ -539,16 +570,64 @@ export class Daemon {
539
570
  constructor(options) {
540
571
  const startedWrapped = process.env['SHELLPUPPET_DAEMON_STARTED_WRAPPED'] === '1';
541
572
  delete process.env['SHELLPUPPET_DAEMON_STARTED_WRAPPED'];
542
- this.options = { ...options, startedWrapped: options.startedWrapped ?? startedWrapped };
573
+ this.options = { ...options,
574
+ home: path.resolve(options.home),
575
+ startedWrapped: options.startedWrapped ?? startedWrapped };
543
576
  this.logger = options.logger;
544
- 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
+ };
545
585
  this.sessionEnv = options.sessionEnv ?? DEFAULT_SESSION_ENV;
546
586
  this.launchProfiles = options.launchProfiles ?? { profiles: [], problems: [] };
547
587
  this.daemonEnv = options.daemonEnv ?? process.env;
588
+ this.cliPath = fileURLToPath(new URL('../../dist/cli/index.js', import.meta.url));
548
589
  this.compiledPolicy = compilePolicy(options.policy);
549
590
  this.manager = new SessionManager(compilePolicy(options.policy), this.logger, {
550
591
  sessionEnv: this.sessionEnv,
551
- }, (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
+ });
552
631
  this.sessionFeed = new SessionFeed(this.version, () => this.listedSummaries().map((summary) => this.summaryWithPrompt(summary)), this.logger);
553
632
  this.server = http.createServer((req, res) => {
554
633
  this.handleRequest(req, res).catch((error) => {
@@ -601,18 +680,15 @@ export class Daemon {
601
680
  // ------------------------------------------------------------------ start
602
681
  async start() {
603
682
  const { home } = this.options;
604
- const homeResult = await ensureHome(home);
605
- if (homeResult.warning !== undefined) {
606
- this.logger.warn('home hardening warning', { warning: homeResult.warning });
607
- }
683
+ ensureHome(home);
608
684
  // Defer to an incumbent that is running, even one too busy to answer its
609
685
  // health check; clear a record whose daemon has gone (design §2.3).
610
686
  const existing = readDaemonState(home);
611
687
  if (existing !== null) {
612
688
  if (await this.incumbentRunning(existing))
613
689
  throw new AlreadyRunningError(existing);
614
- this.logger.info('clearing stale daemon state', { stalePid: existing.pid });
615
- removeDaemonStateIf(home, existing);
690
+ if (this.stopping)
691
+ throw new Error('Daemon stopped during startup.');
616
692
  }
617
693
  await new Promise((resolve, reject) => {
618
694
  this.server.once('error', reject);
@@ -628,6 +704,10 @@ export class Daemon {
628
704
  resolve();
629
705
  });
630
706
  });
707
+ if (this.stopping) {
708
+ await this.closeServerOnly();
709
+ throw new Error('Daemon stopped during startup.');
710
+ }
631
711
  const address = this.server.address();
632
712
  if (address === null || typeof address === 'string') {
633
713
  throw new Error('Failed to determine bound port.');
@@ -646,30 +726,53 @@ export class Daemon {
646
726
  pid: process.pid,
647
727
  version: this.version,
648
728
  startedAt: new Date().toISOString(),
729
+ instanceId: this.instanceId,
649
730
  startedWrapped: this.options.startedWrapped ?? false,
650
731
  };
651
- // Atomic claim; on losing the race, defer to the winner (design §2.2:
652
- // the race is normal, not exceptional). A file that holds no record at all,
653
- // such as an emptied one, is cleared like a stale record.
654
- if (!claimDaemonState(home, state)) {
655
- const winner = inspectDaemonState(home);
656
- if (winner.kind === 'record' && (await this.incumbentRunning(winner.state))) {
657
- await this.closeServerOnly();
658
- throw new AlreadyRunningError(winner.state);
659
- }
660
- if (winner.kind === 'record')
661
- removeDaemonStateIf(home, winner.state);
662
- if (winner.kind === 'not-a-record') {
663
- this.logger.warn('clearing a daemon.json that holds no daemon record', {
664
- length: winner.raw.length,
665
- });
666
- 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);
667
741
  }
668
- if (!claimDaemonState(home, state)) {
669
- await this.closeServerOnly();
670
- throw new Error(`Could not claim ${daemonStatePath(home)}: it could not be read, or another ` +
671
- `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.');
672
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.');
673
776
  }
674
777
  // Belt and braces for the unlink/claim TOCTOU sliver: shortly after
675
778
  // start-up, if the published record names someone else and nobody is
@@ -678,7 +781,7 @@ export class Daemon {
678
781
  this.raceCheckTimer = setTimeout(() => {
679
782
  const current = readDaemonState(home);
680
783
  if (current !== null &&
681
- current.pid !== process.pid &&
784
+ current.instanceId !== this.instanceId &&
682
785
  this.manager.size() === 0 &&
683
786
  this.sockets.size === 0) {
684
787
  this.logger.info('lost start-up race after claim, stopping', {
@@ -701,13 +804,13 @@ export class Daemon {
701
804
  this.logger.warn('sessionEnv "passthrough" hands every session the daemon environment, including ' +
702
805
  'these variables whose names look like credentials; use "clean" or a list to keep them out', { names: exposed });
703
806
  }
704
- this.publishedState = state;
705
807
  this.statePublishTimer = setInterval(() => {
706
808
  void this.keepStatePublished();
707
809
  }, this.options.statePublishCheckMs ?? STATE_PUBLISH_CHECK_MS);
708
810
  this.statePublishTimer.unref();
709
811
  const idleMs = this.options.idleMs ?? DEFAULT_IDLE_MS;
710
812
  this.idleTimer = setInterval(() => {
813
+ this.lapseIdleClaims();
711
814
  // Reap sessions whose grace has lapsed before judging idleness. A
712
815
  // rejected sweep must be caught here, or it becomes an
713
816
  // unhandledRejection and the handler in index.ts stops the daemon.
@@ -757,7 +860,7 @@ export class Daemon {
757
860
  * process that had the same pid.
758
861
  */
759
862
  async incumbentRunning(record) {
760
- if (record.pid === process.pid && record.port === this.portValue)
863
+ if (record.port === this.portValue)
761
864
  return false;
762
865
  if (await this.isHealthy(record.port))
763
866
  return true;
@@ -783,7 +886,7 @@ export class Daemon {
783
886
  */
784
887
  async keepStatePublished() {
785
888
  const published = this.publishedState;
786
- if (published === null || this.stopPromise !== null || this.statePublishRunning)
889
+ if (published === null || this.stopping || this.statePublishRunning || !this.homeOwner?.held())
787
890
  return;
788
891
  this.statePublishRunning = true;
789
892
  try {
@@ -793,7 +896,7 @@ export class Daemon {
793
896
  return;
794
897
  if (file.kind === 'record') {
795
898
  const current = file.state;
796
- if (current.pid === published.pid && current.port === published.port) {
899
+ if (current.instanceId === this.instanceId && current.pid === published.pid && current.port === published.port) {
797
900
  this.foreignOwnerReported = null;
798
901
  return;
799
902
  }
@@ -808,6 +911,8 @@ export class Daemon {
808
911
  }
809
912
  return;
810
913
  }
914
+ if (this.stopping || !this.homeOwner?.held())
915
+ return;
811
916
  removeDaemonStateIf(home, current);
812
917
  }
813
918
  else if (file.kind === 'not-a-record') {
@@ -847,8 +952,8 @@ export class Daemon {
847
952
  }
848
953
  // ------------------------------------------------------------------- stop
849
954
  /**
850
- * Kill every session's process tree, close everything, remove the state
851
- * 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.
852
957
  * The daemon must never exit and strand running agent CLIs (design §2.3).
853
958
  */
854
959
  stop(opts = {}) {
@@ -856,11 +961,76 @@ export class Daemon {
856
961
  // awaits the one real shutdown.
857
962
  if (this.stopPromise === null) {
858
963
  this.stopping = true;
859
- 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();
860
981
  }
861
982
  return this.stopPromise;
862
983
  }
863
- 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() {
864
1034
  if (this.idleTimer !== null)
865
1035
  clearInterval(this.idleTimer);
866
1036
  if (this.raceCheckTimer !== null)
@@ -873,6 +1043,9 @@ export class Daemon {
873
1043
  clearTimeout(timer);
874
1044
  this.promptGraceTimers.clear();
875
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));
876
1049
  // Stop LISTENING first, before tearing down session trees. Killing process
877
1050
  // trees is not fast (`taskkill /T` on a loaded machine can take seconds
878
1051
  // per session), and a daemon that still answers on its port while shutting
@@ -922,17 +1095,6 @@ export class Daemon {
922
1095
  if (timer !== undefined)
923
1096
  clearTimeout(timer);
924
1097
  }
925
- if (opts.removeState !== false) {
926
- // Remove this daemon's record, or a file that holds none. A file that
927
- // cannot be read says nothing about what it holds, so it stays.
928
- const file = inspectDaemonState(this.options.home);
929
- if (file.kind === 'record' && file.state.pid === process.pid) {
930
- removeDaemonState(this.options.home);
931
- }
932
- else if (file.kind === 'not-a-record') {
933
- removeDaemonStateIfNotARecord(this.options.home, file.raw);
934
- }
935
- }
936
1098
  // Only now terminate lingering keep-alive connections, so close() cannot hang.
937
1099
  this.server.closeAllConnections();
938
1100
  await listenerClosed;
@@ -1042,8 +1204,8 @@ export class Daemon {
1042
1204
  }
1043
1205
  return null;
1044
1206
  }
1045
- auditDashboardRefusal(req, reason) {
1046
- this.audit.record('dashboard', 'refuse', undefined, {
1207
+ auditDashboardRefusal(req, reason, actor = 'dashboard') {
1208
+ this.audit.record(actor, 'refuse', undefined, {
1047
1209
  method: req.method ?? '',
1048
1210
  path: pathOnly(req.url),
1049
1211
  reason,
@@ -1100,6 +1262,7 @@ export class Daemon {
1100
1262
  if (grantPresented) {
1101
1263
  const redeemed = this.tokens.redeemDashboardGrant(grant, this.now());
1102
1264
  if (redeemed !== null) {
1265
+ this.retireDashboardFeeds();
1103
1266
  this.audit.record('dashboard', 'grant-redeem');
1104
1267
  res.writeHead(303, {
1105
1268
  location: '/dashboard',
@@ -1113,6 +1276,8 @@ export class Daemon {
1113
1276
  return;
1114
1277
  }
1115
1278
  const proof = cookie === null ? null : this.tokens.issueDashboardProof();
1279
+ if (proof !== null)
1280
+ this.retireDashboardFeeds();
1116
1281
  this.sendDashboardPage(res, proof, req.method === 'HEAD');
1117
1282
  return;
1118
1283
  }
@@ -1148,6 +1313,7 @@ export class Daemon {
1148
1313
  this.pendingDashboardGrants.delete(grant);
1149
1314
  if (this.stopping || !opened.launched || opened.mode === 'default-browser') {
1150
1315
  this.tokens.revokeDashboardGrant(grant);
1316
+ this.retireDashboardFeeds();
1151
1317
  this.auditDashboardRefusal(req, 'launch-failed');
1152
1318
  return false;
1153
1319
  }
@@ -1237,12 +1403,14 @@ export class Daemon {
1237
1403
  async waitAcrossSessions(res, url) {
1238
1404
  const hide = queryFlag(url, 'hideReasoning');
1239
1405
  const now = queryFlag(url, 'now');
1406
+ const stalled = queryFlag(url, 'stalled');
1407
+ const prompt = queryFlag(url, 'prompt');
1240
1408
  const timeoutText = url.searchParams.get('timeout');
1241
1409
  const timeout = timeoutText === null ? DEFAULT_WAIT_TIMEOUT_MS : Number(timeoutText);
1242
- if (hide === null || now === null || url.searchParams.get('prompt') !== 'true' ||
1410
+ if (hide === null || now === null || stalled === null || prompt === null || (!prompt && !stalled) ||
1243
1411
  !Number.isFinite(timeout) || timeout < 0 || timeout > MAX_WAIT_TIMEOUT_MS ||
1244
1412
  ['text', 'regex', 'quiet', 'debounce', 'matchAfterInput'].some((key) => url.searchParams.has(key))) {
1245
- 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.' });
1246
1414
  return;
1247
1415
  }
1248
1416
  const requested = url.searchParams.getAll('session');
@@ -1255,10 +1423,13 @@ export class Daemon {
1255
1423
  this.waitsInFlight += 1;
1256
1424
  try {
1257
1425
  while (!res.destroyed) {
1258
- 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];
1259
1430
  const waitedMs = Date.now() - started;
1260
1431
  if (sessions.length > 0 || now || waitedMs >= timeout) {
1261
- 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 });
1262
1433
  return;
1263
1434
  }
1264
1435
  await new Promise((resolve) => setTimeout(resolve, Math.min(WAIT_POLL_INTERVAL_MS, timeout - waitedMs)));
@@ -1292,6 +1463,39 @@ export class Daemon {
1292
1463
  this.lastActivity = Date.now();
1293
1464
  this.writeSessionList(res, url);
1294
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
+ }
1295
1499
  /** A cookie mutation: same-origin Fetch Metadata and a matching Origin. */
1296
1500
  isSameOriginMutation(req) {
1297
1501
  if (headerOne(req, 'sec-fetch-site') !== 'same-origin')
@@ -1320,10 +1524,12 @@ export class Daemon {
1320
1524
  async profileDescription(profile) {
1321
1525
  return {
1322
1526
  name: profile.name,
1527
+ role: profile.role ?? 'delegate',
1323
1528
  label: describeProfileText(profile.label ?? '', profile.name),
1324
1529
  purpose: describeProfileText(profile.purpose ?? '', profile.name),
1325
1530
  command: profile.command,
1326
1531
  args: [...profile.args],
1532
+ ...(profile.resume ? { canResume: true } : {}),
1327
1533
  folderRequired: profile.askCwd,
1328
1534
  anyFolder: profile.anyFolder,
1329
1535
  folders: profile.folders.map((folder) => ({ name: folder.name, path: folder.path })),
@@ -1519,23 +1725,27 @@ export class Daemon {
1519
1725
  json(res, 415, { error: 'The launch body must be JSON (application/json).' });
1520
1726
  return;
1521
1727
  }
1522
- if (!this.tokens.acceptsDashboardProof(headerOne(req, 'x-shellpuppet-csrf'))) {
1728
+ const documentProof = headerOne(req, 'x-shellpuppet-csrf');
1729
+ if (!this.tokens.acceptsDashboardProof(documentProof)) {
1523
1730
  this.auditDashboardRefusal(req, 'proof');
1524
1731
  json(res, 403, { error: 'Forbidden.' });
1525
1732
  return;
1526
1733
  }
1734
+ await this.launchProfile(req, res, { documentProof });
1735
+ }
1736
+ async launchProfile(req, res, { launcher, documentProof }) {
1527
1737
  let body;
1528
1738
  try {
1529
1739
  body = await readBody(req);
1530
1740
  }
1531
1741
  catch (error) {
1532
1742
  if (error instanceof RequestBodyTooLargeError) {
1533
- this.auditDashboardRefusal(req, 'body-size');
1743
+ this.auditDashboardRefusal(req, 'body-size', launcher?.name);
1534
1744
  json(res, 413, { error: error.message });
1535
1745
  return;
1536
1746
  }
1537
1747
  if (error instanceof Error && error.message.startsWith('Request body')) {
1538
- this.auditDashboardRefusal(req, 'body');
1748
+ this.auditDashboardRefusal(req, 'body', launcher?.name);
1539
1749
  json(res, 400, { error: error.message });
1540
1750
  return;
1541
1751
  }
@@ -1546,21 +1756,49 @@ export class Daemon {
1546
1756
  json(res, 400, { error: 'profile (string) is required.' });
1547
1757
  return;
1548
1758
  }
1759
+ const allowedKeys = ['profile', 'name', 'folder', 'rootIndex', 'folderPath', 'resumeId'];
1760
+ if (documentProof !== undefined)
1761
+ allowedKeys.push('window');
1549
1762
  for (const key of Object.keys(body)) {
1550
- if (key !== 'profile' && key !== 'folder' && key !== 'rootIndex' && key !== 'folderPath') {
1551
- this.auditDashboardRefusal(req, 'body');
1763
+ if (!allowedKeys.includes(key)) {
1764
+ this.auditDashboardRefusal(req, 'body', launcher?.name);
1552
1765
  json(res, 400, {
1553
- 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. ` +
1554
1767
  'A command, arguments and environment value come from the profile.',
1555
1768
  });
1556
1769
  return;
1557
1770
  }
1558
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
+ }
1559
1778
  const profile = this.launchProfiles.profiles.find((entry) => entry.name === profileName);
1560
1779
  if (profile === undefined) {
1561
1780
  json(res, 400, { error: `No such launch profile: ${profileName}` });
1562
1781
  return;
1563
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
+ }
1564
1802
  const folderName = body['folder'];
1565
1803
  const rootIndex = body['rootIndex'];
1566
1804
  const freePath = body['folderPath'];
@@ -1570,13 +1808,13 @@ export class Daemon {
1570
1808
  if (profile.askCwd) {
1571
1809
  if (freePath !== undefined) {
1572
1810
  if (!profile.anyFolder || folderName !== undefined || rootIndex !== undefined) {
1573
- this.auditDashboardRefusal(req, 'body');
1811
+ this.auditDashboardRefusal(req, 'body', launcher?.name);
1574
1812
  json(res, 400, { error: 'This profile does not accept that folder path.' });
1575
1813
  return;
1576
1814
  }
1577
1815
  const choice = resolveAnyFolder(freePath);
1578
1816
  if ('error' in choice) {
1579
- this.auditDashboardRefusal(req, 'body');
1817
+ this.auditDashboardRefusal(req, 'body', launcher?.name);
1580
1818
  json(res, 400, { error: choice.error });
1581
1819
  return;
1582
1820
  }
@@ -1594,7 +1832,7 @@ export class Daemon {
1594
1832
  if (rootIndex !== undefined) {
1595
1833
  const choice = await resolveRootFolder(profile.folderRoots.map((root) => path.resolve(os.homedir(), root)), rootIndex, folderName);
1596
1834
  if ('error' in choice) {
1597
- this.auditDashboardRefusal(req, 'body');
1835
+ this.auditDashboardRefusal(req, 'body', launcher?.name);
1598
1836
  json(res, 400, { error: choice.error });
1599
1837
  return;
1600
1838
  }
@@ -1603,7 +1841,7 @@ export class Daemon {
1603
1841
  else {
1604
1842
  folder = profile.folders.find((entry) => entry.name === folderName);
1605
1843
  if (folder === undefined) {
1606
- this.auditDashboardRefusal(req, 'body');
1844
+ this.auditDashboardRefusal(req, 'body', launcher?.name);
1607
1845
  json(res, 400, { error: `No such folder for profile "${profileName}": ${folderName}` });
1608
1846
  return;
1609
1847
  }
@@ -1611,7 +1849,7 @@ export class Daemon {
1611
1849
  }
1612
1850
  }
1613
1851
  else if (folderName !== undefined || rootIndex !== undefined || freePath !== undefined) {
1614
- this.auditDashboardRefusal(req, 'body');
1852
+ this.auditDashboardRefusal(req, 'body', launcher?.name);
1615
1853
  json(res, 400, {
1616
1854
  error: `Profile "${profileName}" uses a fixed working directory and does not accept a folder.`,
1617
1855
  });
@@ -1619,22 +1857,22 @@ export class Daemon {
1619
1857
  }
1620
1858
  const resolved = freeCwd !== undefined ? { cwd: freeCwd } : rootCwd === undefined ? this.resolveLaunchCwd(profile, folder) : { cwd: rootCwd };
1621
1859
  if ('error' in resolved) {
1622
- this.auditDashboardRefusal(req, 'body');
1860
+ this.auditDashboardRefusal(req, 'body', launcher?.name);
1623
1861
  json(res, 400, { error: resolved.error });
1624
1862
  return;
1625
1863
  }
1626
1864
  // Global policy runs first, then the profile's own deny and allow lists.
1627
1865
  // Both see the real command line, before any Windows shell wrap.
1628
- const globalDecision = evaluateCommand(this.compiledPolicy, profile.command, profile.args);
1866
+ const globalDecision = evaluateCommand(this.compiledPolicy, profile.command, args);
1629
1867
  if (!globalDecision.allowed) {
1630
- this.auditDashboardRefusal(req, 'policy');
1868
+ this.auditDashboardRefusal(req, 'policy', launcher?.name);
1631
1869
  json(res, 403, { error: globalDecision.reason ?? 'Command refused by policy.' });
1632
1870
  return;
1633
1871
  }
1634
1872
  if (profile.policy !== undefined) {
1635
- const ownDecision = evaluateCommand(compileProfilePolicy(profile.policy), profile.command, profile.args);
1873
+ const ownDecision = evaluateCommand(compileProfilePolicy(profile.policy), profile.command, args);
1636
1874
  if (!ownDecision.allowed) {
1637
- this.auditDashboardRefusal(req, 'policy');
1875
+ this.auditDashboardRefusal(req, 'policy', launcher?.name);
1638
1876
  json(res, 403, { error: ownDecision.reason ?? 'Command refused by policy.' });
1639
1877
  return;
1640
1878
  }
@@ -1644,69 +1882,48 @@ export class Daemon {
1644
1882
  // absolute path, so the folder's contents cannot choose the program.
1645
1883
  const resolvedCommand = resolveLaunchCommand(profile.command, resolved.cwd);
1646
1884
  if ('error' in resolvedCommand) {
1647
- this.auditDashboardRefusal(req, 'command');
1885
+ this.auditDashboardRefusal(req, 'command', launcher?.name);
1648
1886
  json(res, 400, {
1649
1887
  error: `Profile "${profile.name}" cannot be started: ${resolvedCommand.error}`,
1650
1888
  });
1651
1889
  return;
1652
1890
  }
1653
- const now = this.now();
1654
- this.pruneLaunchTimes(now);
1655
- if (this.launchTimes.length >= 8) {
1656
- this.auditDashboardRefusal(req, 'rate');
1657
- json(res, 429, {
1658
- error: 'Dashboard launch rate reached (8 in 60 seconds). Wait before starting another profile.',
1659
- });
1660
- return;
1661
- }
1662
- const live = this.manager.liveCount();
1663
- if (this.compiledPolicy.maxSessions === undefined) {
1664
- if (live >= 32) {
1665
- this.auditDashboardRefusal(req, 'limit');
1666
- json(res, 403, {
1667
- error: 'Session limit reached (32 live sessions). Kill a session or set policy.maxSessions.',
1668
- });
1669
- return;
1670
- }
1671
- }
1672
- else {
1673
- const capacity = checkSessionCapacity(this.compiledPolicy, live);
1674
- if (!capacity.allowed) {
1675
- this.auditDashboardRefusal(req, 'limit');
1676
- json(res, 403, { error: capacity.reason ?? 'Session limit reached.' });
1677
- return;
1678
- }
1679
- }
1680
1891
  const { env, copied } = copyDaemonEnv(profile.envFromDaemon, this.daemonEnv);
1681
1892
  const envNames = Object.keys(env);
1682
1893
  const folderLabel = freeCwd !== undefined ? freeCwd : folder?.name ?? (rootCwd !== undefined ? folderName : undefined);
1683
1894
  const options = {
1684
1895
  command: resolvedCommand.file,
1685
- args: [...profile.args],
1896
+ args,
1686
1897
  cwd: resolved.cwd,
1687
1898
  ...(profile.shell !== undefined ? { shell: profile.shell } : {}),
1688
1899
  ...(profile.agent !== undefined ? { agent: profile.agent } : {}),
1689
1900
  ...(profile.readyText !== undefined ? { readyText: profile.readyText } : {}),
1690
1901
  ...(profile.readyQuiet !== undefined ? { readyQuiet: profile.readyQuiet } : {}),
1691
- // The written command stays the session's label, as it was before the
1692
- // path was resolved: the page shows the profile, not a machine path.
1693
- ...(profile.label !== undefined
1694
- ? { label: expandProfileText(profile.label, profile.name, folderLabel) }
1695
- : { 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 }),
1696
1913
  ...(profile.purpose !== undefined
1697
1914
  ? { purpose: expandProfileText(profile.purpose, profile.name, folderLabel) }
1698
1915
  : {}),
1699
1916
  ...(envNames.length > 0 ? { env } : {}),
1700
1917
  // The audit actor, not a caller-declared identity: the dashboard page
1701
1918
  // has no client environment and no other way to name itself.
1702
- startedBy: 'dashboard',
1919
+ startedBy: launcher?.name ?? 'dashboard',
1703
1920
  };
1704
1921
  // Keep the path check adjacent to spawn. A local writer can still replace
1705
1922
  // a directory after this check, as the security model records.
1706
1923
  if (rootCwd !== undefined) {
1707
1924
  const latest = await resolveRootFolder(profile.folderRoots.map((root) => path.resolve(os.homedir(), root)), rootIndex, folderName);
1708
1925
  if ('error' in latest || latest.cwd !== rootCwd) {
1709
- this.auditDashboardRefusal(req, 'body');
1926
+ this.auditDashboardRefusal(req, 'body', launcher?.name);
1710
1927
  json(res, 400, { error: 'Folder is no longer available from this root.' });
1711
1928
  return;
1712
1929
  }
@@ -1714,18 +1931,53 @@ export class Daemon {
1714
1931
  if (freeCwd !== undefined) {
1715
1932
  const latest = resolveAnyFolder(freePath);
1716
1933
  if ('error' in latest || latest.cwd !== freeCwd) {
1717
- this.auditDashboardRefusal(req, 'body');
1934
+ this.auditDashboardRefusal(req, 'body', launcher?.name);
1718
1935
  json(res, 400, { error: 'The chosen folder is no longer available.' });
1719
1936
  return;
1720
1937
  }
1721
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
+ }
1722
1974
  let session;
1723
1975
  try {
1724
1976
  session = (this.options.dashboardSessionFactory ?? ((value) => this.manager.create(value)))(options);
1725
1977
  }
1726
1978
  catch (error) {
1727
1979
  if (error instanceof PolicyViolationError) {
1728
- this.auditDashboardRefusal(req, 'policy');
1980
+ this.auditDashboardRefusal(req, 'policy', launcher?.name);
1729
1981
  json(res, 403, { error: error.message });
1730
1982
  return;
1731
1983
  }
@@ -1762,21 +2014,32 @@ export class Daemon {
1762
2014
  // A launch is an API call: the idle timer counts from it, so a session
1763
2015
  // that has just started is not reaped sooner than `idleMinutes` allows.
1764
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
+ }
1765
2023
  this.sessionFeed.add(this.summaryWithPrompt(session.summary()));
1766
2024
  session.onExit(() => {
1767
2025
  this.geometryController.delete(session.id);
1768
2026
  this.dashboardGeometryOwner.delete(session.id);
2027
+ this.dashboardCredentialOwner.delete(session.id);
2028
+ this.dashboardTransferable.delete(session.id);
1769
2029
  this.updateFeedSession(session.id);
1770
2030
  });
1771
2031
  session.onReady(() => this.updateFeedSession(session.id));
2032
+ this.watchStalls(session);
1772
2033
  // The profile name and the written command line, the file that was
1773
2034
  // actually resolved and started, and copied variable names or "all".
1774
2035
  // Never a value.
1775
- this.audit.record('dashboard', 'start', session.id, {
2036
+ this.audit.record(options.startedBy, 'start', session.id, {
2037
+ startedBy: options.startedBy, ...(launcher ? { launcherId: launcher.id } : {}),
1776
2038
  profile: profile.name,
1777
2039
  command: profile.command,
1778
- args: profile.args,
2040
+ args,
1779
2041
  resolvedCommand: resolvedCommand.file,
2042
+ agent: session.agent,
1780
2043
  ...(profile.envFromDaemon === 'all'
1781
2044
  ? { envFromDaemon: 'all' }
1782
2045
  : copied.length > 0 ? { envFromDaemon: copied } : {}),
@@ -1848,13 +2111,86 @@ export class Daemon {
1848
2111
  this.dropSessionArtifacts(id);
1849
2112
  json(res, 200, { ok: true, killed: id });
1850
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
+ }
1851
2186
  /**
1852
- * Why a `/dashboard/events` upgrade is refused, or null when it may attach.
2187
+ * Authenticate the dashboard event feed and retain its issuing credential.
1853
2188
  * The client token on the query is not a way in. The proof is the
1854
2189
  * subprotocol, not `X-ShellPuppet-CSRF`.
1855
2190
  */
1856
- dashboardUpgradeRefusal(req) {
1857
- if (this.dashboardCookieToken(req.headers.cookie) === null) {
2191
+ dashboardUpgradeCredential(req) {
2192
+ const token = this.dashboardCookieToken(req.headers.cookie);
2193
+ if (token === null) {
1858
2194
  return { code: 401, reason: 'Unauthorized', audit: 'unauthenticated' };
1859
2195
  }
1860
2196
  if (!this.originMatchesRequest(req)) {
@@ -1875,7 +2211,7 @@ export class Daemon {
1875
2211
  });
1876
2212
  if (!accepted)
1877
2213
  return { code: 403, reason: 'Forbidden', audit: 'proof' };
1878
- return null;
2214
+ return token;
1879
2215
  }
1880
2216
  /**
1881
2217
  * Select `sp-csrf.<proof>` when this upgrade's credential is the dashboard
@@ -1932,9 +2268,10 @@ export class Daemon {
1932
2268
  }
1933
2269
  return { ok: true, credential: { kind: 'client', readOnly: false } };
1934
2270
  }
1935
- const dashboard = this.dashboardUpgradeRefusal(req);
1936
- if (dashboard === null) {
1937
- 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 } };
1938
2275
  }
1939
2276
  const viewer = cookieValues(req.headers.cookie, VIEWER_COOKIE)
1940
2277
  .map((value) => ({ value, credential: this.tokens.verifyStreamToken(value) }))
@@ -1972,9 +2309,9 @@ export class Daemon {
1972
2309
  const url = new URL(req.url ?? '/', `http://127.0.0.1:${String(this.portValue ?? 0)}`);
1973
2310
  const segments = url.pathname.split('/').filter((s) => s !== '');
1974
2311
  // Unauthenticated by design (§4.1): clients must be able to poll before
1975
- // the token file settles, and it reveals nothing sensitive.
2312
+ // the token file settles. The instance id is an identity, not a secret.
1976
2313
  if (req.method === 'GET' && url.pathname === '/health') {
1977
- json(res, 200, { ok: true, version: this.version, pid: process.pid });
2314
+ json(res, 200, { ok: true, version: this.version, pid: process.pid, instanceId: this.instanceId });
1978
2315
  return;
1979
2316
  }
1980
2317
  // The viewer page itself is served without auth, and must stay that way:
@@ -2013,7 +2350,7 @@ export class Daemon {
2013
2350
  // learns it. A link whose `s=` had been edited would otherwise spend
2014
2351
  // its grant on a page that then asks for the wrong stream.
2015
2352
  if (url.searchParams.get('s') !== redeemed.sessionId) {
2016
- headers['location'] = `/view?s=${encodeURIComponent(redeemed.sessionId)}`;
2353
+ headers['location'] = `/view?s=${encodeURIComponent(redeemed.sessionId)}${passiveDrive(url) ? '&drive=0' : ''}`;
2017
2354
  res.writeHead(302, headers);
2018
2355
  res.end();
2019
2356
  return;
@@ -2060,10 +2397,18 @@ export class Daemon {
2060
2397
  await this.serveDashboardProfiles(req, res);
2061
2398
  return;
2062
2399
  }
2400
+ if (req.method === 'GET' && url.pathname === '/dashboard/messages') {
2401
+ this.serveDashboardMessages(req, res, url);
2402
+ return;
2403
+ }
2063
2404
  if (req.method === 'POST' && url.pathname === '/dashboard/launch') {
2064
2405
  await this.handleDashboardLaunch(req, res);
2065
2406
  return;
2066
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
+ }
2067
2412
  if (req.method === 'POST' && url.pathname === '/dashboard/folder-picker') {
2068
2413
  const handler = this.handleDashboardFolderPicker(req, res);
2069
2414
  this.folderPickerHandlers.add(handler);
@@ -2100,17 +2445,486 @@ export class Daemon {
2100
2445
  return;
2101
2446
  }
2102
2447
  this.lastActivity = Date.now();
2103
- // Audit actor (design §4.5): adapters self-identify via a header, the MCP
2104
- // adapter as `mcp:<clientInfo.name>` and the CLI as `cli`. Untrusted input,
2105
- // 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.
2106
2450
  const actorHeader = req.headers['x-shellpuppet-actor'];
2107
2451
  const actor = (typeof actorHeader === 'string'
2108
2452
  ? // eslint-disable-next-line no-control-regex
2109
2453
  actorHeader.replace(/[\x00-\x1f\x7f]/g, '').slice(0, 64)
2110
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) {
2111
2921
  try {
2112
2922
  if (segments[0] === 'daemon' && segments[1] === 'shutdown' && req.method === 'POST') {
2113
2923
  const body = await readBody(req);
2924
+ if (this.stopping) {
2925
+ json(res, 200, { ok: true, stopping: true, warnings: this.shutdownWarnings });
2926
+ return;
2927
+ }
2114
2928
  const force = asBoolean(body['force']) ?? false;
2115
2929
  const live = this.manager.liveCount();
2116
2930
  if (live > 0 && !force) {
@@ -2120,9 +2934,10 @@ export class Daemon {
2120
2934
  });
2121
2935
  return;
2122
2936
  }
2937
+ const stopping = this.stop({ restart: body['restart'] === true });
2123
2938
  this.audit.record(actor, 'shutdown', undefined, { force, liveSessions: live });
2124
- json(res, 200, { ok: true, stopping: true });
2125
- void this.stop().then(() => {
2939
+ json(res, 200, { ok: true, stopping: true, warnings: this.shutdownWarnings });
2940
+ void stopping.then(() => {
2126
2941
  this.options.onSelfStop?.('shutdown-request');
2127
2942
  });
2128
2943
  return;
@@ -2141,6 +2956,47 @@ export class Daemon {
2141
2956
  await this.handleDesktopOpen(req, res, actor);
2142
2957
  return;
2143
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
+ }
2144
3000
  if (segments[0] !== 'sessions') {
2145
3001
  json(res, 404, { error: 'Not found.', path: url.pathname });
2146
3002
  return;
@@ -2342,43 +3198,149 @@ export class Daemon {
2342
3198
  json(res, 400, { error: BAD_HIDE_REASONING });
2343
3199
  return;
2344
3200
  }
2345
- 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 () => {
2346
3207
  const snapshot = await session.snapshot();
2347
- 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);
2348
3242
  return;
2349
3243
  }
2350
- // Fails closed: without a signature to read the screen by, nothing
2351
- // is returned, never the screen unfiltered.
2352
- const signature = this.readerFor(session, res);
2353
- 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.` });
2354
3250
  return;
2355
- const snapshot = await session.snapshot();
2356
- const view = await session.styledScreen(REASONING_CONTEXT_LINES);
2357
- const screen = hideReasoning(view.lines, signature, view.firstVisible);
2358
- let tail;
2359
- let tailSource;
2360
- if (count !== undefined) {
2361
- tailSource = await session.styledTail(count, REASONING_CONTEXT_LINES);
2362
- tail = hideReasoning(tailSource.lines, signature, tailSource.firstVisible);
2363
- }
2364
- if (screen === null || tail === null) {
2365
- 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.' });
2366
3256
  return;
2367
3257
  }
2368
- json(res, 200, {
2369
- ...snapshot,
2370
- screen: markFilteredSelectedOption(screen.lines, view.lines).join('\n'),
2371
- cursor: filteredCursor(snapshot.cursor, screen),
2372
- ...(tail !== undefined && tailSource !== undefined
2373
- ? { lastLines: markFilteredSelectedOption(tail.lines, tailSource.lines) }
2374
- : {}),
2375
- reasoning: {
2376
- agent: signature.name,
2377
- hiddenLines: screen.hiddenLines,
2378
- hiddenBlocks: screen.hiddenBlocks,
2379
- ...(tail !== undefined ? { lastLinesHiddenLines: tail.hiddenLines } : {}),
2380
- },
2381
- });
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
+ }
2382
3344
  return;
2383
3345
  }
2384
3346
  if (req.method === 'GET' && action === 'result') {
@@ -2424,9 +3386,9 @@ export class Daemon {
2424
3386
  // caller's request for a race in the session's lifetime. A session
2425
3387
  // whose input pipe has failed refuses the write too, and its error
2426
3388
  // says what to do.
2427
- let before;
3389
+ let written;
2428
3390
  try {
2429
- before = await session.write(data);
3391
+ written = await session.writeWithResult(data);
2430
3392
  }
2431
3393
  catch (error) {
2432
3394
  json(res, 409, {
@@ -2451,11 +3413,18 @@ export class Daemon {
2451
3413
  json(res, 200, {
2452
3414
  ok: true,
2453
3415
  bytes: data.length,
2454
- 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 } : {}),
2455
3420
  });
2456
3421
  return;
2457
3422
  }
2458
- 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
+ });
2459
3428
  return;
2460
3429
  }
2461
3430
  if (req.method === 'POST' && action === 'key') {
@@ -2494,14 +3463,20 @@ export class Daemon {
2494
3463
  json(res, 400, { error: BAD_HIDE_REASONING });
2495
3464
  return;
2496
3465
  }
2497
- const reader = hide ? this.readerFor(session, res) : null;
2498
- 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)
2499
3475
  return;
2500
3476
  const condition = {};
2501
3477
  const text = url.searchParams.get('text');
2502
3478
  const regex = url.searchParams.get('regex');
2503
3479
  const quiet = url.searchParams.get('quiet');
2504
- const prompt = url.searchParams.get('prompt');
2505
3480
  if (text !== null)
2506
3481
  condition.text = text;
2507
3482
  if (regex !== null)
@@ -2513,8 +3488,10 @@ export class Daemon {
2513
3488
  // `prompt === true` only.
2514
3489
  if (prompt !== null)
2515
3490
  condition.prompt = prompt !== 'false' && prompt !== '0';
3491
+ if (stalled)
3492
+ condition.stalled = true;
2516
3493
  const filteredMatch = reader !== null && (condition.text !== undefined || condition.regex !== undefined || condition.prompt === true);
2517
- const muse = signatureFor(session.agent, session.command);
3494
+ const pendingReader = signatureForSession(session);
2518
3495
  let matchView;
2519
3496
  const timeoutParam = url.searchParams.get('timeout');
2520
3497
  const debounceParam = url.searchParams.get('debounce');
@@ -2542,12 +3519,12 @@ export class Daemon {
2542
3519
  ? { matchAfterInput: afterInputParam !== 'false' && afterInputParam !== '0' }
2543
3520
  : {}),
2544
3521
  ...(filteredMatch ? { screenForMatch: () => {
2545
- matchView = filteredWaitScreen(session, reader);
3522
+ matchView = filteredWaitScreen(session, reader, condition.prompt === true);
2546
3523
  return matchView.screen;
2547
- } } : {}),
2548
- ...(muse?.name === 'muse' ? {
3524
+ }, stylesForMatch: () => matchView?.styled } : {}),
3525
+ ...(pendingReader !== null && moduleFor(session.agent)?.readingRules?.pendingComposer === true ? {
2549
3526
  composerPending: () => {
2550
- const result = latestResult(session.styledScreenNow(REASONING_CONTEXT_LINES).lines, muse);
3527
+ const result = latestResult(session.styledScreenNow(REASONING_CONTEXT_LINES).lines, pendingReader);
2551
3528
  return !result.found && result.reason === 'prompt-typed';
2552
3529
  },
2553
3530
  } : {}),
@@ -2561,6 +3538,10 @@ export class Daemon {
2561
3538
  // Nobody to answer, and writing to a closed response throws.
2562
3539
  if (abort.signal.aborted)
2563
3540
  return;
3541
+ if (result.reason === 'stalled') {
3542
+ json(res, 200, { ...result, id: session.id, exited: session.exited, exitCode: session.exitCode });
3543
+ return;
3544
+ }
2564
3545
  if (reader !== null) {
2565
3546
  if (filteredMatch && matchView !== undefined) {
2566
3547
  json(res, 200, {
@@ -2580,10 +3561,10 @@ export class Daemon {
2580
3561
  json(res, 400, { error: overBudgetMessage(reader) });
2581
3562
  return;
2582
3563
  }
2583
- const marked = markFilteredSelectedOption(filtered.lines, view.lines);
3564
+ const marked = markFilteredSelectedOption(filtered.lines, view.lines, session.agent);
2584
3565
  const visiblePrompt = result.prompt === undefined
2585
3566
  ? null
2586
- : detectPrompt(marked.join('\n'));
3567
+ : detectPrompt(marked.join('\n'), session.agent, undefined, filteredPromptStyles(filtered, view));
2587
3568
  const prompt = visiblePrompt !== null && visiblePrompt.signature === result.prompt?.signature
2588
3569
  ? {
2589
3570
  question: visiblePrompt.question,
@@ -2679,7 +3660,16 @@ export class Daemon {
2679
3660
  }
2680
3661
  const hold = body['hold'] === true;
2681
3662
  try {
2682
- 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
+ } });
2683
3673
  }
2684
3674
  catch (error) {
2685
3675
  if (!(error instanceof SessionProgramEndedError))
@@ -2687,21 +3677,35 @@ export class Daemon {
2687
3677
  json(res, 409, { error: endedRefusal(id, error.exitCode) });
2688
3678
  return;
2689
3679
  }
2690
- this.audit.record(actor, 'resize', id, { cols, rows, hold });
2691
- // An API resize takes the grid away from whichever viewport had it, so
2692
- // nobody is left believing they still drive it. It does NOT hold
2693
- // unless asked: a human whose window is now the wrong shape gets it
2694
- // back by moving that window, which is the only escape they have while
2695
- // there is no takeover control to press (§5).
2696
- this.geometryController.delete(id);
2697
- this.dashboardGeometryOwner.delete(id);
2698
- this.announceGeometry(id, session);
2699
3680
  json(res, 200, { ok: true, cols, rows, geometryHeld: session.geometryHeld });
2700
3681
  return;
2701
3682
  }
2702
3683
  json(res, 404, { error: 'Not found.', path: url.pathname });
2703
3684
  }
2704
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
+ }
2705
3709
  if (error instanceof WaitConditionError) {
2706
3710
  json(res, 400, { error: error.message });
2707
3711
  return;
@@ -2777,6 +3781,9 @@ export class Daemon {
2777
3781
  // diverge from the audit trail. Self-declared, not authenticated: see
2778
3782
  // SessionOptions.startedBy.
2779
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']) } : {}),
2780
3787
  ...(asString(body['readyText']) !== undefined
2781
3788
  ? { readyText: asString(body['readyText']) }
2782
3789
  : {}),
@@ -2797,7 +3804,7 @@ export class Daemon {
2797
3804
  json(res, 403, { error: error.message });
2798
3805
  return;
2799
3806
  }
2800
- if (error instanceof CommandNotFoundError) {
3807
+ if (error instanceof CommandNotFoundError || error instanceof WaitConditionError) {
2801
3808
  json(res, 400, { error: error.message });
2802
3809
  return;
2803
3810
  }
@@ -2829,15 +3836,19 @@ export class Daemon {
2829
3836
  session = startedSession;
2830
3837
  // Registration is synchronous with creation, before any asynchronous
2831
3838
  // viewer launch or readiness work can publish a change for this id.
3839
+ this.registerMailboxSession(session);
2832
3840
  this.sessionFeed.add(this.summaryWithPrompt(session.summary()));
2833
3841
  session.onExit(() => {
2834
3842
  this.clearPromptGraceCheck(session.id);
2835
3843
  this.promptStates.delete(session.id);
2836
3844
  this.geometryController.delete(session.id);
2837
3845
  this.dashboardGeometryOwner.delete(session.id);
3846
+ this.dashboardCredentialOwner.delete(session.id);
3847
+ this.dashboardTransferable.delete(session.id);
2838
3848
  this.updateFeedSession(session.id);
2839
3849
  });
2840
3850
  session.onReady(() => this.updateFeedSession(session.id));
3851
+ this.watchStalls(session);
2841
3852
  // Commands are policy-visible by definition, so the command line IS
2842
3853
  // audited (§4.5), unlike typed content. Passed variables are audited by
2843
3854
  // name only, whatever `audit.captureContent` says: a value is a secret
@@ -2846,7 +3857,7 @@ export class Daemon {
2846
3857
  command: options.command,
2847
3858
  args: options.args ?? [],
2848
3859
  ...(envNames.length > 0 ? { envNames } : {}),
2849
- ...(agent !== undefined ? { agent } : {}),
3860
+ agent: session.agent,
2850
3861
  label: session.label,
2851
3862
  });
2852
3863
  // The human's way in (design §3.1): the dashboard, a single-session viewer
@@ -2916,6 +3927,15 @@ export class Daemon {
2916
3927
  const handOver = wantsViewer && !dashboardWatching && !opened.launched && viewerUrl !== '';
2917
3928
  if (handOver)
2918
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);
2919
3939
  json(res, 200, {
2920
3940
  id: session.id,
2921
3941
  label: session.label,
@@ -2926,6 +3946,7 @@ export class Daemon {
2926
3946
  // Without the reason, `ready: true` is ambiguous: it may mean nothing
2927
3947
  // was checked. Callers need to tell those apart before they type.
2928
3948
  readyReason: session.readyReason,
3949
+ ...(readyWait === undefined ? {} : { readyWait, exited: session.exited, exitCode: session.exitCode }),
2929
3950
  geometryHeld: session.geometryHeld,
2930
3951
  viewer: {
2931
3952
  opened: opened.launched,
@@ -2941,12 +3962,12 @@ export class Daemon {
2941
3962
  * readers fail closed.
2942
3963
  */
2943
3964
  readerFor(session, res) {
2944
- const signature = signatureFor(session.agent, session.command);
3965
+ const signature = signatureForSession(session);
2945
3966
  if (signature !== null)
2946
3967
  return signature;
2947
3968
  const known = agentNames().join(', ');
2948
3969
  json(res, 400, {
2949
- error: session.agent !== undefined
3970
+ error: session.agentSource !== 'fallback'
2950
3971
  ? `Session ${session.id} was started as agent "${session.agent}", whose signature is not ` +
2951
3972
  `available now (removed from config, or set aside for running past its time budget), ` +
2952
3973
  `so its screen is not read for hideReasoning or a result.`
@@ -3031,6 +4052,9 @@ export class Daemon {
3031
4052
  this.sessionSockets.delete(id);
3032
4053
  this.geometryController.delete(id);
3033
4054
  this.dashboardGeometryOwner.delete(id);
4055
+ this.dashboardCredentialOwner.delete(id);
4056
+ this.dashboardTransferable.delete(id);
4057
+ this.geometryEpoch.delete(id);
3034
4058
  }
3035
4059
  /** Whether a live viewport is currently driving this session's grid. */
3036
4060
  hasGeometryController(sessionId) {
@@ -3076,7 +4100,8 @@ export class Daemon {
3076
4100
  }
3077
4101
  /** The sessions a client or the dashboard may see: every one but those still starting. */
3078
4102
  listedSummaries() {
3079
- 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 }));
3080
4105
  }
3081
4106
  /**
3082
4107
  * Session list decorated with whatever prompt each session is holding. The
@@ -3093,7 +4118,7 @@ export class Daemon {
3093
4118
  * against prompts that sit for minutes.
3094
4119
  */
3095
4120
  listWithPrompts(hideReasoning = false) {
3096
- const now = Date.now();
4121
+ const now = this.now();
3097
4122
  return this.listedSummaries().map((summary) => {
3098
4123
  const full = this.summaryWithPrompt(summary, now);
3099
4124
  const waiting = full.waitingOnPrompt;
@@ -3102,7 +4127,10 @@ export class Daemon {
3102
4127
  return { ...full, waitingOnPrompt: { waitingMs: waiting.waitingMs, alerted: waiting.alerted } };
3103
4128
  });
3104
4129
  }
3105
- 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;
3106
4134
  const state = this.promptStates.get(summary.id);
3107
4135
  if (state === undefined)
3108
4136
  return summary;
@@ -3122,6 +4150,30 @@ export class Daemon {
3122
4150
  if (session !== undefined)
3123
4151
  this.sessionFeed.update(this.summaryWithPrompt(session.summary()));
3124
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
+ }
3125
4177
  clearPromptGraceCheck(id) {
3126
4178
  const timer = this.promptGraceTimers.get(id);
3127
4179
  if (timer !== undefined)
@@ -3187,8 +4239,8 @@ export class Daemon {
3187
4239
  // scan interval; a lasting disappearance still clears it.
3188
4240
  if (previous !== undefined) {
3189
4241
  if (previous.missingSince === null)
3190
- previous.missingSince = Date.now();
3191
- 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();
3192
4244
  if (remaining > 0) {
3193
4245
  this.schedulePromptGraceCheck(session.id, remaining);
3194
4246
  continue;
@@ -3256,7 +4308,7 @@ export class Daemon {
3256
4308
  }
3257
4309
  this.promptStates.set(session.id, {
3258
4310
  signature: detected.signature,
3259
- since: Date.now(),
4311
+ since: this.now(),
3260
4312
  alerted: false,
3261
4313
  prompt: detected,
3262
4314
  missingSince: null,
@@ -3268,10 +4320,10 @@ export class Daemon {
3268
4320
  previous.signature = detected.signature;
3269
4321
  if (promptChanged)
3270
4322
  this.updateFeedSession(session.id);
3271
- if (!previous.alerted && Date.now() - previous.since >= stallMs) {
4323
+ if (!previous.alerted && this.now() - previous.since >= stallMs) {
3272
4324
  previous.alerted = true;
3273
4325
  this.updateFeedSession(session.id);
3274
- const waitingMs = Date.now() - previous.since;
4326
+ const waitingMs = this.now() - previous.since;
3275
4327
  this.audit.record('daemon', 'prompt-stall', session.id);
3276
4328
  this.logger.warn('session waiting on a prompt', {
3277
4329
  id: session.id,
@@ -3309,15 +4361,34 @@ export class Daemon {
3309
4361
  this.updateFeedSession(id);
3310
4362
  }
3311
4363
  }
4364
+ await this.nudges.tick();
3312
4365
  }
3313
4366
  /** Fan an event out to every `/events` subscriber (TEXT JSON frames). */
3314
4367
  emitEvent(event) {
3315
4368
  const message = JSON.stringify({ ...event, at: new Date().toISOString() });
3316
- for (const ws of this.eventSockets) {
4369
+ for (const ws of this.eventSockets.keys()) {
3317
4370
  if (ws.readyState === ws.OPEN)
3318
4371
  ws.send(message);
3319
4372
  }
3320
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
+ }
3321
4392
  // ------------------------------------------------------------- websockets
3322
4393
  handleUpgrade(req, socket, head) {
3323
4394
  // Node takes its own 'error' listener off the socket before it emits
@@ -3362,14 +4433,14 @@ export class Daemon {
3362
4433
  // The dashboard feed is cookie-only. Its Origin rule is stricter than the
3363
4434
  // client-token sockets below, which still allow a missing Origin.
3364
4435
  if (segments[0] === 'dashboard' && segments[1] === 'events' && segments.length === 2) {
3365
- const refusal = this.dashboardUpgradeRefusal(req);
3366
- if (refusal !== null) {
3367
- this.auditDashboardRefusal(req, refusal.audit);
3368
- 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);
3369
4440
  return;
3370
4441
  }
3371
4442
  this.wss.handleUpgrade(req, socket, head, (ws) => {
3372
- this.attachDashboardSocket(ws);
4443
+ this.attachDashboardSocket(ws, credential);
3373
4444
  });
3374
4445
  return;
3375
4446
  }
@@ -3383,8 +4454,24 @@ export class Daemon {
3383
4454
  reject(401, 'Unauthorized');
3384
4455
  return;
3385
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
+ }
3386
4473
  this.wss.handleUpgrade(req, socket, head, (ws) => {
3387
- this.attachEventSocket(ws);
4474
+ this.callerContext.run(caller.session, () => this.attachEventSocket(ws, caller.session ?? (typeof claimId === 'string' ? claimId : undefined)));
3388
4475
  });
3389
4476
  return;
3390
4477
  }
@@ -3411,6 +4498,13 @@ export class Daemon {
3411
4498
  reject(decision.code, decision.reason);
3412
4499
  return;
3413
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
+ }
3414
4508
  const session = this.manager.get(sessionId);
3415
4509
  if (session === undefined) {
3416
4510
  reject(404, 'Not Found');
@@ -3425,13 +4519,13 @@ export class Daemon {
3425
4519
  // names that credential rather than assuming a browser: `client` for
3426
4520
  // the client token on the query, `viewer` for a viewer cookie,
3427
4521
  // `dashboard` for the dashboard cookie.
3428
- 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 }));
3429
4523
  });
3430
4524
  }
3431
4525
  /** Attach a subscriber to the daemon-wide event stream. */
3432
- attachEventSocket(ws) {
4526
+ attachEventSocket(ws, participant) {
3433
4527
  this.sockets.add(ws);
3434
- this.eventSockets.add(ws);
4528
+ this.eventSockets.set(ws, participant);
3435
4529
  this.lastActivity = Date.now();
3436
4530
  this.audit.record('client', 'events-connect', '-');
3437
4531
  ws.send(JSON.stringify({ type: 'hello', version: this.version }));
@@ -3446,13 +4540,97 @@ export class Daemon {
3446
4540
  // The stream is outbound-only; inbound frames are ignored by design.
3447
4541
  }
3448
4542
  /**
3449
- * Attach a subscriber to the dashboard session feed. Frames are the feed's
3450
- * own: hello, a snapshot, then session deltas. The only inbound frame read is
3451
- * 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.
3452
4546
  * The socket counts as connected so idle shutdown waits while the dashboard
3453
4547
  * is open.
3454
4548
  */
3455
- 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);
3456
4634
  this.sockets.add(ws);
3457
4635
  this.dashboardEventSockets.add(ws);
3458
4636
  this.liveDashboardEventSockets.add(ws);
@@ -3480,16 +4658,18 @@ export class Daemon {
3480
4658
  const unsubscribe = this.subscribeDashboardFeed((frame) => {
3481
4659
  if (ws.readyState === ws.OPEN)
3482
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();
3483
4664
  });
3484
4665
  ws.on('message', (raw) => {
3485
- // This id only speeds roster departure. It grants no daemon action.
3486
- if (this.dashboardWindowIds.has(ws))
4666
+ if (!this.dashboardFeedCurrent(ws))
3487
4667
  return;
3488
4668
  let frame;
3489
4669
  try {
3490
4670
  const bytes = Array.isArray(raw) ? Buffer.concat(raw) : Buffer.from(raw);
3491
- // A registration is a few dozen bytes: never parse anything larger.
3492
- if (bytes.length > MAX_WINDOW_REGISTRATION_BYTES)
4671
+ // Window control frames are small: never parse anything larger.
4672
+ if (bytes.length > 1024)
3493
4673
  return;
3494
4674
  frame = JSON.parse(bytes.toString('utf8'));
3495
4675
  }
@@ -3499,17 +4679,57 @@ export class Daemon {
3499
4679
  if (typeof frame !== 'object' || frame === null)
3500
4680
  return;
3501
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
+ }
3502
4716
  if (claim.type !== 'window-register' || typeof claim.id !== 'string' ||
3503
4717
  !/^[a-z0-9]+-[a-z0-9]+(?:-[1-9][0-9]*)?$/.test(claim.id) || claim.id.length > 100 ||
3504
4718
  typeof claim.instance !== 'string' ||
3505
4719
  !/^[a-z0-9]+-[a-z0-9]+(?:-[1-9][0-9]*)?$/.test(claim.instance) ||
3506
4720
  claim.instance.length > 100)
3507
4721
  return;
3508
- 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();
3509
4727
  });
3510
4728
  ws.on('close', () => {
3511
4729
  const windowClaim = this.dashboardWindowIds.get(ws);
3512
4730
  this.dashboardWindowIds.delete(ws);
4731
+ if (windowClaim !== undefined)
4732
+ this.publishDashboardWindows();
3513
4733
  unsubscribe();
3514
4734
  this.sockets.delete(ws);
3515
4735
  this.dashboardEventSockets.delete(ws);
@@ -3566,16 +4786,30 @@ export class Daemon {
3566
4786
  }
3567
4787
  this.updateFeedSession(sessionId);
3568
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
+ }
3569
4795
  /** What one watcher is told about the grid, from its own point of view. */
3570
4796
  geometryFrame(session, ws) {
3571
4797
  return {
3572
4798
  type: 'geometry',
4799
+ ...(this.widerReads.get(session.id)?.isTemporary() ? { temporary: true } : {}),
3573
4800
  cols: session.cols,
3574
4801
  rows: session.rows,
3575
4802
  // The most a viewport may ask for (§5), with every frame: a page whose
3576
4803
  // window wants more can then size its text for the grid it will be
3577
4804
  // given, rather than proposing one it never will be.
3578
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),
3579
4813
  control: session.geometryHeld
3580
4814
  ? 'held'
3581
4815
  : this.geometryController.get(session.id) === ws
@@ -3625,6 +4859,8 @@ export class Daemon {
3625
4859
  // or program behind it.
3626
4860
  const actor = credential.kind;
3627
4861
  this.sockets.add(ws);
4862
+ if (credential.dashboardToken !== undefined)
4863
+ this.dashboardSocketCredential.set(ws, credential.dashboardToken);
3628
4864
  let watchers = this.sessionSockets.get(session.id);
3629
4865
  if (watchers === undefined) {
3630
4866
  watchers = new Map();
@@ -3676,22 +4912,29 @@ export class Daemon {
3676
4912
  // never picks it up by connecting, whatever the query says, and neither
3677
4913
  // does a `drive=0` socket. Neither inherits a controller that has left:
3678
4914
  // this is the only place a socket becomes the controller without sending
3679
- // `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.
3680
4917
  if (credential.kind === 'dashboard' &&
3681
- // The remembered proof identifies the dashboard credential, not a browser window;
3682
- // 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.
3683
4920
  this.dashboardGeometryOwner.has(session.id) &&
4921
+ (!this.dashboardTransferable.has(session.id) || this.gridOfferedTo(session.id, ws)) &&
3684
4922
  tokensEqual(this.dashboardGeometryOwner.get(session.id), ws.protocol) &&
3685
4923
  !session.exited &&
3686
4924
  !this.hasGeometryController(session.id)) {
3687
4925
  this.geometryController.set(session.id, ws);
4926
+ this.dashboardTransferable.delete(session.id);
4927
+ this.announceGeometry(session.id, session, { resync: false });
3688
4928
  }
3689
4929
  else if (!session.geometryHeld &&
3690
4930
  !readOnly &&
3691
4931
  !passive &&
3692
- !this.hasGeometryController(session.id)) {
4932
+ !this.hasGeometryController(session.id) &&
4933
+ !this.dashboardGeometryOwner.has(session.id)) {
3693
4934
  this.geometryController.set(session.id, ws);
3694
4935
  this.dashboardGeometryOwner.delete(session.id);
4936
+ this.dashboardCredentialOwner.delete(session.id);
4937
+ this.dashboardTransferable.delete(session.id);
3695
4938
  }
3696
4939
  ws.send(JSON.stringify(options.frozen === undefined
3697
4940
  ? this.geometryFrame(session, ws)
@@ -3724,13 +4967,16 @@ export class Daemon {
3724
4967
  // AFTER the resync, so the gate holds it behind the snapshot instead of
3725
4968
  // letting the snapshot's wipe erase it.
3726
4969
  if (session.exited) {
3727
- sync.deliver(exitNotice(session.exitCode));
4970
+ sync.deliver(session.fault === null ? exitNotice(session.exitCode) : `session ended: ${session.fault}`);
3728
4971
  }
3729
4972
  // A stall is announced once, at the moment it trips. Someone who opens the
3730
4973
  // viewer BECAUSE they were told a session is stuck arrives after
3731
4974
  // the only announcement, and is the exact person the badge is for. Replay the
3732
4975
  // current state to them.
3733
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 }));
3734
4980
  if (held?.alerted === true) {
3735
4981
  ws.send(JSON.stringify({
3736
4982
  type: 'prompt-stall',
@@ -3743,11 +4989,12 @@ export class Daemon {
3743
4989
  const unsubscribeData = session.onData((data) => sync.deliver(data));
3744
4990
  this.updateFeedSession(session.id);
3745
4991
  const unsubscribeExit = session.onExit((exitCode) => {
3746
- sync.deliver(exitNotice(exitCode));
4992
+ sync.deliver(session.fault === null ? exitNotice(exitCode) : `session ended: ${session.fault}`);
3747
4993
  // The notice is bytes on the terminal; the page needs a frame to change
3748
4994
  // its own state.
3749
4995
  if (ws.readyState === ws.OPEN) {
3750
- ws.send(JSON.stringify({ type: 'exited', exitCode }));
4996
+ ws.send(JSON.stringify({ type: 'exited', exitCode,
4997
+ ...(session.fault === null ? {} : { fault: session.fault }) }));
3751
4998
  }
3752
4999
  });
3753
5000
  // A protocol error, such as a malformed frame or a reset mid-handshake,
@@ -3764,10 +5011,26 @@ export class Daemon {
3764
5011
  const text = typeof message === 'string' ? message : message.toString('utf8');
3765
5012
  try {
3766
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
+ }
3767
5030
  if (typeof parsed === 'object' &&
3768
5031
  parsed !== null &&
3769
5032
  parsed.type === 'resize') {
3770
- const { cols, rows, take } = parsed;
5033
+ const { cols, rows, take, acceptOffer } = parsed;
3771
5034
  // Fit, Enlarge, Focus and Restore are a resize that says `take`.
3772
5035
  // A passive socket's other resizes, including one a dashboard pane
3773
5036
  // sends because the window moved, are not that act: the grid stays,
@@ -3795,12 +5058,80 @@ export class Daemon {
3795
5058
  cols: Math.min(cols, MAX_VIEWPORT_COLS),
3796
5059
  rows: Math.min(rows, MAX_VIEWPORT_ROWS),
3797
5060
  };
3798
- const handedOver = this.geometryController.get(session.id) !== ws;
3799
- const changed = wanted.cols !== session.cols || wanted.rows !== session.rows;
3800
- 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
+ }
3801
5101
  try {
3802
- await session.resize(wanted.cols, wanted.rows);
3803
- 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)));
3804
5135
  }
3805
5136
  catch (error) {
3806
5137
  // The program has ended (a viewer fitting its window while
@@ -3820,39 +5151,6 @@ export class Daemon {
3820
5151
  error: String(error),
3821
5152
  });
3822
5153
  }
3823
- // Asking is the deliberate act that takes control, whether or not
3824
- // the grid actually moves: a viewport that already fits is still
3825
- // the one driving.
3826
- this.geometryController.set(session.id, ws);
3827
- if (credential.kind === 'dashboard')
3828
- this.dashboardGeometryOwner.set(session.id, ws.protocol);
3829
- else
3830
- this.dashboardGeometryOwner.delete(session.id);
3831
- // A geometry change is a geometry change whoever made it, and
3832
- // `resize` is on the list of audited actions the security page
3833
- // publishes. Only the ones that actually took: a proposal the
3834
- // grid already satisfied moved nothing, and one that failed moved
3835
- // nothing either, so neither is recorded as a success. `hold` is
3836
- // false because a viewport never holds: holding is asked for
3837
- // explicitly, over the API (§5).
3838
- if (changed && applied) {
3839
- this.audit.record(actor, 'resize', session.id, {
3840
- cols: wanted.cols,
3841
- rows: wanted.rows,
3842
- hold: false,
3843
- });
3844
- }
3845
- // Everyone sees the same grid, and each is told whether they are
3846
- // now driving it. A proposal that changed nothing needs no
3847
- // snapshot, because the page already shows this grid. But if the
3848
- // grid changed hands, everyone is told that much, or the old
3849
- // driver goes on believing it is theirs.
3850
- if (changed)
3851
- this.announceGeometry(session.id, session);
3852
- else if (handedOver)
3853
- this.announceGeometry(session.id, session, { resync: false });
3854
- else if (take === true)
3855
- ws.send(JSON.stringify(this.geometryFrame(session, ws)));
3856
5154
  }
3857
5155
  return;
3858
5156
  }
@@ -3901,7 +5199,8 @@ export class Daemon {
3901
5199
  // sequences, so this is not always one keystroke.) .catch keeps the exit
3902
5200
  // race, the session dying mid-write, from escaping as an unhandled
3903
5201
  // rejection.
3904
- void session.write(text).catch((error) => {
5202
+ const report = terminalReportKind(text);
5203
+ void session.write(text, { terminalReport: report !== null, humanInput: report === null }).catch((error) => {
3905
5204
  this.logger.warn('viewer input failed', {
3906
5205
  id: session.id,
3907
5206
  error: String(error),
@@ -3912,7 +5211,6 @@ export class Daemon {
3912
5211
  // because the program asked for it. Nobody typed it, so it is audited
3913
5212
  // as a report and leaves the "last input" indicator alone (§4.5, §5).
3914
5213
  // Content only under captureContent, as for input.
3915
- const report = terminalReportKind(text);
3916
5214
  if (report !== null) {
3917
5215
  this.audit.record(actor, 'report', session.id, {
3918
5216
  kind: report,
@@ -3928,26 +5226,33 @@ export class Daemon {
3928
5226
  this.broadcastControl(session.id, { type: 'input-source', source: 'human' });
3929
5227
  };
3930
5228
  ws.on('message', (message) => {
3931
- void onViewerMessage(message).catch((error) => {
3932
- 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
+ });
3933
5233
  });
3934
5234
  });
3935
5235
  ws.on('close', () => {
3936
- unsubscribeData();
3937
- unsubscribeExit();
3938
- sync.close();
3939
- this.sockets.delete(ws);
3940
- this.sessionSockets.get(session.id)?.delete(ws);
3941
- this.updateFeedSession(session.id);
3942
- // The grid stays where it is; it simply no longer belongs to anyone.
3943
- // The next single-session viewport to arrive, or a `take`, picks it
3944
- // up. A dashboard socket, and a `drive=0` socket, that is already
3945
- // connected does not inherit it.
3946
- if (this.geometryController.get(session.id) === ws) {
3947
- this.geometryController.delete(session.id);
3948
- }
3949
- this.lastActivity = Date.now();
3950
- 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
+ });
3951
5256
  });
3952
5257
  }
3953
5258
  }