shellpuppet 0.2.1 → 0.4.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 (283) hide show
  1. package/README.md +65 -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/liveResumeId.d.ts +6 -0
  18. package/dist/agents/claude/liveResumeId.js +101 -0
  19. package/dist/agents/claude/liveResumeId.js.map +1 -0
  20. package/dist/agents/claude/nudge.d.ts +2 -0
  21. package/dist/agents/claude/nudge.js +38 -0
  22. package/dist/agents/claude/nudge.js.map +1 -0
  23. package/dist/agents/claude/prompts.d.ts +9 -0
  24. package/dist/agents/claude/prompts.js +16 -0
  25. package/dist/agents/claude/prompts.js.map +1 -0
  26. package/dist/agents/claude/reading.d.ts +2 -0
  27. package/dist/agents/claude/reading.js +25 -0
  28. package/dist/agents/claude/reading.js.map +1 -0
  29. package/dist/agents/codex/draft.d.ts +3 -0
  30. package/dist/agents/codex/draft.js +88 -0
  31. package/dist/agents/codex/draft.js.map +1 -0
  32. package/dist/agents/codex/index.d.ts +2 -0
  33. package/dist/agents/codex/index.js +30 -0
  34. package/dist/agents/codex/index.js.map +1 -0
  35. package/dist/agents/codex/lineBreaks.d.ts +6 -0
  36. package/dist/agents/codex/lineBreaks.js +105 -0
  37. package/dist/agents/codex/lineBreaks.js.map +1 -0
  38. package/dist/agents/codex/nudge.d.ts +2 -0
  39. package/dist/agents/codex/nudge.js +34 -0
  40. package/dist/agents/codex/nudge.js.map +1 -0
  41. package/dist/agents/codex/prompts.d.ts +9 -0
  42. package/dist/agents/codex/prompts.js +14 -0
  43. package/dist/agents/codex/prompts.js.map +1 -0
  44. package/dist/agents/codex/reading.d.ts +2 -0
  45. package/dist/agents/codex/reading.js +22 -0
  46. package/dist/agents/codex/reading.js.map +1 -0
  47. package/dist/agents/generic/index.d.ts +3 -0
  48. package/dist/agents/generic/index.js +9 -0
  49. package/dist/agents/generic/index.js.map +1 -0
  50. package/dist/agents/generic/prompts.d.ts +2 -0
  51. package/dist/agents/generic/prompts.js +10 -0
  52. package/dist/agents/generic/prompts.js.map +1 -0
  53. package/dist/agents/grok/actionBox.d.ts +13 -0
  54. package/dist/agents/grok/actionBox.js +127 -0
  55. package/dist/agents/grok/actionBox.js.map +1 -0
  56. package/dist/agents/grok/index.d.ts +2 -0
  57. package/dist/agents/grok/index.js +20 -0
  58. package/dist/agents/grok/index.js.map +1 -0
  59. package/dist/agents/grok/nudge.d.ts +2 -0
  60. package/dist/agents/grok/nudge.js +81 -0
  61. package/dist/agents/grok/nudge.js.map +1 -0
  62. package/dist/agents/grok/prompts.d.ts +4 -0
  63. package/dist/agents/grok/prompts.js +89 -0
  64. package/dist/agents/grok/prompts.js.map +1 -0
  65. package/dist/agents/grok/reading.d.ts +2 -0
  66. package/dist/agents/grok/reading.js +49 -0
  67. package/dist/agents/grok/reading.js.map +1 -0
  68. package/dist/agents/grok/readingRules.d.ts +2 -0
  69. package/dist/agents/grok/readingRules.js +44 -0
  70. package/dist/agents/grok/readingRules.js.map +1 -0
  71. package/dist/agents/hermes/frame.d.ts +25 -0
  72. package/dist/agents/hermes/frame.js +145 -0
  73. package/dist/agents/hermes/frame.js.map +1 -0
  74. package/dist/agents/hermes/index.d.ts +2 -0
  75. package/dist/agents/hermes/index.js +20 -0
  76. package/dist/agents/hermes/index.js.map +1 -0
  77. package/dist/agents/hermes/nudge.d.ts +5 -0
  78. package/dist/agents/hermes/nudge.js +76 -0
  79. package/dist/agents/hermes/nudge.js.map +1 -0
  80. package/dist/agents/hermes/prompts.d.ts +7 -0
  81. package/dist/agents/hermes/prompts.js +101 -0
  82. package/dist/agents/hermes/prompts.js.map +1 -0
  83. package/dist/agents/hermes/reading.d.ts +7 -0
  84. package/dist/agents/hermes/reading.js +102 -0
  85. package/dist/agents/hermes/reading.js.map +1 -0
  86. package/dist/agents/index.d.ts +28 -0
  87. package/dist/agents/index.js +48 -0
  88. package/dist/agents/index.js.map +1 -0
  89. package/dist/agents/input.d.ts +2 -0
  90. package/dist/agents/input.js +9 -0
  91. package/dist/agents/input.js.map +1 -0
  92. package/dist/agents/mimo/index.d.ts +2 -0
  93. package/dist/agents/mimo/index.js +13 -0
  94. package/dist/agents/mimo/index.js.map +1 -0
  95. package/dist/agents/mimo/nudge.d.ts +3 -0
  96. package/dist/agents/mimo/nudge.js +60 -0
  97. package/dist/agents/mimo/nudge.js.map +1 -0
  98. package/dist/agents/mimo/prompts.d.ts +2 -0
  99. package/dist/agents/mimo/prompts.js +40 -0
  100. package/dist/agents/mimo/prompts.js.map +1 -0
  101. package/dist/agents/mimo/reading.d.ts +2 -0
  102. package/dist/agents/mimo/reading.js +31 -0
  103. package/dist/agents/mimo/reading.js.map +1 -0
  104. package/dist/agents/mimo/readingRules.d.ts +2 -0
  105. package/dist/agents/mimo/readingRules.js +79 -0
  106. package/dist/agents/mimo/readingRules.js.map +1 -0
  107. package/dist/agents/mimo/stalls.d.ts +2 -0
  108. package/dist/agents/mimo/stalls.js +81 -0
  109. package/dist/agents/mimo/stalls.js.map +1 -0
  110. package/dist/agents/muse/index.d.ts +2 -0
  111. package/dist/agents/muse/index.js +20 -0
  112. package/dist/agents/muse/index.js.map +1 -0
  113. package/dist/agents/muse/input.d.ts +3 -0
  114. package/dist/agents/muse/input.js +7 -0
  115. package/dist/agents/muse/input.js.map +1 -0
  116. package/dist/agents/muse/nudge.d.ts +2 -0
  117. package/dist/agents/muse/nudge.js +33 -0
  118. package/dist/agents/muse/nudge.js.map +1 -0
  119. package/dist/agents/muse/prompts.d.ts +14 -0
  120. package/dist/agents/muse/prompts.js +132 -0
  121. package/dist/agents/muse/prompts.js.map +1 -0
  122. package/dist/agents/muse/reading.d.ts +2 -0
  123. package/dist/agents/muse/reading.js +33 -0
  124. package/dist/agents/muse/reading.js.map +1 -0
  125. package/dist/agents/muse/readingRules.d.ts +2 -0
  126. package/dist/agents/muse/readingRules.js +49 -0
  127. package/dist/agents/muse/readingRules.js.map +1 -0
  128. package/dist/agents/nudgeReading.d.ts +74 -0
  129. package/dist/agents/nudgeReading.js +252 -0
  130. package/dist/agents/nudgeReading.js.map +1 -0
  131. package/dist/agents/opencode/index.d.ts +2 -0
  132. package/dist/agents/opencode/index.js +21 -0
  133. package/dist/agents/opencode/index.js.map +1 -0
  134. package/dist/agents/opencode/nudge.d.ts +6 -0
  135. package/dist/agents/opencode/nudge.js +189 -0
  136. package/dist/agents/opencode/nudge.js.map +1 -0
  137. package/dist/agents/opencode/prompts.d.ts +6 -0
  138. package/dist/agents/opencode/prompts.js +198 -0
  139. package/dist/agents/opencode/prompts.js.map +1 -0
  140. package/dist/agents/opencode/reading.d.ts +2 -0
  141. package/dist/agents/opencode/reading.js +29 -0
  142. package/dist/agents/opencode/reading.js.map +1 -0
  143. package/dist/agents/opencode/stalls.d.ts +3 -0
  144. package/dist/agents/opencode/stalls.js +14 -0
  145. package/dist/agents/opencode/stalls.js.map +1 -0
  146. package/dist/agents/qoder/index.d.ts +2 -0
  147. package/dist/agents/qoder/index.js +12 -0
  148. package/dist/agents/qoder/index.js.map +1 -0
  149. package/dist/agents/qoder/nudge.d.ts +2 -0
  150. package/dist/agents/qoder/nudge.js +16 -0
  151. package/dist/agents/qoder/nudge.js.map +1 -0
  152. package/dist/agents/qoder/prompts.d.ts +2 -0
  153. package/dist/agents/qoder/prompts.js +6 -0
  154. package/dist/agents/qoder/prompts.js.map +1 -0
  155. package/dist/agents/qoder/reading.d.ts +2 -0
  156. package/dist/agents/qoder/reading.js +41 -0
  157. package/dist/agents/qoder/reading.js.map +1 -0
  158. package/dist/agents/types.d.ts +202 -0
  159. package/dist/agents/types.js +2 -0
  160. package/dist/agents/types.js.map +1 -0
  161. package/dist/cli/index.js +220 -21
  162. package/dist/cli/index.js.map +1 -1
  163. package/dist/client/http.d.ts +8 -2
  164. package/dist/client/http.js +179 -56
  165. package/dist/client/http.js.map +1 -1
  166. package/dist/core/cron.d.ts +6 -0
  167. package/dist/core/cron.js +63 -0
  168. package/dist/core/cron.js.map +1 -0
  169. package/dist/core/dialogs.d.ts +2 -4
  170. package/dist/core/dialogs.js +6 -12
  171. package/dist/core/dialogs.js.map +1 -1
  172. package/dist/core/environment.d.ts +6 -0
  173. package/dist/core/environment.js +35 -0
  174. package/dist/core/environment.js.map +1 -0
  175. package/dist/core/mailbox.d.ts +223 -0
  176. package/dist/core/mailbox.js +549 -0
  177. package/dist/core/mailbox.js.map +1 -0
  178. package/dist/core/manager.d.ts +4 -0
  179. package/dist/core/manager.js +40 -2
  180. package/dist/core/manager.js.map +1 -1
  181. package/dist/core/messageText.d.ts +2 -0
  182. package/dist/core/messageText.js +6 -0
  183. package/dist/core/messageText.js.map +1 -0
  184. package/dist/core/nudge.d.ts +37 -0
  185. package/dist/core/nudge.js +60 -0
  186. package/dist/core/nudge.js.map +1 -0
  187. package/dist/core/promptDetector.d.ts +14 -12
  188. package/dist/core/promptDetector.js +115 -363
  189. package/dist/core/promptDetector.js.map +1 -1
  190. package/dist/core/promptText.d.ts +1 -0
  191. package/dist/core/promptText.js +4 -0
  192. package/dist/core/promptText.js.map +1 -0
  193. package/dist/core/readiness.d.ts +14 -0
  194. package/dist/core/readiness.js +95 -0
  195. package/dist/core/readiness.js.map +1 -0
  196. package/dist/core/reasoning.d.ts +68 -7
  197. package/dist/core/reasoning.js +584 -328
  198. package/dist/core/reasoning.js.map +1 -1
  199. package/dist/core/renderer.d.ts +63 -3
  200. package/dist/core/renderer.js +370 -42
  201. package/dist/core/renderer.js.map +1 -1
  202. package/dist/core/selection.d.ts +1 -1
  203. package/dist/core/selection.js +3 -3
  204. package/dist/core/selection.js.map +1 -1
  205. package/dist/core/session.d.ts +175 -13
  206. package/dist/core/session.js +1030 -93
  207. package/dist/core/session.js.map +1 -1
  208. package/dist/core/stringWidth.d.ts +2 -0
  209. package/dist/core/stringWidth.js +13 -0
  210. package/dist/core/stringWidth.js.map +1 -0
  211. package/dist/core/types.d.ts +62 -4
  212. package/dist/core/types.js +41 -0
  213. package/dist/core/types.js.map +1 -1
  214. package/dist/core/waiter.d.ts +9 -2
  215. package/dist/core/waiter.js +35 -10
  216. package/dist/core/waiter.js.map +1 -1
  217. package/dist/daemon/audit.d.ts +1 -1
  218. package/dist/daemon/audit.js +2 -1
  219. package/dist/daemon/audit.js.map +1 -1
  220. package/dist/daemon/config.d.ts +44 -0
  221. package/dist/daemon/config.js +166 -4
  222. package/dist/daemon/config.js.map +1 -1
  223. package/dist/daemon/folderPicker.js +21 -2
  224. package/dist/daemon/folderPicker.js.map +1 -1
  225. package/dist/daemon/homeOwner.d.ts +15 -0
  226. package/dist/daemon/homeOwner.js +106 -0
  227. package/dist/daemon/homeOwner.js.map +1 -0
  228. package/dist/daemon/index.js +14 -6
  229. package/dist/daemon/index.js.map +1 -1
  230. package/dist/daemon/launchProfiles.d.ts +5 -0
  231. package/dist/daemon/launchProfiles.js +54 -48
  232. package/dist/daemon/launchProfiles.js.map +1 -1
  233. package/dist/daemon/logger.js +1 -1
  234. package/dist/daemon/logger.js.map +1 -1
  235. package/dist/daemon/nudgeScheduler.d.ts +21 -0
  236. package/dist/daemon/nudgeScheduler.js +61 -0
  237. package/dist/daemon/nudgeScheduler.js.map +1 -0
  238. package/dist/daemon/paths.d.ts +20 -16
  239. package/dist/daemon/paths.js +181 -50
  240. package/dist/daemon/paths.js.map +1 -1
  241. package/dist/daemon/restartHold.js +16 -15
  242. package/dist/daemon/restartHold.js.map +1 -1
  243. package/dist/daemon/restartSource.d.ts +7 -0
  244. package/dist/daemon/restartSource.js +89 -0
  245. package/dist/daemon/restartSource.js.map +1 -0
  246. package/dist/daemon/schedules.d.ts +57 -0
  247. package/dist/daemon/schedules.js +181 -0
  248. package/dist/daemon/schedules.js.map +1 -0
  249. package/dist/daemon/screenshot.d.ts +4 -1
  250. package/dist/daemon/screenshot.js +45 -7
  251. package/dist/daemon/screenshot.js.map +1 -1
  252. package/dist/daemon/server.d.ts +82 -13
  253. package/dist/daemon/server.js +1737 -330
  254. package/dist/daemon/server.js.map +1 -1
  255. package/dist/daemon/sessionFeed.js +4 -1
  256. package/dist/daemon/sessionFeed.js.map +1 -1
  257. package/dist/daemon/viewerLauncher.js +3 -2
  258. package/dist/daemon/viewerLauncher.js.map +1 -1
  259. package/dist/daemon/wrappedLaunch.d.ts +1 -0
  260. package/dist/daemon/wrappedLaunch.js +38 -0
  261. package/dist/daemon/wrappedLaunch.js.map +1 -0
  262. package/dist/daemon/wrappedStart.d.ts +13 -0
  263. package/dist/daemon/wrappedStart.js +113 -0
  264. package/dist/daemon/wrappedStart.js.map +1 -0
  265. package/dist/daemon/wrappedSupervisor.d.ts +1 -0
  266. package/dist/daemon/wrappedSupervisor.js +55 -0
  267. package/dist/daemon/wrappedSupervisor.js.map +1 -0
  268. package/dist/mcp/config.js +2 -1
  269. package/dist/mcp/config.js.map +1 -1
  270. package/dist/mcp/index.js +28 -2
  271. package/dist/mcp/index.js.map +1 -1
  272. package/dist/mcp/tools.d.ts +21 -1
  273. package/dist/mcp/tools.js +216 -29
  274. package/dist/mcp/tools.js.map +1 -1
  275. package/dist/viewer/dashboard-folders.js +7 -1
  276. package/dist/viewer/dashboard-layout.js +6 -52
  277. package/dist/viewer/dashboard.css +20 -4
  278. package/dist/viewer/dashboard.html +12 -3
  279. package/dist/viewer/dashboard.js +549 -382
  280. package/dist/viewer/pane.js +744 -136
  281. package/dist/viewer/viewer.css +1 -1
  282. package/dist/viewer/viewer.js +3 -1
  283. package/package.json +1 -1
@@ -5,8 +5,10 @@
5
5
  * Host-header validation on every request, Origin validation on WebSocket
6
6
  * upgrades, bearer-token auth on the API, no CORS headers at all.
7
7
  */
8
+ import { moduleFor } from '../agents/index.js';
8
9
  import * as fs from 'node:fs';
9
10
  import { randomUUID } from 'node:crypto';
11
+ import { AsyncLocalStorage } from 'node:async_hooks';
10
12
  import * as http from 'node:http';
11
13
  import { createRequire } from 'node:module';
12
14
  import * as os from 'node:os';
@@ -14,6 +16,10 @@ import * as path from 'node:path';
14
16
  import { fileURLToPath } from 'node:url';
15
17
  import { WebSocketServer } from 'ws';
16
18
  import { SessionManager, PolicyViolationError, SessionStartError } from '../core/manager.js';
19
+ import { Mailbox, MailboxError, NAME_PATTERN, buildNudge } from '../core/mailbox.js';
20
+ import { buildMessagingPolicy, DEFAULT_NUDGE_INTERVAL_MS, DEFAULT_NUDGES_PER_MINUTE } from './config.js';
21
+ import { NudgeScheduler } from './nudgeScheduler.js';
22
+ import { ScheduleStore, PromptScheduler, watchSchedules } from './schedules.js';
17
23
  import { CommandNotFoundError, DEFAULT_SESSION_ENV, SessionInputFailedError, SessionProgramEndedError, WindowsWithoutConPTYError, credentialShapedNames, } from '../core/session.js';
18
24
  import { NativePtyUnavailableError } from '../core/nativePty.js';
19
25
  import { checkSessionCapacity, commandLine, compilePolicy, evaluateCommand } from '../core/policy.js';
@@ -24,14 +30,16 @@ import { RegexBudgetError } from '../core/regexBudget.js';
24
30
  import { detectPrompt } from '../core/promptDetector.js';
25
31
  import { markFilteredSelectedOption } from '../core/selection.js';
26
32
  import { WaitConditionError } from '../core/waiter.js';
27
- import { agentNames, hideReasoning, latestResult, programName, signatureFor } from '../core/reasoning.js';
28
- import { DEFAULT_WAIT_TIMEOUT_MS, ENV_NAME_PATTERN, MAX_WAIT_TIMEOUT_MS, WAIT_POLL_INTERVAL_MS, howSessionEnded } from '../core/types.js';
33
+ import { agentNames, hideReasoning, latestResult, programName, signatureForSession } from '../core/reasoning.js';
34
+ import { validResumeId, DEFAULT_WAIT_TIMEOUT_MS, ENV_NAME_PATTERN, MAX_WAIT_TIMEOUT_MS, WAIT_POLL_INTERVAL_MS, howSessionEnded } from '../core/types.js';
29
35
  import { DASHBOARD_COOKIE, TokenStore, VIEWER_COOKIE, VIEWER_GRANT_TTL_MS, bearerToken, cookieValues, dashboardCookie, dashboardProofFromProtocol, tokensEqual, viewerCookie, } from './auth.js';
30
36
  import { NULL_AUDITOR } from './audit.js';
31
37
  import { findBrowser, launchDashboard, launchViewer } from './viewerLauncher.js';
32
38
  import { DEFAULT_CAPTURE_TIMEOUT_MS, MAX_CAPTURE_TIMEOUT_MS, MIN_CAPTURE_TIMEOUT_MS, captureProfileRoot, captureViewer, sweepCaptureProfiles, } from './screenshot.js';
33
- import { claimDaemonState, daemonStatePath, ensureHome, inspectDaemonState, readDaemonState, removeDaemonState, removeDaemonStateIf, removeDaemonStateIfNotARecord, } from './paths.js';
39
+ import { claimDaemonState, daemonStatePath, ensureHome, writePrivateRecord, inspectDaemonState, readDaemonState, removeDaemonStateIf, removeDaemonStateIfNotARecord, } from './paths.js';
40
+ import { acquireHomeOwner, AlreadyRunningError } from './homeOwner.js';
34
41
  import { daemonRunning } from './liveness.js';
42
+ import { restoreRestartSource, retryRestartSource, snapshotSourceId } from './restartSource.js';
35
43
  import { packageVersion } from './meta.js';
36
44
  import { terminalReportKind } from './terminalReports.js';
37
45
  import { ViewerSync } from './viewerSync.js';
@@ -193,16 +201,8 @@ const DASHBOARD_HEARTBEAT_TIMEOUT_MS = 10_000;
193
201
  const DASHBOARD_PROOF_META = '<meta name="sp-csrf" content="">';
194
202
  const DASHBOARD_FONT_META = '<meta name="sp-dashboard-font-size" content="">';
195
203
  /** Thrown by `start()` when a healthy daemon already owns this home. */
196
- /** The largest dashboard window registration frame the daemon will parse. */
197
- const MAX_WINDOW_REGISTRATION_BYTES = 256;
198
- export class AlreadyRunningError extends Error {
199
- state;
200
- constructor(state) {
201
- super(`A healthy daemon is already running (pid ${String(state.pid)}, ` +
202
- `port ${String(state.port)}).`);
203
- this.state = state;
204
- this.name = 'AlreadyRunningError';
205
- }
204
+ export { AlreadyRunningError };
205
+ class HomeOwnershipError extends Error {
206
206
  }
207
207
  /** The scheme and authority that open an absolute-form request target (`http://user@host:port`). */
208
208
  const SCHEME_AND_AUTHORITY = /^[a-z][a-z0-9+.-]*:\/\/[^/]*/i;
@@ -234,9 +234,9 @@ function offeredProtocols(req) {
234
234
  .filter((part) => part !== '');
235
235
  }
236
236
  /** The 409 for input, a key or a resize sent to a session that has ended. */
237
- function endedRefusal(id, exitCode) {
237
+ function endedRefusal(id, exitCode, fault = null) {
238
238
  return (`Session ${id} has ${exitCode === null ? 'ended' : 'exited'} ` +
239
- `(${howSessionEnded(exitCode)}) and no longer accepts input or geometry changes.`);
239
+ `(${fault ?? howSessionEnded(exitCode)}) and no longer accepts input or geometry changes.`);
240
240
  }
241
241
  function isRecord(value) {
242
242
  return typeof value === 'object' && value !== null && !Array.isArray(value);
@@ -350,12 +350,18 @@ function overBudgetMessage(signature) {
350
350
  'aside for a minute, so the screen is not returned filtered. Try again shortly.');
351
351
  }
352
352
  /** Read one rendered frame for both a filtered wait predicate and its reply. */
353
- function filteredWaitScreen(session, signature) {
353
+ function filteredWaitScreen(session, signature, prompt) {
354
354
  const view = session.styledScreenNow(REASONING_CONTEXT_LINES);
355
355
  const filtered = hideReasoning(view.lines, signature, view.firstVisible);
356
356
  if (filtered === null)
357
357
  throw new WaitConditionError(overBudgetMessage(signature));
358
- return { screen: markFilteredSelectedOption(filtered.lines, view.lines).join('\n'), filtered };
358
+ const styled = prompt ? filteredPromptStyles(filtered, view) : undefined;
359
+ return { screen: markFilteredSelectedOption(filtered.lines, view.lines, session.agent).join('\n'), filtered, styled };
360
+ }
361
+ /** Wrap flags and padding must describe exactly the rows the wait can read. */
362
+ function filteredPromptStyles(filtered, view) {
363
+ return filtered.rows.map((row, i) => filtered.markers[i]
364
+ ? { text: filtered.lines[i], spans: [] } : view.lines[view.firstVisible + row]);
359
365
  }
360
366
  /**
361
367
  * A query flag: absent, `0` or `false` is off, `1` or `true` is on, and
@@ -413,6 +419,8 @@ function startShapeError(body) {
413
419
  ['label', (value) => typeof value === 'string', 'a string'],
414
420
  ['purpose', (value) => typeof value === 'string', 'a string'],
415
421
  ['readyText', (value) => typeof value === 'string', 'a string'],
422
+ ['waitReady', (value) => typeof value === 'boolean', 'a boolean'],
423
+ ['readyTimeout', (value) => typeof value === 'number' && Number.isFinite(value) && value >= 0, 'a non-negative number of milliseconds'],
416
424
  [
417
425
  'readyQuiet',
418
426
  (value) => typeof value === 'number' && Number.isFinite(value) && value >= 0,
@@ -448,6 +456,12 @@ export class Daemon {
448
456
  logger;
449
457
  tokens = new TokenStore();
450
458
  manager;
459
+ mailbox;
460
+ nudges;
461
+ schedules = new ScheduleStore();
462
+ pendingSchedules = new Map();
463
+ promptScheduler;
464
+ stopScheduleWatch;
451
465
  server;
452
466
  wss = new WebSocketServer({
453
467
  noServer: true,
@@ -477,15 +491,28 @@ export class Daemon {
477
491
  geometryController = new Map();
478
492
  /** A dashboard document keeps its grid while a covered pane reconnects. */
479
493
  dashboardGeometryOwner = new Map();
494
+ /** The credential shared by that dashboard's windows, for transfers between documents. */
495
+ dashboardCredentialOwner = new Map();
496
+ /** Destination document for a released grid. A rosterless release allows a
497
+ * same-credential stream (null). A release awaiting a new assignment has no recipient. */
498
+ dashboardTransferable = new Map();
499
+ dashboardSocketCredential = new WeakMap();
500
+ /** External geometry acts invalidate a temporary wider read's restoration. */
501
+ geometryEpoch = new Map();
502
+ widerReads = new Map();
480
503
  /** Subscribers to the daemon-wide event stream (`/events`). */
481
- eventSockets = new Set();
504
+ eventSockets = new Map();
482
505
  /**
483
506
  * Open `/dashboard/events` sockets. While one is open, a session start does
484
507
  * not launch a per-session viewer window and does not hand back a viewer URL.
485
508
  */
486
509
  dashboardEventSockets = new Set();
487
- /** Opaque roster ids carried by dashboard feed sockets, never used for authorisation. */
510
+ /** Dashboard windows and assignments are owned by the authenticated feed. */
488
511
  dashboardWindowIds = new Map();
512
+ dashboardAssignments = new Map();
513
+ dashboardDesignated = null;
514
+ /** The document proof survives a feed reconnect and expires with the proof ring. */
515
+ dashboardDocumentFocus = new Map();
489
516
  liveDashboardEventSockets = new Set();
490
517
  /** A launched dashboard has 30 seconds to connect before a start may retry. */
491
518
  dashboardWindowStartedAt = 0;
@@ -502,10 +529,13 @@ export class Daemon {
502
529
  portValue = null;
503
530
  waitsInFlight = 0;
504
531
  lastActivity = Date.now();
532
+ shutdownWarnings = [];
505
533
  idleTimer = null;
506
534
  raceCheckTimer = null;
507
535
  statePublishTimer = null;
508
536
  statePublishRunning = false;
537
+ homeOwner;
538
+ claimsRestored = false;
509
539
  /** What this daemon published in daemon.json, once it has claimed it. */
510
540
  publishedState = null;
511
541
  instanceId = randomUUID();
@@ -515,7 +545,9 @@ export class Daemon {
515
545
  promptGraceTimers = new Map();
516
546
  promptScanRunning = false;
517
547
  stopPromise = null;
548
+ shutdownRecords;
518
549
  audit;
550
+ callerContext = new AsyncLocalStorage();
519
551
  /**
520
552
  * What sessions get from the daemon's environment (ADR-008), resolved once so
521
553
  * that what the daemon reports is what its sessions get.
@@ -524,10 +556,13 @@ export class Daemon {
524
556
  /** The profiles the dashboard may name, and the entries that did not load. */
525
557
  launchProfiles;
526
558
  daemonEnv;
559
+ cliPath;
527
560
  /** The global policy, kept here so a launch can report it before creating. */
528
561
  compiledPolicy;
529
562
  /** Accepted launch times, for the sliding sixty-second cap. */
530
563
  launchTimes = [];
564
+ claimTimes = [];
565
+ claimCount = 0;
531
566
  folderPickerBusy = false;
532
567
  folderPickerAbort = null;
533
568
  folderPickerDone = null;
@@ -541,16 +576,67 @@ export class Daemon {
541
576
  constructor(options) {
542
577
  const startedWrapped = process.env['SHELLPUPPET_DAEMON_STARTED_WRAPPED'] === '1';
543
578
  delete process.env['SHELLPUPPET_DAEMON_STARTED_WRAPPED'];
544
- this.options = { ...options, startedWrapped: options.startedWrapped ?? startedWrapped };
579
+ this.options = { ...options,
580
+ home: path.resolve(options.home),
581
+ startedWrapped: options.startedWrapped ?? startedWrapped };
545
582
  this.logger = options.logger;
546
- this.audit = options.audit ?? NULL_AUDITOR;
583
+ const auditor = options.audit ?? NULL_AUDITOR;
584
+ this.audit = {
585
+ captureContent: auditor.captureContent,
586
+ record: (actor, action, session, meta) => auditor.record(actor, action, session, meta,
587
+ // A session's timers and listeners can inherit the request that created
588
+ // them. Daemon observations must not inherit that caller's identity.
589
+ actor === 'daemon' ? undefined : this.callerContext.getStore()),
590
+ };
547
591
  this.sessionEnv = options.sessionEnv ?? DEFAULT_SESSION_ENV;
548
592
  this.launchProfiles = options.launchProfiles ?? { profiles: [], problems: [] };
549
593
  this.daemonEnv = options.daemonEnv ?? process.env;
594
+ this.cliPath = fileURLToPath(new URL('../../dist/cli/index.js', import.meta.url));
550
595
  this.compiledPolicy = compilePolicy(options.policy);
551
596
  this.manager = new SessionManager(compilePolicy(options.policy), this.logger, {
552
597
  sessionEnv: this.sessionEnv,
553
- }, (id) => this.sessionFeed.remove(id));
598
+ identity: {
599
+ token: '',
600
+ instanceId: this.instanceId,
601
+ cliPath: this.cliPath,
602
+ home: this.options.home,
603
+ },
604
+ }, (id) => {
605
+ this.endMailboxParticipant(id);
606
+ this.sessionFeed.remove(id);
607
+ });
608
+ this.mailbox = new Mailbox({
609
+ enabled: options.messaging?.enabled === true,
610
+ reservedNames: new Set((options.messaging?.allow ?? []).flatMap((rule) => rule === 'parent-child' ? [] : rule.members)),
611
+ claimIdleMinutes: options.messaging?.claimIdleMinutes,
612
+ now: () => this.now(),
613
+ policy: buildMessagingPolicy(options.messaging, {
614
+ parentOf: (id) => this.manager.get(id)?.parent,
615
+ }),
616
+ });
617
+ this.nudges = new NudgeScheduler({
618
+ now: () => this.now(),
619
+ intervalMs: options.messaging?.nudgeIntervalMs ?? DEFAULT_NUDGE_INTERVAL_MS,
620
+ perMinute: options.messaging?.nudgesPerMinute ?? DEFAULT_NUDGES_PER_MINUTE,
621
+ deliver: (id) => this.deliverNudge(id),
622
+ });
623
+ this.promptScheduler = new PromptScheduler(this.schedules, () => this.now(), (schedule, current) => this.deliverScheduled(schedule, current), (schedule, { sessionId, outcome, reason }) => this.audit.record('daemon', 'input', sessionId, {
624
+ source: 'schedule', name: schedule.name, session: schedule.session, outcome, reason,
625
+ }));
626
+ this.mailbox.on('message', (event) => {
627
+ const entry = this.mailbox.log().find((item) => item.id === event.id);
628
+ if (entry !== undefined)
629
+ this.messageAudit('msg-send', entry);
630
+ this.emitMessageEvent({ type: 'message', ...event }, entry);
631
+ this.emitDashboardMessageEvent({ type: 'message', ...event });
632
+ if (this.mailbox.participant(event.to.id)?.kind === 'session')
633
+ this.nudges.queue(event.to.id);
634
+ });
635
+ this.mailbox.on('state', (event) => {
636
+ const entry = this.mailbox.log().find((item) => item.id === event.id);
637
+ this.emitMessageEvent({ type: 'message-state', ...event }, entry);
638
+ this.emitDashboardMessageEvent({ type: 'message-state', ...event });
639
+ });
554
640
  this.sessionFeed = new SessionFeed(this.version, () => this.listedSummaries().map((summary) => this.summaryWithPrompt(summary)), this.logger);
555
641
  this.server = http.createServer((req, res) => {
556
642
  this.handleRequest(req, res).catch((error) => {
@@ -603,19 +689,19 @@ export class Daemon {
603
689
  // ------------------------------------------------------------------ start
604
690
  async start() {
605
691
  const { home } = this.options;
606
- const homeResult = await ensureHome(home);
607
- if (homeResult.warning !== undefined) {
608
- this.logger.warn('home hardening warning', { warning: homeResult.warning });
609
- }
692
+ ensureHome(home);
610
693
  // Defer to an incumbent that is running, even one too busy to answer its
611
694
  // health check; clear a record whose daemon has gone (design §2.3).
612
695
  const existing = readDaemonState(home);
613
696
  if (existing !== null) {
614
697
  if (await this.incumbentRunning(existing))
615
698
  throw new AlreadyRunningError(existing);
616
- this.logger.info('clearing stale daemon state', { stalePid: existing.pid });
617
- removeDaemonStateIf(home, existing);
699
+ if (this.stopping)
700
+ throw new Error('Daemon stopped during startup.');
618
701
  }
702
+ const refusePending = (socket) => { socket.destroy(); };
703
+ if (this.options.afterPublish)
704
+ this.server.on('connection', refusePending);
619
705
  await new Promise((resolve, reject) => {
620
706
  this.server.once('error', reject);
621
707
  this.server.listen(0, '127.0.0.1', () => {
@@ -630,6 +716,10 @@ export class Daemon {
630
716
  resolve();
631
717
  });
632
718
  });
719
+ if (this.stopping) {
720
+ await this.closeServerOnly();
721
+ throw new Error('Daemon stopped during startup.');
722
+ }
633
723
  const address = this.server.address();
634
724
  if (address === null || typeof address === 'string') {
635
725
  throw new Error('Failed to determine bound port.');
@@ -651,29 +741,55 @@ export class Daemon {
651
741
  instanceId: this.instanceId,
652
742
  startedWrapped: this.options.startedWrapped ?? false,
653
743
  };
654
- // Atomic claim; on losing the race, defer to the winner (design §2.2:
655
- // the race is normal, not exceptional). A file that holds no record at all,
656
- // such as an emptied one, is cleared like a stale record.
657
- if (!claimDaemonState(home, state)) {
658
- const winner = inspectDaemonState(home);
659
- if (winner.kind === 'record' && (await this.incumbentRunning(winner.state))) {
660
- await this.closeServerOnly();
661
- throw new AlreadyRunningError(winner.state);
662
- }
663
- if (winner.kind === 'record')
664
- removeDaemonStateIf(home, winner.state);
665
- if (winner.kind === 'not-a-record') {
666
- this.logger.warn('clearing a daemon.json that holds no daemon record', {
667
- length: winner.raw.length,
668
- });
669
- removeDaemonStateIfNotARecord(home, winner.raw);
744
+ // Hold the home independently of discovery, including while restoring
745
+ // claims and publishing shutdown records. This also serialises takeovers.
746
+ try {
747
+ this.homeOwner = await acquireHomeOwner(home, state.port, this.instanceId);
748
+ if (this.stopping)
749
+ throw new Error('Daemon stopped during startup.');
750
+ const file = inspectDaemonState(home);
751
+ if (file.kind === 'record' && await this.incumbentRunning(file.state)) {
752
+ throw new AlreadyRunningError(file.state);
670
753
  }
671
- if (!claimDaemonState(home, state)) {
672
- await this.closeServerOnly();
673
- throw new Error(`Could not claim ${daemonStatePath(home)}: it could not be read, or another ` +
674
- `daemon claimed it first.`);
754
+ if (this.stopping)
755
+ throw new Error('Daemon stopped during startup.');
756
+ if (file.kind === 'unreadable')
757
+ throw new Error('Could not read daemon.json to claim the home.');
758
+ Object.assign(state, restoreRestartSource(home, file, this.logger));
759
+ if (file.kind === 'missing') {
760
+ if (!claimDaemonState(home, state))
761
+ throw new Error('Another daemon claimed daemon.json first.');
762
+ }
763
+ else {
764
+ // A failed rename leaves the entire predecessor record in place.
765
+ writePrivateRecord(daemonStatePath(home), state);
766
+ }
767
+ if (this.options.afterPublish) {
768
+ await this.options.afterPublish();
769
+ this.server.off('connection', refusePending);
675
770
  }
676
771
  }
772
+ catch (error) {
773
+ this.releaseOwnership();
774
+ await this.closeServerOnly();
775
+ throw error;
776
+ }
777
+ this.publishedState = state;
778
+ const claimsFile = path.join(home, 'launcher-claims.json');
779
+ try {
780
+ const rows = JSON.parse(fs.readFileSync(claimsFile, 'utf8'));
781
+ if (!Array.isArray(rows))
782
+ throw new Error('Expected saved launcher claims to be an array.');
783
+ this.claimCount = this.mailbox.restoreClaims(rows, this.options.messaging?.enabled ? this.launchProfiles.sessionLaunch ?? [] : []);
784
+ this.claimsRestored = true;
785
+ this.saveLauncherClaims();
786
+ }
787
+ catch (error) {
788
+ if (error.code === 'ENOENT')
789
+ this.claimsRestored = true;
790
+ else
791
+ this.logger.warn(this.claimsRestored ? 'Could not update saved launcher claims.' : 'Could not restore saved launcher claims.');
792
+ }
677
793
  // Belt and braces for the unlink/claim TOCTOU sliver: shortly after
678
794
  // start-up, if the published record names someone else and nobody is
679
795
  // attached to us, bow out quietly. Clients only ever discover the daemon
@@ -681,7 +797,7 @@ export class Daemon {
681
797
  this.raceCheckTimer = setTimeout(() => {
682
798
  const current = readDaemonState(home);
683
799
  if (current !== null &&
684
- current.pid !== process.pid &&
800
+ current.instanceId !== this.instanceId &&
685
801
  this.manager.size() === 0 &&
686
802
  this.sockets.size === 0) {
687
803
  this.logger.info('lost start-up race after claim, stopping', {
@@ -704,13 +820,13 @@ export class Daemon {
704
820
  this.logger.warn('sessionEnv "passthrough" hands every session the daemon environment, including ' +
705
821
  'these variables whose names look like credentials; use "clean" or a list to keep them out', { names: exposed });
706
822
  }
707
- this.publishedState = state;
708
823
  this.statePublishTimer = setInterval(() => {
709
824
  void this.keepStatePublished();
710
825
  }, this.options.statePublishCheckMs ?? STATE_PUBLISH_CHECK_MS);
711
826
  this.statePublishTimer.unref();
712
827
  const idleMs = this.options.idleMs ?? DEFAULT_IDLE_MS;
713
828
  this.idleTimer = setInterval(() => {
829
+ this.lapseIdleClaims();
714
830
  // Reap sessions whose grace has lapsed before judging idleness. A
715
831
  // rejected sweep must be caught here, or it becomes an
716
832
  // unhandledRejection and the handler in index.ts stops the daemon.
@@ -744,6 +860,8 @@ export class Daemon {
744
860
  });
745
861
  }, this.options.promptScanIntervalMs ?? PROMPT_SCAN_INTERVAL_MS);
746
862
  this.promptScanTimer.unref();
863
+ this.stopScheduleWatch = watchSchedules(home, this.schedules, this.logger);
864
+ this.promptScheduler.start();
747
865
  this.logger.info('daemon started', {
748
866
  port: this.portValue,
749
867
  pid: process.pid,
@@ -760,7 +878,7 @@ export class Daemon {
760
878
  * process that had the same pid.
761
879
  */
762
880
  async incumbentRunning(record) {
763
- if (record.pid === process.pid && record.port === this.portValue)
881
+ if (record.port === this.portValue)
764
882
  return false;
765
883
  if (await this.isHealthy(record.port))
766
884
  return true;
@@ -786,7 +904,7 @@ export class Daemon {
786
904
  */
787
905
  async keepStatePublished() {
788
906
  const published = this.publishedState;
789
- if (published === null || this.stopPromise !== null || this.statePublishRunning)
907
+ if (published === null || this.stopping || this.statePublishRunning || !this.homeOwner?.held())
790
908
  return;
791
909
  this.statePublishRunning = true;
792
910
  try {
@@ -796,7 +914,7 @@ export class Daemon {
796
914
  return;
797
915
  if (file.kind === 'record') {
798
916
  const current = file.state;
799
- if (current.pid === published.pid && current.port === published.port) {
917
+ if (current.instanceId === this.instanceId && current.pid === published.pid && current.port === published.port) {
800
918
  this.foreignOwnerReported = null;
801
919
  return;
802
920
  }
@@ -811,6 +929,8 @@ export class Daemon {
811
929
  }
812
930
  return;
813
931
  }
932
+ if (this.stopping || !this.homeOwner?.held())
933
+ return;
814
934
  removeDaemonStateIf(home, current);
815
935
  }
816
936
  else if (file.kind === 'not-a-record') {
@@ -845,13 +965,12 @@ export class Daemon {
845
965
  closeServerOnly() {
846
966
  return new Promise((resolve) => {
847
967
  this.server.close(() => resolve());
848
- // close() waits for idle connections; nothing is connected this early.
849
968
  });
850
969
  }
851
970
  // ------------------------------------------------------------------- stop
852
971
  /**
853
- * Kill every session's process tree, close everything, remove the state
854
- * file (unless we lost the race and it now belongs to the winner).
972
+ * Kill every session's process tree and release our discovery record. A
973
+ * restart leaves a credential-free handoff for the next owner.
855
974
  * The daemon must never exit and strand running agent CLIs (design §2.3).
856
975
  */
857
976
  stop(opts = {}) {
@@ -859,11 +978,84 @@ export class Daemon {
859
978
  // awaits the one real shutdown.
860
979
  if (this.stopPromise === null) {
861
980
  this.stopping = true;
862
- this.stopPromise = this.doStop(opts);
981
+ this.promptScheduler.stop();
982
+ this.stopScheduleWatch?.();
983
+ this.shutdownRecords = this.saveShutdownRecords(opts);
984
+ this.stopPromise = this.doStop();
863
985
  }
864
986
  return this.stopPromise;
865
987
  }
866
- async doStop(opts) {
988
+ saveShutdownRecords(opts) {
989
+ return Promise.resolve().then(() => {
990
+ const state = opts.removeState !== false && this.homeOwner ? this.publishedState : null;
991
+ if (state) {
992
+ // Publish the final claims, source, snapshot and handoff in one turn.
993
+ this.writeShutdownRecord('launcher-claims.json', () => this.saveLauncherClaims());
994
+ if (opts.restart) {
995
+ this.writeShutdownRecord('restart-source.json', () => {
996
+ this.requireHomeOwner();
997
+ writePrivateRecord(path.join(this.options.home, 'restart-source.json'), { restartFrom: this.instanceId });
998
+ });
999
+ this.writeShutdownRecord('previous-sessions.json', () => this.savePreviousSessions());
1000
+ }
1001
+ this.writeShutdownRecord('daemon.json', () => this.finishDiscovery(state, opts.restart === true));
1002
+ }
1003
+ this.releaseOwnership();
1004
+ });
1005
+ }
1006
+ finishDiscovery(state, restart) {
1007
+ const discovery = this.requireHomeOwner();
1008
+ if (discovery.kind === 'unreadable')
1009
+ throw new Error('Could not read daemon.json before shutdown.');
1010
+ const handoff = restart ? { restartFrom: this.instanceId } : {
1011
+ restartFrom: state.restartFrom, restartSourcePending: state.restartSourcePending, restartCandidates: state.restartCandidates,
1012
+ };
1013
+ if (handoff.restartFrom || handoff.restartCandidates) {
1014
+ // If replacement fails, the live record can still confirm a snapshot
1015
+ // stamped by this instance after the storage fault clears.
1016
+ writePrivateRecord(daemonStatePath(this.options.home), handoff);
1017
+ }
1018
+ else if (discovery.kind === 'not-a-record') {
1019
+ removeDaemonStateIfNotARecord(this.options.home, discovery.raw);
1020
+ }
1021
+ else {
1022
+ removeDaemonStateIf(this.options.home, state);
1023
+ }
1024
+ }
1025
+ writeShutdownRecord(file, write, verb = 'save') {
1026
+ try {
1027
+ write();
1028
+ }
1029
+ catch (error) {
1030
+ this.shutdownRecordFailure(file, verb, error);
1031
+ }
1032
+ }
1033
+ shutdownRecordFailure(file, verb, error) {
1034
+ const message = `Could not ${verb} ${file} during shutdown.`;
1035
+ this.shutdownWarnings.push(message);
1036
+ this.logger.warn(message, { code: error.code });
1037
+ }
1038
+ releaseOwnership() {
1039
+ const owner = this.homeOwner;
1040
+ this.homeOwner = undefined;
1041
+ if (owner)
1042
+ this.writeShutdownRecord('daemon-owner', owner.release, 'release');
1043
+ }
1044
+ requireHomeOwner() {
1045
+ const state = this.publishedState;
1046
+ if (this.homeOwner?.held() && state) {
1047
+ const file = inspectDaemonState(this.options.home);
1048
+ // The exclusive home marker still protects the durable files when
1049
+ // discovery is missing, damaged or temporarily inaccessible.
1050
+ if (file.kind !== 'record' && file.kind !== 'restart-handoff')
1051
+ return file;
1052
+ if (file.kind === 'record' && file.state.instanceId === this.instanceId &&
1053
+ file.state.pid === state.pid && file.state.port === state.port)
1054
+ return file;
1055
+ }
1056
+ throw new HomeOwnershipError('This daemon no longer owns the discovery record.');
1057
+ }
1058
+ async doStop() {
867
1059
  if (this.idleTimer !== null)
868
1060
  clearInterval(this.idleTimer);
869
1061
  if (this.raceCheckTimer !== null)
@@ -876,15 +1068,14 @@ export class Daemon {
876
1068
  clearTimeout(timer);
877
1069
  this.promptGraceTimers.clear();
878
1070
  this.folderPickerAbort?.abort(new FolderPickerFailureError('The folder picker was stopped.'));
879
- // Stop LISTENING first, before tearing down session trees. Killing process
880
- // trees is not fast (`taskkill /T` on a loaded machine can take seconds
881
- // per session), and a daemon that still answers on its port while shutting
882
- // down looks alive to every client polling /health. `close()` refuses new
883
- // connections immediately while letting in-flight responses drain on
884
- // their existing socket, notably the reply to this very shutdown request.
885
- const listenerClosed = new Promise((resolve) => {
886
- this.server.close(() => resolve());
887
- });
1071
+ for (const read of this.widerReads.values())
1072
+ read.abort.abort();
1073
+ const readsDone = Promise.allSettled([...this.widerReads.values()].map((read) => read.done));
1074
+ await this.shutdownRecords;
1075
+ // A free port lets a successor retire the ownership marker. Keep it
1076
+ // bound through publication, then close without waiting for PTY teardown.
1077
+ const listenerClosed = this.closeServerOnly();
1078
+ await readsDone;
888
1079
  for (const socket of this.sockets) {
889
1080
  try {
890
1081
  socket.close();
@@ -925,17 +1116,6 @@ export class Daemon {
925
1116
  if (timer !== undefined)
926
1117
  clearTimeout(timer);
927
1118
  }
928
- if (opts.removeState !== false) {
929
- // Remove this daemon's record, or a file that holds none. A file that
930
- // cannot be read says nothing about what it holds, so it stays.
931
- const file = inspectDaemonState(this.options.home);
932
- if (file.kind === 'record' && file.state.pid === process.pid) {
933
- removeDaemonState(this.options.home);
934
- }
935
- else if (file.kind === 'not-a-record') {
936
- removeDaemonStateIfNotARecord(this.options.home, file.raw);
937
- }
938
- }
939
1119
  // Only now terminate lingering keep-alive connections, so close() cannot hang.
940
1120
  this.server.closeAllConnections();
941
1121
  await listenerClosed;
@@ -1045,8 +1225,8 @@ export class Daemon {
1045
1225
  }
1046
1226
  return null;
1047
1227
  }
1048
- auditDashboardRefusal(req, reason) {
1049
- this.audit.record('dashboard', 'refuse', undefined, {
1228
+ auditDashboardRefusal(req, reason, actor = 'dashboard') {
1229
+ this.audit.record(actor, 'refuse', undefined, {
1050
1230
  method: req.method ?? '',
1051
1231
  path: pathOnly(req.url),
1052
1232
  reason,
@@ -1103,6 +1283,7 @@ export class Daemon {
1103
1283
  if (grantPresented) {
1104
1284
  const redeemed = this.tokens.redeemDashboardGrant(grant, this.now());
1105
1285
  if (redeemed !== null) {
1286
+ this.retireDashboardFeeds();
1106
1287
  this.audit.record('dashboard', 'grant-redeem');
1107
1288
  res.writeHead(303, {
1108
1289
  location: '/dashboard',
@@ -1116,6 +1297,8 @@ export class Daemon {
1116
1297
  return;
1117
1298
  }
1118
1299
  const proof = cookie === null ? null : this.tokens.issueDashboardProof();
1300
+ if (proof !== null)
1301
+ this.retireDashboardFeeds();
1119
1302
  this.sendDashboardPage(res, proof, req.method === 'HEAD');
1120
1303
  return;
1121
1304
  }
@@ -1151,6 +1334,7 @@ export class Daemon {
1151
1334
  this.pendingDashboardGrants.delete(grant);
1152
1335
  if (this.stopping || !opened.launched || opened.mode === 'default-browser') {
1153
1336
  this.tokens.revokeDashboardGrant(grant);
1337
+ this.retireDashboardFeeds();
1154
1338
  this.auditDashboardRefusal(req, 'launch-failed');
1155
1339
  return false;
1156
1340
  }
@@ -1220,9 +1404,10 @@ export class Daemon {
1220
1404
  json(res, 400, { error: hide === null ? BAD_HIDE_REASONING : 'waitingOnly must be true or false.' });
1221
1405
  return;
1222
1406
  }
1223
- json(res, 200, { sessions: waitingOnly ? this.waitingSessions(hide) : this.listWithPrompts(hide), version: this.version });
1407
+ const sessions = waitingOnly ? this.waitingSessions(hide, { includeCwd: true }) : this.listWithPrompts(hide);
1408
+ json(res, 200, { sessions, version: this.version });
1224
1409
  }
1225
- waitingSessions(hideReasoning, ids) {
1410
+ waitingSessions(hideReasoning, { includeCwd, ids }) {
1226
1411
  return this.listWithPrompts(hideReasoning).flatMap((session) => {
1227
1412
  const waiting = session.waitingOnPrompt;
1228
1413
  if (session.exited || waiting === undefined || (ids !== undefined && !ids.has(session.id)))
@@ -1230,6 +1415,7 @@ export class Daemon {
1230
1415
  return [{
1231
1416
  id: session.id,
1232
1417
  label: session.label,
1418
+ ...(includeCwd ? { cwd: session.cwd } : {}),
1233
1419
  ...(waiting.question === undefined ? {} : { question: waiting.question }),
1234
1420
  ...(waiting.options === undefined ? {} : { options: waiting.options }),
1235
1421
  ...(waiting.selectedOption === undefined ? {} : { selectedOption: waiting.selectedOption }),
@@ -1240,12 +1426,14 @@ export class Daemon {
1240
1426
  async waitAcrossSessions(res, url) {
1241
1427
  const hide = queryFlag(url, 'hideReasoning');
1242
1428
  const now = queryFlag(url, 'now');
1429
+ const stalled = queryFlag(url, 'stalled');
1430
+ const prompt = queryFlag(url, 'prompt');
1243
1431
  const timeoutText = url.searchParams.get('timeout');
1244
1432
  const timeout = timeoutText === null ? DEFAULT_WAIT_TIMEOUT_MS : Number(timeoutText);
1245
- if (hide === null || now === null || url.searchParams.get('prompt') !== 'true' ||
1433
+ if (hide === null || now === null || stalled === null || prompt === null || (!prompt && !stalled) ||
1246
1434
  !Number.isFinite(timeout) || timeout < 0 || timeout > MAX_WAIT_TIMEOUT_MS ||
1247
1435
  ['text', 'regex', 'quiet', 'debounce', 'matchAfterInput'].some((key) => url.searchParams.has(key))) {
1248
- json(res, 400, { error: 'A multi-session wait needs prompt=true, optional now, hideReasoning and a timeout from 0 to 300000 ms.' });
1436
+ json(res, 400, { error: 'A multi-session wait needs prompt=true and/or stalled=true, optional now, hideReasoning and a timeout from 0 to 300000 ms.' });
1249
1437
  return;
1250
1438
  }
1251
1439
  const requested = url.searchParams.getAll('session');
@@ -1258,10 +1446,13 @@ export class Daemon {
1258
1446
  this.waitsInFlight += 1;
1259
1447
  try {
1260
1448
  while (!res.destroyed) {
1261
- const sessions = this.waitingSessions(hide, ids);
1449
+ const waiting = prompt ? this.waitingSessions(hide, { ids }) : [];
1450
+ const stalledSessions = stalled ? this.listWithPrompts(hide).flatMap(session => session.exited || session.stalled === undefined || (ids !== undefined && !ids.has(session.id)) ? [] :
1451
+ [{ id: session.id, label: session.label, reason: 'stalled', stalled: session.stalled }]) : [];
1452
+ const sessions = [...(stalled ? waiting.map(session => ({ ...session, reason: 'prompt' })) : waiting), ...stalledSessions];
1262
1453
  const waitedMs = Date.now() - started;
1263
1454
  if (sessions.length > 0 || now || waitedMs >= timeout) {
1264
- json(res, 200, { matched: sessions.length > 0, reason: sessions.length > 0 ? 'prompt' : 'timeout', waitedMs, sessions });
1455
+ json(res, 200, { matched: sessions.length > 0, reason: waiting.length > 0 ? 'prompt' : stalledSessions.length > 0 ? 'stalled' : 'timeout', waitedMs, sessions });
1265
1456
  return;
1266
1457
  }
1267
1458
  await new Promise((resolve) => setTimeout(resolve, Math.min(WAIT_POLL_INTERVAL_MS, timeout - waitedMs)));
@@ -1295,6 +1486,39 @@ export class Daemon {
1295
1486
  this.lastActivity = Date.now();
1296
1487
  this.writeSessionList(res, url);
1297
1488
  }
1489
+ /** Owner-wide history is available only with the dashboard cookie and document proof. */
1490
+ serveDashboardMessages(req, res, url) {
1491
+ const presented = this.dashboardCookiePresented(req.headers.cookie);
1492
+ if (this.dashboardCookieToken(req.headers.cookie) === null) {
1493
+ if (presented)
1494
+ this.auditDashboardRefusal(req, 'unauthenticated');
1495
+ json(res, 401, { error: 'Unauthorised.' });
1496
+ return;
1497
+ }
1498
+ if (!this.isSameOriginRead(req)) {
1499
+ this.auditDashboardRefusal(req, this.cookieRefusalReason(req));
1500
+ json(res, 403, { error: 'Forbidden.' });
1501
+ return;
1502
+ }
1503
+ if (!this.tokens.acceptsDashboardProof(headerOne(req, 'x-shellpuppet-csrf'))) {
1504
+ this.auditDashboardRefusal(req, 'proof');
1505
+ json(res, 403, { error: 'Forbidden.' });
1506
+ return;
1507
+ }
1508
+ const messages = this.mailbox.log();
1509
+ const counts = {};
1510
+ for (const entry of messages) {
1511
+ if (entry.state === 'waiting' || entry.state === 'nudged')
1512
+ counts[entry.to.id] = (counts[entry.to.id] ?? 0) + 1;
1513
+ }
1514
+ const summary = url.searchParams.get('summary') === '1';
1515
+ const groups = (this.options.messaging?.allow ?? []).filter((rule) => typeof rule !== 'string')
1516
+ .map((rule) => ({ group: rule.group, members: rule.members, roles: rule.roles ?? [] }));
1517
+ this.audit.record('dashboard', 'msg-log', undefined, { count: messages.length });
1518
+ this.lastActivity = Date.now();
1519
+ json(res, 200, { enabled: this.options.messaging?.enabled === true,
1520
+ counts, ...(summary ? {} : { messages, groups }) });
1521
+ }
1298
1522
  /** A cookie mutation: same-origin Fetch Metadata and a matching Origin. */
1299
1523
  isSameOriginMutation(req) {
1300
1524
  if (headerOne(req, 'sec-fetch-site') !== 'same-origin')
@@ -1323,10 +1547,12 @@ export class Daemon {
1323
1547
  async profileDescription(profile) {
1324
1548
  return {
1325
1549
  name: profile.name,
1550
+ role: profile.role ?? 'delegate',
1326
1551
  label: describeProfileText(profile.label ?? '', profile.name),
1327
1552
  purpose: describeProfileText(profile.purpose ?? '', profile.name),
1328
1553
  command: profile.command,
1329
1554
  args: [...profile.args],
1555
+ ...(profile.resume ? { canResume: true } : {}),
1330
1556
  folderRequired: profile.askCwd,
1331
1557
  anyFolder: profile.anyFolder,
1332
1558
  folders: profile.folders.map((folder) => ({ name: folder.name, path: folder.path })),
@@ -1522,23 +1748,27 @@ export class Daemon {
1522
1748
  json(res, 415, { error: 'The launch body must be JSON (application/json).' });
1523
1749
  return;
1524
1750
  }
1525
- if (!this.tokens.acceptsDashboardProof(headerOne(req, 'x-shellpuppet-csrf'))) {
1751
+ const documentProof = headerOne(req, 'x-shellpuppet-csrf');
1752
+ if (!this.tokens.acceptsDashboardProof(documentProof)) {
1526
1753
  this.auditDashboardRefusal(req, 'proof');
1527
1754
  json(res, 403, { error: 'Forbidden.' });
1528
1755
  return;
1529
1756
  }
1757
+ await this.launchProfile(req, res, { documentProof });
1758
+ }
1759
+ async launchProfile(req, res, { launcher, documentProof }) {
1530
1760
  let body;
1531
1761
  try {
1532
1762
  body = await readBody(req);
1533
1763
  }
1534
1764
  catch (error) {
1535
1765
  if (error instanceof RequestBodyTooLargeError) {
1536
- this.auditDashboardRefusal(req, 'body-size');
1766
+ this.auditDashboardRefusal(req, 'body-size', launcher?.name);
1537
1767
  json(res, 413, { error: error.message });
1538
1768
  return;
1539
1769
  }
1540
1770
  if (error instanceof Error && error.message.startsWith('Request body')) {
1541
- this.auditDashboardRefusal(req, 'body');
1771
+ this.auditDashboardRefusal(req, 'body', launcher?.name);
1542
1772
  json(res, 400, { error: error.message });
1543
1773
  return;
1544
1774
  }
@@ -1549,21 +1779,49 @@ export class Daemon {
1549
1779
  json(res, 400, { error: 'profile (string) is required.' });
1550
1780
  return;
1551
1781
  }
1782
+ const allowedKeys = ['profile', 'name', 'folder', 'rootIndex', 'folderPath', 'resumeId'];
1783
+ if (documentProof !== undefined)
1784
+ allowedKeys.push('window');
1552
1785
  for (const key of Object.keys(body)) {
1553
- if (key !== 'profile' && key !== 'folder' && key !== 'rootIndex' && key !== 'folderPath') {
1554
- this.auditDashboardRefusal(req, 'body');
1786
+ if (!allowedKeys.includes(key)) {
1787
+ this.auditDashboardRefusal(req, 'body', launcher?.name);
1555
1788
  json(res, 400, {
1556
- error: `The launch body may name only profile, folder, rootIndex and folderPath: "${key}" is not accepted. ` +
1789
+ error: `The launch body may name only ${allowedKeys.join(', ')}: "${key}" is not accepted. ` +
1557
1790
  'A command, arguments and environment value come from the profile.',
1558
1791
  });
1559
1792
  return;
1560
1793
  }
1561
1794
  }
1795
+ const requestedWindow = body['window'];
1796
+ const launchingWindow = requestedWindow === undefined ? undefined : this.dashboardWindows().find((window) => window.pair === requestedWindow && dashboardProofFromProtocol(window.socket.protocol) === documentProof);
1797
+ if (requestedWindow !== undefined && launchingWindow === undefined) {
1798
+ json(res, 409, { error: 'The launching dashboard window has closed.' });
1799
+ return;
1800
+ }
1562
1801
  const profile = this.launchProfiles.profiles.find((entry) => entry.name === profileName);
1563
1802
  if (profile === undefined) {
1564
1803
  json(res, 400, { error: `No such launch profile: ${profileName}` });
1565
1804
  return;
1566
1805
  }
1806
+ const resumeId = body['resumeId'];
1807
+ if (resumeId !== undefined && (!profile.resume || !validResumeId(resumeId))) {
1808
+ json(res, 400, { error: 'Resume requires a profile with resume arguments and a valid resume id.' });
1809
+ return;
1810
+ }
1811
+ const args = [...profile.args];
1812
+ if (typeof resumeId === 'string')
1813
+ args.push(...profile.resume.map(arg => arg === '{id}' ? resumeId : arg));
1814
+ const caller = this.resolveCallerIdentity(req);
1815
+ if (caller.presented && caller.session === undefined) {
1816
+ json(res, 403, { error: 'Session identity was not recognised.' });
1817
+ return;
1818
+ }
1819
+ const requestedName = body['name'] === undefined ? profile.name : body['name'];
1820
+ if (typeof requestedName !== 'string' || !NAME_PATTERN.test(requestedName) ||
1821
+ (body['name'] !== undefined && (/^s[0-9]+$/.test(requestedName) || this.isReservedClaimName(requestedName)))) {
1822
+ json(res, 400, { error: 'Name must be 1 to 40 letters, digits, dots, underscores or hyphens, and must not be reserved.' });
1823
+ return;
1824
+ }
1567
1825
  const folderName = body['folder'];
1568
1826
  const rootIndex = body['rootIndex'];
1569
1827
  const freePath = body['folderPath'];
@@ -1573,13 +1831,13 @@ export class Daemon {
1573
1831
  if (profile.askCwd) {
1574
1832
  if (freePath !== undefined) {
1575
1833
  if (!profile.anyFolder || folderName !== undefined || rootIndex !== undefined) {
1576
- this.auditDashboardRefusal(req, 'body');
1834
+ this.auditDashboardRefusal(req, 'body', launcher?.name);
1577
1835
  json(res, 400, { error: 'This profile does not accept that folder path.' });
1578
1836
  return;
1579
1837
  }
1580
1838
  const choice = resolveAnyFolder(freePath);
1581
1839
  if ('error' in choice) {
1582
- this.auditDashboardRefusal(req, 'body');
1840
+ this.auditDashboardRefusal(req, 'body', launcher?.name);
1583
1841
  json(res, 400, { error: choice.error });
1584
1842
  return;
1585
1843
  }
@@ -1597,7 +1855,7 @@ export class Daemon {
1597
1855
  if (rootIndex !== undefined) {
1598
1856
  const choice = await resolveRootFolder(profile.folderRoots.map((root) => path.resolve(os.homedir(), root)), rootIndex, folderName);
1599
1857
  if ('error' in choice) {
1600
- this.auditDashboardRefusal(req, 'body');
1858
+ this.auditDashboardRefusal(req, 'body', launcher?.name);
1601
1859
  json(res, 400, { error: choice.error });
1602
1860
  return;
1603
1861
  }
@@ -1606,7 +1864,7 @@ export class Daemon {
1606
1864
  else {
1607
1865
  folder = profile.folders.find((entry) => entry.name === folderName);
1608
1866
  if (folder === undefined) {
1609
- this.auditDashboardRefusal(req, 'body');
1867
+ this.auditDashboardRefusal(req, 'body', launcher?.name);
1610
1868
  json(res, 400, { error: `No such folder for profile "${profileName}": ${folderName}` });
1611
1869
  return;
1612
1870
  }
@@ -1614,7 +1872,7 @@ export class Daemon {
1614
1872
  }
1615
1873
  }
1616
1874
  else if (folderName !== undefined || rootIndex !== undefined || freePath !== undefined) {
1617
- this.auditDashboardRefusal(req, 'body');
1875
+ this.auditDashboardRefusal(req, 'body', launcher?.name);
1618
1876
  json(res, 400, {
1619
1877
  error: `Profile "${profileName}" uses a fixed working directory and does not accept a folder.`,
1620
1878
  });
@@ -1622,22 +1880,22 @@ export class Daemon {
1622
1880
  }
1623
1881
  const resolved = freeCwd !== undefined ? { cwd: freeCwd } : rootCwd === undefined ? this.resolveLaunchCwd(profile, folder) : { cwd: rootCwd };
1624
1882
  if ('error' in resolved) {
1625
- this.auditDashboardRefusal(req, 'body');
1883
+ this.auditDashboardRefusal(req, 'body', launcher?.name);
1626
1884
  json(res, 400, { error: resolved.error });
1627
1885
  return;
1628
1886
  }
1629
1887
  // Global policy runs first, then the profile's own deny and allow lists.
1630
1888
  // Both see the real command line, before any Windows shell wrap.
1631
- const globalDecision = evaluateCommand(this.compiledPolicy, profile.command, profile.args);
1889
+ const globalDecision = evaluateCommand(this.compiledPolicy, profile.command, args);
1632
1890
  if (!globalDecision.allowed) {
1633
- this.auditDashboardRefusal(req, 'policy');
1891
+ this.auditDashboardRefusal(req, 'policy', launcher?.name);
1634
1892
  json(res, 403, { error: globalDecision.reason ?? 'Command refused by policy.' });
1635
1893
  return;
1636
1894
  }
1637
1895
  if (profile.policy !== undefined) {
1638
- const ownDecision = evaluateCommand(compileProfilePolicy(profile.policy), profile.command, profile.args);
1896
+ const ownDecision = evaluateCommand(compileProfilePolicy(profile.policy), profile.command, args);
1639
1897
  if (!ownDecision.allowed) {
1640
- this.auditDashboardRefusal(req, 'policy');
1898
+ this.auditDashboardRefusal(req, 'policy', launcher?.name);
1641
1899
  json(res, 403, { error: ownDecision.reason ?? 'Command refused by policy.' });
1642
1900
  return;
1643
1901
  }
@@ -1647,69 +1905,48 @@ export class Daemon {
1647
1905
  // absolute path, so the folder's contents cannot choose the program.
1648
1906
  const resolvedCommand = resolveLaunchCommand(profile.command, resolved.cwd);
1649
1907
  if ('error' in resolvedCommand) {
1650
- this.auditDashboardRefusal(req, 'command');
1908
+ this.auditDashboardRefusal(req, 'command', launcher?.name);
1651
1909
  json(res, 400, {
1652
1910
  error: `Profile "${profile.name}" cannot be started: ${resolvedCommand.error}`,
1653
1911
  });
1654
1912
  return;
1655
1913
  }
1656
- const now = this.now();
1657
- this.pruneLaunchTimes(now);
1658
- if (this.launchTimes.length >= 8) {
1659
- this.auditDashboardRefusal(req, 'rate');
1660
- json(res, 429, {
1661
- error: 'Dashboard launch rate reached (8 in 60 seconds). Wait before starting another profile.',
1662
- });
1663
- return;
1664
- }
1665
- const live = this.manager.liveCount();
1666
- if (this.compiledPolicy.maxSessions === undefined) {
1667
- if (live >= 32) {
1668
- this.auditDashboardRefusal(req, 'limit');
1669
- json(res, 403, {
1670
- error: 'Session limit reached (32 live sessions). Kill a session or set policy.maxSessions.',
1671
- });
1672
- return;
1673
- }
1674
- }
1675
- else {
1676
- const capacity = checkSessionCapacity(this.compiledPolicy, live);
1677
- if (!capacity.allowed) {
1678
- this.auditDashboardRefusal(req, 'limit');
1679
- json(res, 403, { error: capacity.reason ?? 'Session limit reached.' });
1680
- return;
1681
- }
1682
- }
1683
1914
  const { env, copied } = copyDaemonEnv(profile.envFromDaemon, this.daemonEnv);
1684
1915
  const envNames = Object.keys(env);
1685
1916
  const folderLabel = freeCwd !== undefined ? freeCwd : folder?.name ?? (rootCwd !== undefined ? folderName : undefined);
1686
1917
  const options = {
1687
1918
  command: resolvedCommand.file,
1688
- args: [...profile.args],
1919
+ args,
1689
1920
  cwd: resolved.cwd,
1690
1921
  ...(profile.shell !== undefined ? { shell: profile.shell } : {}),
1691
1922
  ...(profile.agent !== undefined ? { agent: profile.agent } : {}),
1692
1923
  ...(profile.readyText !== undefined ? { readyText: profile.readyText } : {}),
1693
1924
  ...(profile.readyQuiet !== undefined ? { readyQuiet: profile.readyQuiet } : {}),
1694
- // The written command stays the session's label, as it was before the
1695
- // path was resolved: the page shows the profile, not a machine path.
1696
- ...(profile.label !== undefined
1697
- ? { label: expandProfileText(profile.label, profile.name, folderLabel) }
1698
- : { label: profile.command }),
1925
+ // An explicit launcher name becomes the label. A configured profile
1926
+ // label remains the default when the launch request omits a name.
1927
+ label: body['name'] === undefined
1928
+ ? (profile.label !== undefined ? expandProfileText(profile.label, profile.name, folderLabel) : profile.name)
1929
+ : requestedName,
1930
+ launchProfile: { profile: profile.name, folder: resolved.cwd,
1931
+ folderChoice: freeCwd !== undefined ? { folderPath: freeCwd } : typeof folderName === 'string'
1932
+ ? { folder: folderName, ...(typeof rootIndex === 'number' ? { rootIndex } : {}) } : {},
1933
+ ...(typeof resumeId === 'string' ? { resumeId } : {}) },
1934
+ role: launcher !== undefined || caller.session === undefined ? (profile.role ?? 'delegate') : 'delegate',
1935
+ ...((launcher?.id ?? caller.session) === undefined ? {} : { parent: launcher?.id ?? caller.session }),
1699
1936
  ...(profile.purpose !== undefined
1700
1937
  ? { purpose: expandProfileText(profile.purpose, profile.name, folderLabel) }
1701
1938
  : {}),
1702
1939
  ...(envNames.length > 0 ? { env } : {}),
1703
1940
  // The audit actor, not a caller-declared identity: the dashboard page
1704
1941
  // has no client environment and no other way to name itself.
1705
- startedBy: 'dashboard',
1942
+ startedBy: launcher?.name ?? 'dashboard',
1706
1943
  };
1707
1944
  // Keep the path check adjacent to spawn. A local writer can still replace
1708
1945
  // a directory after this check, as the security model records.
1709
1946
  if (rootCwd !== undefined) {
1710
1947
  const latest = await resolveRootFolder(profile.folderRoots.map((root) => path.resolve(os.homedir(), root)), rootIndex, folderName);
1711
1948
  if ('error' in latest || latest.cwd !== rootCwd) {
1712
- this.auditDashboardRefusal(req, 'body');
1949
+ this.auditDashboardRefusal(req, 'body', launcher?.name);
1713
1950
  json(res, 400, { error: 'Folder is no longer available from this root.' });
1714
1951
  return;
1715
1952
  }
@@ -1717,18 +1954,53 @@ export class Daemon {
1717
1954
  if (freeCwd !== undefined) {
1718
1955
  const latest = resolveAnyFolder(freePath);
1719
1956
  if ('error' in latest || latest.cwd !== freeCwd) {
1720
- this.auditDashboardRefusal(req, 'body');
1957
+ this.auditDashboardRefusal(req, 'body', launcher?.name);
1721
1958
  json(res, 400, { error: 'The chosen folder is no longer available.' });
1722
1959
  return;
1723
1960
  }
1724
1961
  }
1962
+ if (this.stopping) {
1963
+ json(res, 503, { error: 'The daemon is stopping.' });
1964
+ return;
1965
+ }
1966
+ if (launcher && this.grantedLauncher(req)?.id !== launcher.id) {
1967
+ json(res, 403, { error: 'Session launch permission required.' });
1968
+ return;
1969
+ }
1970
+ const now = this.now();
1971
+ this.pruneLaunchTimes(now);
1972
+ if (this.launchTimes.length >= 8) {
1973
+ this.auditDashboardRefusal(req, 'rate', launcher?.name);
1974
+ json(res, 429, {
1975
+ error: 'Dashboard launch rate reached (8 in 60 seconds). Wait before starting another profile.',
1976
+ });
1977
+ return;
1978
+ }
1979
+ const live = this.manager.liveCount();
1980
+ if (this.compiledPolicy.maxSessions === undefined) {
1981
+ if (live >= 32) {
1982
+ this.auditDashboardRefusal(req, 'limit', launcher?.name);
1983
+ json(res, 403, {
1984
+ error: 'Session limit reached (32 live sessions). Kill a session or set policy.maxSessions.',
1985
+ });
1986
+ return;
1987
+ }
1988
+ }
1989
+ else {
1990
+ const capacity = checkSessionCapacity(this.compiledPolicy, live);
1991
+ if (!capacity.allowed) {
1992
+ this.auditDashboardRefusal(req, 'limit', launcher?.name);
1993
+ json(res, 403, { error: capacity.reason ?? 'Session limit reached.' });
1994
+ return;
1995
+ }
1996
+ }
1725
1997
  let session;
1726
1998
  try {
1727
1999
  session = (this.options.dashboardSessionFactory ?? ((value) => this.manager.create(value)))(options);
1728
2000
  }
1729
2001
  catch (error) {
1730
2002
  if (error instanceof PolicyViolationError) {
1731
- this.auditDashboardRefusal(req, 'policy');
2003
+ this.auditDashboardRefusal(req, 'policy', launcher?.name);
1732
2004
  json(res, 403, { error: error.message });
1733
2005
  return;
1734
2006
  }
@@ -1765,21 +2037,32 @@ export class Daemon {
1765
2037
  // A launch is an API call: the idle timer counts from it, so a session
1766
2038
  // that has just started is not reaped sooner than `idleMinutes` allows.
1767
2039
  this.lastActivity = Date.now();
2040
+ this.registerMailboxSession(session, requestedName);
2041
+ if (launchingWindow && launchingWindow.socket.readyState === launchingWindow.socket.OPEN &&
2042
+ this.dashboardWindowIds.has(launchingWindow.socket)) {
2043
+ const { pair } = launchingWindow;
2044
+ this.dashboardAssignments.set(pair, [...(this.dashboardAssignments.get(pair) ?? []), session.id]);
2045
+ }
1768
2046
  this.sessionFeed.add(this.summaryWithPrompt(session.summary()));
1769
2047
  session.onExit(() => {
1770
2048
  this.geometryController.delete(session.id);
1771
2049
  this.dashboardGeometryOwner.delete(session.id);
2050
+ this.dashboardCredentialOwner.delete(session.id);
2051
+ this.dashboardTransferable.delete(session.id);
1772
2052
  this.updateFeedSession(session.id);
1773
2053
  });
1774
2054
  session.onReady(() => this.updateFeedSession(session.id));
2055
+ this.watchStalls(session);
1775
2056
  // The profile name and the written command line, the file that was
1776
2057
  // actually resolved and started, and copied variable names or "all".
1777
2058
  // Never a value.
1778
- this.audit.record('dashboard', 'start', session.id, {
2059
+ this.audit.record(options.startedBy, 'start', session.id, {
2060
+ startedBy: options.startedBy, ...(launcher ? { launcherId: launcher.id } : {}),
1779
2061
  profile: profile.name,
1780
2062
  command: profile.command,
1781
- args: profile.args,
2063
+ args,
1782
2064
  resolvedCommand: resolvedCommand.file,
2065
+ agent: session.agent,
1783
2066
  ...(profile.envFromDaemon === 'all'
1784
2067
  ? { envFromDaemon: 'all' }
1785
2068
  : copied.length > 0 ? { envFromDaemon: copied } : {}),
@@ -1851,13 +2134,86 @@ export class Daemon {
1851
2134
  this.dropSessionArtifacts(id);
1852
2135
  json(res, 200, { ok: true, killed: id });
1853
2136
  }
2137
+ async handleDashboardRename(req, res, id) {
2138
+ const presented = this.dashboardCookiePresented(req.headers.cookie);
2139
+ if (this.dashboardCookieToken(req.headers.cookie) === null) {
2140
+ if (presented)
2141
+ this.auditDashboardRefusal(req, 'unauthenticated');
2142
+ json(res, 401, { error: 'A dashboard credential is required.' });
2143
+ return;
2144
+ }
2145
+ if (!this.isSameOriginMutation(req)) {
2146
+ this.auditDashboardRefusal(req, this.mutationRefusalReason(req));
2147
+ json(res, 403, { error: 'Forbidden.' });
2148
+ return;
2149
+ }
2150
+ if (!this.tokens.acceptsDashboardProof(headerOne(req, 'x-shellpuppet-csrf'))) {
2151
+ this.auditDashboardRefusal(req, 'proof');
2152
+ json(res, 403, { error: 'Forbidden.' });
2153
+ return;
2154
+ }
2155
+ if ((headerOne(req, 'content-type') ?? '').split(';', 1)[0]?.trim().toLowerCase() !== 'application/json') {
2156
+ json(res, 415, { error: 'The rename body must be JSON.' });
2157
+ return;
2158
+ }
2159
+ let body;
2160
+ try {
2161
+ body = await readBody(req);
2162
+ }
2163
+ catch (error) {
2164
+ if (error instanceof RequestBodyTooLargeError) {
2165
+ json(res, 413, { error: error.message });
2166
+ return;
2167
+ }
2168
+ if (error instanceof Error && error.message.startsWith('Request body')) {
2169
+ json(res, 400, { error: error.message });
2170
+ return;
2171
+ }
2172
+ throw error;
2173
+ }
2174
+ if (Object.keys(body).some((key) => key !== 'name') || typeof body['name'] !== 'string' ||
2175
+ !NAME_PATTERN.test(body['name']) || /^s[0-9]+$/.test(body['name'])) {
2176
+ json(res, 400, { error: 'Name must be 1 to 40 letters, digits, dots, underscores or hyphens, and must not be reserved.' });
2177
+ return;
2178
+ }
2179
+ const session = this.manager.get(id);
2180
+ if (session === undefined) {
2181
+ json(res, 404, { error: `No such session: ${id}` });
2182
+ return;
2183
+ }
2184
+ if (session.exited) {
2185
+ json(res, 409, { error: `Session ${id} has ended and cannot be renamed.` });
2186
+ return;
2187
+ }
2188
+ const previous = this.mailbox.participant(id)?.name;
2189
+ if (previous === undefined) {
2190
+ json(res, 409, { error: 'The session has ended.' });
2191
+ return;
2192
+ }
2193
+ try {
2194
+ this.mailbox.rename(id, body['name']);
2195
+ }
2196
+ catch (error) {
2197
+ if (error instanceof MailboxError) {
2198
+ json(res, error.code === 'duplicate-name' ? 409 : 400, { error: error.message });
2199
+ return;
2200
+ }
2201
+ throw error;
2202
+ }
2203
+ const oldLabel = session.label;
2204
+ session.label = body['name'];
2205
+ this.audit.record('dashboard', 'rename', id, { oldName: previous, newName: body['name'], oldLabel });
2206
+ this.updateFeedSession(id);
2207
+ json(res, 200, { id, name: body['name'], label: session.label });
2208
+ }
1854
2209
  /**
1855
- * Why a `/dashboard/events` upgrade is refused, or null when it may attach.
2210
+ * Authenticate the dashboard event feed and retain its issuing credential.
1856
2211
  * The client token on the query is not a way in. The proof is the
1857
2212
  * subprotocol, not `X-ShellPuppet-CSRF`.
1858
2213
  */
1859
- dashboardUpgradeRefusal(req) {
1860
- if (this.dashboardCookieToken(req.headers.cookie) === null) {
2214
+ dashboardUpgradeCredential(req) {
2215
+ const token = this.dashboardCookieToken(req.headers.cookie);
2216
+ if (token === null) {
1861
2217
  return { code: 401, reason: 'Unauthorized', audit: 'unauthenticated' };
1862
2218
  }
1863
2219
  if (!this.originMatchesRequest(req)) {
@@ -1878,7 +2234,7 @@ export class Daemon {
1878
2234
  });
1879
2235
  if (!accepted)
1880
2236
  return { code: 403, reason: 'Forbidden', audit: 'proof' };
1881
- return null;
2237
+ return token;
1882
2238
  }
1883
2239
  /**
1884
2240
  * Select `sp-csrf.<proof>` when this upgrade's credential is the dashboard
@@ -1935,9 +2291,10 @@ export class Daemon {
1935
2291
  }
1936
2292
  return { ok: true, credential: { kind: 'client', readOnly: false } };
1937
2293
  }
1938
- const dashboard = this.dashboardUpgradeRefusal(req);
1939
- if (dashboard === null) {
1940
- return { ok: true, credential: { kind: 'dashboard', readOnly: false } };
2294
+ const dashboard = this.dashboardUpgradeCredential(req);
2295
+ if (typeof dashboard === 'string') {
2296
+ return { ok: true, credential: { kind: 'dashboard', readOnly: false,
2297
+ dashboardToken: dashboard } };
1941
2298
  }
1942
2299
  const viewer = cookieValues(req.headers.cookie, VIEWER_COOKIE)
1943
2300
  .map((value) => ({ value, credential: this.tokens.verifyStreamToken(value) }))
@@ -2016,7 +2373,7 @@ export class Daemon {
2016
2373
  // learns it. A link whose `s=` had been edited would otherwise spend
2017
2374
  // its grant on a page that then asks for the wrong stream.
2018
2375
  if (url.searchParams.get('s') !== redeemed.sessionId) {
2019
- headers['location'] = `/view?s=${encodeURIComponent(redeemed.sessionId)}`;
2376
+ headers['location'] = `/view?s=${encodeURIComponent(redeemed.sessionId)}${passiveDrive(url) ? '&drive=0' : ''}`;
2020
2377
  res.writeHead(302, headers);
2021
2378
  res.end();
2022
2379
  return;
@@ -2063,10 +2420,18 @@ export class Daemon {
2063
2420
  await this.serveDashboardProfiles(req, res);
2064
2421
  return;
2065
2422
  }
2423
+ if (req.method === 'GET' && url.pathname === '/dashboard/messages') {
2424
+ this.serveDashboardMessages(req, res, url);
2425
+ return;
2426
+ }
2066
2427
  if (req.method === 'POST' && url.pathname === '/dashboard/launch') {
2067
2428
  await this.handleDashboardLaunch(req, res);
2068
2429
  return;
2069
2430
  }
2431
+ if (req.method === 'POST' && segments.length === 4 && segments[0] === 'dashboard' && segments[1] === 'sessions' && segments[3] === 'rename') {
2432
+ await this.handleDashboardRename(req, res, segments[2] ?? '');
2433
+ return;
2434
+ }
2070
2435
  if (req.method === 'POST' && url.pathname === '/dashboard/folder-picker') {
2071
2436
  const handler = this.handleDashboardFolderPicker(req, res);
2072
2437
  this.folderPickerHandlers.add(handler);
@@ -2103,46 +2468,632 @@ export class Daemon {
2103
2468
  return;
2104
2469
  }
2105
2470
  this.lastActivity = Date.now();
2106
- // Audit actor (design §4.5): adapters self-identify via a header, the MCP
2107
- // adapter as `mcp:<clientInfo.name>` and the CLI as `cli`. Untrusted input,
2108
- // so sanitise; it labels log lines and nothing else.
2471
+ // The adapter label remains the audit actor even when a session proves
2472
+ // which session it is. It is still a client-supplied label.
2109
2473
  const actorHeader = req.headers['x-shellpuppet-actor'];
2110
2474
  const actor = (typeof actorHeader === 'string'
2111
2475
  ? // eslint-disable-next-line no-control-regex
2112
2476
  actorHeader.replace(/[\x00-\x1f\x7f]/g, '').slice(0, 64)
2113
2477
  : '') || 'client';
2478
+ const caller = this.resolveCallerIdentity(req);
2479
+ if (caller.presented && caller.session === undefined) {
2480
+ this.audit.record(actor, 'refuse', undefined, { reason: 'session identity not recognised' });
2481
+ json(res, 403, { error: 'Session identity was not recognised.' });
2482
+ return;
2483
+ }
2484
+ if (caller.session !== undefined) {
2485
+ const session = this.manager.get(caller.session);
2486
+ const candidates = headerOne(req, 'x-shellpuppet-resume-ids') ?? headerOne(req, 'x-shellpuppet-resume-id');
2487
+ if (candidates)
2488
+ session?.observeResumeId(...candidates.split(','));
2489
+ const fileResumeId = headerOne(req, 'x-shellpuppet-claude-file-resume-id');
2490
+ if (fileResumeId !== undefined && session?.observeClaudeFileResumeId(fileResumeId)) {
2491
+ res.setHeader('x-shellpuppet-resume-id-recorded', fileResumeId);
2492
+ }
2493
+ }
2494
+ return this.callerContext.run(caller.session, () => this.handleClientRequest(req, res, url, segments, actor));
2495
+ }
2496
+ resolveCallerIdentity(req) {
2497
+ const id = req.headers['x-shellpuppet-session'];
2498
+ const token = req.headers['x-shellpuppet-session-token'];
2499
+ return {
2500
+ presented: id !== undefined || token !== undefined,
2501
+ ...(typeof id === 'string' && typeof token === 'string'
2502
+ && this.manager.recognisesCaller(id, token) ? { session: id } : {}),
2503
+ };
2504
+ }
2505
+ verifiedRestartSnapshot(record) {
2506
+ const state = this.publishedState;
2507
+ const snapshot = snapshotSourceId(record);
2508
+ if (!state || !snapshot)
2509
+ return false;
2510
+ let discovery;
2114
2511
  try {
2115
- if (segments[0] === 'daemon' && segments[1] === 'shutdown' && req.method === 'POST') {
2116
- const body = await readBody(req);
2117
- const force = asBoolean(body['force']) ?? false;
2118
- const live = this.manager.liveCount();
2119
- if (live > 0 && !force) {
2120
- json(res, 409, {
2121
- error: `Refusing to stop: ${String(live)} live session(s). ` +
2122
- `Pass force to kill them.`,
2512
+ discovery = this.requireHomeOwner();
2513
+ }
2514
+ catch {
2515
+ return false;
2516
+ }
2517
+ if (state.restartCandidates) {
2518
+ const home = this.options.home;
2519
+ const resolved = retryRestartSource(home, state, snapshot, this.logger, () => this.requireHomeOwner());
2520
+ if (resolved.restartCandidates)
2521
+ return false;
2522
+ // Remember a verified writer even when it rules out the rows just read.
2523
+ // A later loss of the source must not revive those older rows.
2524
+ delete state.restartCandidates;
2525
+ delete state.restartSourcePending;
2526
+ Object.assign(state, resolved);
2527
+ if (discovery.kind === 'record') {
2528
+ try {
2529
+ writePrivateRecord(daemonStatePath(home), state, () => {
2530
+ if (this.requireHomeOwner().kind !== 'record')
2531
+ throw new Error('Discovery changed during recovery.');
2123
2532
  });
2124
- return;
2125
2533
  }
2126
- this.audit.record(actor, 'shutdown', undefined, { force, liveSessions: live });
2127
- json(res, 200, { ok: true, stopping: true });
2128
- void this.stop().then(() => {
2129
- this.options.onSelfStop?.('shutdown-request');
2130
- });
2131
- return;
2534
+ catch (error) {
2535
+ this.logger.warn('Could not update restart evidence in daemon.json.', { code: error.code });
2536
+ }
2132
2537
  }
2133
- // Behind the token, unlike /health: names of credential-shaped
2134
- // variables are not for anyone who can reach the port.
2135
- if (req.method === 'GET' && segments.length === 1 && segments[0] === 'environment') {
2136
- json(res, 200, this.environmentReport());
2137
- return;
2538
+ else {
2539
+ void this.keepStatePublished();
2138
2540
  }
2139
- if (req.method === 'POST' && segments[0] === 'dashboard' && segments[1] === 'open' && segments.length === 2) {
2140
- await this.handleDashboardOpen(req, res, actor);
2141
- return;
2541
+ }
2542
+ return state.restartFrom === snapshot;
2543
+ }
2544
+ savePreviousSessions() {
2545
+ this.requireHomeOwner();
2546
+ const endedAt = new Date(this.now()).toISOString();
2547
+ const sessions = this.manager.liveProfileSessions().flatMap(session => {
2548
+ // A deferred start has no participant until the program has started and acquired its name.
2549
+ const participant = this.mailbox.participant(session.id);
2550
+ if (!participant)
2551
+ return [];
2552
+ return [{ ...session.launchProfile, name: participant.name === session.id ? null : participant.name,
2553
+ agent: session.agent, resumeId: session.resumeId, endedAt }];
2554
+ });
2555
+ writePrivateRecord(path.join(this.options.home, 'previous-sessions.json'), { version: 1, outgoingInstanceId: this.instanceId, sessions });
2556
+ }
2557
+ saveLauncherClaims(excludeId) {
2558
+ const grants = this.launchProfiles.sessionLaunch ?? [];
2559
+ const file = path.join(this.options.home, 'launcher-claims.json');
2560
+ if (!this.claimsRestored)
2561
+ throw new Error('Saved launcher claims could not be restored.');
2562
+ if (grants.length || fs.existsSync(file)) {
2563
+ let discovery = this.requireHomeOwner();
2564
+ const claims = this.mailbox.savedClaims(grants).filter(claim => claim.id !== excludeId);
2565
+ writePrivateRecord(file, claims, () => { discovery = this.requireHomeOwner(); });
2566
+ if (!this.stopping && (discovery.kind === 'missing' || discovery.kind === 'not-a-record')) {
2567
+ void this.keepStatePublished();
2142
2568
  }
2143
- if (req.method === 'POST' && segments[0] === 'desktop' && segments[1] === 'open' && segments.length === 2) {
2144
- await this.handleDesktopOpen(req, res, actor);
2145
- return;
2569
+ }
2570
+ }
2571
+ grantedLauncher(req) {
2572
+ this.lapseIdleClaims();
2573
+ let id = this.callerContext.getStore();
2574
+ if (id === undefined) {
2575
+ const claim = headerOne(req, 'x-shellpuppet-claim');
2576
+ const secret = headerOne(req, 'x-shellpuppet-claim-secret');
2577
+ if (req.headers['x-shellpuppet-inside-session'] === '1' || !claim || !secret ||
2578
+ !this.mailbox.verifyClaim(claim, secret))
2579
+ return undefined;
2580
+ id = claim;
2581
+ }
2582
+ const caller = this.mailbox.participant(id);
2583
+ return caller && this.launchProfiles.sessionLaunch?.includes(caller.name) ? caller : undefined;
2584
+ }
2585
+ messageAudit(action, entry, actor = 'daemon') {
2586
+ this.audit.record(actor, action, entry.from.id, {
2587
+ fromId: entry.from.id, fromName: entry.from.name,
2588
+ toId: entry.to.id, toName: entry.to.name,
2589
+ messageId: entry.id, length: Buffer.byteLength(entry.text, 'utf8'),
2590
+ });
2591
+ }
2592
+ endMailboxParticipant(id) {
2593
+ for (const [name, pendingId] of this.pendingSchedules)
2594
+ if (pendingId === id)
2595
+ this.pendingSchedules.delete(name);
2596
+ this.nudges.remove(id);
2597
+ // Audit before end can trim old tombstones from retained history.
2598
+ for (const entry of this.mailbox.log({ participantId: id })) {
2599
+ if (entry.to.id === id && (entry.state === 'waiting' || entry.state === 'nudged')) {
2600
+ this.messageAudit('msg-undelivered', entry);
2601
+ }
2602
+ }
2603
+ this.mailbox.end(id);
2604
+ for (const [ws, participant] of this.eventSockets) {
2605
+ if (participant === id)
2606
+ ws.close();
2607
+ }
2608
+ }
2609
+ lapseIdleClaims() {
2610
+ for (const id of this.mailbox.expiredClaims()) {
2611
+ this.claimCount--;
2612
+ this.endMailboxParticipant(id);
2613
+ this.audit.record('daemon', 'msg-lapse', id);
2614
+ }
2615
+ }
2616
+ async deliverNudge(id) {
2617
+ const session = this.manager.get(id);
2618
+ if (session === undefined || session.exited || this.mailbox.participant(id)?.kind !== 'session')
2619
+ return 'done';
2620
+ const pendingIds = session.nudgePendingLine() !== null ? [...session.nudgePendingIds()] : [];
2621
+ // A scheduled body has no mailbox ids. It can clear on proof of consumption,
2622
+ // but a later inbox message can never authorise its submit key.
2623
+ if (session.nudgePendingLine() !== null && pendingIds.length === 0 &&
2624
+ !await this.clearScheduledBody(session))
2625
+ return 'wait';
2626
+ const clearedIds = pendingIds.length > 0 && await session.clearConsumedNudge() ? pendingIds : [];
2627
+ const unread = this.mailbox.inbox(id, { markRead: false });
2628
+ if (clearedIds.length > 0) {
2629
+ this.audit.record('daemon', 'nudge-cleared', id, { messageIds: clearedIds,
2630
+ waitingMessageIds: unread.map((entry) => entry.id) });
2631
+ }
2632
+ const pending = session.nudgePendingLine();
2633
+ if (pending !== null) {
2634
+ if (session.nudgePendingIds().length === 0)
2635
+ return 'wait';
2636
+ const ids = unread.filter((entry) => entry.state === 'waiting').map((entry) => entry.id);
2637
+ if (ids.length === 0)
2638
+ return 'done';
2639
+ const covered = session.nudgePendingIds();
2640
+ if (!session.nudgePendingUntouched()) {
2641
+ if (session.nudgeReadyWithLine(pending) && session.nudgePendingTouchRefusal()) {
2642
+ this.audit.record('daemon', 'nudge-aborted', id, {
2643
+ messageIds: [...covered], count: covered.length, reason: 'person-input-since',
2644
+ });
2645
+ }
2646
+ return 'wait';
2647
+ }
2648
+ if (!session.nudgeReadyWithLine(pending))
2649
+ return 'wait';
2650
+ const inputVersion = session.nudgeInputVersion();
2651
+ const queuedInputVersion = session.nudgeQueuedInputVersion();
2652
+ const screenRevision = session.nudgeScreenRevision();
2653
+ const submitted = await session.submitPendingNudge(pending, (screen) => {
2654
+ const waitingIds = this.mailbox.inbox(id, { markRead: false })
2655
+ .filter((entry) => entry.state === 'waiting').map((entry) => entry.id);
2656
+ return !session.exited && !session.getStalled() &&
2657
+ session.nudgeInputVersion() === inputVersion &&
2658
+ session.nudgeQueuedInputVersion() === queuedInputVersion &&
2659
+ session.nudgeScreenRevision() === screenRevision &&
2660
+ session.answerablePrompt(screen) === null && session.nudgePendingIds().length > 0 &&
2661
+ waitingIds.length === ids.length &&
2662
+ ids.every((messageId) => waitingIds.includes(messageId));
2663
+ });
2664
+ if (!submitted) {
2665
+ if (session.nudgePendingTouchRefusal()) {
2666
+ this.audit.record('daemon', 'nudge-aborted', id, {
2667
+ messageIds: [...covered], count: covered.length, reason: 'person-input-since',
2668
+ });
2669
+ }
2670
+ return 'wait';
2671
+ }
2672
+ this.mailbox.markNudged(ids);
2673
+ this.audit.record('daemon', 'nudge', id, { messageIds: [...covered], count: covered.length,
2674
+ waitingMessageIds: ids.filter((messageId) => !covered.includes(messageId)),
2675
+ staleMessageIds: covered.filter((messageId) => !unread.some((entry) => entry.id === messageId)) });
2676
+ return 'sent';
2677
+ }
2678
+ // Only a message that has not been nudged yet starts a nudge. One that was
2679
+ // nudged but is still unread (the agent did not read its inbox) is listed
2680
+ // in the line again when a later message arrives, so delivery never stops.
2681
+ const ids = unread.filter((entry) => entry.state === 'waiting').map((entry) => entry.id);
2682
+ if (ids.length === 0)
2683
+ return 'done';
2684
+ if (!session.hasPainted() || !session.nudgeReady(this.now()))
2685
+ return 'wait';
2686
+ const line = buildNudge(unread);
2687
+ const result = await this.deliverLine(session, line, undefined, ids, () => {
2688
+ const current = this.mailbox.inbox(id, { markRead: false });
2689
+ return ids.every(messageId => current.some(entry => entry.id === messageId && entry.state === 'waiting'));
2690
+ });
2691
+ if (result.outcome === 'aborted') {
2692
+ this.audit.record('daemon', 'nudge-aborted', id, { messageIds: ids, count: ids.length, reason: result.reason });
2693
+ }
2694
+ if (result.outcome !== 'sent' && result.outcome !== 'queued')
2695
+ return 'wait';
2696
+ this.mailbox.markNudged(ids);
2697
+ this.audit.record('daemon', 'nudge', id, { messageIds: ids, count: ids.length,
2698
+ ...(result.outcome === 'queued' ? { queued: true } : {}) });
2699
+ return 'sent';
2700
+ }
2701
+ async clearScheduledBody(session) {
2702
+ const name = session.pendingSchedule();
2703
+ if (name === undefined || !await session.clearConsumedNudge())
2704
+ return false;
2705
+ if (this.pendingSchedules.get(name) === session.id)
2706
+ this.pendingSchedules.delete(name);
2707
+ return true;
2708
+ }
2709
+ async deliverScheduled(schedule, current) {
2710
+ const id = this.mailbox.sessionIdByName(schedule.session);
2711
+ const session = id === undefined ? undefined : this.manager.get(id);
2712
+ if (!session || session.exited)
2713
+ return { outcome: 'skipped', reason: 'no-session' };
2714
+ if (session.recentInput)
2715
+ return { sessionId: id, outcome: 'skipped', reason: 'recent-input' };
2716
+ const pendingId = this.pendingSchedules.get(schedule.name);
2717
+ if (pendingId !== undefined) {
2718
+ const previous = this.manager.get(pendingId);
2719
+ if (previous?.pendingSchedule() === schedule.name && !await this.clearScheduledBody(previous)) {
2720
+ return { sessionId: id, outcome: 'skipped', reason: 'pending' };
2721
+ }
2722
+ this.pendingSchedules.delete(schedule.name);
2723
+ }
2724
+ if (session.nudgePendingLine() !== null && !await this.clearScheduledBody(session)) {
2725
+ return { sessionId: id, outcome: 'skipped', reason: 'pending' };
2726
+ }
2727
+ try {
2728
+ const result = await this.deliverLine(session, schedule.message, schedule.whenBusy, [], () => current() && this.mailbox.sessionIdByName(schedule.session) === id, schedule.name);
2729
+ // Ordinary input can also arrive while the scheduled write waits in the input queue.
2730
+ if (result.outcome === 'skipped' && session.recentInput)
2731
+ result.reason = 'recent-input';
2732
+ return { ...result, sessionId: id };
2733
+ }
2734
+ finally {
2735
+ if (!session.exited && session.pendingSchedule() === schedule.name)
2736
+ this.pendingSchedules.set(schedule.name, session.id);
2737
+ }
2738
+ }
2739
+ async deliverLine(session, line, whenBusy, ids, currentDelivery, schedule) {
2740
+ if (!session.hasPainted())
2741
+ return { outcome: 'skipped', reason: 'unknown' };
2742
+ const inputVersion = session.nudgeInputVersion();
2743
+ const queuedInputVersion = session.nudgeQueuedInputVersion();
2744
+ const snapshot = await session.snapshot();
2745
+ const state = session.nudgeState(this.now(), whenBusy);
2746
+ if (snapshot.exited)
2747
+ return { outcome: 'skipped', reason: 'session-ended' };
2748
+ if (session.answerablePrompt(snapshot.screen) !== null)
2749
+ return { outcome: 'skipped', reason: 'prompt' };
2750
+ if (!state.ready)
2751
+ return { outcome: 'skipped',
2752
+ reason: state.reason === 'busy' && whenBusy === 'queue' ? 'cannot-queue' : state.reason ?? 'unknown' };
2753
+ // Check the same region again before typing. A running turn can repaint
2754
+ // its transcript, and a separate sidebar can repaint beside an idle pane.
2755
+ const queued = state.queued;
2756
+ const outputAt = session.lastChangeAt();
2757
+ const screenRevision = session.nudgeScreenRevision();
2758
+ let failedCheck = 'line-not-seen';
2759
+ const ready = (screen, phase) => {
2760
+ if (session.exited) {
2761
+ failedCheck = 'session-ended';
2762
+ return false;
2763
+ }
2764
+ if (session.getStalled()) {
2765
+ failedCheck = 'stalled';
2766
+ return false;
2767
+ }
2768
+ const current = phase === 'before' ? session.nudgeState(this.now(), whenBusy) : undefined;
2769
+ if (session.nudgeScreenRevision() !== screenRevision ||
2770
+ (phase === 'before' && (queued || state.paneQuiet ? current?.regionKey !== state.regionKey
2771
+ : session.lastChangeAt() !== outputAt || screen !== snapshot.screen))) {
2772
+ failedCheck = 'screen-changed';
2773
+ return false;
2774
+ }
2775
+ if (session.nudgeQueuedInputVersion() !== queuedInputVersion ||
2776
+ session.nudgeInputVersion() !== inputVersion + (phase === 'submit' ? 1 : 0)) {
2777
+ failedCheck = 'other-input-arrived';
2778
+ return false;
2779
+ }
2780
+ if (session.answerablePrompt(screen) !== null) {
2781
+ failedCheck = 'prompt-showing';
2782
+ return false;
2783
+ }
2784
+ if (!currentDelivery()) {
2785
+ failedCheck = ids.length ? 'messages-changed' : 'schedule-changed';
2786
+ return false;
2787
+ }
2788
+ if (phase === 'before' ? !current?.ready || current.queued !== queued : !session.nudgeReadyWithLine(line, queued, whenBusy)) {
2789
+ failedCheck = 'line-not-seen';
2790
+ return false;
2791
+ }
2792
+ return true;
2793
+ };
2794
+ try {
2795
+ const result = await session.writeNudgeWithReason(line + session.nudgeSubmit(queued), ready, ids, () => failedCheck, schedule, queued);
2796
+ if (result === 'wait')
2797
+ return { outcome: 'skipped', reason: session.nudgePendingLine() !== null ? 'pending' : failedCheck };
2798
+ if (result.startsWith('aborted-')) {
2799
+ const reason = result.slice('aborted-'.length);
2800
+ return { outcome: 'aborted', reason };
2801
+ }
2802
+ }
2803
+ catch (error) {
2804
+ if (error instanceof SessionInputFailedError)
2805
+ return { outcome: 'skipped', reason: 'input-failed' };
2806
+ if (error instanceof SessionProgramEndedError)
2807
+ return { outcome: 'skipped', reason: 'session-ended' };
2808
+ throw error;
2809
+ }
2810
+ return { outcome: queued ? 'queued' : 'sent' };
2811
+ }
2812
+ registerMailboxSession(session, profileName) {
2813
+ const label = profileName ?? session.label;
2814
+ const freeFormGrant = profileName === undefined && this.launchProfiles.sessionLaunch?.includes(label);
2815
+ let name = !freeFormGrant && NAME_PATTERN.test(label) &&
2816
+ (!/^s[0-9]+$/.test(label) || label === session.id) &&
2817
+ !this.mailbox.nameTaken(label) ? label : session.id;
2818
+ if (profileName !== undefined && name === session.id && NAME_PATTERN.test(label) &&
2819
+ !/^s[0-9]+$/.test(label) && !this.isReservedClaimName(label)) {
2820
+ for (let index = 2; index < 10_000; index++) {
2821
+ const candidate = `${label.slice(0, 40 - String(index).length - 1)}-${index}`;
2822
+ if (!this.mailbox.nameTaken(candidate)) {
2823
+ name = candidate;
2824
+ break;
2825
+ }
2826
+ }
2827
+ }
2828
+ this.mailbox.register({ kind: 'session', id: session.id, name, role: session.role });
2829
+ if (NAME_PATTERN.test(session.label))
2830
+ session.label = name;
2831
+ session.onExit(() => this.endMailboxParticipant(session.id));
2832
+ if (session.exited)
2833
+ this.endMailboxParticipant(session.id);
2834
+ }
2835
+ isReservedClaimName(name) {
2836
+ return (this.options.messaging?.allow ?? []).some((rule) => rule !== 'parent-child' && rule.members.includes(name));
2837
+ }
2838
+ async handleMessages(req, res, url, segments, actor) {
2839
+ if (this.options.messaging?.enabled !== true) {
2840
+ json(res, 403, { error: 'Messaging is off.' });
2841
+ return;
2842
+ }
2843
+ this.lapseIdleClaims();
2844
+ const claimId = req.headers['x-shellpuppet-claim'];
2845
+ const claimSecret = req.headers['x-shellpuppet-claim-secret'];
2846
+ const claimPresented = claimId !== undefined || claimSecret !== undefined;
2847
+ const claimValid = typeof claimId === 'string' && typeof claimSecret === 'string' &&
2848
+ this.mailbox.verifyClaim(claimId, claimSecret);
2849
+ const route = segments[1];
2850
+ const creatingClaim = req.method === 'POST' && route === 'claims' && segments.length === 2;
2851
+ if (claimPresented && !claimValid && !creatingClaim) {
2852
+ json(res, 403, { error: 'Messaging claim was not recognised.' });
2853
+ return;
2854
+ }
2855
+ const caller = this.callerContext.getStore() ?? (claimValid ? claimId : undefined);
2856
+ if (creatingClaim) {
2857
+ // Each refusal says only what the daemon knows: a verified session, a valid claim, a mark on the request.
2858
+ if (this.callerContext.getStore() !== undefined) {
2859
+ json(res, 409, { error: 'This session already messages under its own name.' });
2860
+ return;
2861
+ }
2862
+ const marked = req.headers['x-shellpuppet-inside-session'] === '1';
2863
+ if (claimValid || marked) {
2864
+ const reasons = [];
2865
+ if (claimValid) {
2866
+ reasons.push('This client already holds a messaging claim: release it first (msg release), or stop ' +
2867
+ 'presenting it (SHELLPUPPET_CLAIM), to make another.');
2868
+ }
2869
+ if (marked) {
2870
+ reasons.push('This request is marked as coming from inside a ShellPuppet session, and a session ' +
2871
+ 'messages under its own name. A ShellPuppet client adds that mark when SHELLPUPPET_SESSION, ' +
2872
+ 'SHELLPUPPET_SESSION_TOKEN or SHELLPUPPET_DAEMON_INSTANCE is set in its environment; if this is not ' +
2873
+ 'a session, clear them.');
2874
+ }
2875
+ json(res, 409, { error: reasons.join(' ') });
2876
+ return;
2877
+ }
2878
+ const body = await readBody(req);
2879
+ if (typeof body['name'] !== 'string') {
2880
+ json(res, 400, { error: 'A valid name is required.' });
2881
+ return;
2882
+ }
2883
+ const now = this.now();
2884
+ while (this.claimTimes.length > 0 && (this.claimTimes[0] ?? now) <= now - 60_000)
2885
+ this.claimTimes.shift();
2886
+ if (this.claimCount >= 64) {
2887
+ json(res, 429, { error: 'Messaging claim limit reached (64 live claims).' });
2888
+ return;
2889
+ }
2890
+ if (this.claimTimes.length >= 8) {
2891
+ json(res, 429, { error: 'Messaging claim rate reached (8 in 60 seconds).' });
2892
+ return;
2893
+ }
2894
+ const claim = this.mailbox.claim(body['name']);
2895
+ this.claimTimes.push(now);
2896
+ this.claimCount++;
2897
+ if (this.launchProfiles.sessionLaunch?.includes(body['name'])) {
2898
+ try {
2899
+ this.saveLauncherClaims();
2900
+ }
2901
+ catch (error) {
2902
+ this.mailbox.release(claim.claimId);
2903
+ this.claimCount--;
2904
+ throw error;
2905
+ }
2906
+ }
2907
+ this.audit.record(actor, 'msg-claim', claim.claimId, {
2908
+ fromId: claim.claimId, fromName: body['name'], toId: null, toName: null,
2909
+ messageId: null, length: 0, member: this.isReservedClaimName(body['name']),
2910
+ });
2911
+ json(res, 201, claim);
2912
+ return;
2913
+ }
2914
+ if (caller === undefined) {
2915
+ json(res, 403, { error: 'Not a messaging participant.' });
2916
+ return;
2917
+ }
2918
+ if (claimValid)
2919
+ this.mailbox.touchClaim(claimId);
2920
+ if (req.method === 'DELETE' && route === 'claims' && segments.length === 3) {
2921
+ if (!claimValid || claimId !== segments[2]) {
2922
+ json(res, 403, { error: 'The matching claim is required.' });
2923
+ return;
2924
+ }
2925
+ const name = this.mailbox.participant(claimId)?.name;
2926
+ if (name && this.launchProfiles.sessionLaunch?.includes(name))
2927
+ this.saveLauncherClaims(claimId);
2928
+ this.endMailboxParticipant(claimId);
2929
+ this.claimCount--;
2930
+ this.audit.record(actor, 'msg-release', claimId, {
2931
+ fromId: claimId, fromName: name, toId: null, toName: null, messageId: null, length: 0,
2932
+ });
2933
+ json(res, 200, { released: true });
2934
+ return;
2935
+ }
2936
+ const limitText = url.searchParams.get('limit');
2937
+ const limit = limitText === null ? undefined : Number(limitText);
2938
+ if (limit !== undefined && (!Number.isInteger(limit) || limit < 0 || limit > 2000)) {
2939
+ json(res, 400, { error: 'limit must be an integer from 0 to 2000.' });
2940
+ return;
2941
+ }
2942
+ if (req.method === 'POST' && route === undefined) {
2943
+ const body = await readBody(req);
2944
+ const result = this.mailbox.send(caller, body['to'], body['text']);
2945
+ json(res, 201, result);
2946
+ return;
2947
+ }
2948
+ if (req.method === 'GET' && route === 'inbox') {
2949
+ const mark = url.searchParams.get('markRead');
2950
+ if (mark !== null && mark !== 'true' && mark !== 'false') {
2951
+ json(res, 400, { error: 'markRead must be true or false.' });
2952
+ return;
2953
+ }
2954
+ const entries = this.mailbox.inbox(caller, { markRead: mark !== 'false', limit });
2955
+ this.audit.record(actor, 'msg-read', caller, { count: entries.length, source: 'inbox' });
2956
+ json(res, 200, { messages: entries });
2957
+ return;
2958
+ }
2959
+ if (req.method === 'GET' && route === 'outbox') {
2960
+ const messages = this.mailbox.outbox(caller, { limit });
2961
+ this.audit.record(actor, 'msg-read', caller, { count: messages.length, source: 'outbox' });
2962
+ json(res, 200, { messages });
2963
+ return;
2964
+ }
2965
+ if (req.method === 'GET' && route === 'directory') {
2966
+ json(res, 200, { participants: this.mailbox.directory(caller) });
2967
+ return;
2968
+ }
2969
+ if (req.method === 'GET' && route === 'wait') {
2970
+ const raw = url.searchParams.get('timeoutMs');
2971
+ const requested = raw === null ? DEFAULT_WAIT_TIMEOUT_MS : Number(raw);
2972
+ if (!Number.isInteger(requested) || requested < 0) {
2973
+ json(res, 400, { error: 'timeoutMs must be a non-negative integer.' });
2974
+ return;
2975
+ }
2976
+ const controller = new AbortController();
2977
+ const onClose = () => controller.abort();
2978
+ res.on('close', onClose);
2979
+ try {
2980
+ const entry = await this.mailbox.waitForMessage(caller, {
2981
+ ...(url.searchParams.has('from') ? { from: url.searchParams.get('from') } : {}),
2982
+ timeoutMs: Math.min(requested, MAX_WAIT_TIMEOUT_MS), signal: controller.signal,
2983
+ });
2984
+ if (entry !== undefined)
2985
+ this.audit.record(actor, 'msg-read', caller, { count: 1, source: 'wait' });
2986
+ if (!res.destroyed)
2987
+ json(res, 200, { message: entry ?? null });
2988
+ }
2989
+ catch (error) {
2990
+ if (!(error instanceof Error) || error.name !== 'AbortError')
2991
+ throw error;
2992
+ }
2993
+ finally {
2994
+ res.off('close', onClose);
2995
+ }
2996
+ if (claimValid)
2997
+ this.mailbox.touchClaim(claimId);
2998
+ return;
2999
+ }
3000
+ if (req.method === 'GET' && route === 'log') {
3001
+ if (url.searchParams.has('participant') && url.searchParams.get('participant') !== caller) {
3002
+ json(res, 403, { error: 'Log participant must be the caller.' });
3003
+ return;
3004
+ }
3005
+ const messages = this.mailbox.log({ participantId: caller, limit });
3006
+ this.audit.record(actor, 'msg-log', caller, { count: messages.length });
3007
+ json(res, 200, { messages });
3008
+ return;
3009
+ }
3010
+ json(res, 404, { error: 'Messaging route not found.' });
3011
+ }
3012
+ async handleClientRequest(req, res, url, segments, actor) {
3013
+ try {
3014
+ if (url.pathname === '/schedules' && req.method === 'GET') {
3015
+ json(res, 200, { schedules: this.promptScheduler.list() });
3016
+ return;
3017
+ }
3018
+ if (segments[0] === 'daemon' && segments[1] === 'shutdown' && req.method === 'POST') {
3019
+ const body = await readBody(req);
3020
+ if (this.stopping) {
3021
+ await this.shutdownRecords;
3022
+ json(res, 200, { ok: true, stopping: true, warnings: this.shutdownWarnings });
3023
+ return;
3024
+ }
3025
+ const force = asBoolean(body['force']) ?? false;
3026
+ const live = this.manager.liveCount();
3027
+ if (live > 0 && !force) {
3028
+ json(res, 409, {
3029
+ error: `Refusing to stop: ${String(live)} live session(s). ` +
3030
+ `Pass force to kill them.`,
3031
+ });
3032
+ return;
3033
+ }
3034
+ const stopping = this.stop({ restart: body['restart'] === true });
3035
+ this.audit.record(actor, 'shutdown', undefined, { force, liveSessions: live });
3036
+ await this.shutdownRecords;
3037
+ json(res, 200, { ok: true, stopping: true, warnings: this.shutdownWarnings });
3038
+ void stopping.then(() => {
3039
+ this.options.onSelfStop?.('shutdown-request');
3040
+ });
3041
+ return;
3042
+ }
3043
+ // Behind the token, unlike /health: names of credential-shaped
3044
+ // variables are not for anyone who can reach the port.
3045
+ if (req.method === 'GET' && segments.length === 1 && segments[0] === 'environment') {
3046
+ json(res, 200, this.environmentReport());
3047
+ return;
3048
+ }
3049
+ if (req.method === 'POST' && segments[0] === 'dashboard' && segments[1] === 'open' && segments.length === 2) {
3050
+ await this.handleDashboardOpen(req, res, actor);
3051
+ return;
3052
+ }
3053
+ if (req.method === 'POST' && segments[0] === 'desktop' && segments[1] === 'open' && segments.length === 2) {
3054
+ await this.handleDesktopOpen(req, res, actor);
3055
+ return;
3056
+ }
3057
+ if (url.pathname === '/launcher/previous' && req.method === 'GET') {
3058
+ if (!this.grantedLauncher(req)) {
3059
+ json(res, 403, { error: 'Session launch permission required.' });
3060
+ return;
3061
+ }
3062
+ const file = path.join(this.options.home, 'previous-sessions.json');
3063
+ try {
3064
+ // Older version 1 records used the generated session id as an explicit name.
3065
+ const record = JSON.parse(fs.readFileSync(file, 'utf8'), (key, value) => key === 'name' && typeof value === 'string' && /^s[0-9]+$/.test(value) ? null : value);
3066
+ if (!this.verifiedRestartSnapshot(record)) {
3067
+ json(res, 409, { error: 'No verified session snapshot is available for the previous restart.' });
3068
+ return;
3069
+ }
3070
+ json(res, 200, record);
3071
+ }
3072
+ catch (error) {
3073
+ if (error.code === 'ENOENT') {
3074
+ json(res, 409, { error: 'No verified session snapshot is available for the previous restart.' });
3075
+ }
3076
+ else
3077
+ json(res, 500, { error: 'The previous sessions record could not be read.' });
3078
+ }
3079
+ return;
3080
+ }
3081
+ if (url.pathname === '/launcher/launch' && req.method === 'POST') {
3082
+ const caller = this.grantedLauncher(req);
3083
+ if (!caller) {
3084
+ json(res, 403, { error: 'Session launch permission required.' });
3085
+ return;
3086
+ }
3087
+ if ((headerOne(req, 'content-type') ?? '').split(';')[0]?.trim().toLowerCase() !== 'application/json') {
3088
+ json(res, 415, { error: 'The launch body must be JSON.' });
3089
+ return;
3090
+ }
3091
+ await this.launchProfile(req, res, { launcher: caller });
3092
+ return;
3093
+ }
3094
+ if (segments[0] === 'messages') {
3095
+ await this.handleMessages(req, res, url, segments, actor);
3096
+ return;
2146
3097
  }
2147
3098
  if (segments[0] !== 'sessions') {
2148
3099
  json(res, 404, { error: 'Not found.', path: url.pathname });
@@ -2345,43 +3296,149 @@ export class Daemon {
2345
3296
  json(res, 400, { error: BAD_HIDE_REASONING });
2346
3297
  return;
2347
3298
  }
2348
- if (!hide) {
3299
+ // Fails closed: without a signature to read the screen by, nothing
3300
+ // is returned, never the screen unfiltered.
3301
+ const signature = hide ? this.readerFor(session, res) : null;
3302
+ if (hide && signature === null)
3303
+ return;
3304
+ const read = async () => {
2349
3305
  const snapshot = await session.snapshot();
2350
- json(res, 200, count === undefined ? snapshot : { ...snapshot, lastLines: await session.lastLines(count) });
3306
+ if (signature === null)
3307
+ return count === undefined ? { ...snapshot } : { ...snapshot, lastLines: await session.lastLines(count) };
3308
+ const view = await session.styledScreen(REASONING_CONTEXT_LINES);
3309
+ const screen = hideReasoning(view.lines, signature, view.firstVisible);
3310
+ let tail;
3311
+ let tailSource;
3312
+ if (count !== undefined) {
3313
+ tailSource = await session.styledTail(count, REASONING_CONTEXT_LINES);
3314
+ tail = hideReasoning(tailSource.lines, signature, tailSource.firstVisible);
3315
+ }
3316
+ if (screen === null || tail === null) {
3317
+ json(res, 400, { error: overBudgetMessage(signature) });
3318
+ return null;
3319
+ }
3320
+ return {
3321
+ ...snapshot,
3322
+ screen: markFilteredSelectedOption(screen.lines, view.lines, session.agent).join('\n'),
3323
+ cursor: filteredCursor(snapshot.cursor, screen),
3324
+ ...(tail !== undefined && tailSource !== undefined
3325
+ ? { lastLines: markFilteredSelectedOption(tail.lines, tailSource.lines, session.agent) }
3326
+ : {}),
3327
+ reasoning: {
3328
+ agent: signature.name,
3329
+ hiddenLines: screen.hiddenLines,
3330
+ hiddenBlocks: screen.hiddenBlocks,
3331
+ ...(tail !== undefined ? { lastLinesHiddenLines: tail.hiddenLines } : {}),
3332
+ },
3333
+ };
3334
+ };
3335
+ const wider = url.searchParams.get('wider');
3336
+ if (wider === null) {
3337
+ const payload = await read();
3338
+ if (payload !== null)
3339
+ json(res, 200, payload);
2351
3340
  return;
2352
3341
  }
2353
- // Fails closed: without a signature to read the screen by, nothing
2354
- // is returned, never the screen unfiltered.
2355
- const signature = this.readerFor(session, res);
2356
- if (signature === null)
3342
+ const match = /^(\d+)x(\d+)$/.exec(wider);
3343
+ const cols = match === null ? undefined : Number(match[1]);
3344
+ const rows = match === null ? undefined : Number(match[2]);
3345
+ if (cols === undefined || rows === undefined || !Number.isInteger(cols) || !Number.isInteger(rows) ||
3346
+ cols < MIN_GRID_SIDE || rows < MIN_GRID_SIDE || cols > MAX_VIEWPORT_COLS || rows > MAX_VIEWPORT_ROWS) {
3347
+ json(res, 400, { error: `wider must be COLSxROWS with 2 to ${MAX_VIEWPORT_COLS} columns and 2 to ${MAX_VIEWPORT_ROWS} rows.` });
2357
3348
  return;
2358
- const snapshot = await session.snapshot();
2359
- const view = await session.styledScreen(REASONING_CONTEXT_LINES);
2360
- const screen = hideReasoning(view.lines, signature, view.firstVisible);
2361
- let tail;
2362
- let tailSource;
2363
- if (count !== undefined) {
2364
- tailSource = await session.styledTail(count, REASONING_CONTEXT_LINES);
2365
- tail = hideReasoning(tailSource.lines, signature, tailSource.firstVisible);
2366
- }
2367
- if (screen === null || tail === null) {
2368
- json(res, 400, { error: overBudgetMessage(signature) });
3349
+ }
3350
+ const timeoutParam = url.searchParams.get('widerTimeout');
3351
+ const timeout = timeoutParam === null ? 1500 : Number(timeoutParam);
3352
+ if (!Number.isInteger(timeout) || timeout < 250 || timeout > 30_000) {
3353
+ json(res, 400, { error: 'widerTimeout must be an integer from 250 to 30000 ms.' });
2369
3354
  return;
2370
3355
  }
2371
- json(res, 200, {
2372
- ...snapshot,
2373
- screen: markFilteredSelectedOption(screen.lines, view.lines).join('\n'),
2374
- cursor: filteredCursor(snapshot.cursor, screen),
2375
- ...(tail !== undefined && tailSource !== undefined
2376
- ? { lastLines: markFilteredSelectedOption(tail.lines, tailSource.lines) }
2377
- : {}),
2378
- reasoning: {
2379
- agent: signature.name,
2380
- hiddenLines: screen.hiddenLines,
2381
- hiddenBlocks: screen.hiddenBlocks,
2382
- ...(tail !== undefined ? { lastLinesHiddenLines: tail.hiddenLines } : {}),
2383
- },
2384
- });
3356
+ if (session.exited) {
3357
+ json(res, 409, { error: endedRefusal(id, session.exitCode, session.fault) });
3358
+ return;
3359
+ }
3360
+ if (session.geometryHeld) {
3361
+ json(res, 409, { error: 'The grid is held by its owner; a wider read cannot resize it.' });
3362
+ return;
3363
+ }
3364
+ if (this.widerReads.has(id)) {
3365
+ json(res, 409, { error: 'A wider read is already in progress for this session.' });
3366
+ return;
3367
+ }
3368
+ const abort = new AbortController();
3369
+ let finish = () => undefined;
3370
+ const done = new Promise((resolve) => { finish = resolve; });
3371
+ const onClose = () => { if (!res.writableEnded)
3372
+ abort.abort(); };
3373
+ res.on('close', onClose);
3374
+ const original = { cols: session.cols, rows: session.rows };
3375
+ const requested = { cols, rows };
3376
+ const target = { cols: Math.max(cols, original.cols), rows: Math.max(rows, original.rows) };
3377
+ const epoch = this.geometryEpoch.get(id) ?? 0;
3378
+ const announce = () => { if (!session.exited)
3379
+ this.announceGeometry(id, session); };
3380
+ const isTemporary = () => (target.cols !== original.cols || target.rows !== original.rows) &&
3381
+ session.cols === target.cols && session.rows === target.rows && (this.geometryEpoch.get(id) ?? 0) === epoch;
3382
+ this.widerReads.set(id, { abort, done, isTemporary });
3383
+ let payload = null;
3384
+ let restored = true;
3385
+ let readError;
3386
+ this.audit.record(actor, 'wider-read', id, { requested, original });
3387
+ try {
3388
+ if (target.cols !== original.cols || target.rows !== original.rows) {
3389
+ await session.resize(target.cols, target.rows);
3390
+ announce();
3391
+ }
3392
+ const settled = await session.waitFor({ quiet: 250 }, {
3393
+ timeout,
3394
+ quietSince: Date.now(),
3395
+ signal: abort.signal,
3396
+ });
3397
+ if (settled.reason === 'exited' || session.exited) {
3398
+ readError = new SessionProgramEndedError(id, session.exitCode);
3399
+ }
3400
+ else if (!abort.signal.aborted) {
3401
+ payload = await read();
3402
+ }
3403
+ }
3404
+ catch (error) {
3405
+ readError = error;
3406
+ }
3407
+ finally {
3408
+ try {
3409
+ // Only a deliberate geometry act wins. A departing controller does
3410
+ // not choose a new size; keep the control state its departure left.
3411
+ const mayRestore = () => (this.geometryEpoch.get(id) ?? 0) === epoch &&
3412
+ !session.geometryHeld && !session.exited &&
3413
+ session.cols === target.cols && session.rows === target.rows;
3414
+ restored = target.cols === original.cols && target.rows === original.rows
3415
+ ? mayRestore()
3416
+ : await session.resizeIfCurrent(original.cols, original.rows, mayRestore, announce);
3417
+ }
3418
+ catch (error) {
3419
+ // node-pty can record the program's code before the exit event.
3420
+ if (error instanceof SessionProgramEndedError || readError === undefined)
3421
+ readError = error;
3422
+ restored = false;
3423
+ }
3424
+ finally {
3425
+ res.off('close', onClose);
3426
+ this.widerReads.delete(id);
3427
+ finish();
3428
+ }
3429
+ }
3430
+ if (abort.signal.aborted || res.writableEnded)
3431
+ return;
3432
+ if (session.exited || readError instanceof SessionProgramEndedError) {
3433
+ const code = readError instanceof SessionProgramEndedError ? readError.exitCode : session.exitCode;
3434
+ json(res, 409, { error: endedRefusal(id, code, session.fault) });
3435
+ }
3436
+ else if (readError !== undefined) {
3437
+ throw readError instanceof Error ? readError : new Error('Wider read failed with a non-Error value.');
3438
+ }
3439
+ else if (payload !== null) {
3440
+ json(res, 200, { ...payload, restored });
3441
+ }
2385
3442
  return;
2386
3443
  }
2387
3444
  if (req.method === 'GET' && action === 'result') {
@@ -2427,9 +3484,9 @@ export class Daemon {
2427
3484
  // caller's request for a race in the session's lifetime. A session
2428
3485
  // whose input pipe has failed refuses the write too, and its error
2429
3486
  // says what to do.
2430
- let before;
3487
+ let written;
2431
3488
  try {
2432
- before = await session.write(data);
3489
+ written = await session.writeWithResult(data);
2433
3490
  }
2434
3491
  catch (error) {
2435
3492
  json(res, 409, {
@@ -2454,11 +3511,18 @@ export class Daemon {
2454
3511
  json(res, 200, {
2455
3512
  ok: true,
2456
3513
  bytes: data.length,
2457
- verified: await this.verifyTyped(session, data, before),
3514
+ verified: await this.verifyTyped(session, data, written.before),
3515
+ ...(written.submitted !== undefined ? { submitted: written.submitted } : {}),
3516
+ ...(written.submitRetried ? { submitRetried: true } : {}),
3517
+ ...(written.message !== undefined ? { message: written.message } : {}),
2458
3518
  });
2459
3519
  return;
2460
3520
  }
2461
- json(res, 200, { ok: true, bytes: data.length });
3521
+ json(res, 200, { ok: true, bytes: data.length,
3522
+ ...(written.submitted !== undefined ? { submitted: written.submitted } : {}),
3523
+ ...(written.submitRetried ? { submitRetried: true } : {}),
3524
+ ...(written.message !== undefined ? { message: written.message } : {}),
3525
+ });
2462
3526
  return;
2463
3527
  }
2464
3528
  if (req.method === 'POST' && action === 'key') {
@@ -2497,14 +3561,20 @@ export class Daemon {
2497
3561
  json(res, 400, { error: BAD_HIDE_REASONING });
2498
3562
  return;
2499
3563
  }
2500
- const reader = hide ? this.readerFor(session, res) : null;
2501
- if (hide && reader === null)
3564
+ const stalled = queryFlag(url, 'stalled');
3565
+ if (stalled === null) {
3566
+ json(res, 400, { error: 'stalled must be true or false.' });
3567
+ return;
3568
+ }
3569
+ const prompt = url.searchParams.get('prompt');
3570
+ const metadataOnly = stalled && (prompt === null || prompt === 'false' || prompt === '0');
3571
+ const reader = hide && !metadataOnly ? this.readerFor(session, res) : null;
3572
+ if (hide && !metadataOnly && reader === null)
2502
3573
  return;
2503
3574
  const condition = {};
2504
3575
  const text = url.searchParams.get('text');
2505
3576
  const regex = url.searchParams.get('regex');
2506
3577
  const quiet = url.searchParams.get('quiet');
2507
- const prompt = url.searchParams.get('prompt');
2508
3578
  if (text !== null)
2509
3579
  condition.text = text;
2510
3580
  if (regex !== null)
@@ -2516,8 +3586,10 @@ export class Daemon {
2516
3586
  // `prompt === true` only.
2517
3587
  if (prompt !== null)
2518
3588
  condition.prompt = prompt !== 'false' && prompt !== '0';
3589
+ if (stalled)
3590
+ condition.stalled = true;
2519
3591
  const filteredMatch = reader !== null && (condition.text !== undefined || condition.regex !== undefined || condition.prompt === true);
2520
- const muse = signatureFor(session.agent, session.command);
3592
+ const pendingReader = signatureForSession(session);
2521
3593
  let matchView;
2522
3594
  const timeoutParam = url.searchParams.get('timeout');
2523
3595
  const debounceParam = url.searchParams.get('debounce');
@@ -2545,12 +3617,12 @@ export class Daemon {
2545
3617
  ? { matchAfterInput: afterInputParam !== 'false' && afterInputParam !== '0' }
2546
3618
  : {}),
2547
3619
  ...(filteredMatch ? { screenForMatch: () => {
2548
- matchView = filteredWaitScreen(session, reader);
3620
+ matchView = filteredWaitScreen(session, reader, condition.prompt === true);
2549
3621
  return matchView.screen;
2550
- } } : {}),
2551
- ...(muse?.name === 'muse' ? {
3622
+ }, stylesForMatch: () => matchView?.styled } : {}),
3623
+ ...(pendingReader !== null && moduleFor(session.agent)?.readingRules?.pendingComposer === true ? {
2552
3624
  composerPending: () => {
2553
- const result = latestResult(session.styledScreenNow(REASONING_CONTEXT_LINES).lines, muse);
3625
+ const result = latestResult(session.styledScreenNow(REASONING_CONTEXT_LINES).lines, pendingReader);
2554
3626
  return !result.found && result.reason === 'prompt-typed';
2555
3627
  },
2556
3628
  } : {}),
@@ -2564,6 +3636,10 @@ export class Daemon {
2564
3636
  // Nobody to answer, and writing to a closed response throws.
2565
3637
  if (abort.signal.aborted)
2566
3638
  return;
3639
+ if (result.reason === 'stalled') {
3640
+ json(res, 200, { ...result, id: session.id, exited: session.exited, exitCode: session.exitCode });
3641
+ return;
3642
+ }
2567
3643
  if (reader !== null) {
2568
3644
  if (filteredMatch && matchView !== undefined) {
2569
3645
  json(res, 200, {
@@ -2583,10 +3659,10 @@ export class Daemon {
2583
3659
  json(res, 400, { error: overBudgetMessage(reader) });
2584
3660
  return;
2585
3661
  }
2586
- const marked = markFilteredSelectedOption(filtered.lines, view.lines);
3662
+ const marked = markFilteredSelectedOption(filtered.lines, view.lines, session.agent);
2587
3663
  const visiblePrompt = result.prompt === undefined
2588
3664
  ? null
2589
- : detectPrompt(marked.join('\n'));
3665
+ : detectPrompt(marked.join('\n'), session.agent, undefined, filteredPromptStyles(filtered, view));
2590
3666
  const prompt = visiblePrompt !== null && visiblePrompt.signature === result.prompt?.signature
2591
3667
  ? {
2592
3668
  question: visiblePrompt.question,
@@ -2682,7 +3758,16 @@ export class Daemon {
2682
3758
  }
2683
3759
  const hold = body['hold'] === true;
2684
3760
  try {
2685
- await session.resize(cols, rows, { hold });
3761
+ await session.resize(cols, rows, { hold, onApplied: () => {
3762
+ this.audit.record(actor, 'resize', id, { cols, rows, hold });
3763
+ this.geometryEpoch.set(id, (this.geometryEpoch.get(id) ?? 0) + 1);
3764
+ // An API resize takes the grid away from whichever viewport had it.
3765
+ this.geometryController.delete(id);
3766
+ this.dashboardGeometryOwner.delete(id);
3767
+ this.dashboardCredentialOwner.delete(id);
3768
+ this.dashboardTransferable.delete(id);
3769
+ this.announceGeometry(id, session);
3770
+ } });
2686
3771
  }
2687
3772
  catch (error) {
2688
3773
  if (!(error instanceof SessionProgramEndedError))
@@ -2690,21 +3775,35 @@ export class Daemon {
2690
3775
  json(res, 409, { error: endedRefusal(id, error.exitCode) });
2691
3776
  return;
2692
3777
  }
2693
- this.audit.record(actor, 'resize', id, { cols, rows, hold });
2694
- // An API resize takes the grid away from whichever viewport had it, so
2695
- // nobody is left believing they still drive it. It does NOT hold
2696
- // unless asked: a human whose window is now the wrong shape gets it
2697
- // back by moving that window, which is the only escape they have while
2698
- // there is no takeover control to press (§5).
2699
- this.geometryController.delete(id);
2700
- this.dashboardGeometryOwner.delete(id);
2701
- this.announceGeometry(id, session);
2702
3778
  json(res, 200, { ok: true, cols, rows, geometryHeld: session.geometryHeld });
2703
3779
  return;
2704
3780
  }
2705
3781
  json(res, 404, { error: 'Not found.', path: url.pathname });
2706
3782
  }
2707
3783
  catch (error) {
3784
+ if (error instanceof HomeOwnershipError) {
3785
+ json(res, 409, { error: error.message });
3786
+ return;
3787
+ }
3788
+ if (error instanceof MailboxError) {
3789
+ const status = error.code === 'unknown-name' ? 404 :
3790
+ error.code === 'not-allowed' || error.code === 'unknown-sender' ? 403 :
3791
+ error.code === 'duplicate-name' || error.code === 'mailbox-full' ? 409 : 400;
3792
+ const messages = {
3793
+ 'invalid-name': 'A valid participant name is required.',
3794
+ 'duplicate-name': 'That participant name is already held.',
3795
+ 'duplicate-id': 'That participant id is already held.',
3796
+ 'messaging-disabled': 'Messaging is off.',
3797
+ 'unknown-sender': 'Not a messaging participant.',
3798
+ 'unknown-name': 'No live participant has that name.',
3799
+ 'not-allowed': error.message,
3800
+ 'empty-text': 'A message cannot be empty.',
3801
+ 'text-too-large': 'A message exceeds the 16 KiB limit.',
3802
+ 'mailbox-full': 'The mailbox is full.',
3803
+ };
3804
+ json(res, status, { error: messages[error.code] });
3805
+ return;
3806
+ }
2708
3807
  if (error instanceof WaitConditionError) {
2709
3808
  json(res, 400, { error: error.message });
2710
3809
  return;
@@ -2722,6 +3821,10 @@ export class Daemon {
2722
3821
  }
2723
3822
  async handleStart(req, res, actor) {
2724
3823
  const body = await readBody(req);
3824
+ if (this.stopping) {
3825
+ json(res, 503, { error: 'The daemon is stopping.' });
3826
+ return;
3827
+ }
2725
3828
  const command = asString(body['command']);
2726
3829
  if (command === undefined || command === '') {
2727
3830
  json(res, 400, { error: 'command (string) is required.' });
@@ -2780,6 +3883,9 @@ export class Daemon {
2780
3883
  // diverge from the audit trail. Self-declared, not authenticated: see
2781
3884
  // SessionOptions.startedBy.
2782
3885
  startedBy: actor,
3886
+ ...(this.callerContext.getStore() !== undefined ? { parent: this.callerContext.getStore() } : {}),
3887
+ ...(body['waitReady'] === true ? { waitReady: true } : {}),
3888
+ ...(asNumber(body['readyTimeout']) !== undefined ? { readyTimeout: asNumber(body['readyTimeout']) } : {}),
2783
3889
  ...(asString(body['readyText']) !== undefined
2784
3890
  ? { readyText: asString(body['readyText']) }
2785
3891
  : {}),
@@ -2800,7 +3906,7 @@ export class Daemon {
2800
3906
  json(res, 403, { error: error.message });
2801
3907
  return;
2802
3908
  }
2803
- if (error instanceof CommandNotFoundError) {
3909
+ if (error instanceof CommandNotFoundError || error instanceof WaitConditionError) {
2804
3910
  json(res, 400, { error: error.message });
2805
3911
  return;
2806
3912
  }
@@ -2832,15 +3938,19 @@ export class Daemon {
2832
3938
  session = startedSession;
2833
3939
  // Registration is synchronous with creation, before any asynchronous
2834
3940
  // viewer launch or readiness work can publish a change for this id.
3941
+ this.registerMailboxSession(session);
2835
3942
  this.sessionFeed.add(this.summaryWithPrompt(session.summary()));
2836
3943
  session.onExit(() => {
2837
3944
  this.clearPromptGraceCheck(session.id);
2838
3945
  this.promptStates.delete(session.id);
2839
3946
  this.geometryController.delete(session.id);
2840
3947
  this.dashboardGeometryOwner.delete(session.id);
3948
+ this.dashboardCredentialOwner.delete(session.id);
3949
+ this.dashboardTransferable.delete(session.id);
2841
3950
  this.updateFeedSession(session.id);
2842
3951
  });
2843
3952
  session.onReady(() => this.updateFeedSession(session.id));
3953
+ this.watchStalls(session);
2844
3954
  // Commands are policy-visible by definition, so the command line IS
2845
3955
  // audited (§4.5), unlike typed content. Passed variables are audited by
2846
3956
  // name only, whatever `audit.captureContent` says: a value is a secret
@@ -2849,7 +3959,7 @@ export class Daemon {
2849
3959
  command: options.command,
2850
3960
  args: options.args ?? [],
2851
3961
  ...(envNames.length > 0 ? { envNames } : {}),
2852
- ...(agent !== undefined ? { agent } : {}),
3962
+ agent: session.agent,
2853
3963
  label: session.label,
2854
3964
  });
2855
3965
  // The human's way in (design §3.1): the dashboard, a single-session viewer
@@ -2919,6 +4029,15 @@ export class Daemon {
2919
4029
  const handOver = wantsViewer && !dashboardWatching && !opened.launched && viewerUrl !== '';
2920
4030
  if (handOver)
2921
4031
  this.audit.record(actor, 'grant-mint', session.id, { readOnly: false });
4032
+ const cancelled = new AbortController();
4033
+ const onClose = () => cancelled.abort();
4034
+ res.on('close', onClose);
4035
+ if (res.destroyed)
4036
+ cancelled.abort();
4037
+ const readyWait = options.waitReady === true
4038
+ ? await session.waitUntilReady(options.readyTimeout, cancelled.signal)
4039
+ : undefined;
4040
+ res.off('close', onClose);
2922
4041
  json(res, 200, {
2923
4042
  id: session.id,
2924
4043
  label: session.label,
@@ -2929,6 +4048,7 @@ export class Daemon {
2929
4048
  // Without the reason, `ready: true` is ambiguous: it may mean nothing
2930
4049
  // was checked. Callers need to tell those apart before they type.
2931
4050
  readyReason: session.readyReason,
4051
+ ...(readyWait === undefined ? {} : { readyWait, exited: session.exited, exitCode: session.exitCode }),
2932
4052
  geometryHeld: session.geometryHeld,
2933
4053
  viewer: {
2934
4054
  opened: opened.launched,
@@ -2944,12 +4064,12 @@ export class Daemon {
2944
4064
  * readers fail closed.
2945
4065
  */
2946
4066
  readerFor(session, res) {
2947
- const signature = signatureFor(session.agent, session.command);
4067
+ const signature = signatureForSession(session);
2948
4068
  if (signature !== null)
2949
4069
  return signature;
2950
4070
  const known = agentNames().join(', ');
2951
4071
  json(res, 400, {
2952
- error: session.agent !== undefined
4072
+ error: session.agentSource !== 'fallback'
2953
4073
  ? `Session ${session.id} was started as agent "${session.agent}", whose signature is not ` +
2954
4074
  `available now (removed from config, or set aside for running past its time budget), ` +
2955
4075
  `so its screen is not read for hideReasoning or a result.`
@@ -3034,6 +4154,9 @@ export class Daemon {
3034
4154
  this.sessionSockets.delete(id);
3035
4155
  this.geometryController.delete(id);
3036
4156
  this.dashboardGeometryOwner.delete(id);
4157
+ this.dashboardCredentialOwner.delete(id);
4158
+ this.dashboardTransferable.delete(id);
4159
+ this.geometryEpoch.delete(id);
3037
4160
  }
3038
4161
  /** Whether a live viewport is currently driving this session's grid. */
3039
4162
  hasGeometryController(sessionId) {
@@ -3079,7 +4202,8 @@ export class Daemon {
3079
4202
  }
3080
4203
  /** The sessions a client or the dashboard may see: every one but those still starting. */
3081
4204
  listedSummaries() {
3082
- return this.manager.list().filter((summary) => !this.startingIds.has(summary.id));
4205
+ return this.manager.list().filter((summary) => !this.startingIds.has(summary.id))
4206
+ .map((summary) => ({ ...summary, name: this.mailbox.participant(summary.id)?.name ?? summary.id }));
3083
4207
  }
3084
4208
  /**
3085
4209
  * Session list decorated with whatever prompt each session is holding. The
@@ -3096,7 +4220,7 @@ export class Daemon {
3096
4220
  * against prompts that sit for minutes.
3097
4221
  */
3098
4222
  listWithPrompts(hideReasoning = false) {
3099
- const now = Date.now();
4223
+ const now = this.now();
3100
4224
  return this.listedSummaries().map((summary) => {
3101
4225
  const full = this.summaryWithPrompt(summary, now);
3102
4226
  const waiting = full.waitingOnPrompt;
@@ -3105,7 +4229,10 @@ export class Daemon {
3105
4229
  return { ...full, waitingOnPrompt: { waitingMs: waiting.waitingMs, alerted: waiting.alerted } };
3106
4230
  });
3107
4231
  }
3108
- summaryWithPrompt(summary, now = Date.now()) {
4232
+ summaryWithPrompt(summary, now = this.now()) {
4233
+ summary = { ...summary, name: this.mailbox.participant(summary.id)?.name ?? summary.id };
4234
+ if (summary.stalled?.reason === 'server-lost')
4235
+ return summary;
3109
4236
  const state = this.promptStates.get(summary.id);
3110
4237
  if (state === undefined)
3111
4238
  return summary;
@@ -3125,6 +4252,30 @@ export class Daemon {
3125
4252
  if (session !== undefined)
3126
4253
  this.sessionFeed.update(this.summaryWithPrompt(session.summary()));
3127
4254
  }
4255
+ /** One transition drives the feed, audit, log and both notification channels. */
4256
+ watchStalls(session) {
4257
+ session.onStall((stalled) => {
4258
+ if (stalled?.reason === 'server-lost') {
4259
+ // The covered dialog cannot be answered. End its old alert now so the
4260
+ // next scan cannot leave a waiting badge beside the stall notice.
4261
+ const held = this.promptStates.get(session.id);
4262
+ this.clearPromptGraceCheck(session.id);
4263
+ this.promptStates.delete(session.id);
4264
+ if (held?.alerted === true) {
4265
+ this.emitEvent({ type: 'prompt-clear', session: session.id, label: session.label ?? null });
4266
+ this.broadcastControl(session.id, { type: 'prompt-clear' });
4267
+ }
4268
+ }
4269
+ this.updateFeedSession(session.id);
4270
+ const type = stalled === undefined ? 'session-stall-clear' : 'session-stalled';
4271
+ const details = stalled === undefined ? {} : { stalled };
4272
+ this.audit.record('daemon', type, session.id, details);
4273
+ if (stalled !== undefined)
4274
+ this.logger.warn('session stalled', { id: session.id, ...details });
4275
+ this.emitEvent({ type, session: session.id, ...details });
4276
+ this.broadcastControl(session.id, { type, ...details });
4277
+ });
4278
+ }
3128
4279
  clearPromptGraceCheck(id) {
3129
4280
  const timer = this.promptGraceTimers.get(id);
3130
4281
  if (timer !== undefined)
@@ -3163,6 +4314,7 @@ export class Daemon {
3163
4314
  async scanForPromptStalls() {
3164
4315
  const stallMs = this.options.promptStallMs ?? PROMPT_STALL_MS;
3165
4316
  const seen = new Set();
4317
+ const scheduled = new Set(this.schedules.read().filter(s => s.enabled).map(s => this.mailbox.sessionIdByName(s.session)));
3166
4318
  for (const summary of this.manager.list()) {
3167
4319
  const session = this.manager.get(summary.id);
3168
4320
  if (session === undefined || session.exited)
@@ -3171,6 +4323,8 @@ export class Daemon {
3171
4323
  let detected;
3172
4324
  try {
3173
4325
  const snapshot = await session.snapshot();
4326
+ if (scheduled.has(session.id))
4327
+ session.nudgeState(this.now());
3174
4328
  detected = session.answerablePrompt(snapshot.screen);
3175
4329
  }
3176
4330
  catch (error) {
@@ -3190,8 +4344,8 @@ export class Daemon {
3190
4344
  // scan interval; a lasting disappearance still clears it.
3191
4345
  if (previous !== undefined) {
3192
4346
  if (previous.missingSince === null)
3193
- previous.missingSince = Date.now();
3194
- const remaining = previous.missingSince + PROMPT_REPAINT_GRACE_MS - Date.now();
4347
+ previous.missingSince = this.now();
4348
+ const remaining = previous.missingSince + PROMPT_REPAINT_GRACE_MS - this.now();
3195
4349
  if (remaining > 0) {
3196
4350
  this.schedulePromptGraceCheck(session.id, remaining);
3197
4351
  continue;
@@ -3259,7 +4413,7 @@ export class Daemon {
3259
4413
  }
3260
4414
  this.promptStates.set(session.id, {
3261
4415
  signature: detected.signature,
3262
- since: Date.now(),
4416
+ since: this.now(),
3263
4417
  alerted: false,
3264
4418
  prompt: detected,
3265
4419
  missingSince: null,
@@ -3271,10 +4425,10 @@ export class Daemon {
3271
4425
  previous.signature = detected.signature;
3272
4426
  if (promptChanged)
3273
4427
  this.updateFeedSession(session.id);
3274
- if (!previous.alerted && Date.now() - previous.since >= stallMs) {
4428
+ if (!previous.alerted && this.now() - previous.since >= stallMs) {
3275
4429
  previous.alerted = true;
3276
4430
  this.updateFeedSession(session.id);
3277
- const waitingMs = Date.now() - previous.since;
4431
+ const waitingMs = this.now() - previous.since;
3278
4432
  this.audit.record('daemon', 'prompt-stall', session.id);
3279
4433
  this.logger.warn('session waiting on a prompt', {
3280
4434
  id: session.id,
@@ -3312,15 +4466,34 @@ export class Daemon {
3312
4466
  this.updateFeedSession(id);
3313
4467
  }
3314
4468
  }
4469
+ await this.nudges.tick();
3315
4470
  }
3316
4471
  /** Fan an event out to every `/events` subscriber (TEXT JSON frames). */
3317
4472
  emitEvent(event) {
3318
4473
  const message = JSON.stringify({ ...event, at: new Date().toISOString() });
3319
- for (const ws of this.eventSockets) {
4474
+ for (const ws of this.eventSockets.keys()) {
3320
4475
  if (ws.readyState === ws.OPEN)
3321
4476
  ws.send(message);
3322
4477
  }
3323
4478
  }
4479
+ emitMessageEvent(event, entry) {
4480
+ if (entry === undefined)
4481
+ return;
4482
+ const message = JSON.stringify({ ...event, at: new Date().toISOString() });
4483
+ for (const [ws, participant] of this.eventSockets) {
4484
+ if (ws.readyState === ws.OPEN && participant !== undefined &&
4485
+ (participant === entry.from.id || participant === entry.to.id))
4486
+ ws.send(message);
4487
+ }
4488
+ }
4489
+ /** Dashboard notifications carry metadata only; the page fetches text separately. */
4490
+ emitDashboardMessageEvent(event) {
4491
+ const frame = JSON.stringify({ ...event, at: new Date().toISOString() });
4492
+ for (const ws of this.dashboardEventSockets) {
4493
+ if (ws.readyState === ws.OPEN)
4494
+ ws.send(frame);
4495
+ }
4496
+ }
3324
4497
  // ------------------------------------------------------------- websockets
3325
4498
  handleUpgrade(req, socket, head) {
3326
4499
  // Node takes its own 'error' listener off the socket before it emits
@@ -3365,14 +4538,14 @@ export class Daemon {
3365
4538
  // The dashboard feed is cookie-only. Its Origin rule is stricter than the
3366
4539
  // client-token sockets below, which still allow a missing Origin.
3367
4540
  if (segments[0] === 'dashboard' && segments[1] === 'events' && segments.length === 2) {
3368
- const refusal = this.dashboardUpgradeRefusal(req);
3369
- if (refusal !== null) {
3370
- this.auditDashboardRefusal(req, refusal.audit);
3371
- reject(refusal.code, refusal.reason);
4541
+ const credential = this.dashboardUpgradeCredential(req);
4542
+ if (typeof credential !== 'string') {
4543
+ this.auditDashboardRefusal(req, credential.audit);
4544
+ reject(credential.code, credential.reason);
3372
4545
  return;
3373
4546
  }
3374
4547
  this.wss.handleUpgrade(req, socket, head, (ws) => {
3375
- this.attachDashboardSocket(ws);
4548
+ this.attachDashboardSocket(ws, credential);
3376
4549
  });
3377
4550
  return;
3378
4551
  }
@@ -3386,8 +4559,24 @@ export class Daemon {
3386
4559
  reject(401, 'Unauthorized');
3387
4560
  return;
3388
4561
  }
4562
+ const caller = this.resolveCallerIdentity(req);
4563
+ if (caller.presented && caller.session === undefined) {
4564
+ this.audit.record('client', 'refuse', undefined, { reason: 'session identity not recognised' });
4565
+ reject(403, 'Forbidden');
4566
+ return;
4567
+ }
4568
+ const claimId = req.headers['x-shellpuppet-claim'];
4569
+ const claimSecret = req.headers['x-shellpuppet-claim-secret'];
4570
+ const claimPresented = claimId !== undefined || claimSecret !== undefined;
4571
+ if (claimPresented)
4572
+ this.lapseIdleClaims();
4573
+ if (claimPresented && (typeof claimId !== 'string' || typeof claimSecret !== 'string' ||
4574
+ !this.mailbox.verifyClaim(claimId, claimSecret))) {
4575
+ reject(403, 'Forbidden');
4576
+ return;
4577
+ }
3389
4578
  this.wss.handleUpgrade(req, socket, head, (ws) => {
3390
- this.attachEventSocket(ws);
4579
+ this.callerContext.run(caller.session, () => this.attachEventSocket(ws, caller.session ?? (typeof claimId === 'string' ? claimId : undefined)));
3391
4580
  });
3392
4581
  return;
3393
4582
  }
@@ -3414,6 +4603,13 @@ export class Daemon {
3414
4603
  reject(decision.code, decision.reason);
3415
4604
  return;
3416
4605
  }
4606
+ const caller = decision.credential.kind === 'client' ? this.resolveCallerIdentity(req)
4607
+ : { presented: false, session: undefined };
4608
+ if (caller.presented && caller.session === undefined) {
4609
+ this.audit.record('client', 'refuse', undefined, { reason: 'session identity not recognised' });
4610
+ reject(403, 'Forbidden');
4611
+ return;
4612
+ }
3417
4613
  const session = this.manager.get(sessionId);
3418
4614
  if (session === undefined) {
3419
4615
  reject(404, 'Not Found');
@@ -3428,13 +4624,13 @@ export class Daemon {
3428
4624
  // names that credential rather than assuming a browser: `client` for
3429
4625
  // the client token on the query, `viewer` for a viewer cookie,
3430
4626
  // `dashboard` for the dashboard cookie.
3431
- this.attachSocket(ws, session, decision.credential, { passive, frozen: decision.frozen });
4627
+ this.callerContext.run(caller.session, () => this.attachSocket(ws, session, decision.credential, { passive, frozen: decision.frozen, callerSession: caller.session }));
3432
4628
  });
3433
4629
  }
3434
4630
  /** Attach a subscriber to the daemon-wide event stream. */
3435
- attachEventSocket(ws) {
4631
+ attachEventSocket(ws, participant) {
3436
4632
  this.sockets.add(ws);
3437
- this.eventSockets.add(ws);
4633
+ this.eventSockets.set(ws, participant);
3438
4634
  this.lastActivity = Date.now();
3439
4635
  this.audit.record('client', 'events-connect', '-');
3440
4636
  ws.send(JSON.stringify({ type: 'hello', version: this.version }));
@@ -3449,13 +4645,97 @@ export class Daemon {
3449
4645
  // The stream is outbound-only; inbound frames are ignored by design.
3450
4646
  }
3451
4647
  /**
3452
- * Attach a subscriber to the dashboard session feed. Frames are the feed's
3453
- * own: hello, a snapshot, then session deltas. The only inbound frame read is
3454
- * one small window registration; every other inbound frame is ignored.
4648
+ * Attach a subscriber to the dashboard session feed. After hello and a
4649
+ * snapshot, registered windows receive roster and assignment state. A
4650
+ * registered socket may focus, designate or move a pane through the daemon.
3455
4651
  * The socket counts as connected so idle shutdown waits while the dashboard
3456
4652
  * is open.
3457
4653
  */
3458
- attachDashboardSocket(ws) {
4654
+ dashboardPair(window) {
4655
+ return JSON.stringify([window.id, window.instance]);
4656
+ }
4657
+ dashboardWindows() {
4658
+ return [...this.dashboardWindowIds.entries()]
4659
+ .filter(([socket]) => socket.readyState === socket.OPEN)
4660
+ .map(([socket, window]) => ({ socket, pair: this.dashboardPair(window), focused: window.focused }));
4661
+ }
4662
+ dashboardFocusTime(value) {
4663
+ // Documents on this host report the focus event in epoch milliseconds.
4664
+ // A late registration can report the past, but cannot reserve a future turn.
4665
+ const now = performance.timeOrigin + performance.now();
4666
+ return typeof value === 'number' && Number.isFinite(value) ? Math.max(0, Math.min(now, value)) : 0;
4667
+ }
4668
+ updateDashboardOffers(windows) {
4669
+ for (const [id, previous] of this.dashboardTransferable) {
4670
+ const owner = windows.find(w => this.dashboardAssignments.get(w.pair)?.includes(id));
4671
+ const recipient = owner?.socket.protocol;
4672
+ if (recipient === previous || (previous === null && windows.length === 0))
4673
+ continue;
4674
+ this.dashboardTransferable.set(id, recipient);
4675
+ const session = this.manager.get(id);
4676
+ if (session)
4677
+ this.announceGeometry(id, session, { resync: false });
4678
+ }
4679
+ }
4680
+ publishDashboardWindows(move) {
4681
+ const windows = this.dashboardWindows();
4682
+ const roster = [...new Set(windows.map((window) => window.pair))];
4683
+ if (windows.length === 0) {
4684
+ this.dashboardDesignated = null;
4685
+ this.dashboardAssignments.clear();
4686
+ this.updateDashboardOffers(windows);
4687
+ return;
4688
+ }
4689
+ if (!windows.some((window) => window.pair === this.dashboardDesignated)) {
4690
+ this.dashboardDesignated = [...windows].sort((a, b) => b.focused - a.focused)[0].pair;
4691
+ }
4692
+ const live = new Set(this.manager.list().filter((session) => !this.startingIds.has(session.id)).map((session) => session.id));
4693
+ for (const [pair, ids] of this.dashboardAssignments) {
4694
+ if (!roster.includes(pair)) {
4695
+ this.dashboardAssignments.delete(pair);
4696
+ this.dashboardAssignments.set(this.dashboardDesignated, [
4697
+ ...(this.dashboardAssignments.get(this.dashboardDesignated) ?? []), ...ids.filter((id) => live.has(id)),
4698
+ ]);
4699
+ }
4700
+ else
4701
+ this.dashboardAssignments.set(pair, ids.filter((id) => live.has(id)));
4702
+ }
4703
+ const placed = new Set([...this.dashboardAssignments.values()].flat());
4704
+ for (const id of live) {
4705
+ if (placed.has(id))
4706
+ continue;
4707
+ this.dashboardAssignments.set(this.dashboardDesignated, [...(this.dashboardAssignments.get(this.dashboardDesignated) ?? []), id]);
4708
+ }
4709
+ const frame = JSON.stringify({ type: 'window-state', designated: this.dashboardDesignated,
4710
+ windows: roster, assignments: Object.fromEntries(this.dashboardAssignments),
4711
+ ...(move === undefined ? {} : { move }) });
4712
+ for (const window of windows)
4713
+ window.socket.send(frame);
4714
+ this.updateDashboardOffers(windows);
4715
+ }
4716
+ dashboardFeedCurrent(ws) {
4717
+ return this.tokens.verifyDashboardToken(this.dashboardSocketCredential.get(ws)) &&
4718
+ this.tokens.acceptsDashboardProof(dashboardProofFromProtocol(ws.protocol));
4719
+ }
4720
+ retireDashboardFeeds() {
4721
+ for (const protocol of this.dashboardDocumentFocus.keys()) {
4722
+ if (!this.tokens.acceptsDashboardProof(dashboardProofFromProtocol(protocol)))
4723
+ this.dashboardDocumentFocus.delete(protocol);
4724
+ }
4725
+ let changed = false;
4726
+ for (const ws of this.dashboardEventSockets) {
4727
+ if (ws.readyState === ws.OPEN && !this.dashboardFeedCurrent(ws)) {
4728
+ if (this.dashboardWindowIds.delete(ws))
4729
+ changed = true;
4730
+ this.liveDashboardEventSockets.delete(ws);
4731
+ ws.close(1008, 'Dashboard access expired');
4732
+ }
4733
+ }
4734
+ if (changed)
4735
+ this.publishDashboardWindows();
4736
+ }
4737
+ attachDashboardSocket(ws, credential) {
4738
+ this.dashboardSocketCredential.set(ws, credential);
3459
4739
  this.sockets.add(ws);
3460
4740
  this.dashboardEventSockets.add(ws);
3461
4741
  this.liveDashboardEventSockets.add(ws);
@@ -3483,16 +4763,18 @@ export class Daemon {
3483
4763
  const unsubscribe = this.subscribeDashboardFeed((frame) => {
3484
4764
  if (ws.readyState === ws.OPEN)
3485
4765
  ws.send(JSON.stringify(frame));
4766
+ if ((frame.type === 'session-added' || frame.type === 'session-removed') &&
4767
+ this.dashboardWindows()[0]?.socket === ws)
4768
+ this.publishDashboardWindows();
3486
4769
  });
3487
4770
  ws.on('message', (raw) => {
3488
- // This id only speeds roster departure. It grants no daemon action.
3489
- if (this.dashboardWindowIds.has(ws))
4771
+ if (!this.dashboardFeedCurrent(ws))
3490
4772
  return;
3491
4773
  let frame;
3492
4774
  try {
3493
4775
  const bytes = Array.isArray(raw) ? Buffer.concat(raw) : Buffer.from(raw);
3494
- // A registration is a few dozen bytes: never parse anything larger.
3495
- if (bytes.length > MAX_WINDOW_REGISTRATION_BYTES)
4776
+ // Window control frames are small: never parse anything larger.
4777
+ if (bytes.length > 1024)
3496
4778
  return;
3497
4779
  frame = JSON.parse(bytes.toString('utf8'));
3498
4780
  }
@@ -3502,17 +4784,57 @@ export class Daemon {
3502
4784
  if (typeof frame !== 'object' || frame === null)
3503
4785
  return;
3504
4786
  const claim = frame;
4787
+ const current = this.dashboardWindowIds.get(ws);
4788
+ if (current !== undefined) {
4789
+ const pair = this.dashboardPair(current);
4790
+ if (claim.type === 'window-focus') {
4791
+ const at = claim.focusedAt === undefined ? performance.timeOrigin + performance.now() : claim.focusedAt;
4792
+ current.focused = Math.max(current.focused, this.dashboardFocusTime(at));
4793
+ this.dashboardDocumentFocus.set(ws.protocol, { id: current.id, focused: current.focused });
4794
+ this.publishDashboardWindows();
4795
+ }
4796
+ else if (claim.type === 'window-designate') {
4797
+ this.dashboardDesignated = pair;
4798
+ this.publishDashboardWindows();
4799
+ }
4800
+ else if (claim.type === 'window-move' && typeof claim.session === 'string' &&
4801
+ typeof claim.source === 'string' && typeof claim.target === 'string' &&
4802
+ (claim.source === pair || claim.target === pair) &&
4803
+ claim.session.length <= 100 &&
4804
+ this.dashboardAssignments.get(claim.source)?.includes(claim.session)) {
4805
+ const open = this.dashboardWindows().map((window) => window.pair);
4806
+ if (!open.includes(claim.source) || !open.includes(claim.target))
4807
+ return;
4808
+ if (claim.source === claim.target && claim.before === claim.session)
4809
+ return;
4810
+ this.dashboardAssignments.set(claim.source, this.dashboardAssignments.get(claim.source).filter((id) => id !== claim.session));
4811
+ const target = this.dashboardAssignments.get(claim.target) ?? [];
4812
+ const before = typeof claim.before === 'string' ? target.indexOf(claim.before) : -1;
4813
+ const anchor = target[before];
4814
+ target.splice(before < 0 ? target.length : before, 0, claim.session);
4815
+ this.dashboardAssignments.set(claim.target, target);
4816
+ this.publishDashboardWindows({ session: claim.session, target: claim.target,
4817
+ ...(anchor === undefined ? {} : { before: anchor }) });
4818
+ }
4819
+ return;
4820
+ }
3505
4821
  if (claim.type !== 'window-register' || typeof claim.id !== 'string' ||
3506
4822
  !/^[a-z0-9]+-[a-z0-9]+(?:-[1-9][0-9]*)?$/.test(claim.id) || claim.id.length > 100 ||
3507
4823
  typeof claim.instance !== 'string' ||
3508
4824
  !/^[a-z0-9]+-[a-z0-9]+(?:-[1-9][0-9]*)?$/.test(claim.instance) ||
3509
4825
  claim.instance.length > 100)
3510
4826
  return;
3511
- this.dashboardWindowIds.set(ws, { id: claim.id, instance: claim.instance });
4827
+ const previous = this.dashboardDocumentFocus.get(ws.protocol);
4828
+ const focused = Math.max(previous?.id === claim.id ? previous.focused : 0, this.dashboardFocusTime(claim.focusedAt));
4829
+ this.dashboardWindowIds.set(ws, { id: claim.id, instance: claim.instance, focused });
4830
+ this.dashboardDocumentFocus.set(ws.protocol, { id: claim.id, focused });
4831
+ this.publishDashboardWindows();
3512
4832
  });
3513
4833
  ws.on('close', () => {
3514
4834
  const windowClaim = this.dashboardWindowIds.get(ws);
3515
4835
  this.dashboardWindowIds.delete(ws);
4836
+ if (windowClaim !== undefined)
4837
+ this.publishDashboardWindows();
3516
4838
  unsubscribe();
3517
4839
  this.sockets.delete(ws);
3518
4840
  this.dashboardEventSockets.delete(ws);
@@ -3569,16 +4891,30 @@ export class Daemon {
3569
4891
  }
3570
4892
  this.updateFeedSession(sessionId);
3571
4893
  }
4894
+ gridOfferedTo(id, ws) {
4895
+ const recipient = this.dashboardTransferable.get(id);
4896
+ return (recipient === null || recipient === ws.protocol) &&
4897
+ this.dashboardCredentialOwner.has(id) && this.dashboardSocketCredential.has(ws) &&
4898
+ tokensEqual(this.dashboardCredentialOwner.get(id), this.dashboardSocketCredential.get(ws));
4899
+ }
3572
4900
  /** What one watcher is told about the grid, from its own point of view. */
3573
4901
  geometryFrame(session, ws) {
3574
4902
  return {
3575
4903
  type: 'geometry',
4904
+ ...(this.widerReads.get(session.id)?.isTemporary() ? { temporary: true } : {}),
3576
4905
  cols: session.cols,
3577
4906
  rows: session.rows,
3578
4907
  // The most a viewport may ask for (§5), with every frame: a page whose
3579
4908
  // window wants more can then size its text for the grid it will be
3580
4909
  // given, rather than proposing one it never will be.
3581
4910
  max: { cols: MAX_VIEWPORT_COLS, rows: MAX_VIEWPORT_ROWS },
4911
+ // An adopting dashboard must distinguish a fresh session from one
4912
+ // already taken in another window before scheduling its initial fit.
4913
+ owned: this.hasGeometryController(session.id) ||
4914
+ (this.dashboardSocketCredential.has(ws) && this.dashboardGeometryOwner.has(session.id)),
4915
+ // Only a controller's explicit assignment handover offers its grid to
4916
+ // another dashboard pane while the old socket is closing.
4917
+ dashboardTransferable: this.gridOfferedTo(session.id, ws),
3582
4918
  control: session.geometryHeld
3583
4919
  ? 'held'
3584
4920
  : this.geometryController.get(session.id) === ws
@@ -3628,6 +4964,8 @@ export class Daemon {
3628
4964
  // or program behind it.
3629
4965
  const actor = credential.kind;
3630
4966
  this.sockets.add(ws);
4967
+ if (credential.dashboardToken !== undefined)
4968
+ this.dashboardSocketCredential.set(ws, credential.dashboardToken);
3631
4969
  let watchers = this.sessionSockets.get(session.id);
3632
4970
  if (watchers === undefined) {
3633
4971
  watchers = new Map();
@@ -3679,22 +5017,29 @@ export class Daemon {
3679
5017
  // never picks it up by connecting, whatever the query says, and neither
3680
5018
  // does a `drive=0` socket. Neither inherits a controller that has left:
3681
5019
  // this is the only place a socket becomes the controller without sending
3682
- // `take`.
5020
+ // `take`. While a dashboard's grid is remembered for its absent socket,
5021
+ // a viewer or client socket follows it too, until a deliberate resize.
3683
5022
  if (credential.kind === 'dashboard' &&
3684
- // The remembered proof identifies the dashboard credential, not a browser window;
3685
- // any holder may already take this grid deliberately, so restoring it is enough.
5023
+ // The returning document can restore its grid while a release to a
5024
+ // different assignment belongs to that recipient alone.
3686
5025
  this.dashboardGeometryOwner.has(session.id) &&
5026
+ (!this.dashboardTransferable.has(session.id) || this.gridOfferedTo(session.id, ws)) &&
3687
5027
  tokensEqual(this.dashboardGeometryOwner.get(session.id), ws.protocol) &&
3688
5028
  !session.exited &&
3689
5029
  !this.hasGeometryController(session.id)) {
3690
5030
  this.geometryController.set(session.id, ws);
5031
+ this.dashboardTransferable.delete(session.id);
5032
+ this.announceGeometry(session.id, session, { resync: false });
3691
5033
  }
3692
5034
  else if (!session.geometryHeld &&
3693
5035
  !readOnly &&
3694
5036
  !passive &&
3695
- !this.hasGeometryController(session.id)) {
5037
+ !this.hasGeometryController(session.id) &&
5038
+ !this.dashboardGeometryOwner.has(session.id)) {
3696
5039
  this.geometryController.set(session.id, ws);
3697
5040
  this.dashboardGeometryOwner.delete(session.id);
5041
+ this.dashboardCredentialOwner.delete(session.id);
5042
+ this.dashboardTransferable.delete(session.id);
3698
5043
  }
3699
5044
  ws.send(JSON.stringify(options.frozen === undefined
3700
5045
  ? this.geometryFrame(session, ws)
@@ -3727,13 +5072,16 @@ export class Daemon {
3727
5072
  // AFTER the resync, so the gate holds it behind the snapshot instead of
3728
5073
  // letting the snapshot's wipe erase it.
3729
5074
  if (session.exited) {
3730
- sync.deliver(exitNotice(session.exitCode));
5075
+ sync.deliver(session.fault === null ? exitNotice(session.exitCode) : `session ended: ${session.fault}`);
3731
5076
  }
3732
5077
  // A stall is announced once, at the moment it trips. Someone who opens the
3733
5078
  // viewer BECAUSE they were told a session is stuck arrives after
3734
5079
  // the only announcement, and is the exact person the badge is for. Replay the
3735
5080
  // current state to them.
3736
5081
  const held = this.promptStates.get(session.id);
5082
+ const stalled = session.getStalled();
5083
+ if (stalled !== undefined)
5084
+ ws.send(JSON.stringify({ type: 'session-stalled', stalled }));
3737
5085
  if (held?.alerted === true) {
3738
5086
  ws.send(JSON.stringify({
3739
5087
  type: 'prompt-stall',
@@ -3746,11 +5094,12 @@ export class Daemon {
3746
5094
  const unsubscribeData = session.onData((data) => sync.deliver(data));
3747
5095
  this.updateFeedSession(session.id);
3748
5096
  const unsubscribeExit = session.onExit((exitCode) => {
3749
- sync.deliver(exitNotice(exitCode));
5097
+ sync.deliver(session.fault === null ? exitNotice(exitCode) : `session ended: ${session.fault}`);
3750
5098
  // The notice is bytes on the terminal; the page needs a frame to change
3751
5099
  // its own state.
3752
5100
  if (ws.readyState === ws.OPEN) {
3753
- ws.send(JSON.stringify({ type: 'exited', exitCode }));
5101
+ ws.send(JSON.stringify({ type: 'exited', exitCode,
5102
+ ...(session.fault === null ? {} : { fault: session.fault }) }));
3754
5103
  }
3755
5104
  });
3756
5105
  // A protocol error, such as a malformed frame or a reset mid-handshake,
@@ -3767,10 +5116,26 @@ export class Daemon {
3767
5116
  const text = typeof message === 'string' ? message : message.toString('utf8');
3768
5117
  try {
3769
5118
  const parsed = JSON.parse(text);
5119
+ if (typeof parsed === 'object' && parsed !== null &&
5120
+ parsed.type === 'release-grid') {
5121
+ // Only the current controller can give up a dashboard grid. Another
5122
+ // document with the same cookie cannot make a live controller yield.
5123
+ if (credential.kind === 'dashboard' && !session.exited && !session.geometryHeld &&
5124
+ this.geometryController.get(session.id) === ws) {
5125
+ const windows = this.dashboardWindows();
5126
+ const target = windows.find(({ pair }) => this.dashboardAssignments.get(pair)?.includes(session.id));
5127
+ if (target)
5128
+ this.dashboardTransferable.set(session.id, target.socket.protocol);
5129
+ else if (windows.length === 0)
5130
+ this.dashboardTransferable.set(session.id, null);
5131
+ this.announceGeometry(session.id, session, { resync: false });
5132
+ }
5133
+ return;
5134
+ }
3770
5135
  if (typeof parsed === 'object' &&
3771
5136
  parsed !== null &&
3772
5137
  parsed.type === 'resize') {
3773
- const { cols, rows, take } = parsed;
5138
+ const { cols, rows, take, acceptOffer } = parsed;
3774
5139
  // Fit, Enlarge, Focus and Restore are a resize that says `take`.
3775
5140
  // A passive socket's other resizes, including one a dashboard pane
3776
5141
  // sends because the window moved, are not that act: the grid stays,
@@ -3798,12 +5163,80 @@ export class Daemon {
3798
5163
  cols: Math.min(cols, MAX_VIEWPORT_COLS),
3799
5164
  rows: Math.min(rows, MAX_VIEWPORT_ROWS),
3800
5165
  };
3801
- const handedOver = this.geometryController.get(session.id) !== ws;
3802
- const changed = wanted.cols !== session.cols || wanted.rows !== session.rows;
3803
- let applied = false;
5166
+ if (!this.widerReads.has(session.id) && acceptOffer !== true) {
5167
+ // Wider restores and conditional offer takes check ownership
5168
+ // in the session's resize queue below.
5169
+ const handedOver = this.geometryController.get(session.id) !== ws;
5170
+ const changed = wanted.cols !== session.cols || wanted.rows !== session.rows;
5171
+ let applied = false;
5172
+ try {
5173
+ if (changed)
5174
+ await session.resize(wanted.cols, wanted.rows);
5175
+ applied = true;
5176
+ }
5177
+ catch (error) {
5178
+ if (error instanceof SessionProgramEndedError)
5179
+ return;
5180
+ this.logger.warn('viewer resize failed', { id: session.id, error: String(error) });
5181
+ }
5182
+ this.geometryController.set(session.id, ws);
5183
+ this.dashboardTransferable.delete(session.id);
5184
+ this.geometryEpoch.set(session.id, (this.geometryEpoch.get(session.id) ?? 0) + 1);
5185
+ if (credential.kind === 'dashboard') {
5186
+ this.dashboardGeometryOwner.set(session.id, ws.protocol);
5187
+ this.dashboardCredentialOwner.set(session.id, credential.dashboardToken);
5188
+ }
5189
+ else {
5190
+ this.dashboardGeometryOwner.delete(session.id);
5191
+ this.dashboardCredentialOwner.delete(session.id);
5192
+ }
5193
+ if (changed && applied) {
5194
+ this.audit.record(actor, 'resize', session.id, {
5195
+ cols: wanted.cols, rows: wanted.rows, hold: false,
5196
+ });
5197
+ }
5198
+ if (changed)
5199
+ this.announceGeometry(session.id, session);
5200
+ else if (handedOver)
5201
+ this.announceGeometry(session.id, session, { resync: false });
5202
+ else if (take === true)
5203
+ ws.send(JSON.stringify(this.geometryFrame(session, ws)));
5204
+ return;
5205
+ }
3804
5206
  try {
3805
- await session.resize(wanted.cols, wanted.rows);
3806
- applied = true;
5207
+ const applied = await session.resizeIfCurrent(wanted.cols, wanted.rows,
5208
+ // A viewport that left while its take waited in the queue made
5209
+ // no lasting choice: skip it so the pending wider restore runs.
5210
+ () => !session.geometryHeld && !session.exited && ws.readyState === ws.OPEN &&
5211
+ (acceptOffer !== true || this.gridOfferedTo(session.id, ws)) &&
5212
+ (this.sessionSockets.get(session.id)?.has(ws) ?? false), (changed) => {
5213
+ const handedOver = this.geometryController.get(session.id) !== ws;
5214
+ // The controller change and epoch belong to the same queued
5215
+ // act as the resize, before a queued wider restore can run.
5216
+ this.geometryController.set(session.id, ws);
5217
+ this.dashboardTransferable.delete(session.id);
5218
+ this.geometryEpoch.set(session.id, (this.geometryEpoch.get(session.id) ?? 0) + 1);
5219
+ if (credential.kind === 'dashboard') {
5220
+ this.dashboardGeometryOwner.set(session.id, ws.protocol);
5221
+ this.dashboardCredentialOwner.set(session.id, credential.dashboardToken);
5222
+ }
5223
+ else {
5224
+ this.dashboardGeometryOwner.delete(session.id);
5225
+ this.dashboardCredentialOwner.delete(session.id);
5226
+ }
5227
+ if (changed) {
5228
+ this.audit.record(actor, 'resize', session.id, {
5229
+ cols: wanted.cols, rows: wanted.rows, hold: false,
5230
+ });
5231
+ this.announceGeometry(session.id, session);
5232
+ }
5233
+ else if (handedOver)
5234
+ this.announceGeometry(session.id, session, { resync: false });
5235
+ else if (take === true)
5236
+ ws.send(JSON.stringify(this.geometryFrame(session, ws)));
5237
+ }, true);
5238
+ if (!applied && ws.readyState === ws.OPEN)
5239
+ ws.send(JSON.stringify(this.geometryFrame(session, ws)));
3807
5240
  }
3808
5241
  catch (error) {
3809
5242
  // The program has ended (a viewer fitting its window while
@@ -3823,39 +5256,6 @@ export class Daemon {
3823
5256
  error: String(error),
3824
5257
  });
3825
5258
  }
3826
- // Asking is the deliberate act that takes control, whether or not
3827
- // the grid actually moves: a viewport that already fits is still
3828
- // the one driving.
3829
- this.geometryController.set(session.id, ws);
3830
- if (credential.kind === 'dashboard')
3831
- this.dashboardGeometryOwner.set(session.id, ws.protocol);
3832
- else
3833
- this.dashboardGeometryOwner.delete(session.id);
3834
- // A geometry change is a geometry change whoever made it, and
3835
- // `resize` is on the list of audited actions the security page
3836
- // publishes. Only the ones that actually took: a proposal the
3837
- // grid already satisfied moved nothing, and one that failed moved
3838
- // nothing either, so neither is recorded as a success. `hold` is
3839
- // false because a viewport never holds: holding is asked for
3840
- // explicitly, over the API (§5).
3841
- if (changed && applied) {
3842
- this.audit.record(actor, 'resize', session.id, {
3843
- cols: wanted.cols,
3844
- rows: wanted.rows,
3845
- hold: false,
3846
- });
3847
- }
3848
- // Everyone sees the same grid, and each is told whether they are
3849
- // now driving it. A proposal that changed nothing needs no
3850
- // snapshot, because the page already shows this grid. But if the
3851
- // grid changed hands, everyone is told that much, or the old
3852
- // driver goes on believing it is theirs.
3853
- if (changed)
3854
- this.announceGeometry(session.id, session);
3855
- else if (handedOver)
3856
- this.announceGeometry(session.id, session, { resync: false });
3857
- else if (take === true)
3858
- ws.send(JSON.stringify(this.geometryFrame(session, ws)));
3859
5259
  }
3860
5260
  return;
3861
5261
  }
@@ -3904,7 +5304,8 @@ export class Daemon {
3904
5304
  // sequences, so this is not always one keystroke.) .catch keeps the exit
3905
5305
  // race, the session dying mid-write, from escaping as an unhandled
3906
5306
  // rejection.
3907
- void session.write(text).catch((error) => {
5307
+ const report = terminalReportKind(text);
5308
+ void session.write(text, { terminalReport: report !== null, humanInput: report === null }).catch((error) => {
3908
5309
  this.logger.warn('viewer input failed', {
3909
5310
  id: session.id,
3910
5311
  error: String(error),
@@ -3915,7 +5316,6 @@ export class Daemon {
3915
5316
  // because the program asked for it. Nobody typed it, so it is audited
3916
5317
  // as a report and leaves the "last input" indicator alone (§4.5, §5).
3917
5318
  // Content only under captureContent, as for input.
3918
- const report = terminalReportKind(text);
3919
5319
  if (report !== null) {
3920
5320
  this.audit.record(actor, 'report', session.id, {
3921
5321
  kind: report,
@@ -3931,26 +5331,33 @@ export class Daemon {
3931
5331
  this.broadcastControl(session.id, { type: 'input-source', source: 'human' });
3932
5332
  };
3933
5333
  ws.on('message', (message) => {
3934
- void onViewerMessage(message).catch((error) => {
3935
- this.logger.warn('viewer message failed', { id: session.id, error: String(error) });
5334
+ this.callerContext.run(options.callerSession, () => {
5335
+ void onViewerMessage(message).catch((error) => {
5336
+ this.logger.warn('viewer message failed', { id: session.id, error: String(error) });
5337
+ });
3936
5338
  });
3937
5339
  });
3938
5340
  ws.on('close', () => {
3939
- unsubscribeData();
3940
- unsubscribeExit();
3941
- sync.close();
3942
- this.sockets.delete(ws);
3943
- this.sessionSockets.get(session.id)?.delete(ws);
3944
- this.updateFeedSession(session.id);
3945
- // The grid stays where it is; it simply no longer belongs to anyone.
3946
- // The next single-session viewport to arrive, or a `take`, picks it
3947
- // up. A dashboard socket, and a `drive=0` socket, that is already
3948
- // connected does not inherit it.
3949
- if (this.geometryController.get(session.id) === ws) {
3950
- this.geometryController.delete(session.id);
3951
- }
3952
- this.lastActivity = Date.now();
3953
- this.audit.record(actor, 'ws-close', session.id);
5341
+ this.callerContext.run(options.callerSession, () => {
5342
+ unsubscribeData();
5343
+ unsubscribeExit();
5344
+ sync.close();
5345
+ this.sockets.delete(ws);
5346
+ this.sessionSockets.get(session.id)?.delete(ws);
5347
+ this.updateFeedSession(session.id);
5348
+ // The grid stays where it is. A dashboard's grid stays remembered for
5349
+ // that dashboard document, which takes it back when it reconnects; any
5350
+ // other socket follows it until a deliberate resize. Otherwise the next
5351
+ // single-session viewport to arrive, or a `take`, picks it up. A
5352
+ // dashboard socket, and a `drive=0` socket, that is already connected
5353
+ // does not inherit it.
5354
+ if (this.geometryController.get(session.id) === ws) {
5355
+ this.geometryController.delete(session.id);
5356
+ this.announceGeometry(session.id, session, { resync: false });
5357
+ }
5358
+ this.lastActivity = Date.now();
5359
+ this.audit.record(actor, 'ws-close', session.id);
5360
+ });
3954
5361
  });
3955
5362
  }
3956
5363
  }